Learn to Code via Tutorials on Repl.it!

← Back to all posts
How to Make A Discord Bot - Part 7 (Updated 2021)
FishballNooodle (211)

Today we will be doing something very interesting, requested by @polarbear2015mw (0), I will be teaching you all over how to assign roles and also how to auto role. Lastly, we will be going over how to create join messages.

Assigning, Creating & Removing Roles

Creating Roles

Firstly, we need to know that we can actually create a role ourselves, so this is pretty useless...but I'll still go through it, it's really easy.
We will be using the add_roles of the guild object which we can get by using ctx.
guild.add_roles(name, reason,colour,hoist,mentionable,reason)
So this is how the code will look like:

@client.command()
async def create_role(ctx,name,*,reason=None):
  role = await ctx.guild.create_role(name=name,colour=discord.Colour.orange(),hoist=True,mentionable=True,reason=reason)
  await ctx.send(f'{ctx.guild.owner.mention}, {ctx.author} has made the role {role.mention}'

As you can see, there was a lot of arguments being passed over there.
I will explain each of them:

  • name - name of the role
  • colour - colour of the role
  • hoist - This is a boolean, if True it will be shown separately from other members
  • mentionable - if True, the role will light up blue when you do @rolename
  • reason - reason for making role(Shows in Audit Log), as you can see in the def command, it is by default None, so it's optional. Also, note that it has the * which make reason a keyword argument

    Note that the name in the input cannot have spaces because reason is already taken as the keyword argument for this function.
    If you don't want this, you can remove the reason argument totally(It's not really useful) and replace it with the name as the keyword.

Removing Roles to a member

First, we need to get the member object, so similar to the last tutorial, we will be accepting a member as a member object, like this. member:discord.Member and the role object similarly role:discord.Role.We will also need the reason for the removal.
The code should look like this:

@client.command()
async def remove_role(ctx,role:discord.Role,member:discord.Member,*,reason=None):
  await member.remove_roles(reason=reason)
  await ctx.send(f'{ctx.author.mention}, has removed the role {role.name} from {member.mention}'

The command should be typed like this:

By the way, if I didn't explain what .mention does, it pings the relevant user or role. And. name prints the string form so it doesn't ping the other people in the role unnecessarily.

Adding Roles From a Member

This is almost exactly the same as the one above so i'm not gonna explain.
Here's the code:

@client.command()
async def **add**_role(ctx,role:discord.Role,member:discord.Member,*,reason=None):
  await member.**add**_roles(reason=reason)
  await ctx.send(f'{ctx.author.mention}, has **added** the role {role.name} from {member.mention}'

Auto Role

So now what, you don't want to add role manually, you want them to add automatically, probably by a command. I will be using the command |gamer to give the person the role called 'gamer'.
How we will do this is we will not actually be taking in any other arguments other than ctx and the reason.
We will get the role using id, see my discord tutorial on Developer Mode to learn how to get the role id.
Next, we will use member.add_roles method where it will take in the role and reason.
Lastly, we will be doing a quick check to see if he has the role before we add the role to him. If he already has the role it will return an error message.

Note that the role has already been created.

Here's How the Code looks like:
@client.command()
async def gamer(ctx,*,reason):
member = ctx.author
role = client.get_role(2476234827364)
#put your own role id here
if role in member.roles:
await member.add_roles(role,reason=reason)
await ctx.send(f'You have been given the role {role.name}")
else:
await ctx.send("You already have that role")

Join & Leave Messages (Upon Request)

We will be using @client.event this time since no command will be needed to activate it and also a built-in client method is discord.on_member_join and discord.on_member_remove (kick or ban). It needs 1 argument which is member, which you can take it fro
So there's really not much explanation for this one.

Note: I would prefer if you put this function just after on_ready()

@client.event
async def on_member_join(member):
  #This can be set to a specific channel, for example a 'Welcome'
  channel = client.get_channel(8263541721827)
  #This should be your own channel id
  await channel.send(f"Welcome {member.mention} to our server, hope you will like it here.")
#Leave function is same
@client.event
async def on_member_remove(member):
  channel = client.get_channel(8263541721827)
  #This should be your own channel id
  await channel.send(f"Bye {member.mention} !!!")

By now, you would have noticed a pattern.
ctx, keyword arguments(*), client.event, methods, classes and you would probably know to understand the async await type by now. You can now call yourself a pro at discord.py. For that, I would like to give you something very valuable...
The Legendary Discord.PY Handbook
It's really just the module documentation, it consists of almost all data you want to access and how to do so. With that let me do my outro.

This ends my 7-day discord.py series. Hope you all enjoyed it, thanks for the constant support over the past few tutorials. You can still post your questions under this post if you have any in the future.
Stay Safe and Happy Coding!!!
:)

Comments
hotnewtop
slavstic (0)

This command does not do anything when a member joins. It doesn't even show any error in the console.

@client.event
async def on_member_join(member):
  channel = client.get_channel(490042165926428672)
  await channel.send(f"Welcome {member.mention} to our server, hope you will like it here.")
FishballNooodle (211)

@slavstic did you put this event before on_ready?
Else I need to see the entire code

slavstic (0)

@FishballNooodle It's pretty much at the end

import discord
from discord.ext import commands
import os
import B


client = discord.Client()
client = commands.Bot(command_prefix=':')
client.remove_command('help')

@client.event
async def on_ready():
    activity = discord.Game(name=":help  for commands")
    await client.change_presence(status=discord.Status.online, activity=activity)
    print ('bot is ready')
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_member_join(member):
  channel = client.get_channel(490042165926428672)
  await channel.send(f"Welcome {member.mention} to our server, hope you will like it here.")

@client.command()
async def help(ctx):
  print (f'{ctx.author.mention} has used help')#console log
  ##embed begins##
  embedVar = discord.Embed(title="Help", description="Studio Bot is not fully functional", color=0x00ff00)
  embedVar.add_field(name="nothing", value="it's useless", inline=False)
  embedVar.add_field(name="That's it", value="nothing more", inline=False)
  await ctx.channel.send(embed=embedVar)

@client.command()
async def add_role(ctx,role:discord.Role,member:discord.Member,reason=None):
  await member.add_roles(reason=reason)
  await ctx.send(f'{ctx.author.mention}, has **added** the role {role.name} from {member.mention}')


@client.command()
async def ping(ctx):
  await ctx.send(ctx.message.author.mention)

B.b()
client.run(os.getenv('TOKEN'))
FishballNooodle (211)

@slavstic
I don't see any problem with the code.
What was the permission code you gave when u invited it.

GMC1000 (0)

Umm I have been trying my own codes and others but none of them seems to work, Even This One I Might Need Some Help Here please..

FishballNooodle (211)

@GMC1000 invite me to your reply if u need my help

AnakinSteve (0)

@FishballNooodle can you pls help my bot send welcome messages?

AriFlopped (0)

Can you list the whole page of coding so we can understand better? I tried the code but it doesn’t work.

FishballNooodle (211)

@Ari7621
What U mean list whole page of coding

AriFlopped (0)

show all the coding in one page
@FishballNooodle

polarbear2015mw (0)

Thank you so much but how would I make it so the command would add a specific role every time its used

FishballNooodle (211)

@polarbear2015mw
so you want them to do something like...
|add_role (role name)

FishballNooodle (211)

@FishballNooodle
This can be dangerous if you let them add any role they want.
They could even add the moderator role upon them self :o
Ok its possible, just go to the role settings and make those roles you don't want them to get unmentionable.
Then you can do this code:

@client.command
async def add_role(ctx,role:discord.Role,*,reason=None):
  await ctx.member.add_roles(role,reason=reason)
  await ctx.send(f'{role.name} given to {ctx.author.mention}')

Upvote this if it worked

polarbear2015mw (0)

@FishballNooodle
No, what I'm asking is if I do like |verify <@user> it would add a role to a user

FishballNooodle (211)

@polarbear2015mw
so U are the admin right?
Didn't I explain under the 2 part, bruh

FishballNooodle (211)

@FishballNooodle
instead of putting role:discord.role
U just get the role obj by ... role=client.get_role(RoleID)
await member.add_roles(role,reason=reason)