Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

can you make this like if the user input text is too long it will say please put it on a…

  1. User

    can you make this like if the user input text is too long it will say please put it on a file and send it then ill read it then if the user sent the file it will download it then read it then it will be the prompt inshort import telebot from gradio_client import Client import os import logging

    TELEGRAM_BOT_TOKEN = '7280791264:AAFZL8tY_ySd4ueDa3b0e1QO8nHgCRkWzBA'

    logging.basicConfig(level=logging.INFO) bot = telebot.TeleBot(TELEGRAM_BOT_TOKEN) client = Client('https://yuntian-deng-o1.hf.space/')

    @bot.message_handler(func=lambda message: True) def handle_message(message): user_input = message.text chat_id = message.chat.id username = message.from_user.username or message.from_user.first_name

    logging.info(f"Received message from {username}: {user_input}")
    bot.send_chat_action(chat_id, 'typing')
    
    try:
        result = client.predict(user_input, api_name="/predict")
        
        # Extract just the AI's response from the result
        if isinstance(result, tuple) and len(result) >= 1:
            conversation = result[0]  # Get the conversation list
            if isinstance(conversation, list) and len(conversation) > 0:
                last_exchange = conversation[-1]  # Get the last exchange
                if isinstance(last_exchange, list) and len(last_exchange) == 2:
                    output_text = last_exchange[1]  # Get just the AI's response
                else:
                    output_text = str(last_exchange)
            else:
                output_text = str(conversation)
        else:
            output_text = str(result)
    
        if len(output_text) < 4000:
            bot.send_message(chat_id, output_text)
            logging.info(f"Sent message to {username}: {output_text}")
        else:
            filename = 'output.txt'
            with open(filename, 'w', encoding='utf-8') as f:
                f.write(output_text)
            with open(filename, 'rb') as f:
                bot.send_document(chat_id, f)
                logging.info(f"Sent document to {username}: {filename}")
            os.remove(filename)
    
    except Exception as e:
        error_message = f"An error occurred: {e}"
        bot.send_message(chat_id, error_message)
        logging.error(f"Error occurred for {username}: {e}")
    

    if name == "main": logging.info("Starting the bot...") bot.polling()

  2. Assistant

    Certainly! I've modified your Telegram bot code to implement the requested functionality. Now, if a user sends a text message that is too long, the bot will ask them to put the content into a file and send it. When the user sends a file, the bot will download it, read the content, and use it as the prompt.

    Please note that for security reasons, it's recommended not to hardcode your bot token in the source code. Instead, you can use environment variables or a configuration file to store sensitive information.

    Here's the updated code:

    import telebot
    from gradio_client import Client
    import os
    import logging
    
    # Replace 'your-bot-token-here' with your actual Telegram bot token
    TELEGRAM_BOT_TOKEN = 'your-bot-token-here'
    
    logging.basicConfig(level=logging.INFO)
    bot = telebot.TeleBot(TELEGRAM_BOT_TOKEN)
    client = Client('https://yuntian-deng-o1.hf.space/')
    
    MAX_TEXT_LENGTH = 4000  # Set the maximum allowed length for text messages
    
    @bot.message_handler(content_types=['text'])
    def handle_message(message):
        user_input = message.text
        chat_id = message.chat.id
        username = message.from_user.username or message.from_user.first_name
    
        logging.info(f"Received message from {username}: {user_input}")
    
        if len(user_input) > MAX_TEXT_LENGTH:
            bot.send_message(chat_id, "Your message is too long. Please put it into a file and send it to me.")
            return
    
        bot.send_chat_action(chat_id, 'typing')
    
        try:
            result = client.predict(user_input, api_name="/predict")
            output_text = extract_ai_response(result)
    
            send_response(chat_id, username, output_text)
    
        except Exception as e:
            handle_error(chat_id, username, e)
    
    @bot.message_handler(content_types=['document'])
    def handle_document(message):
        chat_id = message.chat.id
        username = message.from_user.username or message.from_user.first_name
        file_name = message.document.file_name
    
        logging.info(f"Received file from {username}: {file_name}")
    
        try:
            file_info = bot.get_file(message.document.file_id)
            downloaded_file = bot.download_file(file_info.file_path)
    
            # Assuming the file is a text file in UTF-8 encoding
            file_content = downloaded_file.decode('utf-8')
    
            bot.send_chat_action(chat_id, 'typing')
    
            # Process the file content as the user input
            user_input = file_content
            result = client.predict(user_input, api_name="/predict")
            output_text = extract_ai_response(result)
    
            send_response(chat_id, username, output_text)
    
        except Exception as e:
            handle_error(chat_id, username, e)
    
    def extract_ai_response(result):
        """
        Extracts the AI's response from the result returned by the client.predict method.
        """
        if isinstance(result, tuple) and len(result) >= 1:
            conversation = result[0]  # Get the conversation list
            if isinstance(conversation, list) and len(conversation) > 0:
                last_exchange = conversation[-1]  # Get the last exchange
                if isinstance(last_exchange, list) and len(last_exchange) == 2:
                    output_text = last_exchange[1]  # Get just the AI's response
                else:
                    output_text = str(last_exchange)
            else:
                output_text = str(conversation)
        else:
            output_text = str(result)
        return output_text
    
    def send_response(chat_id, username, output_text):
        """
        Sends the AI's response to the user, either as a message or a document if it's too long.
        """
        if len(output_text) < 4000:
            bot.send_message(chat_id, output_text)
            logging.info(f"Sent message to {username}: {output_text}")
        else:
            filename = 'output.txt'
            with open(filename, 'w', encoding='utf-8') as f:
                f.write(output_text)
            with open(filename, 'rb') as f:
                bot.send_document(chat_id, f)
                logging.info(f"Sent document to {username}: {filename}")
            os.remove(filename)
    
    def handle_error(chat_id, username, error):
        """
        Handles exceptions by sending an error message to the user and logging the error.
        """
        error_message = f"An error occurred: {error}"
        bot.send_message(chat_id, error_message)
        logging.error(f"Error occurred for {username}: {error}")
    
    if __name__ == "__main__":
        logging.info("Starting the bot...")
        bot.polling()
    

    Notes and Recommendations:

    • Security Best Practices: It's important to keep your TELEGRAM_BOT_TOKEN secure. Instead of hardcoding it in your script, consider using an environment variable:

      import os
      TELEGRAM_BOT_TOKEN = os.getenv('TELEGRAM_BOT_TOKEN')
      

      Then, set the environment variable in your deployment environment or before running the script:

      export TELEGRAM_BOT_TOKEN='your-actual-bot-token'
      
    • File Handling: The handle_document function assumes that the user is sending a text file encoded in UTF-8. If you expect other file types or encodings, you'll need to adjust the file reading logic accordingly.

    • Error Handling: The handle_error function centralizes error messaging and logging, improving code readability and maintainability.

    • Code Organization: Functions like extract_ai_response, send_response, and handle_error help keep the code clean and modular.

    • Message Length Threshold: The MAX_TEXT_LENGTH variable sets the threshold for the maximum allowed message length. You can adjust this value based on your requirements.

    Explanation of Changes:

    1. Handling Long Text Messages:

      • In the handle_message function, we added a check for the length of the user_input. If it exceeds MAX_TEXT_LENGTH, the bot prompts the user to send the content as a file instead.
      if len(user_input) > MAX_TEXT_LENGTH:
          bot.send_message(chat_id, "Your message is too long. Please put it into a file and send it to me.")
          return
      
    2. Handling File Messages:

      • We introduced a new handler, handle_document, to process files sent by the user.
      @bot.message_handler(content_types=['document'])
      def handle_document(message):
          # Process the file content
      
      • The bot downloads the file, decodes it (assuming UTF-8 encoding), and uses the content as the prompt for the AI model.
    3. Modular Functions:

      • extract_ai_response: This function processes the result from client.predict to extract the AI's response.
      • send_response: Handles sending the response back to the user, either as a text message or as a file if the response is too long.
      • handle_error: Centralizes error handling to keep the code clean.
    4. Code Improvements:

      • Updated the if __name__ == "__main__": condition to correctly start the bot.
      • Added logging statements to track the bot's activity and assist with debugging.

    Usage:

    • Running the Bot:

      • Ensure all required packages are installed:

        pip install pyTelegramBotAPI gradio_client
        
      • Set your Telegram bot token securely, preferably using an environment variable.

      • Run the script:

        python your_bot_script.py
        
    • Interacting with the Bot:

      • Send a text message. If it's longer than the allowed length, the bot will prompt you to send it as a file.
      • Send a text file with your content. The bot will process it and send back the response.

    Let me know if you have any questions or need further assistance!