使用机器人授予和删除角色,Discord.py
Give and remove roles with a bot, Discord.py
我如何在 Discord.py 中创建一个机器人来分配 role.json
文件中存在的角色,同时使用相同的命令删除和添加相同的角色。例如,?role <rolename>
将同时添加和删除角色,具体取决于用户是否分配了角色。我对如何实现这个有点困惑。
我当前的机器人使用 ?roleadd <rolename>
?roleremove <rolename>
.
我不确定你的 role.json
文件在哪里发挥作用,但我将如何执行这样的命令
@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)
这使用 Role
converter 从名称、ID 或提及中自动解析 role
对象。
这段代码基本上只是检查命令发起者是否是服务器的所有者,然后将指定的角色分配给他。
@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}")
让我分解一下代码:
@bot.command()
@commands.is_owner()
这些只是普通的函数装饰器。它们几乎是不言自明的。但还是让我说吧。
@bot.command()
只是定义它是一个命令。
@commands.is_owner()
检查发出该命令的人是否为所有者。
async def role(ctx, role:discord.Role):
> 这一行定义函数。
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
我如何在 Discord.py 中创建一个机器人来分配 role.json
文件中存在的角色,同时使用相同的命令删除和添加相同的角色。例如,?role <rolename>
将同时添加和删除角色,具体取决于用户是否分配了角色。我对如何实现这个有点困惑。
我当前的机器人使用 ?roleadd <rolename>
?roleremove <rolename>
.
我不确定你的 role.json
文件在哪里发挥作用,但我将如何执行这样的命令
@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)
这使用 Role
converter 从名称、ID 或提及中自动解析 role
对象。
这段代码基本上只是检查命令发起者是否是服务器的所有者,然后将指定的角色分配给他。
@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}")
让我分解一下代码:
@bot.command()
@commands.is_owner()
这些只是普通的函数装饰器。它们几乎是不言自明的。但还是让我说吧。
@bot.command()
只是定义它是一个命令。
@commands.is_owner()
检查发出该命令的人是否为所有者。
async def role(ctx, role:discord.Role):
> 这一行定义函数。
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