Discord.js重启后messageUpdate/messageDelete事件异常及属性读取报错求助
解决方案:Discord.js Partial Message 属性读取空指针错误
问题根源
启用MESSAGE Partials后,机器人重启前的消息触发messageUpdate/messageDelete事件时,你拿到的是Partial Message对象——这种对象只包含消息ID、频道ID等最基础的元数据,author、member这类关联属性会是null,直接访问就会抛出Cannot read properties of null错误。
解决步骤
必须先通过fetch()方法获取完整的消息对象,再访问author等属性。具体修改如下:
1. 修改messageUpdate事件代码
module.exports = class { constructor(client) { this.client = client; } async run(oldMessage, newMessage) { const data = {}; const client = this.client; data.config = client.config; // 处理Partial对象:获取完整的newMessage if (newMessage.partial) { try { newMessage = await newMessage.fetch(); } catch (err) { console.error('获取完整消息失败:', err); return; } } // 现在可以安全访问author属性了 if (newMessage.author.bot) return; if (!newMessage.editedAt) return; // 你的邀请链接审核代码 // code that deleted invites if member has not permissions } };
2. 修改messageDelete事件代码
module.exports = class { constructor(client) { this.client = client; } async run(message) { const data = {}; const client = this.client; data.config = client.config; // 处理Partial对象:获取完整的message if (message.partial) { try { message = await message.fetch(); } catch (err) { console.error('获取完整消息失败:', err); return; } } // 安全访问author属性 if (message.author.bot) return; // 你的消息 snipe 代码 // Code that snipes deleted message } };
额外注意事项
fetch()是异步操作,必须用await,且要包裹在try-catch里——如果消息已经被彻底删除(比如频道也被删除),fetch会失败,此时直接终止流程即可。- 若需要访问
messageUpdate事件里的oldMessage属性,同样要检查oldMessage.partial并执行fetch操作。
内容的提问来源于stack exchange,提问作者Luciferas
相关产品推荐
相关产品推荐

