简体   繁体   English

discord.py 中的“for”循环不按顺序执行 if…elif 语句

[英]`for` loop in discord.py does not execute if…elif statements sequentially

As the title states, I created a simple bot using discord.py that responds to a list of commands as such (the code has been truncated for brevity):如标题所述,我使用 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)

However, executing code with my_list = [1, 2, 3, 4] sometimes returns the following response (which changes randomly with repeated execution):但是,使用my_list = [1, 2, 3, 4]执行代码有时会返回以下响应(随着重复执行随机变化):

"You said one"
"You said three"
"You said two"
"You said four"

What is happening?怎么了? I don't understand how simple code can return different results with each execution?我不明白每次执行时简单的代码如何返回不同的结果? What do I do to prevent this from happening?我该怎么做才能防止这种情况发生?

A rough solution could be to asyncio.sleep() (will need to import asyncio ) for a little bit after each iteration, so each request has time to be processed in the correct order.一个粗略的解决方案可能是在每次迭代后对asyncio.sleep() (需要import asyncio )进行一段时间,这样每个请求都有时间以正确的顺序处理。

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

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