discord.py |如何检查用户是否具有特殊角色?

时间:2020-10-26 17:35:44

标签: python-3.x discord.py

我希望所有具有“通知”角色的用户都能收到DM。但是我想使用@ client.event做到这一点,但这给我带来了很多问题。

例如,这是语音支持。消息“ 1”在语音通道中播放文件。如果有人需要支持者的帮助,则所有支持者都应收到直接消息。问题是您不能将ctx用于client.event。

@client.event
async def on_message(message):
    if message.content.startswith('1'):
        print('Hi')
        role = 'notify'
        msg = 'Hello World!'
        members = [m for m in '''What do I must put in here?''' if discord.guild.User in m.roles]
        for m in members:
            try:
                await m.send(msg)
                print(f":white_check_mark: Message sent to {m}")
            except:
                print(f":x: No DM could be sent to {m}")
                return
    else:
        print('Error')

1 个答案:

答案 0 :(得分:1)

您应该使用discord.utils.getguild.get_role()client.get_guild()获得行会和角色。之后,您可以遍历成员的角色并检查他们是否具有该角色,如果有,则可以发送消息。

@client.event
async def on_message(message):
    if message.content.startswith('1'):
        print('Hi')
        guild = client.get_guild(guild id)
        role = guild.get_role(role id)
        msg = 'Hello World!'
        members = [member for member in guild.members if role in member.roles]
        for m in members:
            try:
                await m.send(msg)
                print(f":white_check_mark: Message sent to {m}")
            except:
                print(f":x: No DM could be sent to {m}")
                return
    else:
        print('Error')

但是此代码的效率很低,因为每次有人发送消息时,您都要遍历所有成员。因此,您应该在代码中添加on_ready事件,并在其中创建members列表。

@client.event
async def on_ready():
    global members
    guild = client.get_guild(guild id)
    role = guild.get_role(role id)
    members = [member for member in guild.members if role in member.roles]

on_ready事件仅运行一次,因此,如果您在运行漫游器后向某人添加特定角色,它将不会向该成员发送dm。因此,您还需要创建一个任务循环以每120秒或更长时间检查一次(如果您确定不会将该角色赋予其他任何人,则无需创建任务)。

@tasks.loop(seconds=120)
async def check_role():
    global members
    guild = client.get_guild(guild id)
    role = guild.get_role(role id)
    members = [member for member in guild.members if role in member.roles]
check_role.start()

因此,最后,您的代码应如下所示:

@client.event
async def on_ready():
    global members
    guild = client.get_guild(guild id)
    role = guild.get_role(role id)
    members = [member for member in guild.members if role in member.roles]

@tasks.loop(seconds=120)
async def check_role():
    global members
    guild = client.get_guild(guild id)
    role = guild.get_role(role id)
    members = [member for member in guild.members if role in member.roles]

@client.event
async def on_message(message):
    if message.content.startswith('1'):
        print('Hi')
        for m in members:
            try:
                await m.send(msg)
                print(f":white_check_mark: Message sent to {m}")
            except:
                print(f":x: No DM could be sent to {m}")
                return
    else:
        print('Error')

我也不确定,但是您可以尝试使用AuditLogs。我不知道如何很好地使用它,但是您可以检查API参考audit log data