如何在禁止命令中使用“else:”? (不和谐.py)

时间:2021-02-03 01:14:40

标签: python discord.py

我正在发出禁令命令。
我希望我的禁止命令显示一条消息,说明该成员没有使用该命令的权限。
我试图做到,但我对“else:”知之甚少。有人能帮我吗?到目前为止,这是我的禁令命令:

@client.command()
@commands.has_permissions(ban_members=True)
async def ban(member : discord.Member, *, reason=None):
    await member.ban(reason=reason)
    await message.channel.send(f'Banned {member.mention}')
  else:
    await message.channel.send("You don't have permission to use this command.")

3 个答案:

答案 0 :(得分:3)

根据 Discord API,如果您没有权限,ban() 会引发异常 Forbidden

https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.ban

要捕获异常并对其进行处理而不是引发它,请使用 try/except

try:
    await member.ban(reason=reason)
    await message.channel.send(f'Banned {member.mention}')
except Forbidden:
    await message.channel.send("You don't have permission to use this command.")

答案 1 :(得分:2)

else 关键字一直用于计算机编程。

我认为了解 else 关键字如何工作的最佳方式是使用一些示例。

部分伪代码如下所示:

鲍勃的生日示例

if (today is Bob's birthday): 
   give Bob a cake
else:
   tell Bob, "NO CAKE FOR YOU!"

时间示例

if (hour < 18):
  greeting = "Good day"
else:
  greeting = "Good evening"

数字示例

if x < 100:
   print("X IS LESS THAN ONE-HUNDRED")
else:
   print("X IS GREATER THAN OR EQUAL TO ONE-HUNDRED")

答案 2 :(得分:1)

您可以使用命令的错误处理程序来执行此操作以及这样做的可取方式

@client.command()
@commands.has_permissions(ban_members=True)
async def ban(member : discord.Member, *, reason=None):
    await member.ban(reason=reason)
    await message.channel.send(f'Banned {member.mention}')

@ban.error
async def ban_error(ctx, error):
    if isinstance(error, commands.CheckFailure):
        await ctx.send("You don't have permission to use this command")
    else: raise(error)