如何监听Discord.js机器人发送的指定标题Embed或文本消息?
在Discord.js中监听机器人自身发送的消息
要实现监听机器人自己发送的消息(包括普通文本和指定标题的Embed),核心是利用Discord.js的messageCreate事件,同时配置正确的权限意图(Intents),以下是具体实现步骤:
1. 配置必要的权限意图
Discord.js v14+ 需要明确声明所需意图,初始化客户端时务必包含以下项:
const { Client, GatewayIntentBits } = require('discord.js'); const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent // 必须开启,才能读取消息内容和Embed数据 ] });
2. 监听普通文本消息
通过messageCreate事件捕获所有消息,先判断消息作者是否为机器人自身,再匹配文本内容执行后续操作:
client.on('messageCreate', async (message) => { // 只处理机器人自己发的消息 if (message.author.id !== client.user.id) return; // 匹配你需要监听的文本内容,比如"任务执行完毕" if (message.content === '任务执行完毕') { // 这里写捕获后的后续逻辑,比如发送通知、触发其他功能 await message.channel.send('已捕获到机器人发送的文本消息,执行后续操作...'); } });
3. 监听标题为'Success'的Embed消息
同样使用messageCreate事件,检查消息中的Embed数组,筛选出标题为'Success'的目标Embed:
client.on('messageCreate', async (message) => { // 只处理机器人自己发的消息 if (message.author.id !== client.user.id) return; // 跳过没有Embed的消息 if (message.embeds.length === 0) return; // 查找标题为'Success'的Embed const targetEmbed = message.embeds.find(embed => embed.title === 'Success'); if (targetEmbed) { // 捕获到目标Embed后的后续操作 await message.channel.send('已捕获到标题为"Success"的Embed,执行后续操作...'); } });
注意事项
- 务必在Discord开发者平台的「Privileged Gateway Intents」中开启
Message Content Intent,否则无法读取消息内容和Embed数据。 - 若使用Discord.js v13及以下版本,意图写法需替换为
Intents.FLAGS格式。
内容的提问来源于stack exchange,提问作者Brace Sproul
相关产品推荐
相关产品推荐

