繁体   English   中英

Discord.py bot同时响应2个if语句

[英]Discord.py bot responds to 2 if statements at the same time

我正在为我的 discord.py 机器人的音乐模块编写离开命令。 当机器人不在 VC 中时,我希望机器人在有人使用>leave时说出一条消息。 我试图在下面写出来,但是每当机器人在 VC 中并且我键入>leave时,它都会在下面显示两条消息,但是当机器人不在 VC 中时不会发生这种情况。 我根本没有收到任何错误。 我的问题是,我怎样才能让我的机器人说:“我什至不在 VC 中,你这个怪人。” 当有人使用>leave时,只有当机器人不是 VC 时?

@bot.command()
async def leave(ctx):

  voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)

  if voice.is_connected():
    await voice.disconnect()
    await ctx.send("I have left the VC.")

  if not voice.is_connected():
    await ctx.send("I'm not even in a VC you weirdo.")

问题是当await voice.disconnect()执行时, voice.is_connected()会 output false,因为 bot 确实与你之前的命令断开连接,所以第一个 if 语句下面的 if 语句将被执行。 有两种方法可以修复它,一种推荐的方法是使用elif ,另一种方法是切换 if 语句:

elif

@bot.command()
async def leave(ctx):

  voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)

  if voice.is_connected():
    await voice.disconnect()
    await ctx.send("I have left the VC.")

  elif not voice.is_connected():
    await ctx.send("I'm not even in a VC you weirdo.")

切换示例

@bot.command()
async def leave(ctx):

  voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)

  if not voice.is_connected():
    await ctx.send("I'm not even in a VC you weirdo.")

  if voice.is_connected():
    await voice.disconnect()
    await ctx.send("I have left the VC.")

正如 knosmos 在评论中指出的那样,您也可以只使用 else 语句:

@bot.command()
async def leave(ctx):

  voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)

  if voice.is_connected():
    await voice.disconnect()
    await ctx.send("I have left the VC.")
  else:
    await ctx.send("I'm not even in a VC you weirdo.")

您还可以使用else语句而不是elif来使代码更简洁:

@bot.command()
async def leave(ctx):

  voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)

  if voice.is_connected():
    await voice.disconnect()
    await ctx.send("I have left the VC.")

  else:
    await ctx.send("I'm not even in a VC you weirdo.")

许多人已经在之前的答案中解释了要做什么。 我下面的代码应该可以帮助您更好地理解您当前的逻辑。

x = True
if x:
    print('True')
    x = False
if not x:
    print('False')

首先,我们将 x 设置为 True。 然后我们检查 x 是否为真。 如果是这样,我们可以打印它,并将 x 设置为 false。 最后,我们将检查 x 是否为假,并且确实如此。 所以我们打印错误。

同样的事情也发生在你身上。 你检查你是否连接,如果是,你离开。 然后你检查你是否不在vc中。

所以就像很多人说的那样,你要么使用 elif 语句来检查你是否不在 vc 中,要么你可以使用 else 语句。

正确的

x = True
if x:
    print('True')
    x = False
elif not x:
    print('False')
`

您正在断开机器人并检查机器人是否一个接一个地连接到任何 VC...

使用elif

您当前的代码:如果机器人在 VC 中

  voice = discord.utils.get(bot.voice_clients, guild=ctx.guild) #gets VC ID

  if voice.is_connected(): #This condition is true
    await voice.disconnect() #after this, voice.is_connected() is false
    await ctx.send("I have left the VC.") #print that

  elif not voice.is_connected(): #After the above, this is also true, use elif here
    await ctx.send("I'm not even in a VC you weirdo.")

暂无
暂无

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

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