繁体   English   中英

如何在 discord.py 中获取用户活动?

[英]How to get user activity in 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')

正如 Ceres 所说,您需要允许意图。 Go 到您的开发者页面https://discord.com/developers/applications和 go 到机器人。 向下滚动一点,你会看到: 打开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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM