#Telegram bot API + chatGPT API (Python)

Create Telegram bot using chatGPT API

BotFather steps: (From Telegram find BotFather contact)

User:
*/start*

BotFather, [Feb 5, 2023 at 2:08:07 PM]:
I can help you create and manage Telegram bots. If you're new to the Bot API, please see the manual.
You can control me by sending these commands:
*/newbot* - create a new bot
...
User:, [Feb 5, 2023 at 2:08:40 PM]:
*/newbot*

BotFather, [Feb 5, 2023 at 2:08:40 PM]:
Alright, a new bot. How are we going to call it? Please choose a name for your bot.

User, [Feb 5, 2023 at 2:09:23 PM]:
*Dec_22_chatGPT*

BotFather, [Feb 5, 2023 at 2:09:23 PM]:
Good. Now let's choose a username for your bot. It must end in `bot`. 
Like this, for example: TetrisBot or tetris_bot.

User, [Feb 5, 2023 at 2:10:14 PM]:
*chat_dec_22_bot*

BotFather, [Feb 5, 2023 at 2:10:14 PM]:
Done! Congratulations on your new bot. You will find it at t.me/chat_dec_22_bot. You can now add a description, about section and profile picture for your bot, see /help for a list of commands. By the way, when you've finished creating your cool bot, ping our Bot Support if you want a better username for it. Just make sure the bot is fully operational before you do this.

Use this token to access the HTTP API:
6185472765:PIbwepibvWEfvweurwEO$I#)$#$D
Keep your token secure and store it safely, it can be used by anyone to control your bot.

For a description of the Bot API, see this page: https://core.telegram.org/bots/api

Pre-requisites:

OpenAI.com valid API key

Telegram API key

Steps:

  1. The best practice is to run the app in their own virtual environment

    python -m venv .myenv
    source .myenv/bin/activate
  2. Install the aiogram and openai libraries:

pip install aiogram
pip install openai
  1. Register a new bot with BotFather on Telegram and obtain the API key.

  2. Create a new Python file like "chatGPT_telegram_bot.py" and import the necessary libraries:

chatGPT_telegram_bot.py
-----------------------
#!/bin/python

import openai
import os
from aiogram import Bot, Dispatcher, executor, types

from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.middlewares import BaseMiddleware
from aiogram.types import Message
  1. Initialize the OpenAI API client and the Telegram bot with the API key obtained from BotFather:

openai.api_key = "YOUR_OPENAI_API_KEY"
# Initialize bot and dispatcher
bot = Bot(token=API_TOKEN)
dp = Dispatcher(bot)
  1. Define a function to handle user messages:

@dp.message_handler(commands='start')
async def cmd_start(message: Message):
    await message.answer("Hi there! I am Chat GPT bot owned by Sergei L. and  powered by OpenAI.")
  1. Define a function to handle user text messages and send them to the OpenAI API:

@dp.message_handler()
async def chat_bot(message: Message):
    text = message.text
    response = openai.Completion.create(
        engine="text-davinci-003",
        prompt=text,
        max_tokens=1024,
        n=1,
        stop=None,
        temperature=0.5,
    ).choices[0].text
    await bot.send_message(chat_id=message.chat.id, text=response)

if __name__ == '__main__':
    executor.start_polling(dp, skip_updates=True)
  1. Start the bot and make it listen for incoming messages by running "run.sh":

run.sh

--------------
#!/bin/sh

source .myenv/bin/activate
python chatGPT_telegram_bot.py 
if [ $? = 0 ]; then
  echo "Chatbot is running"
else
  echo "Something went wrong"
fi

Now the bot should be ready to receive questions from users and respond to them using the OpenAI API.

To run it in Docker we need to create Dockerfile and Docker image:

Create requirements and Dockerfile

pip freeze > requirements.txt

Put Dockerfile into the same directory with run.sh and chatGPT_telegram_bot.py ifles

NOTE: Make the file run.sh executable

$ sudo chmod +x run.sh

Dockerfile
____________
# Use an official Python runtime as the base image
FROM python:3.9-alpine

# Set the working directory in the container to /app
WORKDIR /home/app

RUN python -m venv .myenv 
# Copy the requirements.txt file to the container

COPY requirements.txt .

# Install required packages specified in the requirements.txt file
RUN source .myenv/bin/activate && pip install --upgrade pip &&\
 pip install --cache-dir .myenv/lib -r requirements.txt 

# Copy the contents of the current directory to the container
COPY . /home/app

# Specify the command to run the app when the container starts
CMD ["./run.sh" ]
```
#Create image "chatbot"
docker build -it chatbot .

# Run chatbot container as a deamon:
docker run -it -d chatbot

Last updated