How to increase the running time of send_action in pyTelegramBotApi?

926 views Asked by At

How I would like to do: the action is dispatched, how it ends file is sent. But it turns out that the action lasts 5 seconds, and then it takes another 5 seconds to send the file, and this time the user does not understand whether the bot is frozen or the file is still being sent. How can I increase the duration of action before sending the file directly?

import telebot
...
def send_file(m: Message, file):
    bot.send_chat_action(m.chat.id, action='upload_document')
    bot.send_document(m.chat.id, file)
2

There are 2 answers

2
RoyalGoose On BEST ANSWER

As Tibebes. M said this is not possible because all actions are sent via API. But threads helped me to solve the problem. The solution looks like this:

from threading import Thread
def send_action(id, ac):
    bot.send_chat_action(id, action=ac)

def send_doc(id, f):
    bot.send_document(id, f)

def send_file(m: Message):
    file = open(...)
    Thread(target=send_action, args=(m.chat.id, 'upload_document')).start()
    Thread(target=send_doc, args=(m.chat.id, file)).start()
...
send_file(m)

Thus, it is possible to make it so that as soon as the action ends, the file is immediately sent without time gaps

0
Konard On

In case async version of these function is used we should do something like this:

async def keep_typing_while(chat_id, func):
    cancel = { 'cancel': False }

    async def keep_typing():
        while not cancel['cancel']:
            await bot.send_chat_action(chat_id, 'typing')
            await asyncio.sleep(5)

    async def executor():
        await func()
        cancel['cancel'] = True

    await asyncio.gather(
        keep_typing(),
        executor(),
    )

And call it like this:

answer = {}

async def openai_caller():
    local_answer = await get_openai_completion(user_context.get_messages())
    answer['role'] = local_answer['role']
    answer['content'] = local_answer['content']

await keep_typing_while(message.chat.id, openai_caller)