首页 > 解决方案 > Discord.py 使用给定的自定义命令打破循环。蟒蛇 3.9.2

问题描述

@client.command(name="start")
async def start(maid_cafe):
    x = len(images)
    if x == 0:
        await maid_cafe.send("0 images cached,\nTry !cache first.")
        return

    loop_run = 1;
    while loop_run < 60:
        if not halt:
            image = random.choice(images)
            await asyncio.sleep(10)
            maid_cafe = client.get_channel(773213667801169930)
            await maid_cafe.send(file=discord.File(f"{image}"))
        else:
            break

这里需要一些帮助,有点在 python 上的循环中挣扎。

这里的问题描述如下。我在代码顶部将停止定义为全局

# Misc.
global halt
global images
images = []
halt = True

我有另一个函数,如果我触发整个循环中断,它就在我在这里首先列出的函数的正下方

@client.command(name="halt")
async def halt(ctx):
    halt = True
    await ctx.send("Send loop coming to a stop.")

现在,当我为函数执行某个短语时,它不会在我的不和谐通道上显示任何内容,也不会在运行窗口上打印出任何错误。但是当我删除

if not halt:
            ...
            ...
            ...
            ...
        else:
            break

该机器人完美地在频道上显示消息,没有任何问题,但代价是我无法停止循环并且它继续持续......

基本上我在这里想要实现的是是否可以创建一个单独的函数来打破循环。

任何帮助将不胜感激!

标签: pythondiscorddiscord.py

解决方案


您的问题的基础halt是设置为True启动时。

此外,我还发现了有关您的代码的其他一些内容:

  • 停止功能/命令什么都不做。我假设您希望它先设置haltTrue然后再设置为False

  • 使用此方法,如果机器人在多个地方运行,则停止命令将结束所有这些。我不知道那是不是你想要的。

  • 如果您更改此代码,您的代码将更具可读性

while loop_run < 60:
    if not halt:
        ...
    else:
       break

有了这个:

while loop_run < 60 and not halt:
    ...
  • loop_run永远不会增加。

推荐阅读