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

求助:Discord机器人误判用户离线及获取用户失败问题

Discord机器人检测离线成员消息的问题解决

问题分析

尝试1的问题

message.author返回的是全局User对象,该对象不会记录用户在服务器内的在线状态,其status属性默认返回offline,导致误判所有用户为离线。同时你未开启必要的特权意图,无法获取服务器内成员的真实状态。

尝试2的问题

bot.get_user(user_id)同样获取的是全局User对象,既没有服务器内状态信息,还可能因为用户不在缓存中返回None,触发AttributeError。正确的做法是获取服务器内的GuildMember对象,它才存储用户在当前服务器的在线状态。

解决方案

要实现需求,需要完成两步操作:

  1. 在Discord开发者后台开启特权意图
  2. 代码中使用GuildMember对象获取状态,并处理缓存情况

步骤1:开启特权意图

进入Discord开发者门户,找到你的机器人应用,在Bot页面下拉到Privileged Gateway Intents,开启Presence Intent和Server Members Intent。

步骤2:正确代码实现

import discord
from discord.ext import commands

# 启用所需的所有意图
intents = discord.Intents.default()
intents.message_content = True
intents.members = True  # 允许获取服务器成员信息
intents.presences = True  # 允许获取成员在线状态

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


@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name}')


@bot.event
async def on_message(message):
    # 忽略机器人发送的消息
    if message.author.bot:
        return
    # 只处理服务器频道的消息,忽略私聊
    if not message.guild:
        return

    # 获取当前服务器内的成员对象(message.author在服务器频道中就是GuildMember类型)
    member = message.author
    # 若缓存中无该成员,可强制拉取最新信息(可选,频繁调用可能触发API限流)
    # member = await message.guild.fetch_member(message.author.id)

    # 检查成员是否处于离线状态
    if member.status == discord.Status.offline:
        await message.delete()
        await message.channel.send(f"{member.mention}, 离线状态下无法发送消息。")

    await bot.process_commands(message)


bot.run('你的机器人TOKEN')

额外注意事项

  • 确保机器人在目标服务器拥有Manage Messages(删除消息)和Send Messages(发送提示)权限。
  • 优先使用缓存中的message.author获取成员对象,避免频繁调用fetch_member触发API限流。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 02:26:04