Search code examples
python-3.xtelegramthread-sleeptelepot

Python while True preventing previous code execution


I'm building a telegram bot using telepot(python) and a weird thing happened:

since the bot is supposed to keep running, I've set a

while 1:
    time.sleep(.3)

at the end of my bot, right after I define how to handle the MessageLoop.

The bot has some print() to assert that the bot is setting up (or better, that it's setting up the message handler) and that it is reading the chat, waiting for any input.

The problem is that if I run the code without the

while 1:
    time.sleep(.3)

it prints the messages and stops the execution (not having a loop to wait for new input), but if I add the while 1: (...) the code stops before being able to print anything.

Here's the code:

"""Launch the bot."""
import json
import telepot
from telepot.loop import MessageLoop
import time
from base import splitter
from base import handler

messageHandler = handler.Handler()

with open('triggers.json') as f:
    triggers = json.load(f)
with open('config.json') as f:
    config = json.load(f)

botKey = config['BOT_KEY']

# define the bot and the botname
bot = telepot.Bot(botKey)
botName = bot.getMe()['username']

# split commands in arrays ordered by priority
configSplitter = splitter.Splitter()
triggers = configSplitter.splitByPriority(triggers)

# define the handler
messageHandler.setBotname(botName)
messageHandler.setMessages(triggers)

# handle the messageLoop
print("setting up the bot...")
MessageLoop(bot, messageHandler.handle).run_as_thread()
print("Multibot is listening!")

# loop to catch all the messages
while 1:
    time.sleep(.3)

Python version: 3.6 32-bit


Solution

  • The solution was to add sys.stdout.flush() after the various print()to restore the functionality of print(), while in order to make the code work again i had to change the telepot function

    MessageLoop(bot, messageHandler.handle).run_as_thread()
    

    which wasn't working properly to:

    bot.message_loop(messageHandler.handle)