discord.py验证菜单开发遇TypeError:Client.event()缺coro参数
解决discord.py机器人的TypeError: Client.event() missing required argument错误
你的错误核心是类名和实例名冲突,同时错误地将类而非实例用于事件装饰器。具体来说:
- 你先创建了
bot = discord.Client(...)实例,又定义了class bot(discord.Client)类,导致后续的@bot.event实际是在操作bot类而非客户端实例。 Client.event作为类方法调用时需要传入协程参数,而你用装饰器的方式错误绑定到类上,从而抛出缺少coro参数的错误。
修正后的完整代码
import discord from discord import app_commands intents = discord.Intents.all() intents.message_content = True # 自定义客户端类,避免和实例名冲突 class MyBot(discord.Client): def __init__(self): super().__init__(intents=intents) # 使用配置好的intents,而非默认值 self.synced = False self.role_id = 1077196175133900932 # 存储角色ID,避免提前绑定角色对象 self.added = False self.tree = app_commands.CommandTree(self) # 将命令树绑定到自定义客户端实例 class ButtonView(discord.ui.View): def __init__(self): super().__init__(timeout=None) @discord.ui.button(label="Verify", style=discord.ButtonStyle.green, custom_id="Verify") async def verify(self, interaction: discord.Interaction, button: discord.ui.Button): role = interaction.guild.get_role(MyBot.role_id) if not role: await interaction.response.send_message("验证角色不存在!", ephemeral=True) return if role not in interaction.user.roles: await interaction.user.add_roles(role) await interaction.response.send_message(f"已为你添加 {role.mention} 角色!", ephemeral=True) else: await interaction.response.send_message(f"你已经拥有 {role.mention} 角色了!", ephemeral=True) # 创建自定义客户端实例 bot = MyBot() @bot.tree.command(guild=discord.Object(id=908141823288045568), name='button', description='启动验证按钮') async def button(interaction: discord.Interaction): await interaction.response.send_message(view=ButtonView()) @bot.event async def on_ready(self): await self.wait_until_ready() if not self.synced: await self.tree.sync(guild=discord.Object(id=908141823288045568)) # 同步服务器命令 self.synced = True if not self.added: self.add_view(ButtonView()) self.added = True await self.change_presence(activity=discord.Game(name="ValiantPS")) print(f"已登录为 {self.user}") # 运行机器人 bot.run('你的机器人Token')
关键修正点
- 重命名自定义客户端类为
MyBot,确保@bot.event绑定到客户端实例而非类。 - 将
CommandTree与自定义客户端实例绑定,统一管理命令和客户端状态。 on_ready方法中全部使用self调用客户端方法,避免混淆类和实例。- 按钮回调直接通过ID获取角色,逻辑更独立,避免依赖客户端属性。
- 添加命令同步逻辑,确保
/button命令能被服务器识别。
内容的提问来源于stack exchange,提问作者Absence
相关产品推荐
相关产品推荐

