【问题标题】:`for` loop in discord.py does not execute if...elif statements sequentiallydiscord.py 中的“for”循环不按顺序执行 if...elif 语句
【发布时间】:2020-08-30 11:32:35
【问题描述】:

正如标题所述,我使用 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"

发生了什么?我不明白每次执行时简单的代码如何返回不同的结果?我该怎么做才能防止这种情况发生?

【问题讨论】:

  • 因为这就是异步的意思
  • 移除 await 所以它不是异步的。
  • 但删除 await 会出现以下错误:“进程未等待”
  • @MadisonCourto 删除 await 会报错。
  • 请参考asyncio

标签: python async-await discord.py


【解决方案1】:

一个粗略的解决方案可能是在每次迭代后到asyncio.sleep()(需要import asyncio)一段时间,这样每个请求都有时间以正确的顺序处理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-16
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多