Найти в Дзене
Хак Аноним

Как создать своего бота ChatGPT в Telegram

Чтобы создать бота с нейросетью ChatGPT в Telegram, нам понадобится:

1. Создать бота в https://t.me/BotFather

2. Api ключ openai https://platform.openai.com/overview

3. Python https://www.python.org/downloads/

4. VScode https://code.visualstudio.com/

5. Установить библиотеки:

pip3 install openai

pip3 install aiogram

6. После установки библиотек переходим к настройке скрипта, заходим в наш .py файл и находим строчку с "openai.api_key = "key"", в строчке "openai.api_key = "key"" вместо "key" вставляем токен «OpenAI», в строчке bot = Bot(token="token")" вместо "token" вставляем токен нашего бота из BotFather.

Код ниже, можно скачать файл по ссылке

import os
import logging
from aiogram import Bot, Dispatcher, types
from aiogram.utils import executor
import openai
logging.basicConfig(level=logging.INFO)
openai.api_key = ""
bot = Bot(token="")
dp = Dispatcher(bot)
if not os.path.exists("users"):
os.mkdir("users")
@dp.message_handler(content_types=types.ContentType.TEXT)
async def process_message(message: types.Message):
if f"{message.chat.id}.txt" not in os.listdir("users"):
with open(f"users/{message.chat.id}.txt", "x") as f:
f.write("")
with open(f"users/{message.chat.id}.txt", "r", encoding="utf-8") as file:
oldmes = file.read()
if message.text == "/clear":
with open(f"users/{message.chat.id}.txt", "w", encoding="utf-8") as file:
file.write("")
return await bot.send_message(chat_id=message.chat.id, text="История очищена!")
try:
send_message = await bot.send_message(chat_id=message.chat.id, text="Обрабатываю запрос, пожалуйста подождите!")
completion = openai.Completion.create(
model="text-davinci-003",
prompt=message.text,
temperature=0.9,
max_tokens=1000,
top_p=1.0,
frequency_penalty=0.0,
presence_penalty=0.6,
stop=["You:"]
)
await bot.edit_message_text(
text=completion.choices[0].text,
chat_id=message.chat.id,
message_id=send_message.message_id,
)
with open(f"users/{message.chat.id}.txt", "a+", encoding="utf-8") as file:
file.write(
message.text.replace("\n", " ")
+ "\n"
+ completion.choices[0].text.replace("\n", " ")
+ "\n"
)
with open(f"users/{message.chat.id}.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
except Exception as e:
await bot.send_message(chat_id=message.chat.id, text=str(e))
if __name__ == "__main__":
executor.start_polling(dp, skip_updates=True)