Building a Telegram Bot with Telethon in Docker

Sourabh KumarSourabh Kumar
4 min read

Creating a Telegram bot with Telethon and running it in a Docker container allows easy deployment and management. This article will guide you through setting up your bot, handling authentication, and ensuring it works seamlessly on any system.

Step 1: Setting Up Your Telethon Script

First, you'll need a basic Telethon script. Here's an example that sets up a client, handles authentication, and prints messages received from a specific user.

bot.py Script:

from telethon import TelegramClient, events, sync
import logging

# Enable logging
logging.basicConfig(level=logging.INFO)

# Define your API credentials
api_id = 'YOUR_API_ID'
api_hash = 'YOUR_API_HASH'
session_name = 'session_name'

# Create the client and connect
client = TelegramClient(session_name, api_id, api_hash)

# Specify the username or user ID of the target user
target_user = 'TARGET_USERNAME_OR_USER_ID'  # Replace with actual username or user ID

@client.on(events.NewMessage)
async def handler(event):
    sender = await event.get_sender()
    if sender.username == target_user or event.sender_id == target_user:
        print(f"Message from {target_user}: {event.message.text}")

async def main():
    # Start the client
    await client.start()
    print("Client started. Listening for messages...")

    # Run the client until manually stopped
    await client.run_until_disconnected()

# Run the bot
with client:
    client.loop.run_until_complete(main())

Explanation:

  • Imports and Logging: Import necessary modules and enable logging.

  • API Credentials and Session: Define your API credentials and session name.

  • Client Creation: Create the TelegramClient instance.

  • Target User: Set the target_user to the username or user ID of the user whose messages you want to read.

  • Event Handler: Handle new messages and print messages from the target user.

  • Main Function: Start the client and keep it running.

  • Run the Bot: Ensure the client runs within the event loop context.

Step 2: Creating the Docker Environment

Dockerfile

Create a Dockerfile to set up the environment for your bot.

# Use an official Python runtime as a parent image
FROM python:3.9-slim

# Set the working directory in the container
WORKDIR /usr/src/app

# Copy the current directory contents into the container
COPY . .

# Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt

# Run bot.py when the container launches
CMD ["python", "./bot.py"]

requirements.txt

Create a requirements.txt file with the dependencies needed for your script.

telethon

Step 3: Building and Running the Docker Container

Build the Docker Image

Build the Docker image using the following command in the directory containing your Dockerfile and script.

docker build -t your-telegram-bot .

Run the Container Interactively for Authentication

Run the container interactively for the first time to handle the authentication.

docker run -it --name telegram-bot-container your-telegram-bot

During this step, you will be prompted to enter your phone number and the verification code sent to you by Telegram.

Save the Session

After the initial run and successful authentication, the session file (session_name.session) will be created in the working directory. You can then commit this container as a new image to include the session file.

docker commit telegram-bot-container your-telegram-bot:authenticated

Push the Docker Image to a Repository

  1. Log in to Docker Hub (if you’re using Docker Hub):

     docker login
    
  2. Tag the Docker Image:

     docker tag your-telegram-bot:authenticated your-dockerhub-username/your-telegram-bot:authenticated
    
  3. Push the Image:

     docker push your-dockerhub-username/your-telegram-bot:authenticated
    

Step 4: Running the Docker Image on Another System

To run the Docker image on another system, follow these steps:

Pull the Docker Image on the New System

  1. Log in to Docker Hub (if you’re using Docker Hub):

     docker login
    
  2. Pull the Image:

     docker pull your-dockerhub-username/your-telegram-bot:authenticated
    

Run the Docker Container

Run the Docker container on the new system.

docker run -d --name telegram-bot-container your-dockerhub-username/your-telegram-bot:authenticated

Conclusion

By following these steps, you ensure that the authentication process is handled interactively only once, and the session is reused in subsequent runs. This setup allows your Telethon-based bot to print messages from the specified user and ensures the Docker image can be reused on any system with the authenticated session.

Feel free to customize the bot logic further to suit your needs. Happy coding!

0
Subscribe to my newsletter

Read articles from Sourabh Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sourabh Kumar
Sourabh Kumar