← All lessons

A Telegram bot: the echo bot

Sign in · Sign up

Lesson 13.5

A bot is a program that reads messages and answers. In Python bots are made with the aiogram library:

from aiogram import Bot, Dispatcher, types

bot = Bot(token="YOUR_TOKEN")
dp = Dispatcher()

@dp.message()
async def echo(message: types.Message):
    await message.answer(f"You wrote: {message.text}")
  • token is the bot's "key" from @BotFather: you never show it to anyone;
  • the handler gets a message, and message.answer(...) sends the reply;
  • the bot runs in a loop: it asks Telegram for new messages by itself.

aiogram is not available in the browser, and the token is a secret. So the check puts a little module telegram into the program: telegram.reply(text) returns the reply, telegram.ANSWER is the reply template with a {text} slot.

The check gives the name name and the list of messages messages. Print the reply to each message and at the end Replied: <how many>.

Hint

The bot's reply is a module function, called with a dot.

telegram.reply(...) takes the message text and returns a ready-made string. Print it in a loop with print, and the number of replies is len(messages).