discord.js如何为发送的MessageEmbed嵌入消息添加表情反应
实现方案
discord.js中频道发送消息的send()方法是异步方法,执行完成后会返回已发送的消息对象实例,你只需要拿到反馈频道里发送的Embed消息实例,调用实例上的react()方法即可添加表情反应,和你给触发命令的原消息加反应的逻辑完全一致。
具体改动点
- 给
collector.on("end")的回调函数添加async标记,支持内部使用await等待异步操作 - 给
appsChannel.send()前添加await关键字,等待Embed消息发送完成,拿到返回的反馈消息对象实例 - 对拿到的反馈消息对象依次调用
react('👍')、react('👎')添加目标表情 - 给所有
react()操作补充空错误捕获,避免机器人缺少频道添加反应权限、原消息被删除等场景抛出未处理的Promise错误,导致命令崩溃 - 顺手修正了原代码注释中
@parom的拼写错误,替换为JSDoc标准的@param标记
修改后完整代码
const { Client, Message, MessageEmbed, Intents } = require("discord.js"); module.exports = { name: "sbfeedback", /** * @param {Client} client * @param {Message} message * @param {String[]} args */ async execute(client, message, args) { const questions = [ "What feedback would you like to give?", "Anything else you would like to add?" ]; let collectCounter = 0; let endCounter = 0; const filter = (m) => m.author.id === message.author.id; const appStart = await message.author.send(questions[collectCounter++]); const channel = appStart.channel; const collector = channel.createMessageCollector(filter); message.delete({timeout: 100}) collector.on("collect", () => { if (collectCounter < questions.length) { channel.send(questions[collectCounter++]); } else { channel.send("Thank you for your feedback! If you would like to suggest anything else please do so with `-sbfeedback`."); collector.stop("fulfilled"); } }); const appsChannel = client.channels.cache.get("886099865094983691"); collector.on("end", async (collected, reason) =>{ if (reason === "fulfilled") { let index = 1; const mappedResponses = collected .map((msg) => { return `${index++}) ${questions[endCounter++]}\n-> ${msg.content}`; }) .join("\n\n"); // 拿到发送到反馈频道的Embed消息实例 const feedbackMsg = await appsChannel.send( new MessageEmbed() .setAuthor(message.author.tag, message.author.displayAvatarURL({ dynamic: true})) .setTitle("!") .setDescription(mappedResponses) .setColor(`RANDOM`) .setTimestamp() ); // 给原触发消息加反应 message.react('👍').then(() => message.react('👎')).catch(() => {}); // 给反馈频道的Embed消息加对应反应 feedbackMsg.react('👍').then(() => feedbackMsg.react('👎')).catch(() => {}); } }); }, };
内容的提问来源于stack exchange,提问作者Icebreaker
相关产品推荐
相关产品推荐

