【问题标题】:Parse Arguments from Discord interactions从 Discord 交互中解析参数
【发布时间】:2021-10-28 07:38:56
【问题描述】:

我目前正在编写一个不和谐的机器人,并想尝试使用新的交互功能(又名斜杠命令)。

我设法让“/test”交互工作,机器人接收命令并执行我的代码(遵循 discord.js 手册)。现在我从interaction.commandName 知道了命令的名称(在本例中为“test”),但我似乎无法获取传入的参数。

以下是我的“test.js”,用于“/test”命令:

const { SlashCommandBuilder } = require('@discordjs/builders');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('test')
        .setDescription('Test with arguments!')
    .addStringOption(option =>
      option.setName("device")
        .setDescription("Some argument")
        .setRequired(true)
        .addChoice("Arg A", "A")
        .addChoice("Arg B", "B")
    ),
    async execute(interaction, log) {
        // log is a function to log to a file...
        // Ignore it, since it is not *currently* in use.
 
        return interaction.reply("You selected the argument ????")
    
        // Delete message after 5 seconds
        .then(setTimeout(() => interaction.deleteReply(), 5000));
    },
};

命令本身被一个同样来自 discord.js 文档的函数调用:

client.on('interactionCreate', async(interaction) => {
  if (!interaction.isCommand()) return;

    const command = client.commands.get(interaction.commandName);

    if (!command) return;

    try {
        await command.execute(interaction, log);
    } catch (error) {
        console.error(error);
        await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
    }
});

我浏览了文档并在网上搜索了很多,但我似乎没有找到任何东西。 如果有人可以帮助我,那就太好了。

【问题讨论】:

    标签: javascript discord discord.js


    【解决方案1】:

    警告:我没有测试这段代码CommandInteractions 有一个options 属性。你可以使用get方法就可以了。

    //the option name is 'TEST' and the user inputted 'hey'
    let option = interaction.options.get("TEST")
    console.log(option.value)
    

    .value 显示输入,如here 所示。如果没有输入,则可以为空(不需要选项并且用户没有输入该选项)

    【讨论】:

      猜你喜欢
      • 2021-09-15
      • 2021-09-15
      • 2023-02-15
      • 2020-12-15
      • 2021-12-11
      • 2021-10-16
      • 1970-01-01
      • 1970-01-01
      • 2018-11-26
      相关资源
      最近更新 更多