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

Discord.js 14:成员加入时无法向指定频道发图报错

Discord.js v14中@napi-rs/canvas欢迎图报错:Cannot read properties of undefined (reading 'cache')

问题原因

你的GuildMemberAdd事件处理函数参数错误:该事件触发时,传入的第一个参数是加入服务器的成员对象(GuildMember),而非客户端实例(Client)。你错误地将参数命名为client,导致后续调用client.channels.cache.get()时,这个client实际指向成员对象——而成员对象没有channels属性,因此会抛出Cannot read properties of undefined (reading 'cache')的错误。

修复方案

1. 修正事件处理函数参数

修改事件代码中的execute函数,先接收成员对象,再通过成员的client属性获取客户端实例:

const { Events, AttachmentBuilder} = require('discord.js');
const Canvas = require('@napi-rs/canvas');

module.exports = {
    name: Events.GuildMemberAdd,
    async execute(member) {
        // 从成员对象中获取客户端实例
        const client = member.client;
        const canvas = Canvas.createCanvas(1024, 500);
        const context = canvas.getContext('2d');

        const background = await Canvas.loadImage('./resources/canvas/images/welcome.png');

        context.drawImage(background, 0, 0, canvas.width, canvas.height);
        
        const attachment = new AttachmentBuilder(await canvas.encode('png'), { name: 'profile-image.png' });

        console.log('sending message');
        const channel = client.channels.cache.get('1099656104100769924');
        // 新增频道存在性判断,避免二次报错
        if (channel) {
            await channel.send({ files: [attachment] });
        } else {
            console.error('指定的欢迎频道不存在');
        }
    },
};

2. 额外优化建议

为了避免其他潜在问题,建议添加异常捕获,并确保资源路径正确:

const { Events, AttachmentBuilder} = require('discord.js');
const Canvas = require('@napi-rs/canvas');

module.exports = {
    name: Events.GuildMemberAdd,
    async execute(member) {
        try {
            const client = member.client;
            const canvas = Canvas.createCanvas(1024, 500);
            const context = canvas.getContext('2d');

            // 确保背景图路径正确,否则会触发异常
            const background = await Canvas.loadImage('./resources/canvas/images/welcome.png');
            context.drawImage(background, 0, 0, canvas.width, canvas.height);
            
            const attachment = new AttachmentBuilder(await canvas.encode('png'), { name: 'profile-image.png' });

            console.log('sending message');
            const channel = client.channels.cache.get('1099656104100769924');
            if (!channel) {
                return console.error('未找到指定的欢迎频道');
            }
            await channel.send({ files: [attachment] });
        } catch (error) {
            console.error('发送欢迎图时出错:', error);
        }
    },
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 23:42:13