Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0314· openaiHugging Face Suzhen/CodeChat

I have this code, and when I run it, it gives me error: [code] [code]

  1. User

    I have this code, and when I run it, it gives me error:

    import json
    import time
    from datetime import datetime, timedelta
    from telegram import Update
    from telegram.ext import Updater, MessageHandler, Filters, CallbackContext
    
    TOKEN = "1935475560:AAEAOFvw10Jm_FHbqjnaLP5zuAKhsEFSDrA"
    SUPPORT_CHANNEL_ID = "-1001818078966"
    SUPPORT_TEAM_FILE = 'teammates.json'
    
    def load_support_teammates(file):
        with open(file, 'r') as f:
            teammates = json.load(f)
        return teammates
    
    SUPPORT_TEAM = load_support_teammates(SUPPORT_TEAM_FILE)
    
    def is_question(text):
        question_keywords = ['?', 'how', 'what', 'when', 'where', 'which', 'who', 'why']
        return any(keyword in text.lower() for keyword in question_keywords)
    
    def handle_messages(update: Update, context: CallbackContext):
        if update.message.document and update.message.document.file_name.endswith(('.zip.enc', '.zip', '.enc')) or is_question(update.message.text):
            if update.message.from_user.id not in SUPPORT_TEAM:
                context.chat_data.setdefault('questions', {})
                context.chat_data['questions'][update.message.message_id] = {
                    'created_at': update.message.date,
                    'is_resolved': False,
                }
    
        elif update.message.from_user.id in SUPPORT_TEAM:
            for question_id in context.chat_data.get('questions', {}):
                context.chat_data['questions'][question_id]['is_resolved'] = True
        else:
            pass
    
    def periodic_check_questions(context: CallbackContext):
        now = datetime.utcnow()
    
        for chat_data in context.chat_data.values():
            if 'questions' not in chat_data:
                continue
    
            for message_id, question_data in chat_data['questions'].items():
                if question_data['is_resolved']:
                    continue
    
                created_at = question_data['created_at']
                waiting_time = now - created_at
    
                if waiting_time >= timedelta(minutes=3):
                    chat = context.bot.get_chat(chat_id)
                    message = chat.get_message(message_id)
                    text = f'Group: {chat.title}\nWaiting Time: {waiting_time}\nOriginal Message:\n{message.text}'
                    context.bot.send_message(SUPPORT_CHANNEL_ID, text=text)
                    chat_data['questions'][message_id]['is_resolved'] = True
    
    def main():
        updater = Updater(token=TOKEN, use_context=True)
        dp = updater.dispatcher
    
        # Initialize chat_data in the context
        dp.chat_data['questions'] = {}
    
        dp.add_handler(MessageHandler(Filters.all, handle_messages))
        dp.job_queue.run_repeating(periodic_check_questions, interval=3, first=0)
    
        updater.start_polling()
        updater.idle()
    
    if __name__ == "__main__":
        main()
    
    No error handlers are registered, logging exception.
    Traceback (most recent call last):
      File "/usr/local/lib/python3.10/dist-packages/apscheduler/executors/base.py", line 125, in run_job
        retval = job.func(*job.args, **job.kwargs)
      File "/home/bot/sandbox/sandbox.py", line 40, in periodic_check_questions
        for chat_data in context.chat_data.values():
    AttributeError: 'NoneType' object has no attribute 'values'
    
  2. Assistant

    The error occurs because the context.chat_data.values() part of the code is dealing with a NoneType object. Instead of iterating through the context.chat_data, you should iterate through the context.dispatcher.chat_data. Replace the periodic_check_questions function with the following:

    def periodic_check_questions(context: CallbackContext):
        now = datetime.utcnow()
    
        for chat_id, chat_data in context.dispatcher.chat_data.items():
            if 'questions' not in chat_data:
                continue
    
            for message_id, question_data in chat_data['questions'].items():
                if question_data['is_resolved']:
                    continue
    
                created_at = question_data['created_at']
                waiting_time = now - created_at
    
                if waiting_time >= timedelta(minutes=3):
                    chat = context.bot.get_chat(chat_id)
                    message = chat.get_message(message_id)
                    text = f'Group: {chat.title}\nWaiting Time: {waiting_time}\nOriginal Message:\n{message.text}'
                    context.bot.send_message(SUPPORT_CHANNEL_ID, text=text)
                    chat_data['questions'][message_id]['is_resolved'] = True
    

    Make sure you update the job queue to run every 3 minutes (180 seconds) instead of every 3 seconds:

    dp.job_queue.run_repeating(periodic_check_questions, interval=180, first=0)
    

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.