Break Loop with Command(用命令中断循环)
问题描述
在我的 Python - Discord Bot 中,我想创建一个命令,它会导致循环运行.当我输入第二个命令时,循环应该停止.这么粗略的说:
In my Python - Discord Bot, I wanted to create a command, which causes a loop to run. The loop should stop when I enter a second command. So roughly said:
@client.event
async def on_message(message):
if message.content.startswith("!C1"):
while True:
if message.content.startswith("!C2"):
break
else:
await client.send_message(client.get_channel(ID), "Loopstuff")
await asyncio.sleep(10)
所以它每 10 秒在频道中发布一次Loopstuff",并在我输入 !C2 时停止
So it posts every 10 seconds "Loopstuff" in a Channel and stops, when I enter !C2
但我自己无法弄清楚.-.
But I cant figure it out on my own .-.
推荐答案
在你的 on_message
函数中 message
内容不会改变.因此,另一条消息将导致 on_message
再次被调用一次.您需要一种同步方法,即.!C2
消息到达时将改变的全局变量或类成员变量.
Inside your on_message
function message
content won't change. So another message will cause on_message
to be called one more time. You need a synchronisation method ie. global variable or class member variable which will be changed when !C2
message arrives.
keepLooping = False
@client.event
async def on_message(message):
global keepLooping
if message.content.startswith("!C1"):
keepLooping = True
while keepLooping:
await client.send_message(client.get_channel(ID), "Loopstuff")
await asyncio.sleep(10)
elif message.content.startswith("!C2"):
keepLooping = False
附带说明,最好提供一个独立的示例,而不仅仅是一个函数.
As a side note it's good to provide a standalone example not just a single function.
这篇关于用命令中断循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:用命令中断循环


基础教程推荐
- 对多索引数据帧的列进行排序 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01