python - 如何在 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 所说,您需要允许意图。转到您的开发者页面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。
推荐阅读
- python - 如何识别每个 id 的不完整详细信息?
- javascript - leetcode 加热器问题的二进制搜索算法
- ios - Swift:EKEventEditViewController 中没有显示日历和错误消息(没有崩溃)
- python - Python/Bloomberg API - 动态安全屏幕
- python - 用于 Visual Studio 的类似 Jupyter 的 Markdown
- c - 评估文件的权限位
- arrays - JSX 呈现一个字母初始按钮,其中包含一组以相同字母开头的按钮
- node.js - Parse Json 在字段中返回 - 字符
- typescript - 为什么我无法打开带有打字稿伪造链接的文件对话框
- reactjs - 转换路由(页面)时状态重置