python - Discord.py 在游戏事件中发挥作用

标签 python python-3.x discord.py

我正在尝试制作一个机器人,它可以在有人玩游戏时发挥作用。 例如有人玩CSGO,机器人会在玩游戏时给他CSGO角色。 我似乎无法弄清楚。

@client.event
async def on_member_update(before, after):
    if after.activity != before.activity:
        role = discord.utils.get(after.guild.roles, name=after.activity)
        if role == None:
            await create_role(name=after.activity, hoist=True)
        await after.add_roles(role)
    elif before.activity != after.activity and not after.activity:
        role = discord.utils.get(after.guild.roles, name=after.activity)
        if role in after.roles: 
            await after.remove_roles(role)

最佳答案

您可以在 on_member_update 中查看成员(member)正在玩的游戏事件。为此,您需要检查 Member.activity参数。

它会是这样的:

@client.event
async def on_member_update(before, after):
    games = ["game1", "game2", "game3"]
    if after.activity and after.activity.name.lower() in games:
            # Assuming the role name is the same as the game
            role = discord.utils.get(after.guild.roles, name=after.activity)
            await after.add_roles(role)
    elif before.activity and before.activity.name.lower() in games and not after.activity:
            role = discord.utils.get(after.guild.roles, name=after.activity)
            if role in after.roles: 
                await after.remove_roles(role)

引用文献:

关于python - Discord.py 在游戏事件中发挥作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66186815/

相关文章:

python - 在 Python 中保留函数上下文

python - 从绘图屏幕上单击的两点画线,然后删除艺术家

python - 如何使用discord.py删除角色?

python - Discord 丰富的嵌入按钮

python - Pandas 在第二次之后从右到左拉出部分字符串。别的先。如果 2 不存在

python - 我可以使我的类可迭代,仅使用其可迭代属性之一吗?

python - 使用单元测试来衡量 Django 性能

python - 从 pandas 数据帧生成字典,其中多个列组合为键,其余列作为值?

python - 为什么我不能接受客户?

python - Discord.py Cog//如何发送消息到特定 channel