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

Discord多功能机器人性别角色选择菜单报错:Callback需为协程

问题修复方案

错误根源

你给select类添加了@client.command()装饰器,这个装饰器仅用于注册异步命令函数,不能作用于类,直接触发了TypeError: Callback must be a coroutine.报错。

修复步骤

  1. 移除select类上方的@client.command()装饰器
  2. 让Role类继承commands.Cog,这是discord.py定义命令扩展的标准方式
  3. 在代码末尾将Role Cog添加到客户端实例中

修正后的完整代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 04:40:41