The architecture of a simple Telegram bot: what to store, what to log
Next step
Open the bot or continue inside this section.
Article -> plan in AI
Paste this article URL into any AI and get an implementation plan for your project.
Read this article: https://vibecode.morecil.ru/en/telegram-boty/telegram-bot-architecture-logging-storage/
Work in my current project context.
Create an implementation plan for this stack:
1) what to change
2) which files to edit
3) risks and typical mistakes
4) how to verify everything works
If there are options, provide "quick" and "production-ready". How to use
- Copy this prompt and send it to your AI chat.
- Attach your project or open the repository folder in the AI tool.
- Ask for file-level changes, risks, and a quick verification checklist.
Imagine: you decided to write a Telegram bot. For example, a bot for receiving orders, collecting orders, automating support or notifications.
Everything looks simple at the start. You write a message handler, connect webhook or polling, and the bot already responds to the user.
But after a few days, questions arise:
- where to store users
- do i need to keep messages
- how to understand why the bot fell
- how to track errors
- what events to log
This is where the bot architecture begins.
Even a simple Telegram bot should have a clear structure of data storage and logging. Without this, the project quickly turns into chaos: it is difficult to find errors, it is difficult to analyze user behavior and it is difficult to scale the system.
In this article, we will examine:
- what parts is the architecture of the Telegram-bot
- which data must be stored
- which data is better not to store
- what events should be logged
- how to organize database tables
- how to set up a logging system
- common mistakes in bot development
Basic architecture of the Telegram bot
In fact, the architecture of a simple bot is quite minimalist. It usually consists of several components.
| Компонент | Назначение |
|---|---|
| Telegram API | принимает и отправляет сообщения |
| Webhook или Polling | доставка обновлений боту |
| Backend-сервер | обработка логики |
| База данных | хранение пользователей и состояния |
| Логи | диагностика и анализ ошибок |
The simple flow of work looks like this:
- The user sends a message to the bot.
- Telegram sends update to your server.
- Backend handles the update.
- The bot performs an action (response, record in the database, etc.).
- The event is logged.
Example of Telegram update
{
"update_id": 123456,
"message": {
"message_id": 55,
"from": {
"id": 123456789,
"username": "alex"
},
"text": "/start"
}
}
Each update contains information about the user, message and event.
What data must be stored
Many novice developers try to save everything. But in practice, you only need to store data that is actually used in the logic of the bot.
The main essence of the Telegram-bot
| Сущность | Зачем хранить |
|---|---|
| Пользователь | идентификация пользователя |
| Чат | тип диалога (личный, группа) |
| Состояние пользователя | этап сценария |
| Действия пользователя | история операций |
The minimum set of tables usually looks like this:
| Таблица | Назначение |
|---|---|
| users | информация о пользователях |
| sessions | текущее состояние сценария |
| actions | действия пользователя |
User table
This table stores information about people who interact with the bot.
| Поле | Описание |
|---|---|
| id | внутренний ID |
| telegram_id | ID пользователя в Telegram |
| username | username |
| first_name | имя |
| created_at | дата первого взаимодействия |
Example of SQL table:
CREATE TABLE users (
id SERIAL PRIMARY KEY,
telegram_id BIGINT UNIQUE,
username TEXT,
first_name TEXT,
created_at TIMESTAMP
);
Why it is important to keep the user:
- activity can be tracked
- you can send notifications
- you can analyze the audience of the bot.
User status table
If the bot contains scripts (for example, questionnaires, menus, checkout), you need to store the current state of the user**.
| Поле | Назначение |
|---|---|
| user_id | пользователь |
| state | текущий этап |
| payload | дополнительные данные |
Example of conditions:
| Состояние | Значение |
|---|---|
| start | пользователь только начал |
| menu | пользователь в главном меню |
| order | оформление заказа |
| support | обращение в поддержку |
This allows the bot to understand the context of the dialogue.
Table of user actions
Sometimes it’s helpful to save user actions for analytics.
| Поле | Описание |
|---|---|
| user_id | пользователь |
| action | действие |
| data | данные |
| created_at | время |
For example:
| user_id | action | data |
|---|---|---|
| 101 | start | /start |
| 101 | open_menu | menu |
| 101 | order | pizza |
Such a table helps to analyze the behavior of users.
What data should not be stored
Beginners often make one mistake: *Save every user message..
It's almost always superfluous.
Telegram already stores the history of messages, and most bots do not need this information.
When not to save messages
| Сценарий | Нужно ли хранить |
|---|---|
| простые команды | нет |
| меню-бот | нет |
| сервисный бот | нет |
When messages are useful to store
| Сценарий | Причина |
|---|---|
| поддержка пользователей | история диалога |
| CRM-бот | анализ общения |
| AI-бот | обучение модели |
Storing all messages increases:
- baseload
- processing
- cost of infrastructure.
What must be logged
Logs are the main diagnostic tool.
Without logs, you can't understand:
- why did the bot stop responding
- why is webhook not working
- where the error occurs.
Minimum set of logs
| Тип события | Нужно ли логировать |
|---|---|
| ошибки | обязательно |
| входящие updates | желательно |
| отправка сообщений | желательно |
| системные события | желательно |
Example of logging update
logger.info("telegram update", {
update_id: update.update_id,
user_id: update.message?.from?.id
})
This helps to track the flow of events.
Logistic of errors
Mistakes are the most important thing to log.
Example:
try {
await bot.sendMessage(chatId, text)
} catch (error) {
logger.error("telegram send error", {
chatId,
error: error.message
})
}
Without such logging, debugging becomes almost impossible.
Good bot logging scheme
Practice shows that three types of logs are enough.
| Тип логов | Назначение |
|---|---|
| info | события системы |
| warn | подозрительные ситуации |
| error | ошибки |
Example of structure:
| Тип | Пример |
|---|---|
| info | пользователь нажал кнопку |
| warn | неизвестная команда |
| error | ошибка отправки сообщения |
Typical bot project architecture
A good design might look like this.
| Папка | Назначение |
|---|---|
| bot | логика Telegram |
| handlers | обработчики команд |
| services | бизнес-логика |
| database | модели и запросы |
| logs | файлы логов |
This structure makes the project understandable and supported.
Typical mistakes in the development of Telegram bots
Novice developers often make the same mistakes.
Keeping everything together
| Ошибка | Почему плохо |
|---|---|
| сохранение всех сообщений | перегружает БД |
| хранение лишних данных | усложняет архитектуру |
Lack of logging
| Ошибка | Последствие |
|---|---|
| нет логов | невозможно отладить |
| логирование только ошибок | трудно анализировать события |
Lack of user status
| Ошибка | Последствие |
|---|---|
| нет state-машины | бот путается в сценариях |
How to apply it through AI
AI assistants can greatly accelerate the development of Telegram bots.
For example, you can ask the model to create an architecture.
Example:
I'm building a Telegram bot.
You need to offer backend architecture.
Conditions:
store users
- keep the state of the script
Log out errors and events
Use PostgreSQL
Show the structure of the tables and an example of logging.
This approach allows you to quickly get the basis of the project.
Outcome
The architecture of a Telegram bot doesn’t have to be complicated.
But even a simple bot should have a clear structure of data storage and logging.
The minimal architecture looks like this:
| Компонент | Назначение |
|---|---|
| users | хранение пользователей |
| sessions | состояние сценария |
| actions | действия пользователя |
| logs | диагностика системы |
If these principles are followed, the bot will:
- ease up
- scale
- it's easier to analyze.