Skip to content
The Chat Archive
gpt-4o-2024-05-13· OpenAI WildChat-4.8M (AI2)

добаввь после ответа от ии инлайн кнопку с помощью который можно остановить работу ии,…

  1. User

    добаввь после ответа от ии инлайн кнопку с помощью который можно остановить работу ии, сделай так, чтобы ии был активин и его можно было с помощью инлайн кнопки отключить после команды /ai, я пишу другую команду но мне отвечает ии, так быть не должно

    import asyncio import telebot from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton from g4f.client import Client import time import requests from yandex_tts_free import YandexFreeTTS import os import shutil import logging

    Настройка логирования

    logging.basicConfig(level=logging.INFO) logger = logging.getLogger(name)

    Установка event loop policy

    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

    client_dict = {} bot = telebot.TeleBot("7327876070:AAHRwkLKchUuVZi2piVf5fDGX4zDhc9pF3Q")

    Доступные модели

    MODELS = ["llama-3-70b", "claude-3-haiku", "Yi-1.5-34B-Chat", "command-r+", "mixtral-8x7b"]

    Доступные голоса

    VOICES = ["oksana", "jane", "alyss", "omazh"]

    Define a name for the logger

    logger_name = "my_bot_logger"

    def create_model_selection_markup(): markup = InlineKeyboardMarkup() for model in MODELS: markup.add(InlineKeyboardButton(model, callback_data=f"model_{model}")) return markup

    def create_voice_selection_markup(): markup = InlineKeyboardMarkup() for voice in VOICES: markup.add(InlineKeyboardButton(voice, callback_data=f"voice_{voice}")) return markup

    @bot.message_handler(commands=['ai']) def send_welcome(message): bot.reply_to(message, "Привет! 👋 Выбери модель ИИ, с которой хочешь общаться:", reply_markup=create_model_selection_markup()) if message.chat.id not in client_dict: client_dict[message.chat.id] = {'client': Client(), 'model': None, 'voice': 'oksana'}

    @bot.callback_query_handler(func=lambda call: True) def handle_callback_query(call): data = call.data.split('_') if data[0] == 'model': client_dict[call.message.chat.id]['model'] = data[1] bot.send_message(call.message.chat.id, f"Модель {data[1]} выбрана! 🤖 Теперь выбери голос для синтеза речи:", reply_markup=create_voice_selection_markup()) elif data[0] == 'voice': client_dict[call.message.chat.id]['voice'] = data[1] bot.send_message(call.message.chat.id, f"Голос {data[1]} выбран! 🎙 Отправь сообщение, чтобы получить ответ от ИИ.")

    @bot.message_handler(func=lambda message: True) def handle_message(message): client_info = client_dict[message.chat.id] client = client_info['client'] model = client_info['model'] voice = client_info['voice']

    start_time = time.time()
    bot.send_message(message.chat.id, "Генерирую ответ на ваш запрос… 🤔")
    
    response = None
    MAX_RETRIES = 3
    retries = 0
    while retries < MAX_RETRIES:
        try:
            response = client.chat.completions.create(
                model=model,
                messages=[{"role": "user", "content": message.text}],
            )
            break
        except requests.exceptions.ConnectionError:
            retries += 1
            logger.error(f"Ошибка соединения. Попытка {retries}/{MAX_RETRIES} 📡")
            time.sleep(5)  # Ждем 5 секунд перед следующей попыткой
        except Exception as e:
            logger.exception(f"Произошла ошибка: {str(e)}")
            bot.reply_to(message, "Извините, произошла ошибка при обработке вашего запроса. Попробуйте еще раз. 😓")
            return
    
    if response is None:
        bot.reply_to(message, "Не удалось получить ответ от модели после нескольких попыток. Пожалуйста, попробуйте позже. 😓")
        return
    
    end_time = time.time()
    execution_time = end_time - start_time
    output_text = response.choices[0].message.content
    
    # Оповещение пользователя о времени выполнения и модели
    bot.send_message(message.chat.id, f"Запрос занял {execution_time:.2f} секунд. Ответ предоставлен моделью {model}. ⏱")
    bot.reply_to(message, output_text)
    
    # Генерация речи с выбранным голосом
    output_path = f'output{message.chat.id}'
    if not os.path.exists(output_path):
        os.makedirs(output_path)
    audio_file = os.path.join(output_path, 'output.mp3')
    
    tts = YandexFreeTTS()
    try:
        tts.generate_speech_ya(output_path, 'output.mp3', output_text, voice)
        
        # Отправка аудиофайла пользователю
        with open(audio_file, 'rb') as audio:
            bot.send_audio(message.chat.id, audio)
        
        # Удаление аудиофайла и папки после отправки
        shutil.rmtree(output_path)
    except Exception as e:
        logger.exception(f"Ошибка при генерации речи: {str(e)}")
        bot.reply_to(message, "Произошла ошибка при синтезе речи. Попробуйте еще раз. 😓")
    
  2. Assistant

    Для того чтобы добавить функционал остановки ИИ после ответа и сделать так, чтобы ИИ был активен и его можно было отключить после команды /ai, необходимо внести изменения в код.

    Вот обновленный пример с добавлением инлайн кнопки для остановки ИИ и логики активации/деактивации ИИ:

    import asyncio
    import telebot
    from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton
    from g4f.client import Client
    import time
    import requests
    from yandex_tts_free import YandexFreeTTS
    import os
    import shutil
    import logging
    
    # Настройка логирования
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)
    
    # Установка event loop policy
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
    
    client_dict = {}
    bot = telebot.TeleBot("YOUR_BOT_TOKEN_HERE")
    
    # Доступные модели
    MODELS = ["llama-3-70b", "claude-3-haiku", "Yi-1.5-34B-Chat", "command-r+", "mixtral-8x7b"]
    
    # Доступные голоса
    VOICES = ["oksana", "jane", "alyss", "omazh"]
    
    # Define a name for the logger
    logger_name = "my_bot_logger"
    
    def create_model_selection_markup():
        markup = InlineKeyboardMarkup()
        for model in MODELS:
            markup.add(InlineKeyboardButton(model, callback_data=f"model_{model}"))
        return markup
        
    def create_voice_selection_markup():
        markup = InlineKeyboardMarkup()
        for voice in VOICES:
            markup.add(InlineKeyboardButton(voice, callback_data=f"voice_{voice}"))
        return markup
    
    def create_stop_ai_markup():
        markup = InlineKeyboardMarkup()
        markup.add(InlineKeyboardButton("🛑 Остановить ИИ", callback_data="stop_ai"))
        return markup
    
    @bot.message_handler(commands=['ai'])
    def send_welcome(message):
        bot.reply_to(message, "Привет! 👋 Выбери модель ИИ, с которой хочешь общаться:", reply_markup=create_model_selection_markup())
        if message.chat.id not in client_dict:
            client_dict[message.chat.id] = {'client': Client(), 'model': None, 'voice': 'oksana', 'ai_active': True}
    
    @bot.callback_query_handler(func=lambda call: True)
    def handle_callback_query(call):
        data = call.data.split('_')
        if data[0] == 'model':
            client_dict[call.message.chat.id]['model'] = data[1]
            bot.send_message(call.message.chat.id, f"Модель {data[1]} выбрана! 🤖 Теперь выбери голос для синтеза речи:", reply_markup=create_voice_selection_markup())
        elif data[0] == 'voice':
            client_dict[call.message.chat.id]['voice'] = data[1]
            bot.send_message(call.message.chat.id, f"Голос {data[1]} выбран! 🎙 Отправь сообщение, чтобы получить ответ от ИИ.")
        elif data[0] == 'stop_ai':
            client_dict[call.message.chat.id]['ai_active'] = False
            bot.send_message(call.message.chat.id, "ИИ остановлен. 🛑")
    
    @bot.message_handler(func=lambda message: True)
    def handle_message(message):
        if message.chat.id not in client_dict or not client_dict[message.chat.id].get('ai_active', False):
            return
        
        client_info = client_dict[message.chat.id]
        client = client_info['client']
        model = client_info['model']
        voice = client_info['voice']
        
        start_time = time.time()
        bot.send_message(message.chat.id, "Генерирую ответ на ваш запрос… 🤔")
        
        response = None
        MAX_RETRIES = 3
        retries = 0
        while retries < MAX_RETRIES:
            try:
                response = client.chat.completions.create(
                    model=model,
                    messages=[{"role": "user", "content": message.text}],
                )
                break
            except requests.exceptions.ConnectionError:
                retries += 1
                logger.error(f"Ошибка соединения. Попытка {retries}/{MAX_RETRIES} 📡")
                time.sleep(5)  # Ждем 5 секунд перед следующей попыткой
            except Exception as e:
                logger.exception(f"Произошла ошибка: {str(e)}")
                bot.reply_to(message, "Извините, произошла ошибка при обработке вашего запроса. Попробуйте еще раз. 😓")
                return
        
        if response is None:
            bot.reply_to(message, "Не удалось получить ответ от модели после нескольких попыток. Пожалуйста, попробуйте позже. 😓")
            return
        
        end_time = time.time()
        execution_time = end_time - start_time
        output_text = response.choices[0].message.content
        
        # Оповещение пользователя о времени выполнения и модели
        bot.send_message(message.chat.id, f"Запрос занял {execution_time:.2f} секунд. Ответ предоставлен моделью {model}. ⏱")
        bot.reply_to(message, output_text, reply_markup=create_stop_ai_markup())
        
        # Генерация речи с выбранным голосом
        output_path = f'output{message.chat.id}'
        if not os.path.exists(output_path):
            os.makedirs(output_path)
        audio_file = os.path.join(output_path, 'output.mp3')
        
        tts = YandexFreeTTS()
        try:
            tts.generate_speech_ya(output_path, 'output.mp3', output_text, voice)
            
            # Отправка аудиофайла пользователю
            with open(audio_file, 'rb') as audio:
                bot.send_audio(message.chat.id, audio)
            
            # Удаление аудиофайла и папки после отправки
            shutil.rmtree(output_path)
        except Exception as e:
            logger.exception(f"Ошибка при генерации речи: {str(e)}")
            bot.reply_to(message, "Произошла ошибка при синтезе речи. Попробуйте еще раз. 😓")
    
    bot.polling()
    

    Изменения:

    1. Добавлена функция create_stop_ai_markup() для создания инлайн кнопки остановки ИИ.
    2. Добавлена обработка callback_data stop_ai в функции handle_callback_query, которая устанавливает флаг ai_active в False.
    3. Обновлена функция handle_message для проверки, активен ли ИИ для текущего чата.
    4. Добавлена инлайн кнопка остановки ИИ к ответному сообщению ИИ с помощью параметра reply_markup в методе bot.reply_to.

    Теперь ИИ будет активироваться после команды /ai, и его можно будет остановить с помощью инлайн кнопки "🛑 Остановить ИИ". Только активный ИИ будет отвечать на сообщения.