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

如何用discord.py检测Discord用户正在玩的游戏?代码问题排查

解决discord.py检测Discord用户游戏活动的问题

问题分析

两段代码的核心问题:

  • 第一段代码错误使用User对象调用activities:User是全局用户实例,不包含服务器内的活动状态,只有Member(服务器成员)对象才有activities属性,因此触发AttributeError。
  • 第二段代码仅检测discord.Game类型:Discord目前将绝大多数游戏活动归类为discord.Activity类型(通过activity.type区分),旧的Game类仅适用于少数情况,导致无法识别当前游戏。

修复后的代码

@bot.command()
async def user_activity(ctx, user_id: int):
    try:
        # 获取服务器内的成员对象(仅能检测同服务器用户)
        member = await ctx.guild.fetch_member(user_id)
        # 遍历所有活动状态
        for activity in member.activities:
            # 匹配"正在玩游戏"类型的活动
            if activity.type == discord.ActivityType.playing:
                await ctx.send(f"{member.name} spielt {activity.name}")
                return
        await ctx.send(f"{member.name} hat keine Spielaktivität.")
    except discord.NotFound:
        await ctx.send("Benutzer nicht gefunden. Stelle sicher, dass der Benutzer auf diesem Server ist.")
    except ValueError:
        await ctx.send("Bitte gib eine gültige Benutzer-ID ein (Zahl).")

关键配置与注意事项

  • 启用必要的机器人意图:在Discord开发者门户的机器人设置中,开启Presence Intent和Server Members Intent,并在代码初始化时启用:
    intents = discord.Intents.default()
    intents.presences = True
    intents.members = True
    
    bot = commands.Bot(command_prefix="你的前缀", intents=intents)
    
  • 活动类型扩展:除了ActivityType.playing(玩游戏),还可检测其他类型:
    • ActivityType.streaming:用户正在直播
    • ActivityType.listening:用户正在听歌(如Spotify)
  • 范围限制:仅能检测与机器人在同一服务器内的用户活动,无法获取跨服务器用户的状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 11:52:24