如何给Discord机器人发送的消息添加emoji表情反应
实现方案
你当前代码里的message是用户触发命令的原始消息,所以调用message.react是给用户的消息加反应。要给机器人发送的embed消息加反应,只需拿到机器人发送的消息实例再调用对应方法即可,修改后的代码如下:
else if(command === "guessage"){ // 发送消息后通过.then拿到机器人发送的消息对象 message.channel.send({ embed: { color: 16758465, title: "Are you...", description: Math.floor((Math.random() * 20) + 11) + " " + "years old?" } }).then(botMsg => { // 给机器人发的这条消息加表情 botMsg.react('👍').then(() => botMsg.react('👎')); const filter = (reaction, user) => { // 增加!user.bot过滤机器人自己加的表情触发 return ['👍', '👎'].includes(reaction.emoji.name) && user.id === message.author.id && !user.bot; }; // 监听用户给机器人这条消息的反应 botMsg.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] }) .then(collected => { const reaction = collected.first(); if (reaction.emoji.name === '👍') { message.reply('you reacted with a thumbs up.'); } else { message.reply('you reacted with a thumbs down.'); } }) .catch(collected => { message.reply('you reacted with neither a thumbs up, nor a thumbs down.'); }); }) }
如果你用的是async/await语法,写法更直观:
// 注意外层函数需要用async修饰,否则无法使用await else if(command === "guessage"){ const botMsg = await message.channel.send({ embed: { color: 16758465, title: "Are you...", description: Math.floor((Math.random() * 20) + 11) + " " + "years old?" } }); // 依次给机器人消息加表情 await botMsg.react('👍'); await botMsg.react('👎'); const filter = (reaction, user) => { return ['👍', '👎'].includes(reaction.emoji.name) && user.id === message.author.id && !user.bot; }; botMsg.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] }) .then(collected => { const reaction = collected.first(); if (reaction.emoji.name === '👍') { message.reply('you reacted with a thumbs up.'); } else { message.reply('you reacted with a thumbs down.'); } }) .catch(() => { message.reply('you reacted with neither a thumbs up, nor a thumbs down.'); }); }
注意事项
- 如果你的discord.js版本高于v14,发送embed的写法需要调整为
{ embeds: [你的embed对象] },否则会报错。 - filter里增加
!user.bot判断是为了避免机器人自己添加的表情被误识别为用户的反应。
内容的提问来源于stack exchange,提问作者user16344690
相关产品推荐
相关产品推荐

