Discord.js代码修改需求:将消息日志转为Embed格式发送
修改Discord.js消息记录为Embed格式
以下是适配Discord.js v14的完整修改代码:
const { Client, EmbedBuilder } = require('discord.js'); const client = new Client({ intents: [/* 确保已启用必要意图,如Guilds、GuildMessages、MessageContent */] }); client.on('messageCreate', message => { if (message.author.bot) { return; } console.log("Message received:", message.content); // Checkpoint if (message.guild && message.guild.id === 'my_server_id') { console.log("Message received from the correct guild."); // Checkpoint const destinationChannel = client.channels.cache.get('my_destination_channel_id'); if (destinationChannel) { console.log("Destination channel found."); // Checkpoint // 创建Embed消息 const logEmbed = new EmbedBuilder() .setTitle(message.author.tag) .setDescription(message.content || '*无内容(可能为附件/表情)*') .setColor('#0099ff') // 可选:设置Embed主题色 .setThumbnail(message.author.displayAvatarURL({ dynamic: true })) // 可选:添加用户头像缩略图 .setTimestamp(); // 可选:添加消息时间戳 destinationChannel.send({ embeds: [logEmbed] }); } else { console.log(`Destination channel not found in the destination guild.`); } } }); client.login('你的Bot令牌');
关键修改说明:
- 引入
EmbedBuilder用于创建结构化Embed消息 - 替换原文本发送逻辑,构建Embed核心内容:
setTitle设为消息发送者的完整标签(如dyno#1234)setDescription设为消息内容,同时兼容无文本的情况(比如仅发表情/附件)- 可选添加颜色、头像缩略图、时间戳优化展示效果
- 使用
{ embeds: [logEmbed] }作为send方法参数,符合Discord.js v14的Embed发送规范
针对Discord.js v13的适配:
若项目使用v13版本,仅需将EmbedBuilder替换为MessageEmbed,其余逻辑一致:
const { MessageEmbed } = require('discord.js'); // ... const logEmbed = new MessageEmbed() .setTitle(message.author.tag) .setDescription(message.content || '*无内容(可能为附件/表情)*') .setColor('#0099ff') .setThumbnail(message.author.displayAvatarURL({ dynamic: true })) .setTimestamp(); destinationChannel.send({ embeds: [logEmbed] });
内容的提问来源于stack exchange,提问作者Cariesthuis
相关产品推荐
相关产品推荐

