1
votes

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>.

2
If you already have the role adding/removing logic, the only part missing is the check to see if the user has the role or not: if discord.utils.get(ctx.message.author.roles, name=rolename): removerole; else: addrole - Patrick Haugh
The current bot is in JDA, I could try converting it manually maybe then add that string. - Una Tripolla

2 Answers

1
votes

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.

1
votes

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