Discord.js机器人启动报TypeError,无法跨服务器监听回复snoop指令
机器人启动故障修复指南
故障根因
- 事件绑定错位:代码将消息监听逻辑挂到了
ready事件上。ready事件仅在机器人完成登录时触发一次,回调不存在消息实体参数,执行msg.guild读取时直接触发TypeError: Cannot read property 'guild' of undefined。 - 依赖版本不兼容:报错栈中在Guild初始化阶段抛出的
Cannot read property 'id' of undefined,源于本地安装的是discord.js v11及更早的停更版本,这类版本无法适配Discord当前的官方网关协议,在拉取服务器列表数据时就会直接崩溃。 - 代码逻辑偏差:原代码混入了和需求无关的@角色判断逻辑,还存在变量名错配问题(定义了
snoop计数器却执行未声明的boxes++),完全偏离“跨全服务器监听snoop关键词自动回复”的开发目标。
修复后可运行代码
const { Client, GatewayIntentBits } = require('discord.js'); const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent ] }); const startTime = new Date(); let snoopTriggerCount = 0; client.on('ready', () => { console.log(`机器人登录成功:${client.user.tag}`); }); client.on('messageCreate', (msg) => { // 过滤机器人自身消息,避免触发回复死循环 if (msg.author.bot) return; // 匹配消息中包含snoop的内容,不区分大小写 if (/snoop/i.test(msg.content)) { snoopTriggerCount++; console.log(`检测到snoop触发,来源:服务器${msg.guild?.name || '私聊渠道'},频道${msg.channel.name}`); // 保留原逻辑的随机打字延迟 const delay = Math.floor(Math.random() * (3000 - 2500)) + 2500; msg.channel.sendTyping(); setTimeout(() => { msg.channel.send('snoop').catch(err => console.log('消息发送失败:', err)); }, delay); } }); // 替换为你自己的机器人API令牌 client.login('替换为你的机器人Token');
启动操作步骤
- 卸载本地老旧的discord.js依赖:执行
npm uninstall discord.js - 安装最新稳定版依赖:执行
npm install discord.js - 登录Discord开发者平台,对应该机器人的设置页中开启
Message Content Intent权限,否则机器人无法读取消息内容。
内容的提问来源于stack exchange,提问作者mexicanjoker
相关产品推荐
相关产品推荐

