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

使用discord.py为用户分配角色时遇MissingRequiredArgument错误求助

问题解决:discord.ext.commands.errors.MissingRequiredArgument

错误根源

你的join_ladder命令定义了role: discord.Role和user: discord.Member两个必填参数,但实际使用时你并没有传入这两个参数(从命令注释的!join_ladder能看出,你希望用户直接执行命令无需传参)。而且代码里已经通过role_name获取了目标角色,完全不需要把role作为命令参数。

此外还有两处小问题:

  • leave_ladder里的get_role方法需要传入整数类型的角色ID,你传了字符串会导致报错。
  • leave_ladder的else分支中,ctx.send没加await,消息不会实际发送出去。

修正后的代码

from discord.ext import commands
import discord
import methods

# Intents
intents = discord.Intents.default()
intents.message_content = True
intents.members = True

# 无需同时创建client和bot,保留bot即可
bot = commands.Bot(command_prefix='/', intents=intents)
TOKEN = 'active_token'

channel_name = 'ladder'
role_name = 'Ladder Participant'
LADDER_ROLE_ID = 1055287896376082463  # 把角色ID存为整数常量,方便维护


@bot.command()
async def join_ladder(ctx, user: discord.Member = None):
    """
    加入天梯的命令
    使用方式:/join_ladder(给自己加角色) 或 /join_ladder @用户名(给指定用户加角色)
    """
    # 未指定用户时,默认给执行命令的人加角色
    target_user = user or ctx.author
    if methods.check_ladder_active():
        role = discord.utils.get(target_user.guild.roles, name=role_name)
        if role:
            await target_user.add_roles(role)
            await ctx.send(f'{target_user.mention} 已加入天梯!')
        else:
            await ctx.send(f'服务器中未找到名为「{role_name}」的角色')
    else:
        await ctx.send('天梯当前未开启')


@bot.command()
async def leave_ladder(ctx, user: discord.Member = None):
    """
    退出天梯的命令
    使用方式:/leave_ladder(给自己删角色) 或 /leave_ladder @用户名(给指定用户删角色)
    """
    target_user = user or ctx.author
    if methods.check_ladder_active():
        role = ctx.guild.get_role(LADDER_ROLE_ID)
        if role:
            await target_user.remove_roles(role)
            await ctx.send(f'{target_user.mention} 已退出天梯!')
        else:
            await ctx.send('服务器中未找到目标角色')
    else:
        await ctx.send('天梯当前未开启')  # 补上await


# 启动机器人
bot.run(TOKEN)

核心修正点

  • 移除join_ladder中多余的role参数,代码内通过角色名自动获取目标角色,无需用户传入。
  • 将user设为可选参数,默认值为None,自动 fallback 到命令执行者ctx.author,兼顾给自己和他人操作的场景。
  • 把角色ID改为整数类型,修正get_role的参数类型错误。
  • 给leave_ladderelse分支的ctx.send补上await,确保消息发送成功。
  • 增加角色存在性检查,避免因角色不存在导致的运行时错误。
  • 删除多余的client = discord.Client(...),因为使用commands.Bot即可完成所有操作。

内容的提问来源于stack exchange,提问作者Zachariah Hansen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 00:45:30