Files
cbcren2026/list_notion_pages.py
2026-03-31 01:28:25 -03:00

135 lines
4.8 KiB
Python

#!/usr/bin/env python3
"""
Script para listar todas las páginas y bases de datos accesibles
"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent))
from config import settings
from notion_client import Client
def main():
print("\n" + "=" * 70)
print("📚 LISTANDO TODAS LAS PÁGINAS Y BASES DE DATOS")
print("=" * 70 + "\n")
token = settings.NOTION_API_TOKEN
client = Client(auth=token)
try:
# Buscar todas las páginas sin filtro
print("🔍 Buscando todas las páginas accesibles...\n")
results = client.search(page_size=100)
all_items = results.get("results", [])
# Separar bases de datos y páginas
databases = [item for item in all_items if item.get("object") == "database"]
pages = [item for item in all_items if item.get("object") == "page"]
print(
f"✅ Encontrados: {len(databases)} base(s) de datos y {len(pages)} página(s)\n"
)
if databases:
print("=" * 70)
print("📊 BASES DE DATOS ENCONTRADAS:")
print("=" * 70)
for i, db in enumerate(databases, 1):
db_id = db.get("id", "N/A")
title_list = db.get("title", [])
title = (
title_list[0].get("plain_text", "Sin título")
if title_list
else "Sin título"
)
print(f"\n🔷 {i}. {title}")
print(f" ID: {db_id}")
print(f" URL: https://notion.so/{db_id.replace('-', '')}")
# Mostrar propiedades
props = db.get("properties", {})
if props:
print(f" Propiedades:")
for prop_name, prop_data in list(props.items())[:5]:
prop_type = prop_data.get("type", "unknown")
print(f"{prop_name} ({prop_type})")
if len(props) > 5:
print(f" ... y {len(props) - 5} más")
print("-" * 70)
if pages:
print("\n" + "=" * 70)
print("📄 PÁGINAS ENCONTRADAS:")
print("=" * 70)
for i, page in enumerate(pages, 1):
page_id = page.get("id", "N/A")
# Intentar obtener el título
title = "Sin título"
props = page.get("properties", {})
# Buscar en diferentes ubicaciones del título
if "title" in props:
title_prop = props["title"]
if "title" in title_prop:
title_list = title_prop["title"]
if title_list:
title = title_list[0].get("plain_text", "Sin título")
elif "Name" in props:
name_prop = props["Name"]
if "title" in name_prop:
title_list = name_prop["title"]
if title_list:
title = title_list[0].get("plain_text", "Sin título")
print(f"\n🔷 {i}. {title}")
print(f" ID: {page_id}")
print(f" URL: https://notion.so/{page_id.replace('-', '')}")
print("-" * 70)
if databases:
print("\n" + "=" * 70)
print("💡 SIGUIENTE PASO:")
print("=" * 70)
print("\nSi 'CBC' aparece arriba como BASE DE DATOS:")
print("1. Copia el ID de la base de datos 'CBC'")
print("2. Actualiza tu .env:")
print(" NOTION_DATABASE_ID=<el_id_completo>")
print("\nSi 'CBC' aparece como PÁGINA:")
print("1. Abre la página en Notion")
print("2. Busca una base de datos dentro de esa página")
print("3. Haz click en '...' de la base de datos")
print("4. Selecciona 'Copy link to view'")
print("5. El ID estará en el URL copiado")
print("\n4. Ejecuta: python test_notion_integration.py\n")
else:
print("\n⚠️ No se encontraron bases de datos accesibles.")
print("\n📋 OPCIONES:")
print("\n1. Crear una nueva base de datos:")
print(" - Abre una de las páginas listadas arriba")
print(" - Crea una tabla/database dentro")
print(" - Copia el ID de esa base de datos")
print("\n2. O comparte una base de datos existente:")
print(" - Abre tu base de datos 'CBC' en Notion")
print(" - Click en '...' > 'Connections'")
print(" - Agrega tu integración\n")
except Exception as e:
print(f"❌ Error: {e}\n")
import traceback
traceback.print_exc()
if __name__ == "__main__":
main()