DEV Community

Damilare Abogunrin
Damilare Abogunrin

Posted on

How to Build a Free Telegram Bot to Send and Receive Images Using Python

Telegram bots are powerful tools that can be used to automate tasks, interact with users, and manage operations. In this guide, you’ll learn how to build a Telegram bot capable of sending and receiving images using Python. We'll also show you how to store these images in a database for secure and convenient access—all with free tools.

Step 1: Setting Up Your Telegram Bot

To start, you need to create a bot on Telegram using BotFather:

  1. Open Telegram and search for "BotFather."

  2. Start a chat with BotFather and use the /newbot command.

  3. Follow the instructions to create your bot and receive your bot's unique API token.

Save this token; you’ll use it in your Python script.

Step 2: Installing Required Tools

Before coding, set up your environment:

  1. Install Python on your system from python.org.

  2. Install the required Python libraries:

pip install python-telegram-bot sqlite3 requests

Step 3: Setting Up the Database

We’ll use SQLite to manage the bot’s image data because it’s lightweight and free.

Create an images.db file and initialize the database structure in your Python script:

```import sqlite3

def init_db():
conn = sqlite3.connect("images.db")
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS images (
id INTEGER PRIMARY KEY,
file_id TEXT NOT NULL,
file_path TEXT NOT NULL
)
""")
conn.commit()
conn.close()

init_db()





## Step 4: Writing the Python Code
Here’s the complete script for the bot:



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

# Database initialization
def init_db():
    conn = sqlite3.connect("images.db")
    cursor = conn.cursor()
    cursor.execute("""
    CREATE TABLE IF NOT EXISTS images (
        id INTEGER PRIMARY KEY,
        file_id TEXT NOT NULL,
        file_path TEXT NOT NULL
    )
    """)
    conn.commit()
    conn.close()

def save_image(file_id, file_path):
    conn = sqlite3.connect("images.db")
    cursor = conn.cursor()
    cursor.execute("INSERT INTO images (file_id, file_path) VALUES (?, ?)", (file_id, file_path))
    conn.commit()
    conn.close()

def start(update: Update, context: CallbackContext):
    update.message.reply_text("Welcome! Send me an image, and I'll store it.")

def handle_image(update: Update, context: CallbackContext):
    photo = update.message.photo[-1]  # Get the highest resolution image
    file_id = photo.file_id
    file = context.bot.get_file(file_id)
    file_path = f"images/{file_id}.jpg"

    os.makedirs("images", exist_ok=True)
    file.download(file_path)  # Save the image locally

    save_image(file_id, file_path)
    update.message.reply_text("Image saved successfully!")

def get_image(update: Update, context: CallbackContext):
    conn = sqlite3.connect("images.db")
    cursor = conn.cursor()
    cursor.execute("SELECT file_path FROM images ORDER BY id DESC LIMIT 1")
    result = cursor.fetchone()
    conn.close()

    if result:
        update.message.reply_photo(open(result[0], "rb"))
    else:
        update.message.reply_text("No images found.")

# Main function
def main():
    init_db()

    TOKEN = "YOUR_TELEGRAM_BOT_TOKEN"
    updater = Updater(TOKEN)
    dp = updater.dispatcher

    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(MessageHandler(Filters.photo, handle_image))
    dp.add_handler(CommandHandler("get_image", get_image))

    updater.start_polling()
    updater.idle()

if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

Step 5: Running the Bot

  1. Save the script as bot.py.
  2. Run the script using: python bot.py
  3. Interact with your bot by sending an image and using the /get_image command to retrieve the latest stored image.

Step 6: Deploying the Bot for Free

You can deploy the bot for free using platforms like PythonAnywhere or run it on your local machine. For online deployment:

  1. Sign up on PythonAnywhere.

  2. Upload your script and run it on their free tier.

Conclusion

With this guide, you’ve built a Telegram bot that sends and receives images and stores them securely. The tools used are completely free, making this project budget-friendly while providing powerful functionality.

Feel free to customize the bot further, such as adding authentication or cloud storage integration.

Start creating more useful bots to automate your tasks and enhance your operations!

Top comments (0)