logo
Back to Main Website
Go back
Tomas Vivaldi

ChatGPT + Telegram - A Technical and Informative Overview of the Bot Integration

April 9, 2023

Author: Tomas Vivaldi

The inner dwellings of a highly sophisticated GPT Telegram Bot built to integrate with various of Open AI's many language model.

API

AI

Python

Highlighted

Introduction to the GPT Telegram Bot

The Need for a GPT Telegram Bot

In today's fast-paced world, people are looking for ways to access information quickly and effortlessly. The GPT Telegram Bot aims to provide users with a more convenient and interactive way to communicate with the many language models from OpenAI more directly using the popular messaging platform, Telegram.

The GPT Telegram Bot is a powerful Telegram bot that I created to leverages the capabilities of the ChatGPT, enabling users to ask questions, receive assistance, and engage in conversations with the bot that has different modes to assist users with different tasks.

Key Features of the GPT Telegram Bot

  • Seamless integration with the Telegram platform, allowing users to communicate with the GPT-4 model via text messages.
  • A user-friendly interface that supports various commands and chat modes, catering to diverse user preferences.
  • A robust database system that tracks user interactions, token usage, and subscriptions.
  • An efficient and scalable architecture that can handle multiple users simultaneously while maintaining high responsiveness.

Technical Components of the GPT Telegram Bot

Project File Structure Overview

The GPT Telegram Bot project consists of a well-organized file structure that makes it easy to understand the various components of the bot. Here's an overview of the main files and directories within the project:

Blog Post Image

The Telegram API Integration

The GPT Telegram Bot uses the python-telegram-bot library to interact with the Telegram API. This library provides a convenient way to create and manage Telegram bots, offering a high-level interface that simplifies bot development.

The library enables the GPT Telegram Bot to:

  • Receive and process incoming messages and commands from users.
  • Send text messages and audio messages.
  • Implement custom commands and message handlers.
  • Manage user interactions, such as inline keyboards and callback queries.

The Database Layer

The GPT Telegram Bot relies on the MongoDB database to store user data, manage subscriptions, and maintain the state of conversations. The database.py file contains the ChatbotDatabase class, which provides methods for managing users, dialogs, and subscriptions.

Some of the main operations provided by the ChatbotDatabase class include:

  • Registering new users and checking if a user exists.
  • Initiating new dialogs and managing dialog data.
  • Updating and retrieving user attributes.
  • Managing user subscriptions and checking subscription status.

The GPT Model Integration

The GPT Telegram Bot uses the OpenAI API to communicate with the GPT's language models. The API allows the bot to send user input to the model, process it, and generate a response. The integration with ChatGPT is done primarily within the process_message function in the gpt_telegram_bot.py file.

Together, these components form the foundation of the GPT Telegram Bot, enabling it to deliver a powerful and engaging user experience on the Telegram platform. Now that we have that in mind, lets get started with the interesting part.

Creating the Telegram Bot

The gpt_telegram_bot.py File

The gpt_telegram_bot.py file is the heart of the GPT Telegram Bot. It contains the main logic that integrates the Telegram API with the OpenAI's language models. The bot relies on just a few libraries, such as python-telegram-bot and pymongo, to facilitate seamless interaction between the user, the bot, and the database.

Main Functions and Features

The GPT Telegram Bot comes with various functions and features that enable a smooth user experience. Here are some of the key functions found in the gpt_telegram_bot.py file followed by a picture showing its full structure:

  • start_command: Initializes the bot and displays a welcome message to the user.
  • help_command: Shows a list of available commands and their descriptions.
  • retry_command: Regenerates the last bot answer, providing an alternative response.
  • show_modes_command: Displays a list of available chat modes.
  • set_mode_command: Allows users to change the chat mode.
  • settings_command: Shows the current settings and provides an interface for modifying them.

Blog Post Image

How the GPT Telegram Bot Processes Messages

The process_message Function

The core function for processing user input in the GPT Telegram Bot is process_message. This function takes the user's input, processes it, and sends it to the OpenAI's language model of choice and then returns an appropriate response.

When a user sends a message to the bot, process_message performs the following steps:

  1. Checks if the user is registered in the database and if their subscription is active.
  2. Tokenizes the input message and calculates the number of tokens used.
  3. Processes the user's input according to the bot mode being used.
  4. Calls the OpenAI's language model of choice with the input message and generates a response.
  5. Sends the response back to the user and updates the token usage in the database.

Handling Commands and User Input

The GPT Telegram Bot can handle various commands and user inputs, as mentioned earlier. Each command has a dedicated function that performs a specific action. For example, the /retry command regenerates the last bot answer, while the /settings command allows users to modify their settings.

The bot also handles user input in the form of text messages. It uses the process_message function to generate a response based on the user's input and the currently selected chat mode.

Chat Modes and Models in the GPT Telegram Bot

Chat Modes

The GPT Telegram Bot offers different chat modes. These modes can be defined in the chat_modes.yml file it is fairly simple to include a new mode. It works by passing a input with specific instruction before the user's input. By doing so, it is possible to personalize the output received to cater to various user needs. Here are a few examples followed by what is going on in the backend:

  1. Classic Mode (生): In this mode, the bot behaves simply as a bridge between Telegram and ChatGPT. No prompt is passed before the user's and the response come exactly as it was generated by ChatGPT. However this message is capped to 4096 characters (Telegram's limit)
  2. Code Assistant Mode (👩🏼‍💻): This mode is tailored for users who need assistance with code-related questions. The bot will help with designing, writing, editing, and describing code and provide relevant code examples.
  3. Text Improver Mode (📝): In this mode, the bot focuses on improving and correcting user-submitted text. It aims to maintain the meaning of the original text while enhancing its clarity and style.

As an example, this it how the code to set up the Text Improver Mode is done:

Blog Post Image

GPT Models

The bot utilizes different GPT models, specified in the models.yml file. Here's a brief overview of the models being used at the moment:

  1. text-davinci-003: A legacy model that's cheaper but slower than ChatGPT but with slightly worse capabilities.
  2. gpt-3.5-turbo (ChatGPT): A widely-known model that's fast and affordable. This model is suitable for everyday tasks. If there are tasks.

These models are integrated into the Telegram bot to provide users with the best possible experience based on their chosen chat mode and model.

Running and Deploying the GPT Telegram Bot

Setting Up the Bot

To set up the GPT Telegram Bot, follow these steps:

  1. Install the required Python libraries: python-telegram-bot, pymongo, and openai.
  2. Set up a MongoDB database and configure the mongodb_uri in the bot_config.py file.
  3. Obtain a Telegram API token by creating a new bot through the BotFather.
  4. Update the bot_token in the bot_config.py file with your Telegram API token.
  5. Configure the available GPT models and other settings in the bot_config.py file as needed.

Running the Bot

Once the setup is complete, you can run the GPT Telegram Bot by executing the image from the docker file. This will start the bot, and it will begin listening for incoming messages and commands from users.

Deployment Considerations

When deploying the GPT Telegram Bot, consider the following best practices:

  1. Use a virtual environment to isolate dependencies.
  2. Ensure the server is able to stay online without interruptions, as if the server goes down the bot will be unable to run.
  3. Set up proper logging and error handling to monitor the bot

If you have any questions, feel free to contact me on my website