It seems that this script checked if the thread is archived only at the beginning of the script, could you make the archived check to always happens at the same time with the Checking posts for replies? here's the script:

import time
import requests
import smtplib
import re
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.utils import make_msgid

def get_thread_posts(board, thread_id):
    url = f"https://a.4cdn.org/{board}/thread/{thread_id}.json"
    response = requests.get(url)
    if response.status_code == 200:
        data = response.json()
        return data["posts"]
    return None

def send_email(subject, message, sender_email, recipient_email, image_bytes=None, image_name=None):
    msg = MIMEMultipart()
    msg["From"] = sender_email
    msg["To"] = recipient_email
    msg["Subject"] = subject

    msg.attach(MIMEText(message, "plain"))

    if image_bytes and image_name:
        image = MIMEImage(image_bytes, name=image_name)
        MSGID = make_msgid()
        image.add_header('Content-Disposition', 'inline', filename=image_name)
        image.add_header('Content-ID', '<{}>'.format(MSGID[1:-1]))
        msg.attach(image)

    with smtplib.SMTP("smtp.gmail.com", 587) as server:
        server.starttls()
        server.login(sender_email, sender_password) # Enter your email password here
        text = msg.as_string()
        server.sendmail(sender_email, recipient_email, text)

def notify(reply_count, post, board, thread_id, recipient_email):
    post_image_name = None
    image_bytes = None  # Add this line to fix the UnboundLocalError
    if 'tim' in post and 'ext' in post:
        post_image_name = f"{post['tim']}{post['ext']}"
        image_url = f"https://i.4cdn.org/{board}/{post_image_name}"
        image_bytes = requests.get(image_url).content
    
    post_content = post.get('com', 'No content').replace('<br>', '\n')
    post_content = re.sub('<a.*?>(.*?)</a>', r'\1', post_content)
    post_content = re.sub('<span.*?>(.*?)</span>', r'\1', post_content)
    post_content = re.sub('<[^<]+?>', '', post_content)
    post_content = post_content.strip()
    post_content = post_content.replace('&gt;', '>')
    post_content = post_content.replace('&#039;', "'")
    post_content = post_content.replace('&quot;', '"')
    post_link = f"https://boards.4channel.org/{board}/thread/{thread_id}#p{post['no']}"
    post_header = f"Post with {reply_count} replies ({post_link}):"
    message = f"{post_header}\n\n{post_content}"
    
    if post_image_name:
        message += f"\n\nSee image in the email or at the following link: {image_url}"
    
    send_email("4chan Post Notifier", message, sender_email, recipient_email, image_bytes, post_image_name) # Enter your email here as the sender_email

def count_replies(posts):
    reply_count = {}
    for post in posts:
        com = post.get("com", "")
        hrefs = post.get("com", "").split('href="#p')
        for href in hrefs[1:]:
            num = int(href.split('"')[0])
            if num in reply_count:
                reply_count[num] += 1
            else:
                reply_count[num] = 1
    return reply_count

def monitor_thread(board, thread_id, min_replies, delay, recipient_email, keyword):
    seen_posts = set()
    print(f"Monitoring thread {board}/{thread_id} every {delay} seconds…")
    tries = 0
    while True:
        posts = get_thread_posts(board, thread_id)
        if posts:
            print("Checking posts for replies…")
            reply_count = count_replies(posts)
            for post in posts:
                post_id = post['no']
                replies = reply_count.get(post_id, 0)

                if replies >= min_replies and post_id not in seen_posts:
                    print(f"Found post with {replies} replies. Sending notification…")
                    notify(replies, post, board, thread_id, recipient_email)
                    seen_posts.add(post_id)

            # Check if the thread is archived
            is_archived = any(post.get('archived') for post in posts)
            if is_archived:
                print(f"Thread {board}/{thread_id} is archived. Checking catalog for {keyword} thread and switching to the newest one…")
                latest_thread = get_latest_thread(board, keyword)
                if latest_thread:
                    thread_id = latest_thread
                    tries = 0
                else:
                    tries += 1
                    print(f"No {keyword} thread found in the catalog. Retrying ({tries}/5)…")
                    if tries >= 5:
                        print("No {keyword} thread found after 5 tries. Exiting in 1 minute…")
                        time.sleep(60)
                        if not msvcrt.kbhit():
                            return

        time.sleep(delay)

def get_latest_thread(board, keyword):
    url = f"https://a.4cdn.org/{board}/catalog.json"
    response = requests.get(url)
    if response.status_code == 200:
        data = response.json()
        threads = []
        for page in data:
            for thread in page['threads']:
                if thread.get('sub') and keyword.lower() in thread['sub'].lower():
                    threads.append(thread)
        if threads:
            latest_thread = max(threads, key=lambda t: t['last_modified'])
            return latest_thread['no']
    return None

if __name__ == "__main__":
    BOARD = input("Enter the board to monitor (e.g. g, b): ")
    THREAD_ID = input("Enter thread ID to monitor: ")
    MIN_REPLIES = int(input("Enter minimum replies for notification: "))
    DELAY = int(input("Enter delay time in minutes: ")) * 60
    sender_email = input("Enter email address to send notifications: ")
    sender_password = input("Enter the sender email password (if you encountered error with authentication use this https://support.google.com/accounts/answer/185833?hl=en): ")
    recipient_email = input("Enter email address to receive notifications: ")
    KEYWORD = input("Enter the keyword to search for in thread subjects (e.g. aicg, bocchi): ")
    monitor_thread(BOARD, THREAD_ID, MIN_REPLIES, DELAY, recipient_email, KEYWORD)