Phong Yen Hou, Justin

A recently graduated Full Stack Developer 🖥️ eager to take on new challenges.

Title:

AutoRole Manager for Discord Servers

Overview

This is an automated Discord bot that allows members of our community to adjust their roles on the server by reacting to a specific message.

How Did I Make It?

First, I initialized the project by importing the required libraries and defining some key variables.

import discord
from discord.ext import commands

# Set up the Discord bot
DISCORD_TOKEN = # Your Discord bot token
APPLICATION_ID = # Your Discord application ID
GUILD_ID = # Your Discord server ID

intents = discord.Intents.all()
intents.message_content = True
bot = commands.Bot(command_prefix='.', intents=intents, application_id=APPLICATION_ID)

# Set up the target message for reactions and define the emoji-to-role mapping
MESSAGE_ID = # The target message ID
ROLES = {
    # 'Emoji name': 'Role name'
    'Dota2': 'Dota2',
    'Csgo': 'Csgo2'
}

After setting up all the required components, I began developing the function to detect when a user adds a reaction. This is done by defining async def on_raw_reaction_add.

@bot.event
# Triggered when a user adds a reaction to a message
async def on_raw_reaction_add(payload):
    # Check if the reaction was added to the target message
    if payload.message_id == MESSAGE_ID:
        guild = bot.get_guild(payload.guild_id)
        member = guild.get_member(payload.user_id)

        # Get the corresponding role based on the emoji name
        role = get_role_by_emoji(guild, payload.emoji.name)

        # Check if both the role and member were found
        if role and member:
            await member.add_roles(role)
            await member.send(f'You have been assigned the **{role.name}** role.')

Next, I created a function named async def on_raw_reaction_remove to detect when a user removes a reaction.

@bot.event
# Triggered when a user removes a reaction from a message
async def on_raw_reaction_remove(payload):
    # Check if the reaction was removed from the target message
    if payload.message_id == MESSAGE_ID:
        guild = bot.get_guild(payload.guild_id)
        member = guild.get_member(payload.user_id)

        # Get the corresponding role based on the emoji name
        role = get_role_by_emoji(guild, payload.emoji.name)

        # Check if both the role and member were found
        if role and member:
            await member.remove_roles(role)
            await member.send(f'You have been removed from the **{role.name}** role.')

Lastly, I defined a helper function to retrieve the corresponding role based on the emoji name:

def get_role_by_emoji(guild, emoji_name):
    return discord.utils.get(guild.roles, name=ROLES.get(emoji_name))

Hastag:

  • #Pyton
  • #Self-Learn
  • #Discord
  • #ConsoleApp