Indietro

How to Build a Telegram Bot with Python to Manage Your Group or Channel


How to Build a Telegram Bot with Python to Manage Your Group

The Telegram Bot API is Telegram’s own official way to build bots, and Python is one of the most approachable languages to build one in — the python-telegram-bot library wraps the API into clean, readable async code. This guide builds a real, working bot from scratch: creating it with BotFather, sending your first message, replying automatically, welcoming new members, and running it both on a computer and on an Android phone through Termux. Along the way, it covers practical automation a group or channel admin would actually use — notifications, simple commands, and keeping the bot running reliably.

What You Need Before Building a Telegram Bot

  • A Telegram account: you’ll use this to talk to BotFather and test your bot.

  • Python installed: version 3.9 or newer is recommended for current python-telegram-bot releases.

  • BotFather: Telegram’s official bot for creating and managing bots — no separate signup required.

  • An internet connection: your bot communicates with Telegram’s servers continuously while running.

  • A code editor: anything from VS Code to a plain text editor works; nothing bot-specific is required.

Create a Telegram Bot with BotFather

Short answer: message @BotFather inside Telegram, send /newbot, choose a name and username, and BotFather hands you a token — that token is your bot’s identity and password combined.

  1. Open Telegram and search for @BotFather (the official bot, verified with a blue checkmark).

  2. Start a chat and send /newbot.

  3. Choose a name for your bot — this is the display name shown to users, and it can be anything.

  4. Choose a username — this must be unique and end in bot (for example, mygroup_helper_bot).

  5. BotFather replies with a message containing your bot token — a long string like 123456789:AAFakeExampleTokenDoNotUseThisOne.

Token security matters: treat this token like a password. Anyone who has it can control your bot completely — send messages as it, read its updates, and change its settings. Never commit it to a public code repository, paste it into a public chat, or hardcode it directly into a script you plan to share. Store it in an environment variable or a .env file that stays out of version control.

Install the Python Telegram Bot Library

Short answer: install the library with pip install python-telegram-bot, ideally inside a virtual environment to keep its dependencies isolated from other projects.

  • python-telegram-bot: the library this guide uses — a mature, actively maintained, fully asynchronous wrapper around the Telegram Bot API.

  • Python version requirements: current releases of the library support Python 3.9 and newer; using an up-to-date Python installation avoids compatibility issues.

  • Virtual environments (optional but recommended): isolates your bot’s dependencies from other Python projects on the same machine.

Setting up a virtual environment and installing the library:

python -m venv botenv
source botenv/bin/activate    # On Windows: botenv\Scripts\activate
pip install python-telegram-bot

Send Your First Telegram Message with Python

Short answer: import the library, create a Bot instance with your token, and call send_message with a chat ID and text — this is the simplest possible interaction with the Bot API.

import asyncio
from telegram import Bot

TOKEN = "YOUR_BOT_TOKEN"
CHAT_ID = "YOUR_CHAT_ID"  # your user ID, or a group/channel's numeric ID

async def main():
    bot = Bot(token=TOKEN)
    await bot.send_message(chat_id=CHAT_ID, text="Hello from my Python bot!")

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

  • Import the library: Bot is the class that represents your bot and handles direct API calls.

  • Initialize the bot: pass your token to Bot(token=TOKEN) to authenticate.

  • Use the token: every request to Telegram’s servers is authenticated using this token.

  • Send a message: send_message needs a chat_id (the destination) and text (the message content).

If you don’t yet know a chat’s numeric ID, our Get Telegram Group ID guide covers how to find one.

Reply Automatically to Messages

Short answer: build a simple echo bot using ApplicationBuilder, a MessageHandler, and run_polling() — this is the standard structure every interactive Telegram bot is built on.

from telegram import Update
from telegram.ext import ApplicationBuilder, MessageHandler, ContextTypes, filters

TOKEN = "YOUR_BOT_TOKEN"

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

if __name__ == "__main__":
    application = ApplicationBuilder().token(TOKEN).build()
    application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))
    application.run_polling()

  • Handlers: functions registered to respond to specific kinds of updates — here, MessageHandler reacts to incoming text messages.

  • Updates: every message, command, or event Telegram sends your bot arrives as an Update object, passed automatically into your handler function.

  • Context: ContextTypes.DEFAULT_TYPE gives your handler access to bot-related utilities and any data your application stores between calls.

  • Polling: run_polling() continuously asks Telegram’s servers for new updates — the simplest way to run a bot, and the right choice for most small-to-medium projects. The alternative, webhooks, pushes updates to a public server endpoint instead, which is more efficient at scale but requires a publicly accessible HTTPS URL, so most beginner and small-community bots use polling.

The filter expression filters.TEXT & ~filters.COMMAND is worth understanding, since it shows up in almost every real bot: filters.TEXT matches any text message, and ~filters.COMMAND excludes anything starting with a /. Without that exclusion, your echo handler would also “echo” commands like /start back at users instead of letting a dedicated command handler process them. Handlers are checked in the order they’re added, so a more specific handler (like a command) registered before a general one (like this echo handler) takes priority for matching updates.

Create a /start Command

Short answer: register a CommandHandler for start, and Telegram automatically routes any message beginning with /start to that function.

from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes

TOKEN = "YOUR_BOT_TOKEN"

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    await update.message.reply_text(
        "Welcome! I'm your group's management bot. Send /help to see what I can do."
    )

if __name__ == "__main__":
    application = ApplicationBuilder().token(TOKEN).build()
    application.add_handler(CommandHandler("start", start))
    application.run_polling()

Every command your bot supports follows this same pattern: define an async function, register it with CommandHandler("commandname", function), and add it to the application. A bot commonly registers several of these side by side — /start, /help, /rules, and so on — each pointing to its own handler function.

Create an Auto-Welcome Bot for New Members

Short answer: listen for the filters.StatusUpdate.NEW_CHAT_MEMBERS update, which Telegram sends automatically whenever someone joins a group your bot is in, and reply with a greeting.

from telegram import Update
from telegram.ext import ApplicationBuilder, MessageHandler, ContextTypes, filters

TOKEN = "YOUR_BOT_TOKEN"

async def welcome_new_member(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    for member in update.message.new_chat_members:
        await update.message.reply_text(
            f"Welcome to the group, {member.first_name}! 👋\n"
            "Please check the pinned message for our group rules, "
            "and feel free to introduce yourself."
        )

if __name__ == "__main__":
    application = ApplicationBuilder().token(TOKEN).build()
    application.add_handler(
        MessageHandler(filters.StatusUpdate.NEW_CHAT_MEMBERS, welcome_new_member)
    )
    application.run_polling()

  • New member joins: Telegram sends a service message containing a new_chat_members list whenever someone is added or joins.

  • Bot sends a greeting: the handler loops through that list (a join can add multiple people at once) and replies for each.

  • Group rules and useful links: extend the message text with anything relevant — a link to pinned rules, a welcome resource, or an FAQ command.

For this to work, your bot needs to actually be in the group, and if the group is large or has strict settings, its admin should confirm the bot’s message permissions are enabled.

Useful Telegram Bot Commands for Group Admins

A few practical commands most management bots benefit from:

  • /help: lists available commands — usually the first thing a new member or confused user reaches for.

  • /rules: replies with your group’s rules, saved as a constant string in your code so it’s easy to update.

  • /links: shares useful links (your website, related channels, resources) in one command instead of requiring people to scroll and search.

  • /mute: conceptually, this restricts a user’s ability to send messages — implementing it requires your bot to be a group admin with the right permissions, and the underlying Bot API call is restrict_chat_member with can_send_messages set to False. Building this fully (with target-user selection and permission checks) goes beyond this guide’s beginner scope, but it’s worth knowing the API supports it directly.

  • /stats (optional): a command that replies with basic group information, such as member count via get_chat_member_count, useful for admins who want quick numbers without opening Telegram’s own UI.

Each of these follows the same CommandHandler pattern shown above — the only difference is what the handler function does once it’s triggered.

Send Notifications from Python to Telegram

Short answer: any Python script — a cron job, a monitoring tool, a form handler — can send a Telegram message by calling bot.send_message() the same way the first example in this guide did, making Telegram a lightweight notification channel for almost anything.

Common use cases:

  • Website alerts: a script that pings a site’s uptime and messages a group or channel if it goes down.

  • Cron jobs: a scheduled script (daily, hourly) that reports a summary — sales numbers, new signups, backup status — straight to a Telegram chat.

  • Google Sheets: a script that checks a spreadsheet for new rows or changed values and notifies a group when something updates.

  • Monitoring scripts: server health checks, disk space warnings, or error-log watchers that message an admin the moment something needs attention.

  • Server notifications: deployment scripts that post “deployment succeeded” or “deployment failed” messages to a team’s Telegram chat.

A minimal notification pattern, reusable inside any script:

import asyncio
from telegram import Bot

async def notify(message: str, chat_id: str, token: str) -> None:
    bot = Bot(token=token)
    await bot.send_message(chat_id=chat_id, text=message)

# Example usage inside a larger script:
asyncio.run(notify("Backup completed successfully.", "YOUR_CHAT_ID", "YOUR_BOT_TOKEN"))

Drop this function into any existing Python script — a monitoring tool, a data pipeline, a scheduled task — and it becomes a one-line way to push a notification straight to a Telegram chat or channel.

To actually run a notification script on a schedule (say, once a day), a cron job on Linux or macOS is the standard approach. Saving the script as daily_report.py and adding a line like this to your crontab (crontab -e) runs it every day at 9 AM:

0 9 * * * /usr/bin/python3 /home/youruser/daily_report.py

This pattern — a small script that authenticates once and sends one message — is the basis for most “notification bot” use cases; the complexity lives in whatever logic decides when and what to send, not in the Telegram side of things.

Run Your Telegram Bot with Termux on Android

Short answer: install Termux, install Python inside it, install python-telegram-bot with pip, and run your bot script exactly as you would on a computer — Termux gives Android a real Linux-style terminal capable of running Python normally.

  1. Install Termux from F-Droid (the actively maintained source; the old Play Store version is outdated and no longer supported).

  2. Update package lists and install Python:

pkg update && pkg upgrade
pkg install python

  1. Install dependencies:

pip install python-telegram-bot

  1. Run the bot exactly like on a desktop:

python bot.py

Keep instructions security-focused: don’t paste your bot token into any Termux script downloaded from an untrusted source, and avoid running scripts you haven’t reviewed yourself, since Termux has full access to your device’s storage and network.

A couple of Termux-specific quirks worth knowing before you rely on it:

  • Battery optimization: Android may kill background apps, including Termux, to save power. Disabling battery optimization for Termux specifically (in your phone’s app settings) reduces how often this happens.

  • Keeping the session alive: running termux-wake-lock before starting your bot prevents Android from putting the CPU to sleep while Termux is in the background, which otherwise interrupts a running script.

  • Package build issues: some Python packages with C extensions occasionally need pkg install clang or pkg install rust installed first if pip install fails partway through — this is uncommon for python-telegram-bot itself but can come up with certain optional dependencies.

Keep Your Telegram Bot Running 24/7

Short answer: a bot running with run_polling() only stays online as long as the process is running, so keeping it online continuously requires either a machine that never turns off or a hosting service designed to keep processes alive.

  • Local computer: works for testing, but the bot goes offline the moment you close the terminal, sleep the computer, or lose internet — not suitable for a bot people rely on.

  • Raspberry Pi: a low-power, always-on device that many hobbyists use to run small bots continuously at home, without needing a paid server.

  • VPS (Virtual Private Server): a rented cloud server that stays online independent of your own devices — the standard choice for a bot meant to run reliably long-term.

  • Railway, Render, Fly.io (examples only): platform-as-a-service providers that can host a Python process continuously, often with free or low-cost tiers suitable for a small bot; each has its own deployment process worth checking directly.

  • Termux limitations: Android aggressively manages background processes to save battery, so a bot running in Termux can get killed when the app isn’t in the foreground, even with the screen on. Termux’s wake-lock feature (termux-wake-lock) and disabling battery optimization for the app help, but Termux is still better suited to testing and short-term use than as permanent 24/7 hosting.

For a bot managing an active group or channel, a VPS or a managed hosting platform is generally the more dependable choice once you move past testing.

Common Python Telegram Bot Errors

Error

Cause

Solution

Invalid Token

The bot token is mistyped, expired, or was regenerated in BotFather

Copy the token again from BotFather with /mybots → your bot → API Token, and double-check for extra spaces

Unauthorized

The token doesn’t match any registered bot, often from a copy-paste error

Verify the token is complete and correctly assigned to the Bot or ApplicationBuilder instance

Chat not found

The chat ID is wrong, or the bot hasn’t been added to that chat/hasn’t received a message from that user yet

Confirm the chat ID, and make sure the bot is a member of the group or has been messaged directly by the user

Forbidden

The bot was removed from the chat, blocked by the user, or lacks permission for the action it’s attempting

Check the bot is still a member with the required permissions (e.g., admin rights for restricting members)

Conflict: terminated by other getUpdates request

Two instances of the same bot are polling simultaneously

Make sure only one instance of the script is running, and stop any old process before starting a new one

Best Practices for Telegram Group Management Bots

  • Respect user privacy: only collect and log the data your bot actually needs to function — avoid storing message content or personal details you don’t have a clear reason to keep.

  • Avoid spam: don’t design a bot that messages users who haven’t interacted with it or opted in, and be cautious with any broadcast-style feature so it can’t be misused to flood a chat.

  • Rate limiting: Telegram enforces its own rate limits on bot actions, and hitting them repeatedly can get your bot temporarily restricted — space out bulk actions (like messaging many users) rather than firing them all at once.

  • Logging: log errors and key events (using Python’s logging module) so you can diagnose issues without needing to reproduce them live.

  • Secure token storage: keep your bot token in an environment variable or .env file excluded from version control — never hardcode it into a script you’ll share or publish.

  • Bot permissions: only grant your bot the admin permissions it actually needs (message deletion, member restriction, and so on) rather than full admin rights by default, limiting the damage if the token is ever compromised.

  • Error handling: wrap API calls in try/except blocks where failure is plausible (a user blocking the bot, a chat being deleted) so one failed message doesn’t crash the entire bot process.

  • Test before deploying: run new commands or handlers in a private test group before adding them to a live community group, so mistakes don’t play out in front of real members.

  • Document your commands: keep a simple /help command up to date as you add features — an admin bot that’s hard to understand is a bot that goes unused.

Frequently Asked Questions

How do I make a Telegram bot with Python?

Create a bot with BotFather to get a token, install python-telegram-bot with pip, then use ApplicationBuilder, handlers, and run_polling() to build and run your bot’s logic.

Is python-telegram-bot free?

Yes. It’s an open-source library, free to use, with no licensing cost for building or running bots with it.

How do I send Telegram messages with Python?

Create a Bot instance with your token and call await bot.send_message(chat_id=..., text=...) — this works from any script, not just an interactive bot.

How do I run a Telegram bot on Android?

Install Termux from F-Droid, install Python inside it with pkg install python, install the library with pip install python-telegram-bot, and run your script the same way you would on a desktop.

What is BotFather?

Telegram’s official bot for creating and managing other bots — used to generate a bot’s name, username, and API token, along with other settings like profile pictures and command lists.

Can my bot welcome new members?

Yes. Listening for filters.StatusUpdate.NEW_CHAT_MEMBERS lets your bot detect when someone joins a group it’s in and reply with a greeting automatically.

Can Python bots manage Telegram groups?

Yes, within what the Bot API supports — deleting messages, restricting or banning members, pinning messages, and more — provided the bot has been given admin rights with the relevant permissions in that group.

How do I keep my Telegram bot online?

Run it on something that stays on continuously — a VPS, a Raspberry Pi, or a hosting platform like Railway, Render, or Fly.io — rather than a personal computer or Termux session that can go offline or get killed by the OS.


If your bot setup grows to include member visibility, growth tracking, or community management features, our Telegram Group Members List, Add Members Guide, and Telegram Limits Guide cover related Bot API behavior worth knowing as your bot’s responsibilities expand. Admins combining bot automation with broader community management may also find SMMTO’s Telegram automation and community resources useful.