You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.27 02:24:04