skip to Main Content

I use telethon library.
I can show typing event one (for 5 seconds) but can’t continue doing it.

Because I am using OpenAI that is not super fast I need to show typing event for longer (I can do it with delays).

async with client.action(event.chat_id, 'typing'):
    slow function here

How to do that?

Thank you.

2

Answers


  1. Your "slow function" can be asyncio.sleep:

    async with client.action(event.chat_id, 'typing'):
        await asyncio.sleep(60)  # 1 minute
    

    …but the idea of having the context manager is for you to put your long-running operation inside:

    async with client.action(event.chat_id, 'typing'):
        result = await function_that_takes_long()
    
    await client.send_message(chat, result)
    

    which would be far more accurate than "a minute or two".

    Make sure that function_that_takes_long does not block the thread, or the asyncio event loop won’t be able to make any progress (and, by extension, Telethon won’t be able to keep sending the action notification).

    If your function is not really async, you should probably reach out for loop.run_in_executor.

    Login or Signup to reply.
  2. To make typing status longer than 5 seconds, 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 execute 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)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search