[英]`for` loop in discord.py does not execute if…elif statements sequentially
如標題所述,我使用 discord.py 創建了一個簡單的機器人,它響應這樣的命令列表(為簡潔起見,代碼已被截斷):
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix = '!')
@bot.command()
async def respond_to_me(ctx):
my_list = [1, 2, 3, 4]
for item in my_list:
if item == 1: await ctx.send("You said one")
elif item == 2: await ctx.send("You said two")
elif item == 3: await ctx.send("You said three")
elif item == 4: await ctx.send("You said four")
else: pass
bot.run(bot_token)
但是,使用my_list = [1, 2, 3, 4]
執行代碼有時會返回以下響應(隨着重復執行隨機變化):
"You said one"
"You said three"
"You said two"
"You said four"
怎么了? 我不明白每次執行時簡單的代碼如何返回不同的結果? 我該怎么做才能防止這種情況發生?
一個粗略的解決方案可能是在每次迭代后對asyncio.sleep()
(需要import asyncio
)進行一段時間,這樣每個請求都有時間以正確的順序處理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.