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

如何获取Discord回复消息的目标消息ID?

Discord.js Pin命令:获取回复目标消息ID

原命令代码

import { SlashCommandBuilder } from 'discord.js';
import { client } from '../index.js';
import * as functions from '../functions/functions.js';
// Creates an Object in JSON with the data required by Discord's API to create a SlashCommand
const create = () => {
  const command = new SlashCommandBuilder()
    .setName('pin')
    .setDescription('przypnij wiadomość na którą odpowiadasz');

  return command.toJSON();
};
const invoke = async (interaction) => {
  try {
    const message = interaction;
    await message.pin();
    console.log(`Pinned message ID: ${message.id}`);
  } catch (error) {
    console.error('Error pinning message:', error);
  }
};
export { create, invoke };

问题说明

使用上述命令时,希望获取该命令所回复的目标消息的ID,需要类似普通消息message.reference的功能。

解决方案

在Discord.js v14+中,交互对象的interaction.message属性包含了消息引用信息,和普通消息的reference结构一致。你可以通过以下方式获取目标消息并执行pin操作:

  1. 从interaction.message.reference.messageId提取目标消息ID
  2. 通过频道的messages.fetch()方法获取完整的目标消息对象
  3. 对目标消息执行pin()操作

修改后的invoke函数示例:

const invoke = async (interaction) => {
  try {
    // 检查当前命令是否是回复某条消息发送的
    if (!interaction.message.reference) {
      return interaction.reply({ content: '请在回复某条消息时使用此命令!', ephemeral: true });
    }

    // 获取目标消息ID
    const targetMessageId = interaction.message.reference.messageId;
    // 从当前频道获取目标消息
    const targetMessage = await interaction.channel.messages.fetch(targetMessageId);
    
    // 执行pin操作
    await targetMessage.pin();
    console.log(`Pinned target message ID: ${targetMessageId}`);
    await interaction.reply({ content: `已成功置顶消息:https://discord.com/channels/${interaction.guildId}/${interaction.channelId}/${targetMessageId}`, ephemeral: true });
  } catch (error) {
    console.error('Error pinning message:', error);
    await interaction.reply({ content: '置顶消息失败,请检查权限或消息是否存在!', ephemeral: true });
  }
};

关键说明

  • interaction.message是发送这条交互命令的消息对象,它的reference属性包含了回复目标的信息
  • 必须先判断reference是否存在,避免用户直接发送命令而非回复消息时出错
  • 使用ephemeral: true可以让回复只对命令使用者可见,避免频道消息杂乱

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 23:01:08