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

Discord.js报错Type Error: Cannot read properties of undefined (reading 'send')求助

排查Discord.js发送DM时的Cannot read properties of undefined (reading 'send')错误

错误原因

这个错误表明message.author.send()调用中,message.author为undefined,或者机器人无法向用户发送DM,常见触发场景:

  • 用户关闭了隐私设置中「允许来自服务器成员的直接消息」选项,导致机器人无法发送DM
  • 在Discord.js v14+版本中,频道类型判断方式已变更,原代码的判断逻辑可能引发异常
  • 命令通过Webhook等无作者上下文的消息触发,此时message.author不存在

修复方案

1. 添加错误捕获与提示

在发送DM的逻辑后增加错误捕获,避免程序崩溃并给用户明确提示:

async execute(client, message) {
  // 先验证消息发送者存在
  if (!message.author) return message.reply({ content: "无法识别消息发送者!" });

  const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+';
  const passString = Array.from({ length: 20 }, () => possible[Math.floor(Math.random() * possible.length)]).join('');

  return message.author
    .send(passString)
    .then(() => {
      // 适配v14+版本的DM频道判断,旧版本可使用message.channel.type === 'dm'
      if (message.channel.isDMBased?.()) return;
      message.reply({ content: "我已经把随机密码发送到你的私信里了!" });
    })
    .catch(err => {
      message.reply({ content: "无法给你发送私信,请检查隐私设置是否允许接收服务器成员的消息!" });
      console.error(err);
    });
}

2. 版本适配频道判断

如果使用Discord.js v14及以上版本,替换原有的message.channel.type === 'dm'为message.channel.isDMBased(),v14已弃用直接判断type字符串值的写法。

3. 前置验证发送者

在执行发送逻辑前先检查message.author是否存在,避免Webhook等特殊场景触发错误。

4. 简化密码生成逻辑(可选)

用Array.from替代循环,让密码生成代码更简洁:

const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+';
const passString = Array.from({ length: 20 }, () => possible[Math.floor(Math.random() * possible.length)]).join('');

内容的提问来源于stack exchange,提问作者Fawnino

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 11:54:20