We write a Telegram bot in Python using the ChatGPT API

This article is a free translation of an article into medium.complus the implementation of the ChatGPT API in the Telegram bot.

The topic of how to write a telegram bot is already quite trivial, there are a lot of articles on the Internet, so here I didn’t touch on this matter so deeply, I’ll post links to the source code below, it won’t be difficult to figure it out. The main motive for writing this article was the fact that ChatGPT is not available in a number of countries, including Russia, and we wanted to make it truly accessible to the public.

Ready/working telegram bot ChatGPT available here.

To the question “Who are you?” the neural network itself responds something like this: “I am ChatGPT, the largest language model created by OpenAI. I am designed for natural language processing and can help you answer questions, discuss topics, or provide information on various topics.”

In other words, in my subjective opinion, the neural network is sharpened primarily to support the conversation, ideally to show that a living person is sitting there, and not a trained AI model. Therefore, when you play with chat, do not forget about it, you should not expect reliable and accurate data from the chat, or deep meaning, now it is not about that, not yet about it.

So how to access the service ChatGPT from prohibited countries is written in an article on Habré, I want to draw your attention to the fact that you will first need to create a gmail mail with confirmation by SMS to a foreign phone number, then when registering on the ChatGPT website, also confirm the phone number by SMS, and these two phone numbers are not at all must be the same, so services for selling mobile phone numbers per SMS are quite suitable.

Package installation

First, install the required package in python:

# Install openai 
pip install openai 

# Import Library 
import openai  

You can read more about the OpenAI API in the documentation:

https://beta.openai.com/docs/api-reference/introduction

Getting an API key

You can generate an API key after registering on the site at:

https://beta.openai.com/account/api-keys

# Предоставляем ключ API 
openai.api_key = "Your_Key"

Choosing a trained model

We choose the trained model, namely “text-davinci-003”, it is the most powerful GPT-3 model and was trained on data until June 2021. You can find out more about the different models here:

https://beta.openai.com/docs/models/gpt-3

# Выбираем обученную модель
engine="text-davinci-003" 

Checking the Model

Let’s test the model! Let’s start by asking ChatGPT to name the best Python machine learning library:

# Запрос 
prompt = "Назови лучшую Python библиотеку по машинному обучению" 

# Модель 
completion = openai.Completion.create(engine=engine, 
                                      prompt=prompt, 
                                      temperature=0.5, 
                                      max_tokens=1000) 

The code above specifies to use the “text-davinci-003” model, with a temperature of 0.5. Temperature is a number between 0 and 1. A lower number means a more well-defined response, while a higher number allows the model to take on more risk. The response will look something like this:

# Выводим ответ 
print(completion)  

We display only the text of the answer:

# Печатаем только текст ответа
print( completion.choices[0]['text'] )
У меня был такой ответ:
Scikit-learn.

Go ahead! How about typing a question in the terminal and getting the answer there:

prompt = str(input())
completion = openai.Completion.create(engine=engine,
                                      prompt=prompt,
                                      temperature=0.5,
                                      max_tokens=1000)
                                      print('\nОтвет:')
print( completion.choices[0]['text'] )

Actually in the code above, after running, the script is waiting for data input due to the input () function. The answer will be received only after entering the request.

Wrapping code in a function

For convenience, let’s wrap the resulting Python code in a simple function:

# Функция для ChatGPT
def ask(prompt):
    completion = openai.Completion.create(engine="text-davinci-003", 
                                          prompt=prompt, 
                                          temperature=0.5, 
                                          max_tokens=1000)
    print( 'Вопрос:', prompt )
    print( '\nОтвет:' )
    print( completion.choices[0]['text'] )

Now all you have to do is write your question in the “ask()” function.

ask('самая красивая женщина на земле')
# Ответ
# На земле нет одной самой красивой женщины. Красота и прелесть относятся к индивидуальным вкусам и предпочтениям.

As you can see the ChatGPT API is easy to use, but be aware that the answers it gives are not always 100% correct.

We fasten the ChatGPT API to the telegram bot

Telegram bot sources posted in github repository.

To create a telegram bot, we need a token, which we can get from Bot Father. You can also set the name of the bot, image and description.

Clone the repository:

git clone git@github.com:ViktorAllayarov/ChatGPT_telegram_bot.git

# переходим в папку с проектом
cd ChatGPT_telegram_bot

Next, we create a local virtual environment:

python3 -m venv env
# или
py -3.10 -m venv env

Go to the virtual environment and update the pip package manager:

# для Linux/macOS
source env/bin/activate

для Windows
source env/scripts/activate

далее обновляем pip
python -m pip install --upgrade pip

устанавливаем все зависимости
pip install -r requirements.txt

The main.py file has a piece of code that pulls the environment variables using the library dotenv:

env = {
    **dotenv_values(".env.prod"),
    **dotenv_values(".env.dev"),  # override
}
openai.api_key = env["API_KEY_CHATGPT"]
bot = telebot.TeleBot(env["TG_BOT_TOKEN"])
db_link = env["DB_LINK"]

so we need to create a file .env.prod or .env.dev (or both files) and set the necessary variables there

# файл .env.prod
API ключ CHATGPT
API_KEY_CHATGPT=
# токен телеграм бота
TG_BOT_TOKEN=
# ссылка на БД SQLite3,
# файл базы создастся в корне проекта
# при первом запросе в боте
# база записывает всех пользователей, которые пользуются ботом
DB_LINK=db.db

Now you can run the project:

python main.py

I hope this article was interesting and useful, thanks for visiting it on this site.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *