首页 > 解决方案 > 当我停止运行 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)

标签: pythontelegram

解决方案


循环永远不会终止,while因为它总是正确的并且没有任何break语句。你可以把它改成这样:

while 1:
    time.sleep(10)
    break

编辑:

您也可以将while循环更改为:

while time.sleep(10):
    break

现在它会在 10 秒后终止循环,通过这种方式,您可以缩短代码而不是编写while 1.


推荐阅读