Pretending that telegram bot is typing?
Asked Answered
H

4

7

How can I make a bot to pretend that it is typing a message?

The following text appears in the chat when the bot pretend to type:

enter image description here

I use the python aiogram framework but a suggestion for the native Telegram API would be also helpful.

Haler answered 30/4, 2020 at 9:42 Comment(0)
G
15

I seriously suggest using the python-telegram-bot library which has an extensive Wiki. The solution for what you want is described in code snippets.

You can manually send the action:

bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)

Or create a decorator which can then be used on any function you wish to show that action on whilst processing:

from functools import wraps
from telegram import (ChatAction)

def send_typing_action(func):
    """Sends typing action while processing func command."""

    @wraps(func)
    def command_func(update, context, *args, **kwargs):
        context.bot.send_chat_action(chat_id=update.effective_message.chat_id, action=ChatAction.TYPING)
        return func(update, context,  *args, **kwargs)

    return command_func

@send_typing_action
def my_handler(update, context):
    pass # Will send 'typing' action while processing the request.
Glebe answered 30/4, 2020 at 10:1 Comment(2)
But, "typing" status goes away after few second even if processing the request isn't finished! How to get "typing" for longer time?Castanets
Yeah, it looks like the /sendChatAction endpoint only lasts for 5 seconds and then stays off until the bot sends a response. In other words, making additional requests doesn't turn the typing indicator back on afaict.Kisor
P
1

On Node Telegraf

ctx.replyWithChatAction('typing')
Pepita answered 17/11, 2023 at 17:48 Comment(0)
B
0

For aiogram module you can use types.Message built in method answer_chat_action.

from aiogram import types

async def answer(message: types.Message):
    await message.answer_chat_action("typing")
    await message.answer("Hi!")
    

Here is another action types such as upload_photo, record_video_note and so on. And here is aiogram documentation.

Behalf answered 15/1, 2023 at 21:45 Comment(1)
docs.aiogram.dev/en/latest/telegram/types/… link is broken.Unroot
U
0

To make your bot pretend that it is typing less than 5 seconds use code like this:

await bot.send_chat_action(chat_id, 'typing')
await asyncio.sleep(5)
await message.answer(text)

To make your bot pretend that it is typing, and you need to do it 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)

await message.answer(answer['content'])

Also, instead of

await bot.send_chat_action(chat_id, 'typing')

you can try:

await message.answer_chat_action("typing")
Unroot answered 29/2 at 20:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.