Reputation: 51
How do I make a bot in Discord.py that will assign roles present in a role.json
file, while using the same command to both remove and add the same role. For example, ?role <rolename>
will both add and remove a role, depending on if the user has the role assigned. I'm a bit confused on how to achieve this.
My current bot uses ?roleadd <rolename>
?roleremove <rolename>
.
Upvotes: 1
Views: 10919
Reputation: 11
This code basically just checks that if the command raiser is the owner of the server or not and then assigns the specified role to him.
@bot.command()
@commands.is_owner()
async def role(ctx, role:discord.Role):
"""Add a role to someone"""
user = ctx.message.mentions[0]
await user.add_roles(role)
await ctx.send(f"{user.name} has been assigned the role:{role.name}")
Let me break the code down:
@bot.command()
@commands.is_owner()
These are just plain function decorators. They are pretty much self-explanatory. But still let me tell.
@bot.command()
just defines that it is a command.
@commands.is_owner()
checks that the person who has raised that command is the owner.
async def role(ctx, role:discord.Role):
> This line defines the function.
user = ctx.message.mentions[0] #I don't know about this line.
await user.add_roles(role) #This line adds the roles to the user.
await ctx.send(f"{user.name} has been assigned the role:{role.name}")
#It just sends a kind of notification that the role has been assigned
Upvotes: 1
Reputation: 60984
I'm not sure where your role.json
file comes into play, but here's how I would implement such a command
@bot.command(name="role")
async def _role(ctx, role: discord.Role):
if role in ctx.author.roles:
await ctx.author.remove_roles(role)
else:
await ctx.author.add_roles(role)
This uses the Role
converter to automatically resolve the role
object from its name, id, or mention.
Upvotes: 1