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

discord.py批量封禁(Mass-Ban)命令已封禁用户计数错误问题

问题原因

你遇到的核心问题是对ctx.guild.bans()返回值的类型认知错误:

  • await ctx.guild.bans() 返回的是 discord.BanEntry 对象的可迭代序列,并非discord.User对象列表。每个BanEntry结构为:BanEntry(user=被封禁用户对象, reason=封禁原因)
  • 你直接判断x in banlist时,x是discord.User类型,和BanEntry类型永远无法匹配,因此该条件分支永远不会执行,failed自然不会累加。

此外代码还存在另外两个逻辑错误:

  • 当前如果检测到开发者在封禁目标列表中,会直接跳过所有其他目标的处理逻辑,不会执行后续循环
  • massban_error 回调中的failed += 1是无效代码,failed是massban函数内的局部变量,错误回调无法直接访问该变量
修复方案
@commands.command(aliases = ["multiban" , "mass-ban" , "multi-ban"])
@commands.bot_has_permissions(ban_members = True)
@commands.has_permissions(ban_members = True)
async def massban(self , ctx , targets: commands.Greedy[discord.User] , * , grund="Kein Grund angegeben"):
    with ctx.channel.typing():
        ban_entries = await ctx.guild.bans()
        # 提取所有已封禁的用户对象,方便后续匹配
        banned_users = [entry.user for entry in ban_entries]
        banned = 0
        days = 0
        tries = 0
        failed = 0
        developer = self.client.get_user(705557092802625576)
        
        for x in targets:
            tries += 1
            # 跳过开发者
            if x == developer:
                failed += 1
                continue
            # 检查是否已经被封禁
            if x in banned_users:
                failed += 1
                continue
            try:
                await ctx.guild.ban(x , reason = f"{grund}" , delete_message_days = days)
                banned += 1
            except Exception as e:
                failed += 1
                print(e)
        
        embed = discord.Embed(color = 0xff2200 , title = "Massban ausgeführt :tools:" ,
                            description = f"Es wurde versucht, **{tries}** Personen zu bannen. Ergebnisse: \n**{banned}** Nutzer wurde/n gebannt. \n**{failed}** Nutzer konnte/n nicht gebannt werden.")
        embed.set_footer(text = f"User-ID: {ctx.author.id}" , icon_url = f"{ctx.message.author.avatar_url}")
        embed.set_author(name = f"{ctx.author}" , icon_url = f"{ctx.message.author.avatar_url}")
        return await ctx.reply(embed = embed , mention_author = False)

@massban.error
async def massban_error(self , ctx , error):
    if isinstance(error , commands.MissingPermissions):
        await ctx.send(f"{ctx.author.mention} Berechtigungs-Fehler! [Gebrauchte Berechtigung: ban_members]")
    elif isinstance(error , commands.BotMissingPermissions):
        await ctx.send(f"{ctx.author.mention} Berechtigungs-Fehler! [Gebrauchte Berechtigung: ban_members]")
    elif isinstance(error , commands.UserNotFound):
        pass
    else:
        raise error
修复说明
  • 提前从封禁条目列表中提取所有已封禁用户对象存入banned_users,判断用户是否已封禁时直接匹配该列表
  • 调整开发者校验逻辑,放入循环内仅跳过开发者本身,不会影响其他目标的封禁处理
  • 移除了错误回调中无效的failed += 1代码
  • 删除了无意义的banned -=1逻辑,封禁失败直接累加failed即可,不需要反向减少banned计数

内容的提问来源于stack exchange,提问作者Itz-Toothless

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 14:36:03