如何从Discord交互(slash命令)中解析获取传入的参数
要获取用户传入的斜杠命令参数,可通过 interaction.options 下对应类型的方法读取,你当前注册的是字符串类型的device选项,使用getString方法即可读取参数值。
代码修改示例
调整test.js的execute逻辑
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) { // 读取用户传入的device参数 const selectedDevice = interaction.options.getString('device'); // 回复内容插入参数值,同时修正原setTimeout的写法问题 return interaction.reply(`You selected the argument ${selectedDevice}`) .then(() => { setTimeout(() => interaction.deleteReply(), 5000); }); }, };
补充注意事项
- 不同参数类型对应不同的读取方法:整数参数用
getInteger、布尔参数用getBoolean、用户参数用getUser,方法入参均为你定义参数时设置的name值 - 如果修改命令参数配置后Discord端没有显示参数输入框,需要重新部署你的斜杠命令到对应服务器/全局,确保Discord端同步了最新的命令结构
内容的提问来源于stack exchange,提问作者PlayWolfYT
相关产品推荐
相关产品推荐

