PAYATHON 2026

如何从 slash command 获取上一条 Discord 消息并禁用按钮

数据小陈

结论

可以在 slash command 触发时禁用上一条消息上的按钮,但无法直接从 slash command interaction 里取得“上一条消息”对象。你需要自己保存消息引用(消息 ID、频道 ID、View),或者按条件检索频道历史再编辑那条消息。slash command 的 interaction.message 通常不存在;interaction.original_response() 拿到的是本次命令的响应消息,不是上一条。

原因

  • interaction.message 只有在按钮、下拉菜单等组件交互中才有,指向组件所在消息。
  • slash command 是新的交互,Discord 不会附带用户上一次交互或上一条 bot 消息的引用。
  • 要禁用旧消息上的按钮,需要用旧消息对象调用 edit(view=...)。旧消息对象必须通过消息 ID 获取,或通过历史消息检索得到。

推荐方案:保存消息 ID 和 View

具体做法是:每次发送带按钮的新消息后,把 (guild_id, user_id) 映射到 (channel_id, message_id, view)。下一次 slash command 或按钮回调先取旧记录,拿到旧消息并禁用其组件。下面示例基于 discord.py 2.x。

import discord
from typing import Optional

# key: (guild_id, user_id) -> (channel_id, message_id, view)
last_view_record: dict[tuple[Optional[int], int], tuple[int, int, discord.ui.View]] = {}

async def disable_previous(interaction: discord.Interaction):
    key = (interaction.guild_id, interaction.user.id)
    record = last_view_record.pop(key, None)
    if record is None:
        return

    channel_id, message_id, old_view = record
    channel = interaction.client.get_channel(channel_id)
    if channel is None:
        return

    try:
        old_message = await channel.fetch_message(message_id)
        for item in old_view.children:
            item.disabled = True
        await old_message.edit(view=old_view)
    except (discord.NotFound, discord.Forbidden, discord.HTTPException):
        # 消息被删、没权限或编辑失败时,清掉记录即可
        pass

在 slash command 中先禁用旧消息,再发送新消息并记录:

@tree.command(name='profile', description='Display your profile')
async def profile(interaction: discord.Interaction, user: discord.Member = None):
    await disable_previous(interaction)

    command_output = get_profile()
    view = ProfileView(interaction.user)
    await interaction.response.send_message(embed=command_output, view=view)
    message = await interaction.original_response()
    last_view_record[(interaction.guild_id, interaction.user.id)] = (
        message.channel.id,
        message.id,
        view,
    )

按钮回调里也按同样方式记录新消息。当前按钮所在消息可以直接用 interaction.message 禁用:

class AttackButton(discord.ui.Button):
    def __init__(self, author: discord.abc.User):
        super().__init__(label='Attack')
        self.author = author

    async def callback(self, interaction: discord.Interaction):
        old_view = self.view
        for item in old_view.children:
            item.disabled = True
        await interaction.message.edit(view=old_view)

        command_output = get_player_attack_message()
        new_view = AttackView(interaction.user)
        await interaction.response.send_message(embed=command_output, view=new_view)
        message = await interaction.original_response()
        last_view_record[(interaction.guild_id, interaction.user.id)] = (
            message.channel.id,
            message.id,
            new_view,
        )

对应的 View 建议设置 timeout=None,并保存 author:

class AttackView(discord.ui.View):
    def __init__(self, author: discord.Member):
        super().__init__(timeout=None)
        self.author = author
        self.add_item(AttackButton(author))

    async def interaction_check(self, interaction: discord.Interaction) -> bool:
        if interaction.user.id != self.author.id:
            await interaction.response.send_message(
                content='You do not have permission to use this',
                ephemeral=True,
            )
            return False
        return True

不保存记录时:检索频道历史

如果不想保存消息 ID,可以用 interaction.channel.history(limit=...) 往前找 bot 消息。但这条路径更脆弱:需要给消息加可识别标记,例如 embed footer、按钮 custom_id 前缀或数据库记录。还要处理 Read Message History 权限。没有明确标记时,很容易把别的 bot 消息或别的玩家的消息当成“上一条”,所以生产环境建议优先保存消息 ID。

注意事项

  • interaction.original_response() 不能用来取旧消息;它只代表当前这次 interaction 的响应。
  • 旧消息如果被删除、频道被删或 bot 没有读取/编辑权限,fetch_message 或 edit 会抛异常,需要捕获。
  • 如果你把按钮消息做成 ephemeral,普通 channel.fetch_message 通常拿不到它,后续编辑方式也不同;这种场景下不要依赖频道历史检索。
  • 内存字典在 bot 重启后会丢失。需要长期可靠时,把 channel_id、message_id 和恢复 View 所需的数据存入数据库。重启后如果不需要按钮继续可用,也可以直接把旧消息的 view 编辑为 None 清掉按钮。
  • 同一用户快速连点可能产生竞态,建议按用户 ID 加 asyncio.Lock,保证先禁用旧消息再发送新消息。
  • 编辑 bot 自己发送的消息通常不需要 Manage Messages,但需要能访问该频道并读取历史消息;用 fetch_message 时尤其要注意 Read Message History 权限。

备注:内容仅供参考。