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

Discord.py编写unban命令触发'str'无mention属性错误原因查询

错误原因

  1. unban函数的member参数未指定discord.py的类型转换器,默认会将用户输入的内容解析为普通字符串,字符串不存在mention属性,调用member.mention时直接抛出AttributeError。
  2. 额外存在两处逻辑错误:
    • embed创建时机错误,未匹配到真实的被封禁用户对象就提前创建embed,即使参数类型正确也无法正常拿到提及信息
    • 私信发送与return语句缩进错误,会导致循环第一次遍历封禁列表时,无论是否匹配到目标用户,都会直接执行私信逻辑并退出函数,完全不符合预期
    • 原代码中await member.send同样会因为member是字符串类型,没有send方法触发同类报错

修复方案

你可以选择保留手动匹配用户名+识别码的逻辑,调整执行顺序,使用匹配到的真实user对象调用属性和方法即可,修复后的参考代码如下:

@client.command()
async def unban(ctx, *, member):
    banned_users = await ctx.guild.bans()
    # 拆分输入的用户名和识别码,处理格式错误情况
    try:
        member_name, member_discriminator = member.split('#')
    except ValueError:
        await ctx.send("输入格式错误,请使用「用户名#识别码」的格式,例如:张三#1234")
        return
    guild = ctx.guild

    for ban_entry in banned_users:
        user = ban_entry.user
        # 匹配到目标被封禁用户
        if (user.name, user.discriminator) == (member_name, member_discriminator):
            await ctx.guild.unban(user)
            # 使用匹配到的真实user对象生成embed、发送私信
            embed = discord.Embed(title="解封通知", description=f"{user.mention} 已被解封", colour=discord.Colour.red())
            await ctx.send(embed=embed)
            try:
                await user.send(f"你已被解除在 **{guild.name}** 的封禁")
            except discord.Forbidden:
                # 处理用户关闭了私信权限的情况
                await ctx.send(f"无法向 {user.mention} 发送解封私信,用户已关闭陌生人私信权限")
            return
    # 遍历完所有封禁名单未找到目标用户的提示
    await ctx.send(f"未在封禁列表中找到用户 `{member}`")

如果想要更简单的实现,可以直接使用discord.py内置的类型转换器,不需要手动拆分用户名和识别码,参数修改为member: discord.User即可,框架会自动帮你解析为用户对象,只需额外添加参数错误的处理逻辑即可。

内容的提问来源于stack exchange,提问作者VΣrtex_

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 23:24:03