Emir
Emir

Reputation: 15

How can I run two different tasks in pyTelegramBotAPI?

I want to run two different tasks in pyTelegramBotAPI. But the task after the bot run task is not running.

import telebot, asyncio, datetime

bot = telebot.Telebot(token)

def task1():
    bot.polling()

def task2():
    now = datetime.datetime.now()
    if now.hour == 12 and now.minute == 30:
        bot.send_document(admin_id, open("work_db.db", "rb"))

if __name__ == '__main__':
    asyncio.run(task1) # This task is running
    asyncio.create_task(task2()) # This is not working

After the bot runs, subsequent tasks do not run.

Upvotes: 0

Views: 638

Answers (2)

MIKIBURGOS
MIKIBURGOS

Reputation: 57

I'm sorry to post instead of commenting on your post, but I don't have enough reputation to do so.

Your code has a mistake in task2, it only checks once and (I assume) you want it to check indefinitely.

This is the code you should write instead:

async def task2():
while True:
    now = datetime.datetime.now()
    if now.hour == 12 and now.minute == 30:
        bot.send_document(admin_id, open("work_db.db", "rb"))
    else:
        await asyncio.sleep(60)

This code checks the time every minute, but you can tweak it to check less times and/or to be more precise. With this function, Kalosst0's answer should work.

Upvotes: 0

Kalosst0
Kalosst0

Reputation: 38

  1. Mark functions with async async def task1():
  2. Create main async function and start tasks in it
import telebot, asyncio, datetime

bot = telebot.Telebot(token)

async def main():
    await asyncio.gather(*(task1(), task2())) # You can optionally add return_exceptions=True

async def task1():
    bot.polling()

async def task2():
    now = datetime.datetime.now()
    if now.hour == 12 and now.minute == 30:
        bot.send_document(admin_id, open("work_db.db", "rb"))

if __name__ == '__main__':
    asyncio.run(main())

Upvotes: 0

Related Questions