Discord多功能机器人性别角色选择菜单报错:Callback需为协程
问题修复方案
错误根源
你给select类添加了@client.command()装饰器,这个装饰器仅用于注册异步命令函数,不能作用于类,直接触发了TypeError: Callback must be a coroutine.报错。
修复步骤
- 移除
select类上方的@client.command()装饰器 - 让
Role类继承commands.Cog,这是discord.py定义命令扩展的标准方式 - 在代码末尾将
RoleCog添加到客户端实例中
修正后的完整代码
import discord from discord.ext import commands import traceback import random import discordutils import asyncio # 初始化客户端示例(根据你的实际配置调整) intents = discord.Intents.default() intents.message_content = True client = commands.Bot(command_prefix="!", intents=intents) class Select(discord.ui.Select): def __init__(self): options=[ discord.SelectOption(label="Man"), discord.SelectOption(label="Woman"), discord.SelectOption(label="Gender-Fluyd"), discord.SelectOption(label="Non-Binary"), discord.SelectOption(label="Other"), ] super().__init__(placeholder="Gender", min_values=1, max_values=1, options=options) async def callback(self, interaction: discord.Interaction): user = interaction.user guild = interaction.guild selected_gender = self.values[0] # 简化重复逻辑,增加容错处理 role = discord.utils.get(guild.roles, name=selected_gender) if role: await user.add_roles(role) await interaction.response.send_message(f"Role {selected_gender} added!", ephemeral=True) else: await interaction.response.send_message(f"Role {selected_gender} not found on this server!", ephemeral=True) class SelectView(discord.ui.View): def __init__(self, *, timeout=30): super().__init__(timeout=timeout) self.add_item(Select()) class Role(commands.Cog): def __init__(self, client): self.client = client @commands.command() async def role(self, ctx): await ctx.send("What is your gender?", view=SelectView()) # 将Cog注册到客户端 client.add_cog(Role(client)) # 运行机器人(替换为你的Bot令牌) # client.run("YOUR_BOT_TOKEN")
关键修改说明
- 移除了
select类上错误的装饰器,该装饰器仅用于命令函数,与UI组件类无关 - 将
Role类改为继承commands.Cog,确保@commands.command()能正确注册命令 - 简化了
callback中的重复代码,添加了角色不存在的容错逻辑 - 类名改为大驼峰格式(
Select而非select),符合Python命名规范
内容的提问来源于stack exchange,提问作者Valentin Renaut
相关产品推荐
相关产品推荐

