Discord机器人FAQ嵌入消息添加命令:如何获取已发送MessageEmbed的标题与描述?
如何获取Discord嵌入消息的标题和描述信息
嘿,我来帮你搞定这个问题!你现在的代码里试图用msg.content去读取嵌入消息的内容,但实际上Discord的嵌入消息并不存在于消息的普通content属性中——它们是存储在msg.embeds数组里的。这就是你觉得msg对象“拿不到正确内容”的核心原因。
正确的获取方式
要获取已发送嵌入消息的标题和描述,你需要从msg.embeds数组里取出对应的MessageEmbed对象:
- 先检查
msg.embeds数组是否有内容(避免空数组报错) - 取出数组的第一个元素(因为你要编辑的是那条唯一的嵌入消息)
- 然后通过该对象的
.title和.description属性获取对应的信息
修改后的完整代码
我帮你调整了代码,修复了获取嵌入内容的逻辑,同时把嵌套的then结构换成了更简洁易读的async/await:
if (message.member.hasPermission("MANAGE_SERVER")) { try { let m1 = await message.channel.send("What is the title of the FAQ?"); const filter = (m) => m.author.id === message.author.id; const collectedTitle = await message.channel.awaitMessages(filter, { max: 1, time: false }); const msg2 = collectedTitle.first(); if (msg2.content.toLowerCase() === `cancel`) { await m1.edit("Cancelled"); return; } await msg2.delete(); let m2 = await m1.edit("What do you want the description of the FAQ to be?"); const collectedDesc = await message.channel.awaitMessages(filter, { max: 1, time: false }); const msg3 = collectedDesc.first(); if (msg3.content.toLowerCase() === `cancel`) { await m2.edit("Cancelled"); return; } await msg3.delete(); const targetChannel = bot.channels.cache.get("804492953388974080"); if (!targetChannel) { await m2.edit("Target channel not found!"); return; } const msg = await targetChannel.messages.fetch("815234402098741259"); if (!msg) { await m2.edit("Target FAQ message not found!"); return; } // 检查目标消息是否包含嵌入 if (!msg.embeds.length) { await m2.edit("The target message doesn't have an embed!"); return; } const existingEmbed = msg.embeds[0]; // 构建新嵌入,保留原有内容并追加新FAQ条目 let newEmbed = new Discord.MessageEmbed() .setTitle(existingEmbed.title || "FAQ") // 保留原标题,无则用默认值 .setDescription(`${existingEmbed.description || ""}**${msg2.content}** = ${msg3.content}\n`) // 追加新条目 .setColor("BLUE"); await msg.edit(newEmbed); await m2.edit("Sent"); await message.delete(); } catch (error) { console.error("Error adding FAQ entry:", error); await message.channel.send("An error occurred while adding the FAQ entry."); } }
关键修改点说明
- 替换
msg.content为existingEmbed.description:现在会正确读取原有嵌入消息的描述内容,而非普通文本内容 - 添加空值检查:增加了对目标频道、目标消息、嵌入是否存在的检查,避免程序崩溃
- 改用
async/await简化嵌套:把原来多层嵌套的then改成顺序执行的代码,可读性和维护性大幅提升 - 保留原标题:如果原有嵌入有标题会自动继承,没有则使用默认的"FAQ"标题
这样修改后,你就能正确获取到已发送嵌入消息的标题和描述,顺利追加新的FAQ条目啦!
内容的提问来源于stack exchange,提问作者Sprocx
相关产品推荐
相关产品推荐

