我有一个用python编写的discord机器人,并且我正在尝试创建命令以将列入黑名单的消息(令人讨厌的事情)说出来。它应该给出错误消息,并由于某种原因而同时执行if和else语句。为什么会这样呢?我在做什么错了?
我尝试添加break
pass
,但仍然执行else语句
这是我当前的命令代码:
@client.command()
async def say(ctx, *, message):
if message == '@everyone':
await ctx.message.delete()
await ctx.send('Do not abuse this command')
if message == '@here':
await ctx.message.delete()
await ctx.send('Do not abuse this command')
for role in ctx.guild.roles:
if message == f'<@&{role.id}>':
await ctx.message.delete()
await ctx.send('Nice try but do not abuse this command')
else:
await ctx.send(message)
await ctx.message.delete()
print(f'{ctx.message.author} ({ctx.author.id}) in {ctx.guild.name} ({ctx.guild.id}) made me say: {message}')
答案 0 :(得分:0)
您的代码中有几个问题。第一个是在if
之后,代码不会离开函数,因此它将运行代码。
此外,else
关键字与for
循环相关,因此行为如下所示:
https://book.pythontips.com/en/latest/for_-_else.html。但基本上else
与上面的if
无关。
您想要实现的目标可能是这样的:
@client.command()
async def say(ctx, *, message):
if message == '@everyone':
await ctx.message.delete()
await ctx.send('Do not abuse this command')
elif message == '@here':
await ctx.message.delete()
await ctx.send('Do not abuse this command')
elif:
for role in ctx.guild.roles:
if message == f'<@&{role.id}>':
await ctx.message.delete()
await ctx.send('Nice try but do not abuse this command')
else:
await ctx.send(message)
await ctx.message.delete()
print(f'{ctx.message.author} ({ctx.author.id}) in {ctx.guild.name} ({ctx.guild.id}) made me say: {message}')