Search code examples
javascriptnode.jsdiscorddiscord.js

Use Slash Commands in all servers where have a bot without GuildID (Discord.js v12)


I want people to be able to use Slash Commands against my bot on any server, as long as the bot is there. I have further granted the bot application.commands permission. I was referencing this answer, but it seems to require the server's GuildID. Can I allow anyone using Slash Commands to come to my bot without a GuildID? And how do people use it? (I use Commands Handler)

sorry for my bad english


Solution

  • You probably want to use a global slash command. Global meaning that it works across all guilds the bot is in and you don't need to provide any guild id.

    client.on("ready", () => {
    
        // Register global slash command
        client.api.applications(client.user.id).commands.post({
            data: {
                name: "hello",
                description: "Say 'Hello, World!'"
            }
        });
    
        // Listen for an interaction (e.g. user typed command)
        client.ws.on("INTERACTION_CREATE", (interaction) => {
            // Access command properties
            const commandId = interaction.data.id;
            const commandName = interaction.data.name;
            
            // Reply only to commands with name 'hello'
            if (commandName == "hello") {
                // Reply to an interaction
                client.api.interactions(interaction.id, interaction.token).callback.post({
                    data: {
                        type: 4,
                        data: {
                            content: "Hello, World!"
                        }
                    }
                });
            }
        });
    
    });
    

    This is how would a user use your command:

    enter image description here

    And the reply looks like this:

    enter image description here