How a Telegram bot works
BotFather and the token, what an update is, polling and webhooks
A Telegram bot is an ordinary Telegram account, but it's controlled by a program, not a person. Bots take shop orders, run quizzes, send reminders, moderate groups. This very site uses a bot to send login codes and evening reminders.
Step 1: BotFather and the token
- Open @BotFather in Telegram (Telegram's official bot).
/newbot→ the bot's name → the bot's username (it must end inbot, e.g.my_test_bot).- BotFather gives you a token: a long string like
123456789:AA....
⚠️ The token is the bot's password. Anyone with the token can control your bot. Don't write it in code, don't upload it to GitHub — keep it in a
.envfile (Git course, lesson 5). If the token leaks, replace it with/revokein BotFather.
An update is a message from Telegram
When a user writes to the bot, Telegram sends your program an update — data in JSON form. In Python it becomes a dict:
update = {
"update_id": 1001,
"message": {
"message_id": 55,
"from": {"id": 7001, "first_name": "Malika", "language_code": "uz"},
"chat": {"id": 7001, "type": "private"},
"text": "/start",
},
}
msg = update["message"]
print("From:", msg["from"]["first_name"])
print("Chat ID:", msg["chat"]["id"])
print("Text:", msg["text"])
print("Command:", msg["text"].startswith("/"))
# Output: From: Malika
# Output: Chat ID: 7001
# Output: Text: /start
# Output: Command: True
chat.id says who to reply to. The bot gives that number when it answers.
How updates arrive: polling and webhooks
| Method | How | When |
|---|---|---|
| Polling | the program keeps asking Telegram "any new messages?" | learning, small bots — simple |
| Webhook | Telegram itself sends to your server's address | big bots — needs an HTTPS server |
This course uses polling — it works on your own computer too.
Practice Python
From a list of updates, pick only the text messages and print who wrote what (a photo has no text):
Aziz: Salom
Malika: /start
input() data
Show solution
updates = [
{"message": {"from": {"first_name": "Aziz"}, "text": "Salom"}},
{"message": {"from": {"first_name": "Jasur"}, "photo": ["rasm.jpg"]}},
{"message": {"from": {"first_name": "Malika"}, "text": "/start"}},
]
for u in updates:
xabar = u["message"]
if "text" in xabar:
print(f"{xabar['from']['first_name']}: {xabar['text']}")