简体   繁体   English

使用discord.py,如何向角色名称中包含空格的用户添加角色?

[英]Using discord.py, how can I add a role to a user that contains spaces in its name?

I have seen that you can add a role using a bot using discord.py. 我已经看到您可以使用使用discord.py的机器人添加角色。 I want to make my code so that you can add roles with multiple words as its name so you don't get errors like 'Role "Chief" not found' when the command was -giverole Chief Executive Officer. 我想编写代码,以便您可以添加名称中包含多个单词的角色,以便在命令为-giverole首席执行官时不会出现诸如“未找到角色“首席””的错误。 I also want to add another parameter in which you ping the user you want to give the role to. 我还想添加另一个参数,您可以在其中ping您要授予角色的用户。

This is for my discord server. 这是给我的不和谐服务器使用的。 I have got a working code that can give a role to you (whoever executes the command) and the role can only be one word: Eg 'Members' 我有一个可以给您(无论执行命令的人)角色的工作代码,并且该角色只能是一个词:例如,“成员”

@client.command(pass_context=True)
async def giverole(ctx, role: discord.Role):
    await client.add_roles(ctx.message.author, role)

Input: -giverole <mention_user> <role_name> (must be compatible to give a role that is multiple words) 输入: -giverole <mention_user> <role_name> (必须兼容以提供多个单词的角色)

Output: I can sort out a message that it sends. 输出:我可以整理出它发送的消息。

You can use a converter to get the Member to send the role to just like you use it to get the Role itself. 您可以使用转换器来使Member发送角色,就像使用它来获取Role本身一样。 To accept multiple-word roles, use the keyword-only argument syntax . 要接受多词角色,请使用仅关键字参数语法 You can also use role mentions when invoking the command. 您也可以在调用命令时使用角色提及。 (eg !giverole @Patrick @Chief Executive Officer ). (例如!giverole @Patrick @Chief Executive Officer )。

@client.command(pass_context=True)
async def giverole(ctx, member: discord.Member, *, role: discord.Role):
    await client.say(f"Giving the role {role.mention} to {member.mention}")
    await client.add_roles(member, role)

You can use discord.utils.get to get the role from a string, in this case role_name 您可以使用discord.utils.get从字符串中获取角色,在这种情况下为role_name

@client.command(pass_context=True)
async def giverole(ctx, *,role_name:str):
  role = discord.utils.get(ctx.message.server.roles, name=role_name)
  await client.add_roles(ctx.message.author, role)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM