Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
3.6 kB
1
Indexable
Never
import os
from datetime import datetime
from aiogram import Bot, types
from aiogram.dispatcher import Dispatcher
from aiogram.utils import executor
import openai
import json

# Set the current working directory to the directory of the script
os.chdir(os.path.dirname(os.path.abspath(__file__)))

# Load OpenAI API request config and Telegram token
with open("config.json") as f:
    config = json.load(f)
openai.api_key = config["openai_key"]
bot = Bot(token=config["telegram_token"])
dp = Dispatcher(bot)

# Create a folder for chat history
HISTORY_FOLDER = 'history'
if not os.path.exists(HISTORY_FOLDER):
    os.makedirs(HISTORY_FOLDER)

async def send_welcome(message: types.Message):
    keyboard = types.InlineKeyboardMarkup()
    author_button = types.InlineKeyboardButton(text="Автор", url="https://t.me/crap536")
    keyboard.add(author_button)
    await message.answer("Добро пожаловать в ChatGPT! Я являюсь языковой моделью, обученной OpenAI. Не стесняйтесь спрашивать меня о чем угодно, и я сделаю все возможное, чтобы дать полезный ответ.", reply_markup=keyboard)

@dp.message_handler(commands=['start'])
async def start_command_handler(message: types.Message):
    await send_welcome(message)

@dp.message_handler()
async def handle_message(message: types.Message):
    answer = ""
    if message.text:
        user_id = str(message.chat.id)[-1]  # Get the last digit of the user's id
        print(f"User: {message.chat.first_name} {message.chat.last_name}: {message.text}")

        # Load conversation history
        history_file = f"{HISTORY_FOLDER}/{message.chat.id}.txt"
        if os.path.exists(history_file):
            with open(history_file, 'r') as f:
                history = f.read().split('\n')
        else:
            history = []

        # Remove any empty lines
        history = list(filter(None, history))

        # Construct prompt from previous messages
        prompt = ""
        if len(history) > 0:
            prompt = '\n'.join(history[-3:])
            prompt += f"\nUser {user_id}: {message.text}\n"

        # Send request to OpenAI API
        response = openai.Completion.create(
            engine=config["openai_engine"],
            prompt=prompt,
            max_tokens=config["openai_max_tokens"],
            temperature=config["openai_temperature"]
        )
        answer = response['choices'][0]['text'].strip()

        # Remove any initial random words
        while answer and not answer[0].isalnum():
            answer = answer[1:]

        if answer and any(char in answer for char in ['.', '!', '?']):
            # Avoid answering questions generated by the model itself
            if answer.lower().startswith("bot:") or answer.lower().startswith("chatgpt:"):
                return

            await message.answer(answer)

            # Append bot's response to history
            history.append(f"{answer}")

        else:
            await message.answer("Я не смог найти ответ на ваш вопрос, попробуйте переформулировать вопрос.")

        # Save updated conversation history to file
        with open(history_file, 'w') as f:
            f.write('\n'.join(history))

        print(f"Bot: {answer}")

print(f"Бот успешно запущен!\n\nЛог сообщений:")
executor.start_polling(dp)