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

Discord.py Ban/Hackban命令报错:AttributeError: 'NoneType'无ban属性

解决Discord.py机器人Hackban功能的AttributeError问题

问题原因

报错AttributeError: 'NoneType' object has no attribute 'ban'是因为client.get_guild(1037550844935147622)返回了None,导致后续调用guild.ban()失败。常见触发原因:

  • 机器人并未加入ID为1037550844935147622的服务器
  • 机器人的intents未启用服务器缓存,无法获取有效服务器对象
  • 硬编码的服务器ID存在错误

解决方案

直接使用命令触发时的当前服务器对象ctx.guild替代硬编码的服务器ID查询,既避免ID错误问题,又能确保获取到有效服务器对象(命令本身就在该服务器内触发)。同时补充以下检查:

  1. 替换服务器对象获取逻辑:
    将guild = client.get_guild(1037550844935147622)改为guild = ctx.guild

  2. 确认机器人intents配置:
    初始化client时需启用guilds intents,示例代码:

    intents = discord.Intents.default()
    intents.guilds = True
    client = commands.Bot(command_prefix='你的前缀', intents=intents)
    
  3. 验证机器人权限:
    确保机器人在目标服务器内拥有Ban Members权限

修改后的完整代码

@client.command(description="Bans People!") # Bans people
@commands.has_any_role('Staff')
async def ban(ctx, x: typing.Union[discord.Member, int], *, reason=None):
    guild = ctx.guild
    if isinstance(x, discord.Member):
        await x.ban(reason=reason)
        await ctx.send(f'Banned {x.mention}')
    else:
        await guild.ban(discord.Object(id=x))
        await ctx.reply(f'User has been hackbanned!\nUser: <@{x}>')

(注:将x in ctx.guild.members替换为isinstance(x, discord.Member)更准确,因为discord.Member类型的对象必然是当前服务器成员)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 23:45:34