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

Nextcord机器人在线成员统计显示0而非1的问题求助

问题原因及修复方案

核心问题1:未启用成员意图(Intents)

Discord API要求必须启用members意图才能获取服务器完整成员列表,否则guild.members只会返回机器人自身,导致统计结果为0。

修复步骤:

  1. 登录Discord开发者门户,进入你的机器人页面,开启Privileged Gateway Intents中的Server Members Intent。
  2. 在机器人初始化代码中添加意图配置:
import nextcord
from nextcord.ext import commands

intents = nextcord.Intents.default()
intents.members = True  # 启用成员意图

bot = commands.Bot(command_prefix="!", intents=intents)

核心问题2:循环任务启动方式错误

你用self.bot.loop.create_task(self.online_members())启动循环任务的方式不正确,tasks.loop装饰的任务需要调用.start()方法启动。

修复代码:

将__init__方法中的启动代码替换为:

def __init__(self, bot):
    self.bot = bot
    self.online_members.start()  # 正确启动循环任务

问题3:语法错误(count =+ 1)

count =+ 1是将count赋值为正1,而非累加计数,应改为count += 1。

优化后的完整代码

import nextcord
from nextcord.ext import tasks
from nextcord.ext import commands

class online_member(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.online_members.start()

    @tasks.loop(minutes=10)
    async def online_members(self):
        guild = self.bot.get_guild(1057394146601611334)
        if not guild:
            print("无法找到指定服务器")
            return
            
        count = 0
        for member in guild.members:
            if not member.bot and member.status != nextcord.Status.offline:
                count += 1
                
        kanal = self.bot.get_channel(1060686055055048798)
        if not kanal:
            print("无法找到指定频道")
            return
            
        await kanal.edit(name=f"Online Members: {count}")

def setup(bot):
    bot.add_cog(online_member(bot))

额外建议

  • 添加空值判断(如服务器/频道不存在时的提示),方便快速排查问题。
  • 状态判断可更明确:member.status in (nextcord.Status.online, nextcord.Status.idle, nextcord.Status.dnd),精准统计在线、闲置、请勿打扰状态的成员。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 00:30:43