繁体   English   中英

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 object 与User object 混淆。 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!')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM