How Telegram Bots Work Using Python and SQLite3

How Telegram Bots Work Using Python and SQLite3

How Telegram Bots Work Using Python and SQLite3

Telegram bots can be built with Python, which provides a simple and flexible environment for bot development. SQLite3 is used to manage the database, allowing you to handle user data, history, and bot functions efficiently.

Below is a detailed guide to creating a Telegram bot using Python and SQLite3 with standard libraries.


1. Project Initialization

First, you need to install the necessary libraries and set up your project structure.

Required Libraries:

  • python-telegram-bot: For interacting with the Telegram API.
  • sqlite3: For database management (built into Python).

Install the required library:

bash
pip install python-telegram-bot

File Structure:

plaintext
telegram_bot/ |-- main.py # Main bot logic |-- database.py # SQLite3 functions |-- handlers.py # Message handling logic |-- config.py # API token and settings

2. Registering a Bot on Telegram

To create a bot on Telegram:

  1. Open BotFather in Telegram.
  2. Send the /newbot command.
  3. Provide the bot's name and username.
  4. You will receive an API token.

Store the API token in a config.py file:

python
# config.py API_TOKEN = "your_bot_token"

3. Configuring SQLite3 Database

Creating the Database:

python
# database.py import sqlite3 def init_db(): conn = sqlite3.connect("bot_database.db") cursor = conn.cursor() # Create a table for storing user data cursor.execute(""" CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, telegram_id INTEGER UNIQUE, username TEXT, joined_date TEXT ) """) conn.commit() conn.close() def add_user(telegram_id, username, joined_date): conn = sqlite3.connect("bot_database.db") cursor = conn.cursor() cursor.execute(""" INSERT OR IGNORE INTO users (telegram_id, username, joined_date) VALUES (?, ?, ?) """, (telegram_id, username, joined_date)) conn.commit() conn.close()

4. Bot's Core Logic

Setting Up the Bot:

python
# main.py from telegram import Update from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext from database import init_db, add_user import datetime # Import API token from config import API_TOKEN # Initialize the database init_db() # Handle the /start command def start(update: Update, context: CallbackContext) -> None: user = update.effective_user telegram_id = user.id username = user.username or "No Username" joined_date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") # Add user to the database add_user(telegram_id, username, joined_date) update.message.reply_text(f"Hello, {username}! You've successfully registered with the bot.") # Echo message handler def echo(update: Update, context: CallbackContext) -> None: update.message.reply_text(f"You said: {update.message.text}") # Main function to run the bot def main(): updater = Updater(API_TOKEN) dispatcher = updater.dispatcher # Add CommandHandler for /start dispatcher.add_handler(CommandHandler("start", start)) # Add MessageHandler for echoing text messages dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, echo)) # Start the bot updater.start_polling() updater.idle() if __name__ == "__main__": main()

5. Explanation of Standard Libraries

Python Standard Libraries:

  1. sqlite3:

    • Used for database management.
    • Performs operations like inserting, retrieving, and updating data using SQL queries.

    Example:

    python
    conn = sqlite3.connect("example.db") cursor = conn.cursor() cursor.execute("SELECT * FROM users") rows = cursor.fetchall()
  2. datetime:

    • Used for handling dates and times.
    • Provides formatting and timestamp functionality.

    Example:

    python
    import datetime now = datetime.datetime.now() formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
  3. os:

    • Helps in managing files and directories.

    Example:

    python
    import os if not os.path.exists("data"): os.mkdir("data")

6. Testing the Bot

  1. Run the bot:
    bash
    python main.py
  2. Open Telegram, find your bot, and send the /start command.

7. Conclusion

This example is a simple yet functional bot implementation. It allows you to create a Telegram bot that stores user data in an SQLite3 database and responds to messages.

Need more details? Feel free to ask! 😊