【问题标题】:Give and remove roles with a bot, Discord.py使用机器人 Discord.py 授予和删除角色
【发布时间】:2019-01-22 07:07:15
【问题描述】:

如何在 Discord.py 中创建一个机器人,该机器人将分配 role.json 文件中的角色,同时使用相同的命令来删除和添加相同的角色。例如,?role <rolename> 将添加和删除角色,具体取决于用户是否分配了角色。我对如何实现这一点有点困惑。

我当前的机器人使用?roleadd <rolename> ?roleremove <rolename>

【问题讨论】:

  • 如果你已经有角色添加/删除逻辑,唯一缺少的部分是检查用户是否有角色:if discord.utils.get(ctx.message.author.roles, name=rolename): removerole; else: addrole
  • 当前机器人在 JDA 中,我可以尝试手动转换它,也许然后添加该字符串。

标签: python discord discord.py discord.py-rewrite


【解决方案1】:

这段代码基本上只是检查命令发起者是否是服务器的所有者,然后将指定的角色分配给他。

@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

【讨论】:

  • 请为您的回答提供一些背景信息,而不仅仅是发布代码。为什么这能回答这个问题?
【解决方案2】:

我不确定你的 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 对象。

【讨论】:

  • 谢谢,roles.json 只是机器人获准分配的角色数组。
  • @UnaTripolla 获得role 后,您可以对照json 的内容检查role.namerole.id,以确定机器人是否可以分配角色。
猜你喜欢
  • 2021-09-17
  • 1970-01-01
  • 2020-12-13
  • 2021-08-07
  • 2020-04-09
  • 2019-04-20
  • 1970-01-01
  • 2019-06-01
  • 2021-04-12
相关资源
最近更新 更多