Discord.js TypeError: 读取undefined的send属性报错,MongoDB私信功能失效
Discord机器人联动Mongo变更监听发信报错问题修复
程序基础功能
- 建立本地MongoDB连接,监听
test数据库下tools集合的变更事件 - 匹配集合记录中存储的验证码字段,读取记录绑定的关联用户ID
- 等待5秒定时触发后,向目标用户发送扫描结果通知
原始问题代码
const { MongoClient, ReadPreference } = require('mongodb'); const MONGO_URL = 'mongodb://127.0.0.1:27017/'; (async() => { const mongoClient = await MongoClient.connect(MONGO_URL, { appname: 'test', readPreference: ReadPreference.PRIMARY, useNewUrlParser: true, }); const db = await mongoClient.db('test'); const changeStream = db.collection('tools').watch([], { 'fullDocument': 'updateLookup' }); changeStream.on('change', (event) => { tool.findOne({ code: datos, }, async(err, s) => { console.log(datos) const userID2 = s.userID; if (!s) { console.log("pin no encontrado") } if (userID2 != undefined) { try { setTimeout(function() { console.log("userID2 = " + userID2) console.log("Event" = event); console.log("event.updateDescription.updatedFields =" + event.updateDescription.updatedFields) const user = client.users.cache.get(userID2) console.log("const user = " + user) user.send("Resultados del scan: \nEstá el usuario cheat? " + event.updateDescription.updatedFields.cheats + "\nCheats que tiene el usuario: " + event.updateDescription.updatedFields.namecheats) }), 5000 } catch (e) { console.log("[ERROR]", e) } } else { return } }); }) })(); })
控制台输出与报错栈
651312 userID2 = 794601739960844348 { _id: { _data: '82600D5062000000012B022C0100296E5A1004D5046A26D5AE482380F594D10FDC475546645F69640064600CA9A0FE28E8160C78C34E0004' }, operationType: 'update', clusterTime: Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1611485282 }, fullDocument: { _id: 600ca9a0fe28e8160c78c34e, serverID: '802595009617723412', userID: '794601739960844348', __v: 0, cheats: 'true', code: '651312' }, ns: { db: 'test', coll: 'tools' }, documentKey: { _id: 600ca9a0fe28e8160c78c34e }, updateDescription: { updatedFields: { cheats: 'true' }, removedFields: [] } } { cheats: 'true' } const user = undefined /home/jonh/bot-tool/src/index.js:101 user.send("Resultados del scan: \nEstá el usuario cheat? " + event.updateDescription.updatedFields.cheats + "\nCheats que tiene el usuario: " + event.updateDescription.updatedFields.namecheats) ^ TypeError: Cannot read property 'send' of undefined at Timeout._onTimeout (/home/jonh/bot-tool/src/index.js:101:34) at listOnTimeout (node:internal/timers:556:17) at processTimers (node:internal/timers:499:7) npm ERR! code 1 npm ERR! path /home/jonh/bot-tool npm ERR! command failed npm ERR! command sh -c node . npm ERR! A complete log of this run can be found in: /root/.npm/_logs/2021-01-24T10_48_02_631Z-debug.log
已验证的故障特征
- 数据库连接、集合变更监听逻辑运行正常,可准确读取到格式合规的目标用户ID(本次读取到的ID为
794601739960844348) - 通过
client.users.cache.get(userID2)获取的用户对象始终返回undefined,无法调用发送消息方法 - 此前尝试改用远程拉取用户信息的方式实现发信,未解决故障
根因定位与修复方案
- 缓存机制不匹配:Discord.js内置的用户缓存默认仅存储和bot存在过交互的用户,未与bot互发过消息、无共同服务器的用户不会被纳入本地缓存,直接通过
cache.get查询必然返回undefined - 代码语法与逻辑错误:
- 原代码中
console.log("Event" = event)属于无效赋值表达式,会直接触发执行错误 - 原代码中
setTimeout括号位置错误,定时器回调逻辑脱离try-catch捕获范围,所有未捕获异常会直接导致进程崩溃 - 空值判断顺序颠倒:先读取
s.userID字段、后判断s是否存在,当数据库查询无结果时会触发空引用报错 - 未在上下文初始化
tool集合对象、datos验证码变量,存在潜在空引用风险
- 原代码中
- 远程拉取失败原因:未等待Discord机器人客户端完成
ready就绪事件监听,就初始化Mongo变更监听逻辑,此时bot的API鉴权流程未完成,远程用户拉取请求会直接失败
修复要点
- 等待bot客户端触发
ready事件后,再初始化Mongo连接与变更监听逻辑,保证API鉴权流程完成后再执行远程请求 - 替换本地缓存查询逻辑,改用异步远程拉取方式获取用户对象:
// 替代原cache.get逻辑 const user = await client.users.fetch(userID2) - 调整空值判断顺序:先判断数据库查询结果
s是否存在,再读取其字段 - 修正
setTimeout的括号位置,将完整回调逻辑包裹在try-catch捕获范围内 - 补充未定义变量、集合对象的初始化逻辑,增加空值兜底判断
内容的提问来源于stack exchange,提问作者ñeñeñe22
相关产品推荐
相关产品推荐

