解析来自 Discord 交互的参数

Pla*_*fYT 2 javascript discord discord.js

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

\n

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

\n

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

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

该命令本身由一个函数调用,该函数也来自 Discord.js 的文档:

\n
client.on(\'interactionCreate\', async(interaction) => {\n  if (!interaction.isCommand()) return;\n\n    const command = client.commands.get(interaction.commandName);\n\n    if (!command) return;\n\n    try {\n        await command.execute(interaction, log);\n    } catch (error) {\n        console.error(error);\n        await interaction.reply({ content: \'There was an error while executing this command!\', ephemeral: true });\n    }\n});\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n

MrM*_*cal 6

警告:我没有测试此代码 CommandInteraction是否有属性options。你可以使用get它的方法。

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

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