Discord消息转发机器人发送自身标签而非原发送者标签问题求解
问题根因
- 代码中拼接使用的
client.user.tag指向机器人自身的账号标识,client是当前运行的机器人实例,因此永远返回机器人的标签。 - 原消息发送者的标识存储在事件回调的
msg对象中,调用msg.author.tag即可获取原发送者的Discord标签。
修正后的完整代码
const Discord = require('discord.js'); const { Client, Intents } = require('discord.js'); // 注意intents要确保包含GUILDS、GUILD_MESSAGES等必要权限,避免消息事件无法触发 const client = new Client({ intents: [4611] }); let targetChannel = '906686653874176090' //target channel client.once('ready', () => { console.log('Ready! - Made By Woodington'); }); client.on('messageCreate', gotMessage); function gotMessage(msg) { // 新增判断:跳过机器人自身发送的消息,避免触发循环转发 if (msg.author.bot) return; if (msg.channel.id !== targetChannel) { client.channels.fetch(targetChannel) // 替换client.user.tag为msg.author.tag .then(channel => channel.send(`${msg.content}\n发送者:${msg.author.tag}`)) .catch(console.error); } }
可选优化
如果需要同时转发原消息的附件、Embed等内容,可以调整send方法的参数:
channel.send({ content: `${msg.content}\n发送者:${msg.author.tag}`, // 转发原消息的所有附件 files: msg.attachments.map(att => att.url), // 转发原消息的所有Embed embeds: msg.embeds })
内容的提问来源于stack exchange,提问作者Woodington14
相关产品推荐
相关产品推荐

