[英]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.