Discord.py如何从DM查看某个服务器中有哪些角色的用户?

Discord.py How do I check which roles has a user in a certain Server from DM?

我需要可以检测用户在直接消息中的角色的机器人。我可以通过服务器聊天来完成,但我也需要通过直接消息来完成。 我当前的代码简化了:

import discord

client = discord.Client()

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

role1 = 'ROLE_ID'

@client.event
async def on_message(message):
    #only user with role1 is able to send the command
    if message.content.lower().startswith('can I?'):
        for r in message.author.roles:
            if str(r.id) in role1:
                await message.channel.send('Yes you can!')
                return

    #everyone is able to send the command $hello
    if message.content.startswith('Hello'):
        await message.channel.send('Hi!')

    
client.run('TOKEN')```



不要将 Member 对象与 User 对象混淆。 User 没有作用,因为它与 Member 的服务器无关。 您可以做的是将该用户的成员带到所需的服务器:

import discord

client = discord.Client()

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

role1_id = 000000000000000000000
guild1_id = 000000000000000000000

@client.event
async def on_message(message):
    if message.content.lower().startswith('can I?'):
        if message.guild:
            member = ctx.author
        else:  # private message
            guild = client.get_guild(guild1_id)
            member = await guild.fetch_member(ctx.author.id)
        #  only user with role1 is able to send the command
        for r in member.roles:
            if r.id == role1_id:
                await message.channel.send('Yes you can!')
                return

    #everyone is able to send the command $hello
    if message.content.startswith('Hello'):
        await message.channel.send('Hi!')