Give and remove roles with a bot, Discord.py

元气小坏坏 提交于 2020-06-01 05:53:10

问题


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


回答1:


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.




回答2:


import discord
from discord.ext import commands

@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.nick or user.name} a été promu au rang de {role.name}")```


来源:https://stackoverflow.com/questions/51858123/give-and-remove-roles-with-a-bot-discord-py

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!