Python Telegram Bot: How to Build Your Own Chatbots with Python

Telegram is one of the most popular messaging apps, known for its speed, security, and flexibility. If you're looking to automate tasks, provide customer support, or create interactive chatbots, the Python Telegram Bot library is the perfect tool for you. In this article, we’ll explore how to build Telegram bots using Python and showcase three practical examples.

What is Python Telegram Bot?

Python Telegram Bot is a powerful library that allows developers to interact with Telegram’s Bot API easily. With it, you can:

  • Send and receive messages

  • Handle commands

  • Process media files

  • Manage users and groups

This library is an excellent choice for building feature-rich Telegram bots without delving into complex API handling.


Getting Started with Python Telegram Bot

Before we dive into examples, let’s set up our development environment.


Installation

Ensure you have Python installed, then run:


Getting a Telegram Bot Token

  1. Open Telegram and search for BotFather.

  2. Start a chat and type /newbot to create a new bot.

  3. Follow the instructions and copy the bot token provided.

You’ll use this token to authenticate your bot with Telegram’s API.


Example 1: Simple Echo Bot

This basic bot replies with the same message a user sends.

from telegram import Update
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext

def start(update: Update, context: CallbackContext):
    update.message.reply_text('Hello! Send me any message, and I will echo it back!')

def echo(update: Update, context: CallbackContext):
    update.message.reply_text(update.message.text)

def main():
    updater = Updater("YOUR_BOT_TOKEN")
    dp = updater.dispatcher
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(MessageHandler(Filters.text & ~Filters.command, echo))
    updater.start_polling()
    updater.idle()

if __name__ == '__main__

This bot listens for incoming messages and replies with the same text.


Example 2: Weather Bot

This bot fetches weather updates using OpenWeatherMap API.

Install Required Libraries:

Code:

import requests
from telegram import Update
from telegram.ext import Updater, CommandHandler, CallbackContext

def get_weather(city):
    api_key = "YOUR_OPENWEATHERMAP_API_KEY"
    url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
    response = requests.get(url).json()
    if response["cod"] != 200:
        return "City not found!"
    temp = response["main"]["temp"]
    weather = response["weather"][0]["description"]
    return f"Weather in {city}: {temp}°C, {weather}"

def weather(update: Update, context: CallbackContext):
    if context.args:
        city = " ".join(context.args)
        update.message.reply_text(get_weather(city))
    else:
        update.message.reply_text("Usage: /weather [city]")

def main():
    updater = Updater("YOUR_BOT_TOKEN")
    dp = updater.dispatcher
    dp.add_handler(CommandHandler("weather", weather))
    updater.start_polling()
    updater.idle()

if __name__ == '__main__

Users can type /weather city_name to get weather updates.


Example 3: Task Reminder Bot

This bot schedules reminders for users.

import threading
import time
from telegram import Update
from telegram.ext import Updater, CommandHandler, CallbackContext

def set_reminder(update: Update, context: CallbackContext):
    try:
        delay = int(context.args[0])
        message = " ".join(context.args[1:])
        update.message.reply_text(f"Reminder set for {delay} seconds.")
        threading.Thread(target=reminder, args=(update, delay, message)).start()
    except (IndexError, ValueError):
        update.message.reply_text("Usage: /remind [seconds] [message]")

def reminder(update, delay, message):
    time.sleep(delay)
    update.message.reply_text(f"Reminder: {message}")

def main():
    updater = Updater("YOUR_BOT_TOKEN")
    dp = updater.dispatcher
    dp.add_handler(CommandHandler("remind", set_reminder))
    updater.start_polling()
    updater.idle()

if __name__ == '__main__

Users can type /remind 60 Take a break! to get a reminder after 60 seconds.


Conclusion

Building a Telegram bot with Python is straightforward with the Python Telegram Bot library. Whether you're making a simple echo bot, a weather bot, or a task reminder, this framework simplifies the process. Try building your own bot today and explore the possibilities!

If you found this guide useful, share it with others and start coding your own Python Telegram Bot today!