Discord机器人调用message.send()无法发送本地图片求助
问题:Discord机器人调用
message.send()无法发送图片,仅能发送文字 我无法排查出为何调用message.send()时图片无法发送。目前我只能发送文字内容,无法发送图片。频道权限无误,因为机器人当前拥有Administrator权限。
机器人代码
client.on('messageCreate', msg => { if (msg.content === '!random') { // Find the channel with the specified name const channel = client.channels.cache.find(ch => ch.name === 'mod-default-log'); console.log('Channel:', channel); // log the channel object try { // Declare the attachment as a collection const attachment = new Collection([{ file: fs.readFileSync('./images/1b509fe1549a1c08861ebc00dd39b68ec29c2758.png'), name: 'image.png' }]); console.log('Attachment:', attachment); // log the attachment object // Send the message with the attachment channel.send('This is a message with a file attachment from a URL!', attachment); } catch (error) { console.error(error.message); // log error message } } });
Intents配置
const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, ]});
调试输出
Attachment: Collection(1) [Map] { undefined => undefined }
问题分析与修复方案
1. Collection初始化错误
你创建Collection的方式不符合Discord.js要求:Collection需要传入键值对数组(如[['key1', value1], ['key2', value2]]),而非对象数组。这直接导致集合中的键和值都为undefined,也就是你看到的调试输出结果。
2. 消息发送参数格式错误
channel.send()的第二个参数不能直接传Collection,正确做法是传入包含files属性的配置对象,其中files是附件对象的数组。
修正后的代码
// 先导入AttachmentBuilder(Discord.js v14+版本使用) const { AttachmentBuilder } = require('discord.js'); client.on('messageCreate', msg => { if (msg.content === '!random') { const channel = client.channels.cache.find(ch => ch.name === 'mod-default-log'); console.log('Channel:', channel); try { // 使用AttachmentBuilder创建附件对象 const attachment = new AttachmentBuilder( fs.readFileSync('./images/1b509fe1549a1c08861ebc00dd39b68ec29c2758.png'), { name: 'image.png' } ); console.log('Attachment:', attachment); // 按正确格式发送消息 channel.send({ content: 'This is a message with a file attachment from a URL!', files: [attachment] }); } catch (error) { console.error(error.message); } } });
额外注意事项
- 若使用Discord.js v13或更早版本,需用
MessageAttachment替代AttachmentBuilder。 - 确认图片路径正确,
fs.readFileSync能正常读取目标文件,路径错误也会导致图片发送失败。
内容的提问来源于stack exchange,提问作者mr almoomoo
相关产品推荐
相关产品推荐

