问题
In my discord bot, I have 2 commands do give and create roles. They work perfectly fine, but if the role name includes a space, I have an issue. It counts the second word toward the second argument, making the command produce an error.
# Giverole
@client.command(name='giverole',
aliases=['gr'],
brief='Assgins role to a user',
pass_ctx=True)
async def giverole(ctx, rname, *, member: discord.Member):
role = get(member.guild.roles, name=rname)
await member.add_roles(role)
await ctx.send(f'Role added to user {member.mention}')
print('Giverole command executed\n- - -')
# Createrole
@client.command(name='createrole',
brief='Creates a role',
aliases=['cr','makerole'],
pass_ctx=True)
async def createrole(ctx, rname: str, clr: discord.Colour):
if ctx.author.guild_permissions.manage_roles:
await ctx.guild.create_role(name=rname, colour=clr)
await ctx.send('Role created with name: ' + rname)
print('Createrole command executed\n- - -')
else:
await ctx.send('You lack permission.')
print('Createrole command executed\n- - -')
Ideally, I should be able to do something like k!giverole Bot Tester @user
, but instead I get an "Invalid user" error. Is there any way for me to support spaces in the role name? Thanks in advance!
回答1:
You have a few options:
Use a role converter and require the role to be mentioned:
async def giverole(ctx, role: discord.Role, member: discord.Member):
Require the role to be wrapped in quotes:
k!giverole "Bot Tester" @user
Switch the positions of the two arguments so that the converted user comes first, and the potentially spaced name comes as the keyword-only argument.
async def giverole(ctx, member: discord.Member, *, rname):
I would recommend the first option, but you may want to try the others as well to see which one you prefer.
来源:https://stackoverflow.com/questions/56006198/is-there-a-way-to-include-spaces-in-my-argument