首页 > 解决方案 > 如何在 discord.py 中获取用户活动?

问题描述

我正在尝试制作一个机器人,它将用户正在玩的内容写入聊天,但即使游戏正在运行,也不会一直显示

我究竟做错了什么?

工作代码:

from discord.ext import tasks
import discord

intents = discord.Intents.all()
intents.presences = True


class MyClient(discord.Client):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    async def on_ready(self):
        print('Logged in as')
        print(self.user.name)
        print(self.user.id)
        print('------')

    @tasks.loop(seconds=5)
    async def activity_task(self, message):
        mentions = message.mentions
        if len(mentions) == 0:
            await message.reply("Remember to give someone to get status!")
        else:
            activ = mentions[0].activity
            if activ is None:
                await message.reply("None")
            else:
                await message.reply(activ.name)

    @activity_task.before_loop
    async def before_my_task(self):
        await self.wait_until_ready()

    async def on_message(self, message):
        if message.content.startswith('!status'):
            self.activity_task.start(message)


client = MyClient(intents=intents)
client.run('token')

标签: pythonpython-3.xdiscorddiscord.py

解决方案


正如 Ceres 所说,您需要允许意图。转到您的开发者页面https://discord.com/developers/applications,然后转到机器人。向下滚动一点,您会看到: 打开presence and server members intent.

现在,在您的代码中,您必须在开头添加以下内容:

intents = discord.Intents.all()

将您的机器人启动代码更改为此

client = MyClient(intents=intents)

现在,有了意图,您需要 OTHER 人的活动。因此,在该activity_task方法中,您不能使用message.author,因为这将返回发送消息的人,而不是您提到的人。

将其更改为:

async def activity_task(self, message):
        mentions = message.mentions
        if len(mentions) == 0:
            await message.reply("Remember to give someone to get status!")
        else:
            activ = mentions[0].activity
            if activ == None:
                await messag.reply("None")
            else:    
                await message.reply(activ.name)

现在,如果你这样做!status @[valid ping here],它应该返回他们正在做的任何事情。必须注意:它必须是有效的 ping。


推荐阅读