Discord.js消息更新检测报错:TypeError: Cannot Read property 'content' of undefined
解决Discord.js机器人监听消息编辑时的"Cannot read property 'content' of undefined"错误
嘿,我一眼就揪出问题所在了,咱们一步步来修复:
直接报错原因:函数调用未传参
你在messageUpdate事件里调用find()的时候,完全没把编辑后的新消息传进去!这就导致find函数里的msg参数是undefined,自然会报错说读不到content属性。
额外要注意的Discord.js细节
从Discord.js v13版本开始,messageUpdate事件传递的oldMessage和newMessage有可能是Partial(部分)对象——也就是只包含消息ID这类基础信息,没有完整的content内容。所以我们得先判断并获取完整的消息对象,不然还是会踩坑。
修复后的完整代码
function find(msg) { // 先判断消息是否存在且有内容,避免无意义报错 if (!msg || !msg.content) return; const blacklisted = ['words', 'that', 'I', 'cant', 'say', 'on', 'this', 'website']; // 统一预处理消息内容:移除空格、特殊字符,转小写 const processedContent = msg.content .replace(/\s/g, '') .replace(/[^A-Za-z0-9]/g, '') .toLowerCase(); // 用Array.some()替代for循环,让黑名单检测逻辑更简洁高效 const foundInText = blacklisted.some(word => processedContent.includes(word.toLowerCase())); if (foundInText) { // 给异步操作加catch,避免机器人因权限问题崩溃 msg.delete().catch(err => console.error('删除消息失败:', err)); msg.reply('Watch your language, dont be a bad boy').catch(err => console.error('发送警告失败:', err)); } } client.on('messageUpdate', async (oldMessage, newMessage) => { // 处理Partial消息,获取完整的消息对象 if (newMessage.partial) { try { await newMessage.fetch(); } catch (err) { console.error('获取完整消息失败:', err); return; } } // 把编辑后的新消息传入find函数 find(newMessage); });
关键改动说明
- 调用
find时传入了newMessage,让函数能拿到编辑后的消息内容 - 增加了
msg和msg.content的存在性检查,提前规避意外报错 - 用
Array.some()替代原始for循环,让黑名单检测逻辑更简洁易读 - 增加Partial消息处理逻辑,确保能获取到完整的消息内容
- 给
delete()和reply()添加错误捕获,避免机器人因权限缺失或网络问题崩溃
内容的提问来源于stack exchange,提问作者Thebrayman69
现在测试一下编辑消息的场景,应该就能正常检测违规内容啦!
相关产品推荐
相关产品推荐

