Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk4 min

Build Your First Telegram Bot in Python: A Beginner’s Guide

Create a bot with @BotFather, connect it to Python with python-telegram-bot, and test a simple reply loop locally with polling.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

You can build a first Telegram bot with Python by creating a bot through Telegram’s @BotFather, installing the python-telegram-bot library, and running a short script that replies to messages. This guide uses the library’s current v22-style asynchronous API and polling, a practical setup for learning on your own computer.

How a Telegram bot works

Your Python program communicates with Telegram through the Bot API, an HTTPS interface that accepts requests and returns JSON-encoded responses. With polling, the program repeatedly checks Telegram for updates—such as a message sent to your bot—and a handler in your code decides what to do with each update. Telegram outlines the process in its official “From BotFather to ‘Hello World’” tutorial.

As an Amazon Associate I earn from qualifying purchases.

This example uses python-telegram-bot, a library that provides an asynchronous interface and higher-level helpers in telegram.ext. Its current documentation lists Python 3.10+ compatibility and Bot API 10.0 support; check the documentation for changes if you are reading this later.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Create a bot and protect its token

  1. Open Telegram and start a chat with @BotFather, Telegram’s official bot-creation tool.
  2. Send /newbot and follow the prompts to choose a display name and username. The username must meet Telegram’s requirements; BotFather will tell you if it needs changing.
  3. BotFather will provide an authentication token. Your program uses this credential to connect as the bot. Treat it like a password: do not publish it in a code repository, a screenshot, or a message.

Store the token outside your source code, such as in an environment variable. If it is exposed, use BotFather to replace or revoke it, and update the value your program reads. Do not paste a real token into an example or a public report.

Install the library

Use a Python environment where you can install packages, then run the documented installation command:

pip install python-telegram-bot --upgrade

A virtual environment can keep this project’s dependencies separate from other Python projects. The exact commands for creating and activating one depend on your operating system and shell; consult Python’s documentation for your platform rather than assuming one command works everywhere.

Write a bot that replies

Create a file named bot.py. This example reads the token from an environment variable, registers a /start command handler and a text-message handler, and starts polling.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import os
from telegram import Update
from telegram.ext import (
    Application,
    CommandHandler,
    ContextTypes,
    MessageHandler,
    filters,
)

TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN")
if not TOKEN:
    raise RuntimeError("Set the TELEGRAM_BOT_TOKEN environment variable first.")

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    await update.message.reply_text("Hi! Send me a message and I’ll echo it.")

async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    await update.message.reply_text(update.message.text)

app = Application.builder().token(TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))

app.run_polling()

Set TELEGRAM_BOT_TOKEN in the environment where you run the script; the method for doing that varies by operating system and shell. Avoid putting the token directly into the file, since source files are easy to share or commit accidentally.

What the pieces do

  • Application.builder().token(TOKEN).build() creates the library’s application object, which dispatches incoming updates to registered handlers.
  • CommandHandler("start", start) routes the /start command to the asynchronous start function.
  • MessageHandler(filters.TEXT & ~filters.COMMAND, echo) accepts text that is not a command and routes it to echo.
  • run_polling() starts the application’s polling lifecycle and handles orderly shutdown when the process is stopped. The callback functions use await because this library’s current API is asynchronous.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Run it and test the reply

  1. In the same environment where the token variable is set, run python bot.py. Depending on your installation, the command to launch Python may instead be python3.
  2. Open Telegram, find your bot by its username, and start a chat. A bot cannot receive a private message from you until you initiate the conversation.
  3. Send /start. The bot should reply with the greeting.
  4. Send ordinary text. The bot should echo that text while the script remains running.

Polling is a convenient first approach when running a local script: your program asks Telegram for updates, so this exercise does not require setting up a public webhook endpoint. The library also supports webhooks, which are another way to receive updates and are commonly considered when designing a deployed service. Webhook setup and hosting are separate deployment decisions, not prerequisites for this learning example.

Troubleshoot common first-run problems

  • The script says the token is missing. Confirm that TELEGRAM_BOT_TOKEN is set in the environment from which you launch Python, and check for spelling mistakes in the variable name.
  • The bot does not reply. Confirm that you started a chat with the bot and sent /start or text while the script was still running.
  • /start works but ordinary text does not. Check that the message is text and that the handler uses the text filter shown above. Commands are intentionally excluded from the echo handler.
  • Telegram rejects the connection. Recheck that the token is current and copied correctly. If it was exposed, replace it through BotFather and set the new value in your environment.
  • A tutorial’s code does not match this example. Check which version of python-telegram-bot it targets. The project changed to an asynchronous architecture in v20, so older v13 tutorials may use materially different patterns, including an Updater-centered approach.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.