Discord.js 14"/>
Discord.js 14
当一个成员在 discord.js 14 中使用
@napi-rs/canvas
加入我的服务器时,我试图发送图像。
当机器人尝试发送消息时出现此错误。
我试图用 discordjs.guide 来实现
Cannot read properties of undefined (reading 'cache')
这是我的活动代码:
const { Events, AttachmentBuilder} = require('discord.js');
const Canvas = require('@napi-rs/canvas');
module.exports = {
name: Events.GuildMemberAdd,
async execute(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');
channel.send(({ files: [attachment] }));
},
};
这是我的
index.js
文件
const { Client, Collection, Events, GatewayIntentBits } = require('discord.js');
const fs = require('node:fs');
const path = require('node:path');
const { token, prefix } = require('./config.json');
const { channel } = require('node:diagnostics_channel');
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildMembers]});
clientmands = new Collection();
const foldersPath = path.join(__dirname, 'commands');
const commandFolders = fs.readdirSync(foldersPath).filter(file => file.endsWith('.js'));
for (const folder of commandFolders) {
const commandsPath = path.join(foldersPath, folder);
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require (filePath)
if ('data' in command && 'execute' in command) {
clientmands.set(command.data.name, command);
} else {
console.log(`[WARNING] The command on ${filePath} dont have "data" or "execute" property.`);
}
}
}
const eventsPath = path.join(__dirname, 'events');
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const filePath = path.join(eventsPath, file);
const event = require(filePath);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
}
client.login(token);
我尝试了很多解决方案,但没有任何效果我正在使用最新版本的 discord.js v14.
回答如下:由于你似乎需要
execute
函数中的client作为第一个参数,所以你需要将client传递给函数。
您可以通过将
(...args) => event.execute(...args)
替换为 (...args) => event.execute(client, ...args)
来实现
这样做会将客户端作为第一个参数和所有事件的附加参数发送到命令的
execute
函数。
确保您正确调整了所有其他命令的执行功能,因为它们将受到该更改的影响。
更多推荐
Discord.js 14
发布评论