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

使用discord.py开发解封命令时遇AttributeError错误求助

Discord.py Slash命令Unban功能报错排查与解决

报错信息

discord.app_commands.errors.CommandInvokeError: Command 'unban' raised an exception: AttributeError: 'str' object has no attribute 'id'

当前使用的Unban命令代码

@bot.tree.command(name="unban",description="Unban a member from the server.")
@app_commands.checks.has_permissions(ban_members=True)
@app_commands.describe(member = "The member you want to unban.")
async def unban(interaction: discord.Interaction, *, member: discord.User):
    await interaction.guild.unban(member)
    emb = discord.Embed(title=f"User Unbanned", description=f"{member.mention} has been unbanned.")
    await interaction.channel.send(embed=emb)
    dm = await bot.create_dm(member)
    emb = discord.Embed(title="",description=f"You have been unbanned from {interaction.guild.name}.")
    await dm.send(embed=emb)

尝试过的操作与困惑

  • 曾把member参数设为字符串,触发其他错误
  • 尝试遍历封禁用户列表时失败:因使用Slash命令无ctx,interaction.guild.bans()(加await后仍报错)无法正常获取列表
  • 运行命令时输入的是用户ID,按之前认知discord.User应自动将ID转为对象,但用discord.Member输入ID会触发转换失败,对此存在困惑

问题根源与解决步骤

1. 错误原因

输入用户ID时,discord.py的自动转换未正确将字符串ID转为discord.User对象,导致传入的仍是字符串,调用member.id时触发AttributeError。另外,discord.Member仅适用于服务器内存在的成员,被封禁用户已不在服务器,所以无法转换为Member对象,这就是用discord.Member会失败的核心原因。

2. 修复后的命令代码

@bot.tree.command(name="unban",description="解封服务器成员")
@app_commands.checks.has_permissions(ban_members=True)
@app_commands.describe(member_id = "需要解封的用户ID")
async def unban(interaction: discord.Interaction, member_id: str):
    try:
        # 手动转换ID为整数并获取用户对象
        user = await bot.fetch_user(int(member_id))
        await interaction.guild.unban(user)
        
        # 发送服务器通知
        emb = discord.Embed(title="用户已解封", description=f"{user.mention} 已被成功解封")
        await interaction.response.send_message(embed=emb)
        
        # 尝试发送DM通知(忽略用户关闭DM的情况)
        try:
            dm_emb = discord.Embed(description=f"你已从 {interaction.guild.name} 服务器解封")
            await user.send(embed=dm_emb)
        except discord.Forbidden:
            pass
    except ValueError:
        await interaction.response.send_message("请输入有效的用户ID", ephemeral=True)
    except discord.NotFound:
        await interaction.response.send_message("未找到该用户", ephemeral=True)
    except discord.Forbidden:
        await interaction.response.send_message("我没有解封该用户的权限", ephemeral=True)

3. 关键说明

  • 用member_id: str接收输入,手动转换为整数后调用bot.fetch_user()获取用户对象,避免自动转换失败的问题
  • 被封禁用户不在服务器内,必须用discord.User类型,不能用discord.Member
  • 使用interaction.response.send_message()替代interaction.channel.send(),这是Slash命令的标准响应方式,ephemeral=True可让消息仅命令执行者可见
  • 增加异常处理,覆盖无效ID、用户不存在、权限不足等场景,提升命令稳定性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 05:05:11