Files
Brancheneinstufung2/company-explorer/backend/scripts/notion_tools/update_notion_task.py
Floke d021b6b71c refactor: [30388f42] Strukturiere Root-Skripte thematisch neu
- Organisiert eine Vielzahl von Skripten aus dem Root-Verzeichnis in thematische Unterordner, um die Übersichtlichkeit zu verbessern und die Migration vorzubereiten.
- Verschiebt SuperOffice-bezogene Test- und Hilfsskripte in .
- Verschiebt Notion-bezogene Synchronisations- und Import-Skripte in .
- Archiviert eindeutig veraltete und ungenutzte Skripte in .
- Die zentralen Helfer  und  bleiben im Root, da sie von mehreren Tools als Abhängigkeit genutzt werden.
2026-03-06 10:16:08 +00:00

93 lines
3.5 KiB
Python

import requests
import json
import os
import sys
# Use the same token file as the other scripts
TOKEN_FILE = 'notion_token.txt'
def get_notion_token():
"""Reads the Notion API token from the specified file."""
try:
with open(TOKEN_FILE, 'r') as f:
return f.read().strip()
except FileNotFoundError:
print(f"Error: Token file not found at '{TOKEN_FILE}'")
print("Please create this file and place your Notion Integration Token inside.")
sys.exit(1)
def parse_markdown_to_blocks(md_content):
"""
Parses a simple markdown string into Notion API block objects.
This is a simplified parser for this specific task.
"""
blocks = []
lines = md_content.split('\n')
for line in lines:
stripped = line.strip()
if line.startswith("# "):
blocks.append({ "object": "block", "type": "heading_1", "heading_1": {"rich_text": [{"type": "text", "text": {"content": line[2:]}}]}})
elif line.startswith("## "):
blocks.append({ "object": "block", "type": "heading_2", "heading_2": {"rich_text": [{"type": "text", "text": {"content": line[3:]}}]}})
elif stripped.startswith("* ") or stripped.startswith("- "):
blocks.append({ "object": "block", "type": "bulleted_list_item", "bulleted_list_item": {"rich_text": [{"type": "text", "text": {"content": stripped[2:]}}]}})
elif stripped: # Any non-empty line becomes a paragraph
blocks.append({ "object": "block", "type": "paragraph", "paragraph": {"rich_text": [{"type": "text", "text": {"content": line}}]}})
# Add a divider for visual separation
blocks.insert(0, {"type": "divider", "divider": {}})
blocks.insert(0, {
"object": "block", "type": "heading_2", "heading_2": {
"rich_text": [{"type": "text", "text": {"content": "Gemini Task-Update:"}}]
}
})
return blocks
def append_blocks_to_page(token, page_id, blocks):
"""
Appends a list of block objects to a Notion page.
"""
# In Notion, the page ID is the block ID for appending content
url = f"https://api.notion.com/v1/blocks/{page_id}/children"
headers = {
"Authorization": f"Bearer {token}",
"Notion-Version": "2022-06-28",
"Content-Type": "application/json"
}
payload = {"children": blocks}
print(f"Appending {len(blocks)} blocks to Notion Page ID: {page_id}...")
try:
response = requests.patch(url, headers=headers, json=payload)
response.raise_for_status()
print("SUCCESS: Content appended to Notion task.")
except requests.exceptions.HTTPError as e:
print(f"ERROR: Failed to update Notion page. Response: {e.response.text}")
sys.exit(1)
except Exception as e:
print(f"ERROR: An unexpected error occurred: {e}")
sys.exit(1)
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: python update_notion_task.py <page_id> \"<content_string>\"")
print("Example: python update_notion_task.py 12345-abc... \"- Task 1\n- Task 2\"")
sys.exit(1)
page_id = sys.argv[1]
content_to_append = sys.argv[2]
# Basic validation for page_id
if not isinstance(page_id, str) or len(page_id) < 32:
print(f"Error: Invalid Page ID provided: '{page_id}'")
sys.exit(1)
notion_token = get_notion_token()
content_blocks = parse_markdown_to_blocks(content_to_append)
append_blocks_to_page(notion_token, page_id, content_blocks)