使用discord.js开发Discord机器人时如何通过消息链接获取消息内容
实现方案
该需求完全可实现,核心逻辑为解析Discord消息链接的固定结构,提取对应ID后调用discord.js开放API拉取消息内容即可,具体操作如下:
前置原理
Discord消息链接的格式固定为:https://discord.com/channels/<公会ID>/<频道ID>/<消息ID>
仅需拆分链接提取三个ID参数,即可调用API定位到对应消息。
注意:机器人必须拥有目标消息所在频道的
VIEW_CHANNEL、READ_MESSAGE_HISTORY权限,且仅能拉取自身所在服务器内的消息,无法跨服拉取其他服务器内容。
完整代码实现
你可以直接替换你原有代码中的execute部分,参考实现如下:
async execute(message, args) { // 校验参数是否传入消息链接 if (!args.length) { return message.reply("请传入需要查询的Discord消息链接") } const msgLink = args[0] // 正则匹配提取链接中的三个ID const linkReg = /https?:\/\/(?:www\.)?discord(?:app)?\.com\/channels\/(\d+)\/(\d+)\/(\d+)/i const matchRes = msgLink.match(linkReg) if (!matchRes) { return message.reply("请传入有效的Discord消息链接") } const [, guildId, channelId, msgId] = matchRes try { // 拉取目标频道 const targetChannel = await message.client.channels.fetch(channelId) if (!targetChannel.viewable) { return message.reply("我没有权限访问该消息所在频道") } // 拉取目标消息 const targetMsg = await targetChannel.messages.fetch(msgId) // 构造返回Embed const embed = new Discord.MessageEmbed() .setAuthor({ name: targetMsg.author.tag, iconURL: targetMsg.author.displayAvatarURL() }) .setDescription(`**消息链接内容:**\n${targetMsg.content || "该消息无文本内容"}`) .setTimestamp(targetMsg.createdTimestamp) .setFooter({ text: `来自频道 #${targetChannel.name}` }) // 若消息存在图片附件,可直接展示 if (targetMsg.attachments.size > 0) { const firstImg = targetMsg.attachments.find(att => att.contentType?.startsWith("image/")) if (firstImg) embed.setImage(firstImg.url) } return message.reply({ embeds: [embed] }) } catch (err) { console.error(err) return message.reply("拉取消息失败,请确认链接有效且我拥有对应权限") } }
额外说明
- 如果需要支持拉取私信(DM)的消息,可单独判断匹配到的
guildId为@me的场景,调用用户对象的DM频道拉取消息即可 - 若需要展示消息的其他字段(比如回复引用、Embed内容等),可直接读取
targetMsg对象的对应属性拼接即可
内容的提问来源于stack exchange,提问作者JoonyWoony
相关产品推荐
相关产品推荐

