'How to make a person be given a role, discord.py?
For example, a person mentions the role of @role1 and the bot gives him this role. How to do it?
Solution 1:[1]
For the rewrite branch:
role = discord.utils.get(ctx.guild.roles, name="role to add name")
user = ctx.message.author
await user.add_roles(role)
For the async branch:
user = ctx.message.author
role = discord.utils.get(user.server.roles, name="role to add name")
await client.add_roles(user, role)
Solution 2:[2]
I think this is a good solution. Just make it so it requires a role, or a role mention.
We basically make a command where it requires two arguments: a role, and a mentioned member. You can configure this to make it so only administrators can run this command. If the Role doesn't exist, it will send a "This is not a correct role" message. Let me know if you face any issues!
from discord.ext import commands
from discord.utils import get
import discord
intents = discord.Intents.all()
client = commands.Bot(command_prefix = '!', intents=intents, case_intensitive=True)
@client.event
async def on_ready():
print('Bot is online!')
@client.command()
async def addrole(ctx, user: discord.Member, role: discord.Role):
try:
await user.add_roles(role)
await ctx.send(f'{user.mention} was given the role: {role.name}')
except commands.BadArgument:
await ctx.send('That is not a correct role!')
client.run('TOKEN')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
