Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.9 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}")
        
        # Add message to chat history
        now = datetime.now()
        history_file = f"{HISTORY_FOLDER}/{message.chat.id}.txt"
        with open(history_file, 'a') as f:
            f.write(f"{now.strftime('%Y-%m-%d %H:%M:%S')} User {user_id}: {message.text}\n")
        
        # Send request to OpenAI API
        response = openai.Completion.create(
            engine=config["openai_engine"],
            prompt=message.text,
            max_tokens=config["openai_max_tokens"],
            temperature=config["openai_temperature"]
        )
        answer = response['choices'][0]['text'].strip()
        if answer:
            await message.answer(answer)
            
            # Add response to chat history
            with open(history_file, 'a') as f:
                f.write(f"{now.strftime('%Y-%m-%d %H:%M:%S')} ChatGPT {user_id}: {answer}\n")
        else:
            await message.answer("Я не смог найти ответ на ваш вопрос, попробуйте переформулировать вопрос.")
        print(f"Bot: {answer}")

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