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
}
}
使用上面的代码,我可以通过 DM 机器人使用斜杠命令。但是,如何在频道中使用斜杠命令?
它在不和谐的开发者文档中说:
<块引用>为了使斜线命令在公会内工作,公会必须 使用 applications.commands 范围授权您的应用程序。这 bot 范围还不够。
如何使用 JDA 做到这一点?
答案 0 :(得分:2)
要生成这样的授权 URL,请执行以下步骤:
bot
和 applications.commands
的授权网址请注意,正如此处的评论正确指出的那样,全局命令最多需要 1 小时才能传播。如果你想测试你的机器人,你可以使用立即显示的公会命令。
要创建公会命令,请使用 jda.getGuildById(guildId)
获取公会,然后使用相同的方法在该 Guild
实例而不是 JDA
实例上创建命令。请注意,获取公会需要 JDA 准备就绪,因此请确保在构建 JDA 实例后先调用 awaitReady()
。