Discord.js中如何存储命令选项并实现echo命令机器人回复?
Discord.js Echo命令实现问题及报错解决
问题描述
我是Discord.js新手,想要实现echo命令:获取命令的input选项内容并让机器人回复,同时想知道能不能把命令选项存入变量。当前运行代码时出现报错:TypeError: Cannot read properties of undefined (reading 'ephemeral')
项目代码及报错日志
package.json
{ "name": "bot", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" }
index.js
const fs = require('node:fs'); const path = require('node:path'); const {Client,GatewayIntentBits, Collection} = require('discord.js'); const {token} = require('./config.json'); const { execute } = require('./commands/ping'); const ping = require('./commands/ping'); const client = new Client({intents: [GatewayIntentBits.Guilds]}); client.commands = new Collection(); const commandPath = path.join(__dirname, 'commands'); const commandFiles = fs.readdirSync(commandPath).filter(file => file.endsWith('.js')); for (const file of commandFiles) { const filePath = path.join(commandPath, file); const command = require(filePath); client.commands.set(command.data.name, command); } client.once('ready',()=> { console.log("ready"); }); client.on('interactionCreate', async interaction => { if(!interaction.isChatInputCommand()) return; const command = client.commands.get(interaction.commandName) if(!command) return; try { await command.execute(interaction); } catch(error) { console.error(error); await interaction.reply({content: "there was an error while executing this command", ephemeral: true}); } }); client.login(token);
echo.js
const {SlashCommandBuilder} = require('discord.js'); module.exports = { data: new SlashCommandBuilder() .setName('echo') .setDescription('returns input') .addStringOption(option => option.setName('input') .setDescription("the option to echo back") .setRequired(true)), async execute(interaction) { await interaction.reply(); } }
ping.js
const {SlashCommandBuilder} = require('discord.js'); module.exports = { data: new SlashCommandBuilder() .setName('ping') .setDescription('replies with pong'), async execute(interaction) { await interaction.reply("pong!") } }
deploy-commands.js
const {REST} = require("@discordjs/rest"); const {Routes} = require("discord.js"); const {clientId, guildId, token} = require("./config.json"); const path = require("node:path"); const fs = require("node:fs"); const commands = []; const commandPath = path.join(__dirname, 'commands'); const commandFiles = fs.readdirSync(commandPath).filter(file => file.endsWith('.js')); for (const file of commandFiles) { const filePath = path.join(commandPath, file); const command = require(filePath); commands.push(command.data.toJSON()); } const rest = new REST({version: 10}).setToken(token); rest.put(Routes.applicationGuildCommands(clientId, guildId), {body:commands}) .then(() => console.log("registered commands")) .catch(console.error);
config.json
{ "token": "hidden", "clientId": "1009394510117212162", "guildId": "1009401102929768479" }
报错日志
C:\Users\perry\Desktop\bot>node . ready TypeError: Cannot read properties of undefined (reading 'ephemeral') at ChatInputCommandInteraction.reply (C:\Users\perry\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:102:30) at Object.execute (C:\Users\perry\Desktop\bot\commands\echo.js:14:27) at Client. (C:\Users\perry\Desktop\bot\index.js:32:23) at Client.emit (node:events:527:28) at InteractionCreateAction.handle (C:\Users\perry\node_modules\discord.js\src\client\actions\InteractionCreate.js:81:12) at Object.module.exports [as INTERACTION_CREATE] (C:\Users\perry\node_modules\discord.js\src\client\websocket\handlers\INTERACTION_CREATE.js:4:36) at WebSocketManager.handlePacket (C:\Users\perry\node_modules\discord.js\src\client\websocket\WebSocketManager.js:352:31) at WebSocketShard.onPacket (C:\Users\perry\node_modules\discord.js\src\client\websocket\WebSocketShard.js:481:22) at WebSocketShard.onMessage (C:\Users\perry\node_modules\discord.js\src\client\websocket\WebSocketShard.js:321:10) at WebSocket.onMessage (C:\Users\perry\node_modules\ws\lib\event-target.js:199:18)
解决方法
1. 报错原因及修复
报错根源在echo.js的execute方法:调用await interaction.reply();时未传入任何参数。Discord.js的reply()方法会尝试读取参数对象中的ephemeral属性,无参数时参数为undefined,因此触发该错误。
2. 实现Echo命令并获取选项
修改echo.js的execute方法,通过interaction.options.getString('input')获取用户输入的选项内容,完成回复逻辑:
const {SlashCommandBuilder} = require('discord.js'); module.exports = { data: new SlashCommandBuilder() .setName('echo') .setDescription('返回输入内容') .addStringOption(option => option.setName('input') .setDescription("要返回的内容") .setRequired(true)), async execute(interaction) { // 将命令选项内容存入变量 const userInput = interaction.options.getString('input'); // 直接回复用户输入内容 await interaction.reply(userInput); // 若需私密回复(仅用户可见),可传入对象参数: // await interaction.reply({ content: userInput, ephemeral: true }); } }
3. 命令选项存入变量的说明
完全可以将命令选项存入变量,上述代码中已将input选项内容存入userInput变量,你可基于此变量进行后续操作,比如内容修改、数据库存储等。
4. 额外注意事项
- 修改
echo.js后无需重新运行deploy-commands.js,仅执行逻辑变更不影响命令结构。 - 确保Discord.js版本为v10(代码中
REST({version: 10})已指定),版本不一致可能引发其他问题。
内容的提问来源于stack exchange,提问作者mel.pear
相关产品推荐
相关产品推荐

