【问题标题】:How to use slash command in channel with JDA?如何在 JDA 频道中使用斜杠命令?
【发布时间】:2021-09-18 08:28:55
【问题描述】:
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 开发者文档中说:

为了使 Slash Commands 在公会中起作用,公会必须 使用 applications.commands 范围授权您的应用程序。这 bot 范围不够。

JDA 究竟是如何做到这一点的?

【问题讨论】:

    标签: discord-jda


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2018-02-17
      • 2014-03-21
      • 2021-11-11
      • 1970-01-01
      • 2023-02-26
      • 1970-01-01
      • 2012-03-12
      • 1970-01-01
      • 2021-11-09
      相关资源
      最近更新 更多