discord.py的Cog中使用discord_buttons_plugin按钮事件报错如何解决
问题根源
@buttons.click 装饰器在Python解析类定义的阶段就会执行,而Cog的__init__方法是你后续实例化Cog对象时才会运行,这就导致装饰器执行时buttons变量还未定义,直接触发报错。
解决方案
方案1:全局实例化ButtonsClient(推荐)
直接在代码入口处实例化ButtonsClient,所有Cog都可以直接调用该实例:
import discord from discord.ext import commands from discord_buttons_plugin import ButtonsClient # 先实例化Bot对象 client = commands.Bot(command_prefix="自定义前缀") # 全局实例化ButtonsClient,所有Cog可直接调用 buttons = ButtonsClient(client) class UserCommands(discord.Cog): def __init__(self, client): self.client = client # 直接使用全局的buttons实例即可,参数填按钮对应的custom_id @buttons.click("你按钮对应的custom_id") async def btn(self, ctx): # 你的按钮响应逻辑 await ctx.reply("按钮触发成功") # 加载Cog client.add_cog(UserCommands(client)) client.run("你的Bot Token")
方案2:Cog内手动注册回调
如果你希望每个Cog单独管理自己的按钮实例,可以放弃装饰器写法,在__init__中手动绑定回调:
class UserCommands(discord.Cog): def __init__(self, client): self.client = client self.buttons = ButtonsClient(client) # 手动注册按钮回调,传入按钮对应的custom_id和回调函数 self.buttons.click("你按钮对应的custom_id")(self.btn) async def btn(self, ctx): # 你的按钮响应逻辑 await ctx.reply("按钮触发成功")
注意事项
- 按钮回调函数必须接收
ctx(按钮交互上下文)参数,否则会触发参数不匹配报错 - 发送带按钮的消息时,按钮设置的
custom_id必须和注册回调时使用的id完全一致,否则回调不会被触发
内容的提问来源于stack exchange,提问作者error 1044
相关产品推荐
相关产品推荐

