Search code examples
pythondiscorddiscord.py

Ho To Get A Role Of A User discord python


I'm tying to add a command for specific users by role

I'm Trying This code

import os
import discord

intents = discord.Intents.all()
client = discord.Client(command_prefix='.',intents=intents)


@client.event
async def on_message(message):
    if message.author == client.user:
        return
    if message.content.startswith('.start') and 'Premium' in message.author.roles:
      await message.channel.send("Server Is Starting")
    else: 
      await message.channel.send("You need a MOD role to use this command")

client.run('my token')

when i wrote the command in discord i got (You need a MOD role to use this command)

and when i try to test if i have the role by adding (print(message.author.roles[1])) i got (Premium)


Solution

  • Working through this, step by step:

    Therefore, a fixed version of the code would be:

    import os
    import discord
    
    intents = discord.Intents.all()
    client = discord.Client(command_prefix='.',intents=intents)
    
    
    @client.event
    async def on_message(message):
        if message.author == client.user:
            return
        if message.content.startswith('.start') and any(role.name=='Premium' for role in message.author.roles):
          await message.channel.send("Server Is Starting")
        else: 
          await message.channel.send("You need a MOD role to use this command")
    
    client.run('my token')