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

discord.py查询服务器在线成员数 报错guilds cannot be iterated如何解决

问题原因与修复方案

触发guilds cannot be iterated错误的核心原因

你直接遍历了ctx.guild对象本身,该对象不可迭代,要获取服务器成员列表需要遍历ctx.guild.members属性。
除了这个报错之外,你的代码还存在多处逻辑错误和语法错误,全部修复点如下:

  • 遍历对象修正为ctx.guild.members
  • 计数器累加写法错误:= +1是错误写法,仅会给变量赋值为1,不会累加,正确写法是+= 1
  • 全局计数器会导致多次调用命令时数值累加错误,需要将计数器定义移到命令函数内部
  • 变量名拼写错误:后续引用时写了不存在的coun1,正确变量名是count1
  • f-string语法错误:f标识需要放在引号外侧,不能放在引号内部
  • Discord.py v2.0及以上版本需要开启成员意图才能获取完整的成员列表,需要在开发者后台开启对应权限,同时初始化client时声明成员意图
  • 需要正确导入discord.Status类判断成员在线状态

修复后完整代码

# 初始化client时需要开启成员意图,示例如下:
import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.members = True # 开启成员意图
intents.presences = True # 开启状态感知意图,否则无法读取成员在线状态

client = commands.Bot(command_prefix='你设置的指令前缀', intents=intents)

@client.command()
async def stats(ctx):
    count_online = 0
    count_offline = 0
    # 遍历成员列表,而非ctx.guild本身
    for member in ctx.guild.members:
        if member.status == discord.Status.online:
            count_online += 1
        else:
            count_offline += 1
    embed = discord.Embed(title=f"{ctx.guild.name} Stats", color=0x000000)
    embed.add_field(name="总成员数", value=ctx.guild.member_count, inline=False)
    embed.add_field(name="在线人数", value=f"{count_online} :green_circle:", inline=True)
    embed.add_field(name="离线人数", value=f"{count_offline} :red_circle:", inline=True)
    await ctx.send(embed=embed)

额外注意事项

你需要先到Discord开发者后台,找到你的Bot应用,在「Privileged Gateway Intents」板块下开启Server Members Intent和Presence Intent两个权限,否则无法正常获取成员列表和成员状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 19:36:03