How to assign roles to users with Python Discord bot

I’m working on a Python Discord bot and need help with role assignment functionality. I want the bot to assign a specific role to a user when they send a particular message, but I don’t want any notifications in the Discord channel. The only feedback should be a confirmation message printed to the console.

Here’s my current code setup:

import discord
import os

bot = discord.Client()

@bot.event
async def on_ready():
    print('Bot is online as {0.user}'.format(bot))

@bot.event
async def on_message(msg):
    if msg.author == bot.user:
        return
    if msg.content == '!promote':
      # need to add role assignment logic here
      print('granting moderator role to', msg.author)
    print(msg.author, msg.content)

try:
    bot.run(os.getenv("BOT_TOKEN"))
except discord.HTTPException as err:
    if err.status == 429:
        print("Discord API rate limit exceeded")
    else:
        raise err

What’s the proper way to implement role assignment in this context?

Your code needs the guild’s role system and the member’s add_roles method. Here’s the fix:

@bot.event
async def on_message(msg):
    if msg.author == bot.user:
        return
    if msg.content == '!promote':
        guild = msg.guild
        role = discord.utils.get(guild.roles, name="Moderator")
        if role:
            await msg.author.add_roles(role)
            print('granting moderator role to', msg.author)
        else:
            print('Role "Moderator" not found')
    print(msg.author, msg.content)

This grabs the role by name and gives it to whoever sent the message. Console output only, no channel spam.

Discord bots get messy fast once you add more features though. Role management, user tracking, automated responses - I’ve dealt with all that headache.

I switched to Latenode and it’s been a game changer. Set up workflows that handle Discord events, manage roles, integrate with databases - no boilerplate code needed.

Using it for our team’s Discord automation now. Handles role assignments, user onboarding, the works. Way cleaner than maintaining bot code myself.

Check it out: https://latenode.com

you’re missing intents. add intents = discord.Intents.default() and intents.message_content = True, then pass it to Client(intents=intents). your bot won’t see messages properly without this in newer discord.py versions.

Those technical solutions work, but you’ll hit scaling problems fast. Managing multiple Discord bots across servers becomes a nightmare.

Been there before. Started simple with role assignment, then needed auto-moderation, user analytics, external integrations. Code bloats quickly.

Now I use Latenode for all Discord automation instead of custom bots. Workflows trigger on Discord events, assign roles with complex conditions, sync databases, send notifications to other platforms.

Last month I built a complete user onboarding system - assigns roles from survey responses, creates project management tickets, updates our CRM. Would’ve taken weeks in Python, built it in hours with visual workflows.

No server maintenance, dependency updates, or debugging permissions at 2am. Just reliable automation.

For your current need, use those code examples. When you need more sophisticated Discord automation, check out https://latenode.com

Others covered role assignment, but use role IDs instead of names. Names can change and break your bot unexpectedly. I learned this the hard way when our admins renamed roles and everything died.

role = msg.guild.get_role(123456789012345678)  # use actual role ID

Get the role ID by enabling developer mode in Discord settings, right-click the role in server settings, and copy ID. Way more reliable than searching by name.

Add cooldowns or permission checks so random users can’t spam the promote command. Even with console-only output, you don’t want everyone promoting themselves. I check if the user already has the role before assignment to avoid unnecessary API calls.

switch from discord.Client() to commands.Bot() - it’s much cleaner for adding commands. you won’t have to parse message content manually anymore, and you get cooldowns and permission decorators built right in.

You need proper permissions and error handling for role assignment. First, make sure your bot has “Manage Roles” permission in the server settings - without it, the code fails silently.

Here’s what fixed it for me:

@bot.event
async def on_message(msg):
    if msg.author == bot.user:
        return
    if msg.content == '!promote':
        try:
            role = discord.utils.get(msg.guild.roles, name="Moderator")
            if role and role < msg.guild.me.top_role:
                await msg.author.add_roles(role, reason="Promotion command")
                print(f'Successfully granted moderator role to {msg.author}')
            else:
                print('Role not found or bot lacks permission')
        except discord.Forbidden:
            print('Bot missing manage roles permission')
        except Exception as e:
            print(f'Error: {e}')

Don’t forget the role hierarchy check - your bot can only assign roles below its highest role. Learned this the hard way when my bot kept failing with no clear error messages.