簡體   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