如何使用Discord.py获取指定ID用户的在线状态?
问题分析与修复方案
你的代码存在几个关键问题导致无法正常运行:
on_message函数参数错误:Discord.py 的on_message仅接受message一个参数,额外添加的member参数会导致事件无法触发。- 未定义
MyID变量:需要明确指定目标用户的整数ID。 - 逻辑触发方式错误:当前代码试图在消息事件中判断成员,但这不是检测在线状态的正确方式。
- 缺少必要的意图权限:要获取用户在线状态,必须开启
presences意图。
方案一:使用命令主动查询用户在线状态
这是最直观的方式,通过发送命令来获取目标用户的当前状态:
import discord from discord.ext import commands TOKEN = "你的机器人令牌" TARGET_USER_ID = 123456789012345678 # 替换为目标用户的整数ID intents = discord.Intents.default() intents.message_content = True # 允许读取消息内容 intents.members = True # 允许获取服务器成员列表 intents.presences = True # 必须开启此意图才能读取用户在线状态 client = commands.Bot(command_prefix=".", intents=intents) @client.event async def on_ready(): print(f"机器人已成功登录:{client.user}") @client.command(name="check_online") async def check_user_status(ctx): member = ctx.guild.get_member(TARGET_USER_ID) if not member: await ctx.send("目标用户不在当前服务器中") return # 映射状态到中文描述 status_text = { discord.Status.online: "在线", discord.Status.idle: "闲置", discord.Status.dnd: "请勿打扰", discord.Status.offline: "离线" } current_status = status_text.get(member.status, "未知状态") await ctx.send(f"用户 <@{TARGET_USER_ID}> 当前状态:{current_status}") print(f"用户 {TARGET_USER_ID} 状态:{current_status}") client.run(TOKEN)
方案二:监听用户状态变化自动通知
如果需要实时监控目标用户的状态变化,可以使用 on_presence_update 事件:
import discord from discord.ext import commands TOKEN = "你的机器人令牌" TARGET_USER_ID = 123456789012345678 intents = discord.Intents.default() intents.members = True intents.presences = True client = commands.Bot(command_prefix=".", intents=intents) @client.event async def on_ready(): print(f"机器人已成功登录:{client.user}") @client.event async def on_presence_update(before, after): # 只关注目标用户的状态变化 if after.id != TARGET_USER_ID: return if before.status == after.status: return # 状态未变化则忽略 status_text = { discord.Status.online: "在线", discord.Status.idle: "闲置", discord.Status.dnd: "请勿打扰", discord.Status.offline: "离线" } new_status = status_text.get(after.status, "未知状态") print(f"用户 {TARGET_USER_ID} 状态变更为:{new_status}") # 可选:将通知发送到指定频道 # channel = client.get_channel(123456789012345678) # 替换为目标频道ID # await channel.send(f"用户 <@{TARGET_USER_ID}> 的状态变为:{new_status}") client.run(TOKEN)
重要注意事项
- 必须在Discord开发者后台中,为你的机器人开启 Presence Intent 和 Server Members Intent,否则无法获取成员状态和信息。
TARGET_USER_ID必须是整数类型,不能是字符串或用户提及标签。- 确保你的机器人令牌
TOKEN正确且未泄露。
内容的提问来源于stack exchange,提问作者autofarkind
相关产品推荐
相关产品推荐

