Doc-opened.py for checking loaded/unloaded links but also shows nested links not in host model

i created this script to tell me when i open a project if i have closed/unloaded links. its sorta working. the first thing i run into is i will get the nested links also reported which aren’t in my host model. I’m still trying to get this to work a bit better to get closed/Not Loaded/not found but I figure i could ask how i could not include these nested links.

# -*- coding: utf-8 -*-
# pyRevit | IronPython 2.7
# Hook: doc-opened.py
# Alerts if any Revit links are unloaded, not found, or closed workset.

import clr, os
clr.AddReference("RevitAPI")

from Autodesk.Revit.DB import *
from pyrevit import forms

# Document comes from event args in doc-opened hook
doc = __eventargs__.Document

def is_project_template(document):
    """Detect if file is a project template (.rte)."""
    try:
        path = document.PathName
        return path and path.lower().endswith(".rte")
    except:
        return False

def get_element_name(elem):
    """Safe way to get element name."""
    try:
        return Element.Name.GetValue(elem)
    except:
        try:
            return elem.get_Parameter(BuiltInParameter.SYMBOL_NAME_PARAM).AsString()
        except:
            return "<Unnamed>"

def check_links():
    problem_links = []

    # --- Check RevitLinkTypes (unloaded or not found) ---
    link_types = FilteredElementCollector(doc).OfClass(RevitLinkType)
    for ltype in link_types:
        name = get_element_name(ltype)
        try:
            if not ltype.IsLoaded(doc):
                problem_links.append(name + "  [Unloaded]")
            else:
                ext_ref = ltype.GetExternalFileReference()
                if ext_ref and ext_ref.GetLinkedFileStatus() == LinkedFileStatus.NotFound:
                    problem_links.append(name + "  [Not Found]")
        except:
            #problem_links.append(name + "  [Error Checking Type]")
            pass

    # --- Check RevitLinkInstances (closed worksets) ---
    link_insts = FilteredElementCollector(doc).OfClass(RevitLinkInstance)
    for inst in link_insts:
        name = get_element_name(inst)
        try:
            if inst.GetLinkDocument() is None:
                problem_links.append(name + "  [Closed Workset?]")
        except:
            #problem_links.append(name + "  [Error Checking Instance]")
            pass

    # --- Show results ---
    if problem_links:
        msg = "Some Revit links are not active in this project.\n\nReview Manage Links:\n\n" + "\n".join(problem_links)
        forms.alert(msg, title="Link Status Alert", warn_icon=True)

# --- Run only for real projects (not families or templates) ---
if not doc.IsFamilyDocument and not is_project_template(doc):
    check_links()

pyRevit nativly loads clr and revitapi, so you only need “from pyrevit import DB”
This should point you in the right direction I think.

# -*- coding: utf-8 -*-
# doc-opened.py — runs automatically every time a model opens.
# Lists top-level Revit link TYPES and INSTANCES, with status tables.

from pyrevit import revit, DB, script

# --------------------------------------------------------------------------- #
# Get the document delivered by the event; fall back for safety when run
# manually from a push-button.
try:
    doc = __eventargs__.Document
except Exception:
    doc = revit.doc

# --------------------------------------------------------------------------- #
def is_project_template(d):
    try:
        return d.PathName.lower().endswith('.rte')
    except Exception:
        return False


def elem_name(e):
    try:
        return DB.Element.Name.GetValue(e)
    except Exception:
        try:
            return e.get_Parameter(DB.BuiltInParameter.SYMBOL_NAME_PARAM).AsString()
        except Exception:
            return '<Unnamed>'


def top_level(rvt_link_type):
    try:                       # Revit 2023+ property
        return not rvt_link_type.IsNestedLink
    except Exception:          # Pre-2023: assume top-level
        return True


def linktype_status(rvt_link_type):
    """Returns Loaded / Unloaded / Not Found without calling IsLoaded()."""
    ext = rvt_link_type.GetExternalFileReference()
    if not ext:
        return 'Unknown'
    status = ext.GetLinkedFileStatus()
    if status == DB.LinkedFileStatus.Loaded:
        return 'Loaded'
    if status == DB.LinkedFileStatus.Unloaded:
        return 'Unloaded'
    if status == DB.LinkedFileStatus.NotFound:
        return 'Not Found'
    return str(status)         # other enum cases (IncorrectVersion, etc.)


def collect_types(d):
    rows = []
    for lt in DB.FilteredElementCollector(d).OfClass(DB.RevitLinkType):
        if top_level(lt):
            rows.append([elem_name(lt), linktype_status(lt)])
    return rows


def collect_instances(d):
    rows = []
    for inst in DB.FilteredElementCollector(d).OfClass(DB.RevitLinkInstance):
        try:
            if not top_level(d.GetElement(inst.GetTypeId())):
                continue
        except Exception:
            continue
        status = 'Closed Workset' if inst.GetLinkDocument() is None else 'Loaded'
        rows.append([elem_name(inst), status])
    return rows

# --------------------------------------------------------------------------- #
if doc and not doc.IsFamilyDocument and not is_project_template(doc):
    type_rows      = collect_types(doc)
    instance_rows  = collect_instances(doc)

    out = script.get_output()
    out.set_title('Revit Link Status (Top-Level)')

    # ---------- Link TYPES table ----------
    out.print_md('### Revit Link **Types**')
    out.print_table(type_rows or [['(none)', '—']], columns=['Type Name', 'Status'])

    # ---------- Link INSTANCES table ----------
    out.print_md('\n### Revit Link **Instances**')
    out.print_table(instance_rows or [['(none)', '—']], columns=['Instance', 'Status'])