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?
To generate such an authorization URL you follow these steps:
bot and applications.commands tickedNote 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With