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

为什么我的Discord.js机器人抛出“TypeError: Cannot read property 'send' of undefined”错误?

问题修复方案

1. 用户缓存缺失报错

你直接从client.users.cache读取服务器所有者对象,如果该用户未被机器人缓存,get方法会返回undefined,调用send方法会直接抛出异常。
修复方式:使用fetch主动拉取用户信息,替换缓存读取逻辑:

// 原代码
await client.users.cache.get(guild.ownerId).send(...)
// 替换为
const owner = await client.users.fetch(guild.ownerId);
await owner.send(...)

2. 附件路径读取失败

你使用的相对路径src/Data/trollge.jpg会随启动脚本的工作目录变化,容易出现文件找不到的错误。
修复方式:使用__dirname拼接绝对路径,确保文件定位准确:

// 顶部引入path模块
const path = require('path');

// 附件配置修改为
files: [{
  attachment: path.join(__dirname, 'Data', 'trollge.jpg'),
  name: 'trollge.jpg'
}]

3. 错误捕获逻辑缺失

原代码的catch只能捕获send方法的错误,前面获取用户的步骤如果报错会直接抛出未捕获异常,建议把所有异步逻辑包裹在try catch中:

client.on('guildCreate', async (guild) => {
    console.log(`[Client]: Joined "${guild.name}"!`);
    guildCache.set(guild.id, {
        bullyTarget: undefined,
        lastInsultGenerated: undefined
    });
    console.log(guildCache);
    console.log('');
    try {
        const owner = await client.users.fetch(guild.ownerId);
        await owner.send({
            content: 'You\'ll ***regret*** adding me.',
            files: [{
              attachment: path.join(__dirname, 'Data', 'trollge.jpg'),
              name: 'trollge.jpg'
            }]
        })
        console.log('[Client]: Sent join message to server owner :D\n');
    } catch (err) {
        console.error('[Client]: 发送入群消息失败:', err);
    }
});

额外优化提示:你现在使用的数值类型intents 4609 功能正常,但使用枚举写法可读性更高,便于后续维护:

const { Client, Collection, GatewayIntentBits } = require('discord.js');
const client = new Client({ 
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.DirectMessages
  ] 
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 16:45:01