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

如何在不使用bot的情况下用Python获取Discord成员在线状态

前置风险提示

Discord官方服务条款明确禁止使用普通用户账号运行自动化程序访问API(即Self Bot),该行为会导致账号被永久封禁,以下内容仅做技术原理说明,请严格遵守平台规则使用。

导入部分替换内容

你需要导入discord客户端、权限配置和状态枚举类,同时因为discord.py是异步框架,需要引入asyncio做异步调度,替换后的导入语句为:

from discord import Client, Intents, Status
import asyncio

注意:你原有代码的同步轮询结构不适配discord.py的异步运行逻辑,原有time.sleep也要替换为异步等待

在线状态获取部分替换内容

首先你需要提前获取目标好友的用户ID:在Discord客户端开启「开发者模式」后,右键好友头像即可复制数字ID,假设你获取到的ID为123456789(替换为你实际的好友ID)。
完整调整后的可运行代码如下,已覆盖你提到的两个占位符逻辑:

from discord import Client, Intents, Status
import asyncio

# 配置权限,必须开启状态获取权限
intents = Intents.default()
intents.presences = True
intents.members = True

client = Client(intents=intents)
# 替换为你目标好友的用户ID
TARGET_FRIEND_ID = 123456789
is_friend_online = False

@client.event
async def on_ready():
    global is_friend_online
    print(f"已登录为 {client.user}")
    # 启动状态轮询任务
    client.loop.create_task(check_friend_status())

async def check_friend_status():
    global is_friend_online
    while True:
        # 获取目标用户对象
        friend = client.get_user(TARGET_FRIEND_ID)
        if not friend:
            # 未获取到用户信息时等待下次轮询
            await asyncio.sleep(1)
            continue
        # 判定是否在线 对应你原有代码的状态获取占位符
        new_status = friend.status == Status.online
        if new_status != is_friend_online:
            if new_status:
                print("Friend is online now")
            else:
                print("Friend is offline now")
            is_friend_online = new_status
        # 异步等待1秒,避免请求频率过高
        await asyncio.sleep(1)

# 替换为你的账号Token
client.run("YOUR_TOKEN_HERE")

补充说明

  • 如果使用官方合规Bot账户运行,需要将Bot添加到和目标用户同属的服务器,且在Discord开发者后台的Bot设置页开启Presence Intent和Server Members Intent权限。
  • 用户Token属于敏感信息,泄露会导致账号被盗,请勿分享给他人。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 12:36:07