1

From understanding basics of async/await I learned that time.sleep() is a blocking function, which freezes the execution. I tried to check it in this simple message_handler while creating a telegram bot.

import telebot
from time import sleep

token = '...'
bot = telebot.TeleBot(token)

@bot.message_handler(commands=['test'])
def test(message):
    bot.send_message(message.chat.id, 'Hello')
    sleep(5)
    bot.send_message(message.chat.id, 'World')

if __name__ == '__main__':
bot.infinity_polling()

A /test command was sent from two devices with a little interval (<5s). I expected the program to send a message 'Hello' to the first device, freeze for 5 seconds and then send 'World', and only after that do the same with the second device. But instead both devices were treated simultaneously.

In this case I cannot understand the process. How does the program respond immediately to the second device, if it was frozen by time.sleep() after responding to the first one?

Duck
  • 53
  • 1
  • 5
  • 1
    Why not just use an Async implementation like aiogram or another one? https://aiogram.dev/. I found this just now. I'm planning to use it for an experiment. – jeasoft Jun 26 '21 at 17:34

1 Answers1

0
import asyncio

async def test(message): # use this as your function
    await asyncio.sleep() # replace time.sleep()
AikoDev
  • 1
  • 2
  • Please read [answer] and [edit] your answer to contain an explanation as to why this code would actually solve the problem at hand. Always remember that you're not only solving the problem, but are also educating the OP and any future readers of this post – chrslg Jan 13 '23 at 16:28