python - 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
该机器人完美地在频道上显示消息,没有任何问题,但代价是我无法停止循环并且它继续持续......
基本上我在这里想要实现的是是否可以创建一个单独的函数来打破循环。
任何帮助将不胜感激!
解决方案
您的问题的基础halt
是设置为True
启动时。
此外,我还发现了有关您的代码的其他一些内容:
停止功能/命令什么都不做。我假设您希望它先设置
halt
为True
然后再设置为False
。使用此方法,如果机器人在多个地方运行,则停止命令将结束所有这些。我不知道那是不是你想要的。
如果您更改此代码,您的代码将更具可读性
while loop_run < 60:
if not halt:
...
else:
break
有了这个:
while loop_run < 60 and not halt:
...
loop_run
永远不会增加。
推荐阅读
- xaml - 如何从另一个 xaml 代码隐藏访问内容页面中的 SwipeView 打开方法
- angular - TemplateRef 类型检查/声明类型
- objective-c - How to set first argument label in objective c to use in swift?
- android - 权限不适用于 android studio 中的 android 10
- twitter-bootstrap - Bootstrap 4 折叠仅在第二次单击时有效
- c++ - 树,无法正确删除节点
- mongodb - 安装卷时,MongoDB 初始化脚本将不起作用
- python - 获取数组中非零元素的左上和右下索引的函数
- c++ - c++ 中是否有任何用于链接列表的内置函数,其工作方式类似于 java 提供的 indexOf 函数?
- python - 为什么我不能将 str 附加到带有循环的列表中?