Discord.js v14 TypeError:无法读取undefined的'guild'属性问题
问题:Discord.js v14斜杠命令/getnews报错TypeError: Cannot read properties of undefined (reading 'guild')
在NodeJS 16环境下使用Discord.js v14开发机器人,尝试创建/getnews斜杠命令,实现用户执行该命令后自动获得「Bot News」角色,但运行后机器人崩溃,报错TypeError: Cannot read properties of undefined (reading 'guild')。
相关代码(getnews.js)
import { SlashCommandBuilder, Client } from 'discord.js'; const client = Client const message = client.msg // Creates an Object in JSON with the data required by Discord's API to create a SlashCommand const create = () => { const command = new SlashCommandBuilder() .setName('getnews') .setDescription('Assigns role for bot news.') return command.toJSON(); }; // Called by the interactionCreate event listener when the corresponding command is invoked const invoke = (interaction) => { let role = message.guild.roles.cache.find(role => role.name === "Bot News"); let member = message.member member.roles.add(role).catch(console.error); }; export { create, invoke };
详细错误栈
Successfully logged in as user#tag file:///C:/Users/Logan/Documents/harrisbot2.0/events/commands/getnews.js:16 let role = message.guild.roles.cache.find(role => role.name === "Bot News"); ^ TypeError: Cannot read properties of undefined (reading 'guild') at Module.invoke (file:///C:/Users/Logan/Documents/harrisbot2.0/events/commands/getnews.js:16:21) at Module.invoke (file:///C:/Users/Logan/Documents/harrisbot2.0/events/interactionCreate.js:8:58) at processTicksAndRejections (node:internal/process/task_queues:96:5)
解决方案
问题分析
- 错误的变量定义:
const client = Client只是引用了Client类,不是实际的客户端实例;client.msg是不存在的属性,导致message变量为undefined,自然无法读取guild属性。 - 误用消息对象:斜杠命令的交互逻辑应该使用传入的
interaction对象,而不是不存在的message对象。
修复后的代码
import { SlashCommandBuilder } from 'discord.js'; const create = () => { const command = new SlashCommandBuilder() .setName('getnews') .setDescription('Assigns role for bot news.') return command.toJSON(); }; const invoke = async (interaction) => { // 先回复交互避免超时 await interaction.deferReply({ ephemeral: true }); // 从interaction中获取公会和成员 const guild = interaction.guild; const member = interaction.member; if (!guild) { return interaction.editReply('此命令只能在服务器中使用!'); } // 查找目标角色 const role = guild.roles.cache.find(role => role.name === "Bot News"); if (!role) { return interaction.editReply('服务器中不存在「Bot News」角色!'); } // 添加角色 try { await member.roles.add(role); await interaction.editReply('已成功为你添加「Bot News」角色!'); } catch (error) { console.error(error); await interaction.editReply('添加角色失败,请检查机器人权限!'); } }; export { create, invoke };
关键改动说明
- 移除了错误的
client和message定义,命令文件无需单独创建客户端实例。 - 使用
interaction对象获取当前交互的公会(interaction.guild)和成员(interaction.member)。 - 增加交互回复逻辑,避免Discord判定命令超时。
- 添加角色不存在、机器人无权限等异常处理,提升稳定性。
内容的提问来源于stack exchange,提问作者Logan Cookson
相关产品推荐
相关产品推荐

