BotFather replies: "Done! Congratulations on your new bot." Below is a long string of digits, a colon and letters. You paste it into your code, save the file, and in the evening push the project to GitHub to show a friend.

The next day your bot is sending someone else's ads. The string was the token — a key that gives full control of the bot. And a public repository can be read by anyone, including people who look for exactly such keys.

Your first bot is one Python file and one rule: the token never goes into the code.

1 file
Of Python with no third-party libraries — and the bot answers /start and echoes text.
1 rule
The token stays out of the code. Only in an environment variable.
0 admin rights
Needed by the learning echo bot. Not in groups, not in channels.

The goal

What you will build

A learning echo bot that works in private chats:

  • answers /start and /help;
  • repeats the text you send;
  • ignores photos and group messages;
  • does not save messages to disk or write them to a log.

What you need

What you do not need

Your own Telegram account

A paid bot builder

A computer with Python 3.10 or newer

A server or hosting

A text editor and a terminal

Third-party libraries

A new learning bot

Admin rights in groups

For the experiment, create a separate bot rather than using a project's live bot.

BotFather creates the bot account and token. A running program is needed for replies; keep the token secret.
Read the diagram from left to right. BotFather creates the bot account and token. A running program is needed for replies; keep the token secret.

First things first

The token rule

Warning

The token is the key to your bot

  • Do not put the token in your code. Not "temporarily", not "just on my machine".
  • Do not publish the token in channels, screenshots, repositories or website code.
  • Do not paste the token into a browser's address bar to test: the address stays in your history.
  • Do not give the token to a bot builder without assessing who runs it: the token gives them real control of the bot.
  • Do not present your bot as Telegram's or another service's support. It misleads people.

The token is not the password to your personal Telegram account. But whoever has it fully controls the bot: they read what people send it and reply in its name.

Registration

Step 1. Register the bot with BotFather

  1. Open @BotFather via the link in Telegram's official documentation. Check the exact name — fakes use similar avatars.
  2. Send /newbot.
  3. Enter a name — what people see, for example "Learning echo bot".
  4. Enter a unique username. BotFather explains the requirements and checks whether it is free.
  5. Save the token in a password manager. It stays in the chat with BotFather, but do not forward that chat or screenshot it.

The code

Step 2. Save the code to a file

Install Python from python.org and check the version: "python3 --version" on macOS and Linux, or "py -3 --version" on Windows. Open a text editor, copy the code in full and save it as "telegram-echo-bot.py" — .py, not .py.txt.

You do not put the token in the code: the program reads it from the "TELEGRAM_BOT_TOKEN" environment variable.

"""Private-chat echo bot. Python 3.10+, standard library only."""

import json
import os
import sys
from urllib.request import Request, urlopen


class BotError(Exception):
    pass


def make_api(bot_token):
    def call(method, **params):
        try:
            request = Request(
                f"https://api.telegram.org/bot{bot_token}/{method}",
                data=json.dumps(params).encode("utf-8"),
                headers={"Content-Type": "application/json"},
            )
            with urlopen(request, timeout=35) as response:
                result = json.load(response)
            if not result["ok"]:
                raise BotError()
            return result["result"]
        except Exception:
            # Never print an exception containing the bot token or response body.
            raise BotError("Telegram request failed. Check the token and connection.") from None

    return call


def run(api):
    if api("getWebhookInfo").get("url"):
        raise BotError("A webhook is configured. Disable it explicitly before polling.")
    offset = 0
    while True:
        updates = api("getUpdates", offset=offset, timeout=25, allowed_updates=["message"])
        for update in updates:
            offset = update["update_id"] + 1
            message = update.get("message", {})
            chat = message.get("chat", {})
            text = message.get("text")
            if chat.get("type") != "private" or not isinstance(text, str) or not text:
                continue
            command = (text.split(maxsplit=1) or [""])[0].split("@")[0]
            if command in ("/start", "/help"):
                reply = "Bot is running. Send text and I will echo it."
            else:
                reply = text[:4096]
            api("sendMessage", chat_id=chat["id"], text=reply)


def main():
    bot_token = os.environ.get("TELEGRAM_BOT_TOKEN", "").strip()
    if not bot_token:
        print("Set TELEGRAM_BOT_TOKEN before starting the bot.", file=sys.stderr)
        return 1
    try:
        run(make_api(bot_token))
    except KeyboardInterrupt:
        return 0
    except BotError as error:
        print(error, file=sys.stderr)
        return 1
    except Exception:
        print("Bot stopped. Check the bot configuration and try again.", file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

What this code does

  • make_api sends requests to the official Bot API. Errors deliberately do not print the request address — it would contain the token.
  • run first checks whether the bot has a webhook configured: if so, the example will not compete with that other connection. Then it repeatedly asks Telegram for new messages (getUpdates) and replies to them (sendMessage).
  • The filter skips everything except text in private chats. The reply is cut to 4,096 characters — the message length limit.
  • main reads the token from the environment and exits cleanly on Ctrl+C.

Running it

Step 3. Run the program

Open a terminal in the folder with the file. You type the token at a hidden prompt: the characters do not show and do not go into your command history. The variable lives only inside the block and disappears when the program stops.

macOS and Linux (Bash)

If your terminal is not running Bash, run "bash" first. Paste the whole block, brackets included: the shell reads every command and only then asks for the token.

(
    read -r -s -p "Bot token: " TELEGRAM_BOT_TOKEN
    printf '\n'
    export TELEGRAM_BOT_TOKEN
    python3 telegram-echo-bot.py
)

Windows (PowerShell)

Start PowerShell in the folder with the file. If "py -3" is not found, install Python and reopen the terminal. The "finally" block clears the variable once the program stops.

& {
    $botCredential = Read-Host "Bot token" -AsSecureString
    $env:TELEGRAM_BOT_TOKEN = [System.Net.NetworkCredential]::new("", $botCredential).Password
    try {
        py -3 telegram-echo-bot.py
    } finally {
        Remove-Item Env:TELEGRAM_BOT_TOKEN -ErrorAction SilentlyContinue
        $botCredential.Dispose()
    }
}

Hidden input reduces the risk of accidental publication, but does not protect against malware on your computer.

The result

Step 4. Test the bot

While the program is running, open a private chat with your bot.

Send

Expected reply

/start

Bot is running. Send text and I will echo it.

Hello

Hello

/help

The same hint as for /start

A photo or a group message

Nothing — a limit of the example, not a bug

Stopping. Press Ctrl+C in the terminal. The bot stops replying: the computer no longer processes messages. If you message the bot while it is stopped and restart quickly, Telegram may still have the message queued, and the bot replies after starting.

The example does not store its queue position permanently, so after a restart a message may be processed twice. Do not use this code for payments or actions that must not repeat.

If something is wrong

Message in the terminal

What to do

Set TELEGRAM_BOT_TOKEN before starting the bot.

You did not enter the token. Run the block again

Telegram request failed. Check the token and connection.

Check the network and the token. Make sure only one copy is running

A webhook is configured. Disable it explicitly before polling.

The bot is already connected another way. Create a new learning bot

Bot stopped. Check the bot configuration and try again.

An unexpected error. Check the file and start again

Errors deliberately do not show the token. Do not publish it to troubleshoot.

Finishing touches

Step 5. Add commands to the menu

In BotFather, send /setcommands, choose your bot and send two lines:

start - Start the bot
help - Show help

The command list only shows hints in the menu. The replies to /start and /help are already in the code. In BotFather you can also set the bot's description.

Emergency

If the token leaks

  1. Open @BotFather → /mybots → your bot, and in the token section revoke the current one. Get a new one.
  2. Update the token wherever you run the program. The old one stops working.
  3. Check the bot's rights in groups and remove extras — changing the token does not touch them.
  4. If the bot collected users' data, assess what may have leaked. A new token does not bring back a stolen database.

Deleting the message or commit with the token does not cancel access already copied. Only revoking helps.

The next step

What next

This run is for learning. Running permanently needs: an always-on server or a trusted platform, secure secret storage, handling of errors and API limits, and — for requests and payments — carefully designed state storage.

An idea for your next project — a timetable bot: the user chooses a day, the bot shows classes and the time zone. That is an extension, not a feature of the code above. Plan the reply for a day with no classes and for an unknown command. A timetable needs no phone number, wallet or admin rights.

Before you share a public link

A note for the owner

Write down where the bot's program runs, who has access to BotFather and how to stop replies if something breaks. The token itself must not be in the note — only where it is stored. If a developer leaves the project, review access: the bot keeps running, and control of it must not depend on one person's memory.

Questions

Is creating a Telegram bot free?

Yes. Registering with BotFather is free. You only pay for a server if the bot needs to run all the time.

Why does my bot not reply?

Most likely the program is not running. BotFather only registers the bot — your code replies, while it is running.

What if I pushed the token to GitHub?

Revoke the token in BotFather straight away and get a new one. Deleting the commit does not help: the key may already have been copied.

Do I need to know how to program?

Not for this example: copying the code and running the commands is enough. To develop the bot further, basic Python helps.

Can I run the bot on my phone?

The example is designed for a computer. Running permanently needs a server that stays on.

Why does the code check for a webhook?

If the bot is already connected to another service via a webhook, the example will not compete with it and tells you so.


Creating a bot takes five minutes in BotFather. Teaching it to reply takes one Python file. Keeping it yours takes one rule: the token lives in an environment variable and a password manager, and nowhere else.

Start with the echo bot, make sure it replies and stops, and only then add features. A good bot grows from a small one that definitely works.