Comprehensive Guide to Building Telegram Bots with Python

Comprehensive Guide to Building Telegram Bots with Python

Comprehensive Guide to Building Telegram Bots with Python

Telegram bots are becoming increasingly popular for automating tasks, managing communities, and providing services. With Python's simplicity and Telegram's open API, you can create feature-rich bots that integrate seamlessly into your workflows. This guide dives deep into creating Telegram bots, integrating them with databases, and exploring their real-world use cases.


Why Are Telegram Bots So Popular?

Telegram bots have gained immense popularity due to their versatility and ease of use. Here are the key reasons:

  1. Rich Features: Telegram bots support functionalities like file sharing, inline keyboards, payments, and even AI-driven interactions.
  2. Ease of Integration: Telegram’s API is open, free, and developer-friendly, making it easy to get started.
  3. Cross-Platform Availability: Telegram works on desktop, mobile, and web, ensuring consistent bot performance.
  4. Scalability: Bots can handle thousands of users simultaneously, making them ideal for businesses and large communities.
  5. Automation: Telegram bots can automate repetitive tasks like notifications, reminders, and data collection.

Getting Started: Setting Up a Telegram Bot with Python

Let’s start by creating a simple bot and progressively add more advanced features.

Step 1: Create a Bot on Telegram

  1. Open Telegram and search for the BotFather.
  2. Start a chat with BotFather and use the /newbot command to create a bot.
  3. Follow the prompts:
    • Provide a name for your bot.
    • Choose a unique username (must end with bot, e.g., MyAwesomeBot).
  4. Once created, you will receive a token. Save this token; it is required to connect your bot to Telegram.

Step 2: Install Required Python Libraries

Install the necessary libraries using pip:

pip install python-telegram-bot requests

Step 3: Write the Basic Bot Code

Here’s the code for a simple bot that responds to messages:

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

def start(update: Update, context: CallbackContext):
    update.message.reply_text('Welcome! I am your Telegram bot. Type any message, and I will echo it back.')

def echo(update: Update, context: CallbackContext):
    update.message.reply_text(f'You said: {update.message.text}')

if __name__ == '__main__':
    TOKEN = 'your-telegram-bot-token'

    updater = Updater(TOKEN)
    dispatcher = updater.dispatcher

    dispatcher.add_handler(CommandHandler('start', start))
    dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, echo))

    updater.start_polling()
    updater.idle()

Step 4: Run the Bot

Save the code in a file (e.g., bot.py) and execute it:

python bot.py

Your bot is now live and can respond to /start and text messages.


Adding More Features to Your Bot

Inline Keyboards

Inline keyboards provide interactive buttons for users. Here’s an example:

from telegram import InlineKeyboardButton, InlineKeyboardMarkup

def menu(update: Update, context: CallbackContext):
    keyboard = [
        [InlineKeyboardButton("Option 1", callback_data='1'),
         InlineKeyboardButton("Option 2", callback_data='2')]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)
    update.message.reply_text('Choose an option:', reply_markup=reply_markup)

# Add this handler
dispatcher.add_handler(CommandHandler('menu', menu))

Scheduled Notifications

You can schedule periodic notifications using Python’s threading library:

import threading
import time

def notify(context: CallbackContext):
    context.bot.send_message(chat_id='your-chat-id', text='This is a scheduled notification.')

def schedule_notifications():
    while True:
        time.sleep(3600)  # Notify every hour
        notify(context)

threading.Thread(target=schedule_notifications).start()

Handling Webhooks

Instead of polling, you can use webhooks for real-time updates. Configure your webhook as follows:

pip install flask

Then, set up a Flask server:

from flask import Flask, request
from telegram import Bot

app = Flask(__name__)

BOT_TOKEN = 'your-telegram-bot-token'
bot = Bot(BOT_TOKEN)

@app.route('/webhook', methods=['POST'])
def webhook():
    update = Update.de_json(request.get_json(), bot)
    dispatcher.process_update(update)
    return 'OK'

if __name__ == '__main__':
    app.run(port=5000)

Set your bot’s webhook URL using the BotFather:

curl -F "url=https://your-server.com/webhook" https://api.telegram.org/bot/setWebhook

Storing Data with Databases

Many bots require a database to store user information, logs, or preferences. Here’s how to integrate SQLite.

Creating the Database

Install SQLite (if not already installed) and create a database:

import sqlite3

connection = sqlite3.connect('bot_data.db')
cursor = connection.cursor()

cursor.execute('''CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY,
    username TEXT,
    chat_id INTEGER
)''')

connection.commit()
connection.close()

Storing User Data

Modify your bot’s /start command to save user data:

def start(update: Update, context: CallbackContext):
    username = update.message.from_user.username
    chat_id = update.message.chat_id

    connection = sqlite3.connect('bot_data.db')
    cursor = connection.cursor()

    cursor.execute('INSERT OR IGNORE INTO users (username, chat_id) VALUES (?, ?)', (username, chat_id))
    connection.commit()
    connection.close()

    update.message.reply_text(f'Hello, {username}! Your information has been saved.')

Fetching Data

You can retrieve user data as needed:

def get_users():
    connection = sqlite3.connect('bot_data.db')
    cursor = connection.cursor()

    cursor.execute('SELECT * FROM users')
    rows = cursor.fetchall()

    connection.close()
    return rows

Real-World Applications of Telegram Bots

  1. Customer Support: Automate FAQs and support tickets.
  2. E-commerce: Process orders, send shipping updates, and manage inventory.
  3. Community Management: Moderate groups, run polls, and schedule events.
  4. Personal Productivity: Create reminders, to-do lists, and habit trackers.
  5. Educational Tools: Deliver lessons, quizzes, and study resources.

Conclusion

Telegram bots, powered by Python, are versatile tools for automating tasks, engaging users, and building creative solutions. By integrating features like databases, notifications, and webhooks, you can create bots that deliver real value. Start with a basic bot, experiment with advanced features, and watch your project grow into a robust application.

Additional Resources

  1. Telegram Bot API Documentation
  2. Python-Telegram-Bot Library
  3. SQLite Documentation

Happy coding!