discord.py 2.0.1 unban命令报错求助:无法转换用户为Member
问题分析与解决方案
错误的核心原因是你使用了discord.Member类型作为参数,但被封禁的用户已经不在当前服务器中,而discord.Member只能代表服务器内的活跃成员,因此Discord的转换器无法将输入的用户标识(如hello123#4650)转换为Member对象,触发了TransformerError。
修正方案1:改用discord.User类型
discord.User代表Discord平台上的用户,不管是否在当前服务器都能被识别,完全适配解封场景。修改代码如下:
@app_commands.command(name="unban", description="unbans specified member.") @app_commands.default_permissions(ban_members=True) async def unban(self, ctx, user: discord.User): await ctx.guild.unban(user) successembed = discord.Embed( title="Success", description=f"{user.mention} has been unbanned." ) await ctx.response.send_message(embed=successembed)
这个方案支持用户通过提及、输入用户ID或用户名+判别式来指定目标,转换器会自动处理为User对象。
修正方案2:支持多格式输入(用户名/ID/提及)
如果需要更灵活的输入方式,可以用字符串参数,遍历服务器封禁列表匹配目标:
@app_commands.command(name="unban", description="unbans specified member.") @app_commands.default_permissions(ban_members=True) async def unban(self, ctx, user_input: str): async for ban_entry in ctx.guild.bans(): user = ban_entry.user # 匹配用户名+判别式、用户ID、用户提及 match_conditions = [ f"{user.name}#{user.discriminator}" == user_input, str(user.id) == user_input, user.mention == user_input ] if any(match_conditions): await ctx.guild.unban(user) successembed = discord.Embed( title="Success", description=f"{user.mention} has been unbanned." ) await ctx.response.send_message(embed=successembed) return # 未找到匹配的封禁用户 error_embed = discord.Embed( title="Error", description="No banned user matched the input provided." ) await ctx.response.send_message(embed=error_embed, ephemeral=True)
这个方案会遍历服务器的封禁列表,找到匹配用户后执行解封,同时处理未找到的异常情况。
内容的提问来源于stack exchange,提问作者raion
相关产品推荐
相关产品推荐

