I remember the first time I tried to build a Telegram bot. I had a vague idea that it would involve some API and Python, but I kept putting it off because the setup looked complicated. Turns out, it takes about 10 minutes once you know the steps. I am going to walk you through exactly what worked for me.

This guide walks you through installing python-telegram-bot, setting up a bot with Telegram’s BotFather, and getting a working bot running on your machine. No fluff, no hand-waving – just the steps that actually work.

TLDR

  • Install with pip install python-telegram-bot
  • Get your bot token from BotFather in the Telegram app
  • Store the token in a separate file (never commit it to git)
  • Use updater.start_polling() to start the bot
  • Use handlers (CommandHandler, MessageHandler) to respond to messages

Prerequisites

Before you start, make sure you have Python installed on your machine. I use Python 3.8 or newer for Telegram bot projects. You also need a Telegram account – the app on your phone and optionally the desktop client.

Installing python-telegram-bot

The python-telegram-bot library is available on PyPI. Install it with pip:


pip install python-telegram-bot

If you prefer conda, you can install from conda-forge:


conda install -c conda-forge python-telegram-bot

That is it. The library installs with all its dependencies. If you run into permission errors, try adding --user or using a virtual environment.

Creating Your Bot Through BotFather

Telegram does not let you create bots directly through code. You register them through BotFather, a built-in Telegram bot that manages other bots. Here is how:

  • Open Telegram and search for BotFather
  • Send /newbot to start the creation process
  • Give your bot a name (this is the display name users see)
  • Give your bot a username (must end in bot, like MyFirstBot)
  • BotFather will give you an API token that looks like 123456789:ABCdefGhIJKlmNoPQRsTUVwxYZ

Copy that token and keep it somewhere safe. Treat it like a password – anyone with this token can control your bot.

Storing Your Token Safely

Create a file called secret.py in your project folder and put your token there:


API_KEY = "your-token-here"

Add secret.py to your .gitignore so it never gets committed to version control. Never hardcode tokens directly in your main bot file.

Your First Bot Code

Here is a minimal bot that responds to a few basic commands. I will break down what each part does after the code.


from telegram.ext import CommandHandler, MessageHandler, Filters, Updater
import secret

print("Server is running...")

def start_handler(update, context):
    update.message.reply_text("Hello! I am your bot. Type /help for commands.")

def help_handler(update, context):
    update.message.reply_text(
        "Available commands:\n"
        "/start - Start the bot\n"
        "/help - Show this message\n"
        "/about - About info"
    )

def about_handler(update, context):
    update.message.reply_text("I am a simple Telegram bot built with python-telegram-bot.")

def echo_handler(update, context):
    update.message.reply_text(f"You said: {update.message.text}")

def error_handler(update, context):
    print(f"Error: {context.error}")

updater = Updater(secret.API_KEY, use_context=True)
dispatcher = updater.dispatcher

dispatcher.add_handler(CommandHandler("start", start_handler))
dispatcher.add_handler(CommandHandler("help", help_handler))
dispatcher.add_handler(CommandHandler("about", about_handler))
dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, echo_handler))
dispatcher.add_error_handler(error_handler)

updater.start_polling(1.0)
updater.idle()

Here is what is happening:

  • Updater – This is the main object that fetches updates from Telegram. It takes your API key and handles the connection.
  • Dispatcher – This routes incoming messages to the right handler functions. Think of it as a switchboard operator.
  • CommandHandler – Handles messages that start with /, like /start or /help. The first argument is the command name, the second is the function to call.
  • MessageHandler – Handles regular text messages. Filters.text & ~Filters.command means “text messages that are not commands”.
  • start_polling(1.0) – Tells the bot to check Telegram for new messages every 1 second. The bot runs in the background.
  • idle() – Keeps the bot running until you manually stop it. Without this, the script would exit immediately.

Running and Testing Your Bot

Save your code to a file (like bot.py) and run it:

You should see “Server is running…” printed to your terminal. Open Telegram, search for your bot by its username, and click Start. Try typing /help and you should get a response.

The two arguments passed to every handler are update and context. The update object contains everything about the incoming message – the text, who sent it, the chat ID, etc. The context object is used by the library for things like sending reply messages. I used update.message.reply_text() throughout because it is the simplest way to send a response in the same chat.

FAQ

Q: My bot is not responding. What went wrong?

The bot not responding usually comes down to a few things. First, check that your API key in secret.py matches exactly what BotFather gave you – a single wrong character breaks everything. Second, make sure you ran start_polling() and not just start_webhook(). Third, if you are behind a corporate firewall or VPN, Telegram might be blocked – try a different network.

Q: How do I deploy this bot to a server?

For a simple always-on bot, you can use a cheap VPS. Upload your code, install Python and the library with pip, and run it with a process manager like systemd or pm2 so it restarts if it crashes. For production bots with high volume, consider using a proper hosting provider with good uptime guarantees.

Q: Can I use async with python-telegram-bot?

Yes, version 20+ of the library is built on asyncio. The async version uses Application instead of Updater and Dispatcher. If you are building anything beyond a simple hobby bot, the async version performs better under load.

Q: How do I handle photos or files?

Use MessageHandler with Filters.photo or Filters.document instead of Filters.text. The update.message.photo object gives you access to the file. The library handles the download for you.

Q: Is python-telegram-bot the same as Telebot or Aiogram?

No, they are different libraries. python-telegram-bot is the most popular pure-Python option. Telebot (pyTelegramBotAPI) has a slightly different API and is also widely used. Aiogram is async-native and popular for that reason. All three work well – I have used all of them at various points.

That Is All You Need to Get Started

Building a Telegram bot with Python is one of those things that looks intimidating until you do it once. After that first working bot, the pattern makes sense and you can build more complex interactions on top of it. I keep a basic bot template in my projects folder that I copy-paste whenever I need a new one – saves me from going through the setup steps every time.

Share.
Leave A Reply