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

discord.py中实现按钮触发/pause命令的技术咨询

解决Discord按钮触发/pause命令的问题

你之前用await interaction.send('/pause')的方式是错误的——这只是发送了一条含命令文本的消息,并不会让机器人实际执行该命令。正确的做法是复用命令逻辑或直接调用命令处理函数,以下是两种可行方案:

方案1:抽离通用逻辑(推荐)

把/pause命令的核心逻辑抽成独立函数,让命令和按钮共用,避免重复代码:

  1. 定义通用暂停逻辑函数:
async def handle_pause(interaction: discord.Interaction):
    voice_client = interaction.guild.voice_client
    if voice_client and voice_client.is_playing():
        voice_client.pause()
        await interaction.response.send_message('已暂停播放', ephemeral=True)
    else:
        await interaction.response.send_message('当前没有正在播放的内容', ephemeral=True)
  1. 让/pause命令调用该函数:
@bot.tree.command(name="pause", description="暂停媒体播放")
async def pause_command(interaction: discord.Interaction):
    await handle_pause(interaction)
  1. 按钮的try块中调用该函数:
@discord.ui.button(emoji = "<:pause:1136251002215989248>", style = discord.ButtonStyle.secondary, custom_id = 'pauseplay')
async def pauseplay_button(self, interaction: discord.Interaction, button: discord.ui.Button):
    try: 
        await handle_pause(interaction)
    except: 
        await interaction.response.send_message('Ошибка', ephemeral = True)

方案2:直接调用已注册的命令

如果不想抽离函数,可以直接获取并调用已注册的/pause命令:

@discord.ui.button(emoji = "<:pause:1136251002215989248>", style = discord.ButtonStyle.secondary, custom_id = 'pauseplay')
async def pauseplay_button(self, interaction: discord.Interaction, button: discord.ui.Button):
    try: 
        # 获取pause命令
        pause_command = interaction.client.tree.get_command("pause")
        if pause_command:
            await pause_command(interaction)
        else:
            await interaction.response.send_message("未找到pause命令", ephemeral=True)
    except: 
        await interaction.response.send_message('Ошибка', ephemeral = True)

注意事项

  • 必须确保交互得到响应:无论是通用函数还是命令中,都要通过interaction.response.send_message()等方法回应交互,避免出现"交互超时"错误。
  • 如果/pause命令需要额外参数,调用时要对应传入参数(方案1中只需在通用函数里处理参数即可)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 16:45:12