You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord.js获取置顶消息内容 解决fetchPinned返回undefined问题

问题原因

interaction.channel.messages.fetchPinned() 返回值不是单条消息对象,是discord.js封装的Collection结构(基于Map扩展的集合类),存储了当前频道下所有的置顶消息,直接对集合对象调用.content必然返回undefined。你需要先从集合中取出具体的单条Message实例,才能访问消息内容属性。

实现示例

以下示例适配discord.js v14版本,需在async函数环境中执行:

  • 获取最新置顶的单条消息内容
const pinnedCollection = await interaction.channel.messages.fetchPinned();
// first()取集合第一条,也就是最新被置顶的消息
const latestPinnedMsg = pinnedCollection.first();

if (latestPinnedMsg) {
  // 取出单条消息后再访问content
  console.log('最新置顶消息内容:', latestPinnedMsg.content);
}
  • 遍历获取所有置顶消息的内容
const pinnedCollection = await interaction.channel.messages.fetchPinned();

pinnedCollection.forEach((singleMsg) => {
  console.log(`消息ID:${singleMsg.id},发送者:${singleMsg.author.username},内容:${singleMsg.content}`);
});
  • 获取指定ID的置顶消息内容
const pinnedCollection = await interaction.channel.messages.fetchPinned();
// 传入目标消息ID即可从集合中取到对应消息
const targetMsg = pinnedCollection.get('目标消息的ID字符串');

if (targetMsg) {
  console.log('指定置顶消息内容:', targetMsg.content);
}
注意事项
  • 如果频道没有任何置顶消息,first()、get()方法会返回null,直接访问.content会抛出报错,一定要做空值判断
  • 如果置顶消息是Embed卡片类型,content字段为空,需要从singleMsg.embeds数组中提取卡片内容
  • 不要对返回的Collection直接访问Message实例才有的属性,所有消息相关的属性都要在取出单条消息后再调用

内容的提问来源于stack exchange,提问作者101

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 04:30:51