问题
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