Hey everyone! I’m working on a Telegram bot and I’m wondering if there’s a way to make it look like it’s typing a message before sending. You know, like when you see ‘Bot is typing…’ in the chat.
I’m using the aiogram framework in Python but I’m open to suggestions for the Telegram API too. Has anyone figured out how to do this? It would be cool to make the bot seem more human-like.
Here’s a simple example of what I’m trying to do:
async def fake_typing(chat_id):
await bot.send_chat_action(chat_id, 'typing')
await asyncio.sleep(3)
await bot.send_message(chat_id, 'Hello! I was just typing.')
@dp.message_handler(commands=['start'])
async def start_command(message: types.Message):
await fake_typing(message.chat.id)
Any ideas on how to improve this or make it work better? Thanks in advance!
As someone who’s dabbled in Telegram bot development, I can share a trick that’s worked well for me. Instead of using a fixed delay, try implementing a variable typing duration based on the length of the message you’re about to send. This makes the bot’s behavior more realistic.
Here’s a simple approach I’ve used:
import random
async def simulate_typing(chat_id, text):
typing_duration = len(text) * 0.05 + random.uniform(0.5, 1.5)
await bot.send_chat_action(chat_id, 'typing')
await asyncio.sleep(typing_duration)
await bot.send_message(chat_id, text)
This function calculates the typing duration based on the message length, adding a bit of randomness to make it more natural. It’s not perfect, but it’s a good starting point. You can adjust the multiplier and random range to fine-tune the behavior for your specific use case.
Remember, while this can make your bot seem more human-like, it’s important to be transparent about the bot’s nature to avoid misleading users.
I’ve found that using the send_chat_action
method repeatedly can create a more convincing typing effect. Here’s a function I’ve used in my projects:
async def extended_typing(chat_id, duration):
end_time = time.time() + duration
while time.time() < end_time:
await bot.send_chat_action(chat_id, 'typing')
await asyncio.sleep(4.5)
async def send_with_typing(chat_id, text):
typing_time = min(len(text) * 0.06, 5)
await extended_typing(chat_id, typing_time)
await bot.send_message(chat_id, text)
This approach keeps the ‘typing’ indicator active for longer messages, making it feel more natural. The 4.5
second sleep is because Telegram’s typing status lasts about 5 seconds. Adjust the multiplier (0.06) to fine-tune the typing speed for your bot’s ‘personality’.
yea, i’ve messed with this before. one thing u could try is adding some randomness to the typing time. like:
async def fake_type(chat_id, msg):
time = len(msg) * 0.1 + random.uniform(1, 3)
await bot.send_chat_action(chat_id, 'typing')
await asyncio.sleep(time)
await bot.send_message(chat_id, msg)
makes it feel more human-like. just my 2 cents!