python - 当我停止运行 python 脚本时如何停止电报机器人运行?
问题描述
这是我第一次使用 python 来控制电报机器人。我在下面运行此代码,并希望机器人停止运行。有人可以教我如何让电报机器人停止吗?
import time
import random
import datetime
import telepot
from telepot.loop import MessageLoop
def bot_test(msg):
chat_id = msg['chat']['id']
command = msg['text']
print('Got command:',command) #text from telegram
if command == '/roll':
bot.sendMessage(chat_id, random.randint(1, 2))
elif command == '/time':
bot.sendMessage(chat_id, str(datetime.datetime.now()))
bot = telepot.Bot('bot token')
MessageLoop(bot, bot_test).run_as_thread()
print ('I am listening ...')
while 1:
time.sleep(10)
解决方案
循环永远不会终止,while
因为它总是正确的并且没有任何break
语句。你可以把它改成这样:
while 1:
time.sleep(10)
break
编辑:
您也可以将while
循环更改为:
while time.sleep(10):
break
现在它会在 10 秒后终止循环,通过这种方式,您可以缩短代码而不是编写while 1
.
推荐阅读
- apache-flink - 为什么在 flink hive shim 中使用反射 api
- rust - 用流程实现“实时通信”的最惯用方式是什么?
- javascript - 我不知道为什么输出是 30 和 NaN
- node.js - 详细堆栈错误:functions@start:`npm run shell`
- c++ - 如何将输入文件中的值分配给许多新(n)变量?
- python - 在 PyQt6 中使用 QStringEncoder 时出现属性错误
- javascript - 带有变量的Javascript打开页面以打开选项卡部分的选项卡
- python - Python selenium-presence_of_all_elements_located 不起作用
- mysql - ERROR 2002 (HY000): Can't connect to local server through socket '/usr/local/mariadb/data/mariadb.sock' (2) in my Mac OS BigSur
- go - 自动滚动 Fyne TextGrid 中的日志文本