Learning objectives
After reading this article you will be able to:
- Create a bot in BotFather and choose a valid username
- Store the token safely and test it with the Bot API
- Run a first echo bot with python-telegram-bot and fix common errors
On this page
Every Telegram bot starts in the same place: a chat with BotFather, Telegram's own bot for creating and configuring other bots. There is no developer portal and no form. You answer a few messages and get back a token, a string that your code uses to prove it controls the bot.
This guide covers the full path: creating the bot, choosing a username, protecting the token, checking that it works and running a first bot. The code uses Python with the python-telegram-bot version 22 API, which requires a Python version that is still supported (the minimum is in the library's docs).
What do I need before starting?#
- A Telegram account, on the phone or the desktop app.
- A Python version that is still supported, only if you want to run the test code.
- A place to keep secrets, such as an environment variable or a
.envfile.
How do I create a bot with BotFather?#
- Open @BotFather in Telegram. Make sure the username is exactly
@BotFather, since lookalike accounts exist. - Send
/newbot. - BotFather asks for a name. This is the display name shown in chats and contact details. It can contain spaces and can be changed later with
/setname. - BotFather asks for a username. It must be 5 to 32 characters, use only Latin letters, numbers and underscores, and end in
bot, such astetris_botorTetrisBot. Usernames are not case sensitive, must be unique, and cannot be changed afterwards. - BotFather replies with the token and a link to your bot,
t.me/<username>.
If the username is taken, BotFather asks for another one. Try adding a word or a number.
What does the token look like and what can it do?#
A token is a number, a colon and a long string of letters and digits. Telegram's documentation shows this shape:
110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsawThat example is not a real credential. The token authenticates your bot, not your account. Anyone who has it can control the bot, so treat it like a password. Telegram's tutorial calls hardcoding it in source code bad practice and recommends environment variables or a settings file.
If it leaks, revoke it through BotFather and generate a new one (Telegram's documentation points to /token for this). Update every place the bot runs, then call getMe (below) with the old token to confirm it now fails. See what are environment variables and what is a dotenv file for ways to keep it out of your repository.
How do I test that the token works?#
The Bot API is plain HTTPS. Every request goes to https://api.telegram.org/bot<token>/METHOD_NAME, with the word bot placed before the token. The getMe method returns the bot's own profile, which makes it a good check.
export BOT_TOKEN="paste-your-token-here"
curl "https://api.telegram.org/bot${BOT_TOKEN}/getMe"A valid token returns JSON with "ok": true and a result object holding the bot's id, name and username. An invalid one returns "ok": false with error_code 401 (or 404 when the token is malformed).
How do I run a first bot?#
Install the library and write a bot that replies to /start and echoes text messages.
pip install "python-telegram-bot>=22,<23"import os
from telegram import Update
from telegram.ext import (
Application,
CommandHandler,
ContextTypes,
MessageHandler,
filters,
)
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
await update.message.reply_text("Hi! Send me a message and I will repeat it.")
async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
await update.message.reply_text(update.message.text)
def main() -> None:
app = Application.builder().token(os.environ["BOT_TOKEN"]).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))
app.run_polling()
if __name__ == "__main__":
main()Run it with BOT_TOKEN set in the same shell, open your bot's link and press Start. The bot uses long polling: it asks Telegram for new updates, so it needs no public URL. For the difference between polling and webhooks, read how to host a Telegram bot 24/7.
How do I finish setting up the bot in BotFather?#
These commands polish the bot. All are optional:
/setdescription: text of up to 512 characters shown under "What can this bot do?" when a user first opens the chat./setabouttext: a shorter bio of up to 120 characters shown on the profile page./setcommands: the list of commands users see when they type/./setname: change the display name.
Commands you register this way only show a menu. Your code still has to handle each one.
What are the most common errors?#
telegram.error.InvalidTokenor401 Unauthorized: the token is wrong, has extra spaces or quotes, or was revoked in BotFather. Copy it again.KeyError: 'BOT_TOKEN': the environment variable is not set in the shell that runs the script.- The bot does not answer: the process is not running, or you never pressed Start.
409 Conflict(telegram.error.Conflict): two instances use the same token with long polling, or a webhook is set. Stop the extra copy, or remove the webhook withdeleteWebhook.- Username rejected: it does not end in
bot, is outside 5 to 32 characters, or is already taken.
If the bot was working and stopped answering, the Telegram bot not responding guide walks through the causes one by one.
How to do this on Square Cloud#
The bot above only answers while its process runs. On your own machine that stops when the computer sleeps, so a bot other people use needs an always-on host.
On Square Cloud, hosting is self-service: you deploy the bot yourself and set BOT_TOKEN as an environment variable on the application, which keeps the token out of your code. The platform supports python-telegram-bot, aiogram, Telethon, Telegraf and grammY. Long polling works without extra configuration, and an HTTPS subdomain is available if you prefer webhooks. The squarecloud.app configuration file is optional: the dashboard can generate it during deploy, or you can write it at the project root.
Each background application, such as a bot, needs at least 256 MB of RAM, and all plans are paid. Details are in host a Telegram bot on Square Cloud.
Bot hosting
Keep your bot online 24/7 with automatic restarts
FAQs
Is it free to create a Telegram bot?
Creating a bot with BotFather has no cost. Running it continuously on a server is a separate matter, since the bot only answers while its process is running somewhere.
Can I change the bot's username later?
No. The username is permanent, but the display name can be changed at any time with /setname. Choose the username carefully.
What do I do if my bot token leaks?
Revoke it through @BotFather and generate a new one (Telegram's docs point to /token for a new token). Update the token everywhere the bot runs, then call getMe with the old one to confirm it now fails.
Do I need to know how to code to get a token?
No. The token comes from a chat with BotFather. You only need code to make the bot do something with it.
More in Bots
See all 33 articles- How much does it cost to host a Discord bot?The cost of hosting a Discord bot depends on RAM, uptime, database and outside services. Learn how to estimate your own bill and where the money goes.
- Running a bot on your phone or PC vs hosting itA bot on your PC or phone (Termux) goes offline when the device shuts down, sleeps or loses its network. Compare the three options and when each one fits.
- How to host a Discord bot 24/7To keep a Discord bot online 24/7, run its process on an always-on machine with automatic restarts. Compare your PC, a VPS with pm2 or systemd, and bot hosting.
- Why your Discord bot keeps going offline (and how to fix it)A Discord bot goes offline when the process dies, the token is invalid, an intent is disabled or memory runs out. Learn to diagnose each cause and fix it.