Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use slash command in channel with JDA?

Tags:

discord-jda

public class HelloWorldBot extends ListenerAdapter
{
    public static void main(String[] args) throws LoginException
    {
        if (args.length < 1) {
            System.out.println("You have to provide a token as first argument!");
            System.exit(1);
        }
        // args[0] should be the token
        // We don't need any intents for this bot. Slash commands work without any intents!
        JDA jda = JDABuilder.createLight(args[0], Collections.emptyList())
                .addEventListeners(new HelloWorldBot())
                .setActivity(Activity.playing("Type /ping"))
                .build();

        jda.upsertCommand("ping", "Calculate ping of the bot").queue(); // This can take up to 1 hour to show up in the client
    }

    @Override
    public void onSlashCommand(SlashCommandEvent event)
    {
        if (!event.getName().equals("ping")) return; // make sure we handle the right command
        long time = System.currentTimeMillis();
        event.reply("Pong!").setEphemeral(true) // reply or acknowledge
                .flatMap(v ->
                        event.getHook().editOriginalFormat("Pong: %d ms", System.currentTimeMillis() - time) // then edit original
                ).queue(); // Queue both reply and edit
    }
}

With the code above, I can make use slash command by DM the bot. However, how do I use slash command in a channel?

It says in the discord developer docs that:

In order to make Slash Commands work within a guild, the guild must authorize your application with the applications.commands scope. The bot scope is not enough.

How exactly do one do that with JDA?

like image 529
zeyuyun1 Avatar asked Jan 18 '26 21:01

zeyuyun1


1 Answers

To generate such an authorization URL you follow these steps:

  1. Open your application dashboard
  2. Open the tab OAuth2 after you selected your application
  3. Generate an authorization URL with the scopes bot and applications.commands ticked
  4. Copy that URL and open it in a new tab
  5. Invite your bot to the guild with that link

Note that, as the comment here correctly points out, the global commands take up to 1 hour to propagate. If you want to test your bot, you can use guild commands which show up instantly.

To create a guild command use jda.getGuildById(guildId) to get the guild, then use the same methods for creating commands on that Guild instance instead of the JDA instance. Note that getting a guild requries for JDA to be ready, so make sure you call awaitReady() first after you build your JDA instance.

like image 87
Minn Avatar answered Jan 22 '26 11:01

Minn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!