import re import logging from telegram import Update, ForceReply from telegram.ext…
- User
import re import logging from telegram import Update, ForceReply from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes, MessageHandler, filters from gradio_client import Client
Включение логирования
logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO ) logger = logging.getLogger(name)
Инициализация клиента Gradio
client = Client("yuntian-deng/o1")
Если ваш Space приватный, передайте ваш токен Hugging Face ниже
client = Client("yuntian-deng/o1mini", huggingface_token="ВАШ_HUGGING_FACE_TOKEN")
Словарь для хранения истории чатов для каждого пользователя
chat_histories = {}
Команда /start
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: user = update.effective_user await update.message.reply_html( rf"Привет, {user.mention_html()}! Я бот, который использует API для общения. Напиши мне что-нибудь!", reply_markup=ForceReply(selective=True), )
Обработка текстовых сообщений
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: user_id = update.effective_user.id user_message = update.message.text
# Получение истории чата пользователя или инициализация новой history = chat_histories.get(user_id, []) try: # Вызов API /predict result = client.predict( inputs=user_message, top_p=1, temperature=1, chat_counter=len(history), chatbot=history, api_name="/predict" ) # Разбор результата chatbot_output, chat_counter, status_code, reset_text = result # Извлечение последнего ответа бота if chatbot_output and len(chatbot_output) > 0: last_message = chatbot_output[-1] if isinstance(last_message, list) and len(last_message) == 2: bot_reply = last_message[1] else: bot_reply = "Произошла непредвиденная ошибка." else: bot_reply = "Произошла непредвиденная ошибка." # Обновление истории чата history.append((user_message, bot_reply)) chat_histories[user_id] = history # Отправка ответа пользователю # Замените эту строку в функции handle_message bot_reply = bot_reply.replace('<br/>', '\n') print(bot_reply) bot_reply = re.sub(r'\*\*(.*?)\*\*', r'<b>\1</b>', bot_reply) # Жирный текст bot_reply = re.sub(r'\*(.*?)\*', r'<i>\1</i>', bot_reply) # Наклонный текст bot_reply = re.sub(r'(.*?)', r'<s>\1</s>', bot_reply) # Зачеркнутый текст bot_reply = re.sub(r'<u>(.*?)</u>', r'<u>\1</u>', bot_reply) # Подчеркнутый текст bot_reply = re.sub(r'<a href="(.*?)">(.*?)</a>', r'<a href="\1">\2</a>', bot_reply) bot_reply = re.sub(r'<pre><code class="(.*?)">(.*?)</code></pre>', r'<pre><code>\2</code></pre>', bot_reply) # Код на любом языке bot_reply = re.sub(r'<code class="(.*?)>(.*?)</code>', r'<code>\2</code>', bot_reply) # Код на любом языке без <pre> await update.message.reply_text(bot_reply, parse_mode='HTML') except Exception as e: logger.error(f"Ошибка при обработке сообщения: {e}") await update.message.reply_text("Извините, произошла ошибка при обработке вашего запроса.", parse_mode='HTML') - Assistant