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

Discord在线时长查询机器人报错:无法找到服务器成员问题排查

Discord机器人在线时长查询问题:找不到服务器成员

我制作了一个Discord机器人,输入>time_online命令后本应显示用户在线时长,但一直抛出“Could not find member polandlp on this server”错误,即便我处于在线状态且机器人拥有全部权限。测试后发现if member:分支并未生效。

import discord
from discord.ext import commands
from datetime import datetime


intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='>', intents=intents)

@bot.command()
async def time_online(ctx):
    user = ctx.author
    guild = ctx.guild

    # Pobierz informacje o stanie użytkownika
    member = guild.get_member(user.id)
    if member:
        if member.status != discord.Status.offline and member.activity is not None:
            # Oblicz czas online
            time_online = datetime.utcnow() - member.activity.start
            minutes_online = time_online.total_seconds() // 60
            await ctx.send(f'{user.name} is online for {minutes_online} minutes.')
        else:
            await ctx.send(f'{user.name} is offline or not currently active.')
    else:
        await ctx.send(f'Could not find member {user.name} on this server.')

@bot.command()
async def ping(ctx):
    await ctx.send('pong')
bot.run("my token")

问题原因

核心问题是未启用服务器成员意图(Members Intent):

  • Discord默认意图不包含成员数据访问权限,guild.get_member(user.id)无法获取到成员对象,返回None触发错误分支
  • 即使代码中配置了意图,还需要在Discord开发者平台手动开启该权限,否则代码配置不会生效

修复步骤

  1. 修改代码的Intents配置
    在原有intents设置中添加成员意图开启:

    intents = discord.Intents.default()
    intents.message_content = True
    intents.members = True  # 新增此行,启用成员意图
    
  2. 在Discord开发者平台开启权限

    • 打开Discord开发者应用页面,进入你的机器人项目
    • 切换到「Bot」标签页,找到「Privileged Gateway Intents」区域
    • 开启「Server Members Intent」并保存更改
  3. 代码简化优化
    服务器内执行命令时,ctx.author本身就是Member类型,无需再调用guild.get_member,可以直接使用:

    @bot.command()
    async def time_online(ctx):
        member = ctx.author
        if member.status != discord.Status.offline and member.activity is not None:
            time_online = datetime.utcnow() - member.activity.start
            minutes_online = time_online.total_seconds() // 60
            await ctx.send(f'{member.name} is online for {minutes_online} minutes.')
        else:
            await ctx.send(f'{member.name} is offline or not currently active.')
    

注意:member.activity.start仅针对有明确开始时间的活动(如游戏、流媒体)有效,如果用户只是在线但没有活动,member.activity会为None,仍会进入“离线或无活动”分支。若要统计单纯在线状态的时长,需要自行维护用户上线时间的缓存,因为Discord不提供用户从离线切换到在线的时间戳。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 04:27:02