Discord工单机器人报错Uncaught ReferenceError: Client is not defined求助
解决Discord工单机器人的ReferenceError: Client is not defined错误
核心错误原因及修复步骤
非法变量声明位置
你将const Discord = require('discord.js')和const Client = new Client(...)写在了module.exports对象的属性中,这是语法错误——变量声明不能作为对象的键值对。这些声明必须放在模块最顶部,脱离module.exports结构。Intents未正确导入
创建Client实例时使用的Intents未从discord.js中引入,导致未定义。需要从discord.js解构出Intents对象。客户端初始化逻辑错位
命令模块(当前的ticket文件)不应负责创建Client实例和调用login,这部分逻辑属于机器人主文件(如index.js)的职责,命令模块只需导出命令执行逻辑即可。其他潜在问题
- 权限字段
SEND_MESSAGE应为复数SEND_MESSAGES,符合discord.js的权限常量命名规则 - Intents数组中重复了
Intents.CHANNEL_UPDATE,需去重 - 使用
message.guild.members.cache.get(user.id)替代find,效率更高且避免不必要的遍历
- 权限字段
修复后的ticket命令模块代码
const { Client, Intents } = require('discord.js'); module.exports = { name: "ticket", aliases: [], permissions: [], description: "open a ticket!", async execute(message, args, cmd, client, discord) { const channel = await message.guild.channels.create(`ticket: ${message.author.tag}`); channel.setParent("1001310144359055401"); channel.updateOverwrite(message.guild.id, { SEND_MESSAGES: false, VIEW_CHANNEL: false, }); channel.updateOverwrite(message.author, { SEND_MESSAGES: true, VIEW_CHANNEL: true, }); const reactionMessage = await channel.send("Thank you for opening a middleman request!"); try { await reactionMessage.react("🔒"); await reactionMessage.react("⛔"); } catch (err) { channel.send("Error sending emojis!"); throw err; } const collector = reactionMessage.createReactionCollector( (reaction, user) => message.guild.members.cache.get(user.id)?.hasPermission("ADMINISTRATOR"), { dispose: true } ); collector.on("collect", (reaction, user) => { switch (reaction.emoji.name) { case "🔒": channel.updateOverwrite(message.author, { SEND_MESSAGES: false }); break; case "⛔": channel.send("Deleting this channel in 5 seconds!"); setTimeout(() => channel.delete(), 5000); break; } }); message.channel .send(`We will be right with you! ${channel}`) .then((msg) => { setTimeout(() => msg.delete(), 7000); setTimeout(() => message.delete(), 3000); }) .catch((err) => { throw err; }); }, };
机器人主文件(示例index.js)结构
const { Client, Intents } = require('discord.js'); const ticketCommand = require('./path/to/ticket.js'); // 替换为你的ticket文件实际路径 // 初始化客户端,注意v14+版本Intents需使用FLAGS前缀 const client = new Client({ intents: [ Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_CHANNELS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MESSAGE_REACTIONS ] }); // 消息监听与命令触发逻辑 client.on('messageCreate', (message) => { if (message.content.startsWith('!ticket')) { ticketCommand.execute(message, [], 'ticket', client, require('discord.js')); } }); // 登录机器人 client.login('你的机器人令牌'); // 替换为实际令牌
内容的提问来源于stack exchange,提问作者krikop
相关产品推荐
相关产品推荐

