⟵ Все статьи
Читать на:

How to Create a Telegram Bot: A Step-by-Step Guide for Beginners

How to Create a Telegram Bot: A Step-by-Step Guide for Beginners

A Telegram bot is a program that simply responds to messages. You can write the first version in an evening, even if you have never programmed before: the code itself fits in twenty lines, and everything else is installing a couple of packages by following instructions.

The main fork in the road comes right after the first launch: on your own computer, the bot only works while the terminal is open and the laptop is not asleep. To make it respond around the clock, it is moved to a server. Below is the entire journey: from registering the bot to its independent life on a VPS.

Step 1. Get a Token from BotFather

All bots are registered through the official Telegram bot — BotFather. Find it in the search (it has a blue checkmark), click Start, and send the command:

/newbot

BotFather will ask for the bot's name (visible to users) and a username — it must end in bot, for example my_first_service_bot. In response, you will receive a string like 8123456789:AAH... — this is the token, the key to your bot.

The token is a password: whoever holds it controls the bot. Do not share it in chats or upload it to public repositories. If you accidentally exposed it, send BotFather the command /revoke and get a new one.

Step 2. Where the Bot Will Live

The bot must be constantly available, so it needs a computer that never turns off — that is, a VPS. It does not require many resources: a typical bot with hundreds of users runs comfortably on 1 vCPU and 2 GB of RAM.

In the NodexGo panel, the process is as follows: click the Create Server button, then choose a location — your real ping to each one is shown next to it; select a plan and system image (use Ubuntu 24.04, all commands below are written for it); enter a server name; choose a billing period of 1, 3, 6, or 12 months. The server will be ready in about a minute, and the IP address and root password will appear in the panel and be sent to your email.

1 vCPU and 2 GB of RAM — more than enough for a bot. The server is ready in a minute.

Create a Server

Step 3. Connect and Prepare the System

Connect via SSH by substituting the provided IP address, then enter the root password from the panel:

ssh root@your-server-ip

Update the system and install Python along with the virtual environment tool:

apt update && apt upgrade -y
apt install -y python3 python3-venv python3-pip

There is no need to work as root all the time — create a separate user under whose name the bot will run:

adduser bot
usermod -aG sudo bot
su - bot

Step 4. Install the Library

The library handles communication with Telegram's servers: you only write the response logic. The most popular one for Python is aiogram. Install it in a separate virtual environment to keep the system clean:

mkdir ~/mybot && cd ~/mybot
python3 -m venv venv
source venv/bin/activate
pip install aiogram

After activating the environment, the label (venv) will appear at the beginning of the line — this means everything is happening inside it.

Step 5. Write Your First Bot

Create the code file:

nano bot.py

Here is a minimal working bot: it responds to the /start command and repeats any message sent to it. The token is taken from an environment variable rather than written directly in the code — this makes it harder to accidentally publish.

import asyncio
import os

from aiogram import Bot, Dispatcher
from aiogram.filters import CommandStart
from aiogram.types import Message

bot = Bot(os.environ["BOT_TOKEN"])
dp = Dispatcher()


@dp.message(CommandStart())
async def start(message: Message):
    await message.answer("Hello! I am running on my own server around the clock.")


@dp.message()
async def echo(message: Message):
    await message.answer(f"You wrote: {message.text}")


async def main():
    await dp.start_polling(bot)


if __name__ == "__main__":
    asyncio.run(main())

Save the file: Ctrl+O, Enter, Ctrl+X. Store the token in a separate .env file and restrict access to it:

echo 'BOT_TOKEN=your-token-from-BotFather' > ~/mybot/.env
chmod 600 ~/mybot/.env

Step 6. First Launch

Try running the bot manually to make sure everything works:

cd ~/mybot
source venv/bin/activate
export $(cat .env | xargs)
python bot.py

Now send a message to your bot in Telegram — it should respond. If it does, stop it with Ctrl+C: from here on, it will start automatically.

Step 7. Make the Bot Run at All Times

While the bot is running manually, it will stop when the SSH session is closed. The proper solution is systemd: it will start the bot when the server boots and restart it if it crashes. Exit to root and create a service file:

exit
nano /etc/systemd/system/mybot.service
[Unit]
Description=Telegram bot
After=network.target

[Service]
User=bot
WorkingDirectory=/home/bot/mybot
EnvironmentFile=/home/bot/mybot/.env
ExecStart=/home/bot/mybot/venv/bin/python /home/bot/mybot/bot.py
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target

Enable autostart and launch the service:

systemctl daemon-reload
systemctl enable --now mybot
systemctl status mybot

The line active (running) means the bot is running on its own. You can close the terminal — it will keep responding.

Step 8. View Logs and Update the Code

Everything the bot writes to the console goes into the system journal. To view it in real time:

journalctl -u mybot -f

After editing bot.py, simply restart the service — no rebuilding is needed:

systemctl restart mybot

What to Add Next

Buttons below messages are created using aiogram keyboards — this is the fastest way to make the bot user-friendly. For storing user data at an early stage, SQLite works well (a file stored alongside the bot), and as load grows you can switch to PostgreSQL.

If the bot starts sending broadcasts or processing payments, be sure to add database backups and monitor memory usage. When resources run low, the server card in the panel has an Upgrade Plan button: the plan is switched to a higher tier, the disk and IP address are preserved, and there is no need to migrate the bot anywhere.

If Something Goes Wrong

The bot is not responding — check the service status with the command systemctl status mybot and look at the journal: most often it is a typo in the token or in the file path.

The error Unauthorized means an invalid token; Conflict means the same token is already being used by another running instance of the bot (for example, one left running on your computer). Stop the extra instance.

Lost SSH access to the server — open the VNC web console in the server card in the panel: it works independently of the network and always lets you in. There you will also find buttons to Reset Root Password and Reinstall OS.

Plans starting from 1 vCPU and 2 GB of RAM, locations in Europe, billing for 1, 3, 6, or 12 months.

View Plans

Мы используем файлы cookie: необходимые — для входа в аккаунт и языка интерфейса, аналитические — чтобы понимать, какими страницами пользуются. Сторонних рекламных систем у нас нет. Подробнее