Published on

Build a Telegram Bot with Python and Docker to Interact with OpenAI Applications.

Overview

Introduction

If you want to build a Telegram bot to interact with OpenAI applications, you can use Python and Docker to create a seamless integration. Docker allows you to containerize your application and dependencies, while Python provides a simple and efficient way to code the bot. By following a few simple steps, you can set up the necessary credentials, install the required libraries, and create a webhook to handle incoming messages. With this foundation in place, you can then use OpenAI's API to integrate powerful AI capabilities into your bot, such as language processing, image recognition, and natural language generation. With the help of Python, Docker, and OpenAI, you can build a powerful and intelligent Telegram bot that can handle a wide range of tasks and interactions.

Preprequisites

create new directory and go to it

mkdir bot && cd bot

create a Telegram bot file

cat <<EOF>main.py
#!/usr/bin/env python
# pylint: disable=unused-argument, wrong-import-position
# This program is dedicated to the public domain under the CC0 license.

import logging
import os

import requests
from dotenv import load_dotenv
from telegram import ForceReply, Update
from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters

# Enable logging
logging.basicConfig(
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
logger = logging.getLogger(__name__)
load_dotenv()


# Define a few command handlers. These usually take the two arguments update and
# context.
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Send a message when the command /start is issued."""
    user = update.effective_user
    await update.message.reply_html(
        rf"Hi {user.mention_html()}! You're talking to Artem's Gpt account! Ask me anything..",
        reply_markup=ForceReply(selective=True),
    )


async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Send a message when the command /help is issued."""
    await update.message.reply_text("Help!")


async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Echo the user message."""
    global res
    url = 'http://api:8000/completion'
    args = update.message.text

    params = {'q': args}
    headers = {'Accept': 'application/json'}

    response = requests.get(url, params=params, headers=headers)

    if response.status_code == 200:
        res = response.json()
    else:
        print('Request failed with status code', response.status_code)

    await update.message.reply_text(res['content'])


def main() -> None:
    """Start the bot."""
    # Create the Application and pass it your bot's token.
    application = Application.builder().token(os.getenv("TELEGRAM_TOKEN")).build()

    # on different commands - answer in Telegram
    application.add_handler(CommandHandler("start", start))
    application.add_handler(CommandHandler("help", help_command))

    # on non command i.e message - echo the message on Telegram
    application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))

    # Run the bot until the user presses Ctrl-C
    application.run_polling()


if __name__ == "__main__":
    main()
EOF

add python requirements file

cat <<EOF>>requirements.txt
requests
python-dotenv
telegram
python-telegram-bot
EOF

add dotenv file

cat <<EOF>>.env
TELEGRAM_TOKEN="<telegram-bot-api-key>"
HOST="api"
EOF

valid telegram bot api key be generated following this instructions

create a Dockerfile for this application

FROM python:3.9-slim-buster

WORKDIR /app

COPY . .

RUN pip install -r requirements.txt

CMD ["python", "main.py"]

add a docker compose file and put it outside the "api" folder

  client:
    build:
      context: bot
      dockerfile: Dockerfile
    volumes:
      - ./bot:/app/client
    command: python client/main.py

check and sync the file structure and content with my GitHub repository

once all ready, try out by starting the applicaiton in docker

docker compose up bot

to check if the bot is healthy, find it in the telegram, access it and type in "/help" you should see message "Bot is healthy."

Conclusion

  • created basic Telegram bot application in Python
  • create Docker configuration for running the application

In the next blog we're going to test both applications in conjunction and create a basic Cloud infrastructure for them.