【问题标题】:Assign discord role when user reacts to message in certain channel当用户对某个频道中的消息做出反应时分配不和谐角色
【发布时间】:2021-01-04 23:18:44
【问题描述】:

我希望用户在我的欢迎和角色不和谐频道中选择某个反应时被分配一个角色。我到处寻找,在 python 中找不到适用于最新版本 discord.py 的代码。这是我目前所拥有的:

import discord

client = discord.Client()

TOKEN = os.getenv('METABOT_DISCORD_TOKEN')


@client.event
async def on_reaction_add(reaction, user):
    role_channel_id = '700895165665247325'
    if reaction.message.channel.id != role_channel_id:
        return
    if str(reaction.emoji) == "<:WarThunder:745425772944162907>":
        await client.add_roles(user, name='War Thunder')


print("Server Running")

client.run(TOKEN)

【问题讨论】:

  • 程序出了什么问题?添加反应时是否出现错误,或者代码没有执行任何操作?
  • 我没有收到任何错误代码,但是是的,代码根本没有做任何事情。

标签: python python-3.x discord discord.py


【解决方案1】:

使用on_raw_reaction_add 而不是on_reaction_add,因为on_reaction_add 仅在消息在机器人的缓存中时才有效,而on_raw_reaction_add 将无论内部消息缓存的状态如何都有效。

所有的 IDS、角色 ID、频道 ID、消息 ID...都是 INTEGER 而不是 STRING,这就是您的代码无法正常工作的原因,因为它将 INT 与 STR 进行比较。

另外还要获取角色,不能只传入角色的名字

下面是工作代码

@client.event
async def on_raw_reaction_add(payload):
    if payload.channel_id == 123131 and payload.message_id == 12121212: #channel and message IDs should be integer:
        if str(payload.emoji) == "<:WarThunder:745425772944162907>":
            role = discord.utils.get(payload.member.guild.roles, name='War Thunder')
            await payload.member.add_roles(role)

编辑:对于on_raw_reaction_remove

@client.event
async def on_raw_reaction_remove(payload):
    if payload.channel_id == 123131 and payload.message_id == 12121212: #channel and message IDs should be integer:
        if str(payload.emoji) == "<:WarThunder:745425772944162907>":
            #we can't use payload.member as its not a thing for on_raw_reaction_remove
            guild = bot.get_guild(payload.guild_id)
            member = guild.get_member(payload.user_id)
            role = discord.utils.get(guild.roles, name='War Thunder')
            await member.add_roles(role)

【讨论】:

  • 知道了。现在要在移除反应时移除角色,我不应该只需要使用 on_raw_reaction_remove 吗?然而这段代码不起作用:py async def on_raw_reaction_remove(payload): # channel and message IDs should be integer: if payload.channel_id == 700895165665247325 and payload.message_id == 756577133165543555: if str(payload.emoji) != "&lt;:WarThunder:745425772944162907&gt;": role = discord.utils.get(payload.member.guild.roles, name='War Thunder') await payload.member.remove_roles(role)
  • 删除我对消息的反应时收到此错误:line 25, in on_raw_reaction_remove guild = bot.get_guild(payload.guild_id) AttributeError: module 'discord.ext.commands.bot' has no attribute 'get_guild'
猜你喜欢
  • 2021-08-08
  • 1970-01-01
  • 2021-03-31
  • 2020-10-03
  • 1970-01-01
  • 2021-05-08
  • 2021-02-24
  • 1970-01-01
  • 2021-05-19
相关资源
最近更新 更多