如何在 JDA 通道中使用斜杠命令?

How to use slash command in channel with 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
    }
}

通过上面的代码,我可以通过 DM 机器人使用斜杠命令。但是,如何在频道中使用斜杠命令?

在 discord 开发者文档中说:

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.

如何使用 JDA 做到这一点?

要生成这样的授权 URL,请按照以下步骤操作:

  1. 打开你的application dashboard
  2. 选择应用程序后,打开选项卡 OAuth2
  3. 生成授权 URL,勾选范围 botapplications.commands
  4. 复制 URL 并在新标签页中打开它
  5. 用 link
  6. 邀请你的机器人加入公会

请注意,正如此处的评论正确指出的那样,全局命令最多需要 1 小时才能传播。如果你想测试你的机器人,你可以使用立即显示的公会命令。

要创建公会命令,请使用 jda.getGuildById(guildId) 获取公会,然后使用相同的方法在 Guild 实例而不是 JDA 实例上创建命令。请注意,获取公会要求 JDA 准备就绪,因此请确保在构建 JDA 实例后先调用 awaitReady()