chat_counter = user_data['chat_counter']
chatbot = user_data['chatbot']
client = user_data['client']
processing_message = await update.message.reply_text('Обрабатываю ваш запрос...')
try:
typing_task = context.application.create_task(send_typing_action(update, context))
result = await asyncio.to_thread(
client.predict,
user_input,
top_p=1,
temperature=1,
chat_counter=chat_counter,
chatbot=chatbot,
api_name="/predict"
)
typing_task.cancel()
chatbot = result[0]
chat_counter = result[1]
user_data['chatbot'] = chatbot
user_data['chat_counter'] = chat_counter
bot_reply = chatbot[-1][1]
soup = BeautifulSoup(bot_reply, 'html.parser')
for br in soup.find_all("br"):
br.replace_with("\n")
supported_tags = ['b', 'strong', 'i', 'em', 'u', 's', 'strike', 'del', 'span', 'a', 'code', 'pre']
for tag in soup.find_all():
if tag.name not in supported_tags:
tag.unwrap()
bot_reply = str(soup)
await processing_message.delete()
await update.message.reply_text(bot_reply, parse_mode='HTML')
except Exception as e:
typing_task.cancel()
await processing_message.delete()
await update.message.reply_text('Произошла ошибка при обработке вашего запроса.')
logging.error(f"Ошибка при обработке сообщения от пользователя {update.effective_user.id}: {e}")
import logging
import asyncio
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, ReplyKeyboardMarkup, KeyboardButton
from telegram.constants import ChatAction
from telegram.ext import (
ApplicationBuilder, ContextTypes,
CommandHandler, MessageHandler, CallbackQueryHandler, filters
)
from gradio_client import Client
from bs4 import BeautifulSoup
import config # Импортируем конфигурационный файл
# Включаем логирование
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO
)
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
keyboard = ReplyKeyboardMarkup(
[['/start', '/mode', '/reset']],
resize_keyboard=True
)
await update.message.reply_text(
'Привет! Я бот. Задавайте ваши вопросы. Вы можете выбрать модель с помощью команды /mode',
reply_markup=keyboard
)
async def mode(update: Update, context: ContextTypes.DEFAULT_TYPE):
keyboard = [[
InlineKeyboardButton("o1", callback_data='o1'),
InlineKeyboardButton("o1-mini", callback_data='o1-mini')
]]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text('Выберите нейросеть:', reply_markup=reply_markup)
async def button_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
query = update.callback_query
await query.answer()
selection = query.data
if selection == 'o1':
model_name = 'yuntian-deng/o1'
elif selection == 'o1-mini':
model_name = 'yuntian-deng/o1mini'
else:
model_name = 'yuntian-deng/o1'
context.user_data['model_name'] = model_name
context.user_data['client'] = Client(model_name)
context.user_data['chat_counter'] = 0
context.user_data['chatbot'] = []
await query.edit_message_text(text=f"Вы выбрали модель: {selection}")
async def send_typing_action(update: Update, context: ContextTypes.DEFAULT_TYPE):
while True:
await context.bot.send_chat_action(chat_id=update.effective_chat.id, action=ChatAction.TYPING)
await asyncio.sleep(2)
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_input = update.message.text
user_data = context.user_data
if 'chat_counter' not in user_data:
user_data['chat_counter'] = 0
if 'chatbot' not in user_data:
user_data['chatbot'] = []
if 'model_name' not in user_data:
user_data['model_name'] = 'yuntian-deng/o1'
if 'client' not in user_data:
user_data['client'] = Client(user_data['model_name'])
chat_counter = user_data['chat_counter']
chatbot = user_data['chatbot']
client = user_data['client']
keyboard = ReplyKeyboardMarkup(
[['/start', '/mode', '/reset']],
resize_keyboard=True
)
processing_message = await update.message.reply_text('Обрабатываю ваш запрос...')
try:
typing_task = context.application.create_task(send_typing_action(update, context))
result = await asyncio.to_thread(
client.predict,
user_input,
top_p=1,
temperature=1,
chat_counter=chat_counter,
chatbot=chatbot,
api_name="/predict"
)
typing_task.cancel()
chatbot = result[0]
chat_counter = result[1]
user_data['chatbot'] = chatbot
user_data['chat_counter'] = chat_counter
bot_reply = chatbot[-1][1]
soup = BeautifulSoup(bot_reply, 'html.parser')
for br in soup.find_all("br"):
br.replace_with("\n")
supported_tags = ['b', 'strong', 'i', 'em', 'u', 's', 'strike', 'del', 'span', 'a', 'code', 'pre']
for tag in soup.find_all():
if tag.name not in supported_tags:
tag.unwrap()
bot_reply = str(soup)
await processing_message.delete()
await update.message.reply_text(bot_reply, parse_mode='HTML', reply_markup=keyboard)
except Exception as e:
typing_task.cancel()
await processing_message.delete()
await update.message.reply_text('Произошла ошибка при обработке вашего запроса.', reply_markup=keyboard)
logging.error(f"Ошибка при обработке сообщения от пользователя {update.effective_user.id}: {e}")
async def reset(update: Update, context: ContextTypes.DEFAULT_TYPE):
model_name = context.user_data.get('model_name', 'yuntian-deng/o1')
client = context.user_data.get('client')
context.user_data.clear()
context.user_data['model_name'] = model_name
context.user_data['client'] = client
keyboard = ReplyKeyboardMarkup(
[['/start', '/mode', '/reset']],
resize_keyboard=True
)
await update.message.reply_text('Контекст успешно очищен.', reply_markup=keyboard)
def main():
TOKEN = config.TOKEN # Используем токен из config.py
if not TOKEN:
print("Необходимо установить переменную окружения TELEGRAM_BOT_TOKEN")
return
application = ApplicationBuilder().token(TOKEN).build()
application.add_handler(CommandHandler('start', start))
application.add_handler(CommandHandler('reset', reset))
application.add_handler(CommandHandler('mode', mode))
application.add_handler(CallbackQueryHandler(button_callback))
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
application.run_polling()
if __name__ == '__main__':
main()