Discord音乐机器人:UI按钮调用Cog中Slash Command函数报错
问题解决:Discord按钮调用Slash Command报错TypeError
错误原因
你通过@discord.app_commands.command装饰器定义的pause方法,已经被包装成了Command对象,而非普通的可调用函数。直接执行await musicCog.pause(interaction)相当于尝试调用这个Command对象,因此触发TypeError: 'Command' 对象不可调用的错误。
解决方案
你可以通过以下两种方式直接调用Slash Command的逻辑,无需抽离功能:
方法1:调用Command的原始回调方法
装饰器会将原始的pause方法保存在Command.callback属性中,直接调用这个属性对应的方法即可,注意要传入cog实例作为第一个参数(因为原始方法是类的实例方法):
@discord.ui.button(label="Pause", style=discord.ButtonStyle.success, emoji="⏸️") async def pause(self, interaction: discord.Interaction, button: discord.ui.Button): print("Pause button clicked") musicCog = self.bot.get_cog('AudioCommands') # 调用原始的pause方法 await musicCog.pause.callback(musicCog, interaction) await interaction.response.send_message("Paused the song!", ephemeral=True)
方法2:使用Command的invoke方法
直接调用Command对象的invoke方法,传入Interaction对象即可执行命令逻辑:
@discord.ui.button(label="Pause", style=discord.ButtonStyle.success, emoji="⏸️") async def pause(self, interaction: discord.Interaction, button: discord.ui.Button): print("Pause button clicked") musicCog = self.bot.get_cog('AudioCommands') # 调用Command的invoke方法执行命令 await musicCog.pause.invoke(interaction) await interaction.response.send_message("Paused the song!", ephemeral=True)
额外修正
注意你的按钮响应消息写的是"Skipped the song!",和暂停功能不符,建议改成"Paused the song!"。
内容的提问来源于stack exchange,提问作者Clayton
相关产品推荐
相关产品推荐

