Herramientas de usuario

bbj_notificaciones.py
#!/usr/local/bin/python3
 
import getpass
import json
import subprocess
import urllib.request
from datetime import datetime
from email.message import EmailMessage
from pathlib import Path
 
API = "http://127.0.0.1:7099/api"
STATE = Path.home() / ".bbj_notificaciones.json"
ME = getpass.getuser()
TO = f"{ME}@texto-plano.xyz"
 
 
def api(method: str, **params) -> dict:
    """Call a bbj API method and return the JSON response."""
    request = urllib.request.Request(
        f"{API}/{method}",
        data=json.dumps(params).encode(),
        headers={"Content-Type": "application/json"},
    )
    with urllib.request.urlopen(request, timeout=30) as response:
        reply = json.load(response)
    if reply.get("error"):
        raise RuntimeError(f"bbj {method}: {reply['error']}")
    return reply
 
 
def user_name(usermap: dict, user_id: str) -> str:
    """Return the user name for USER_ID, or 'anónimo'."""
    return usermap.get(user_id, {}).get("user_name", "anónimo")
 
 
def format_thread(thread_id: str, since: float) -> str | None:
    """Render the posts of THREAD_ID newer than SINCE, skipping mine."""
    reply = api("thread_load", thread_id=thread_id)
    thread, usermap = reply["data"], reply["usermap"]
    posts = [
        message
        for message in thread["messages"]
        if message["created"] > since and user_name(usermap, message["author"]) != ME
    ]
    if not posts:
        return None
    lines = [f"== {thread['title']}"]
    for post in posts:
        date = datetime.fromtimestamp(post["created"]).strftime("%d/%m %H:%M")
        lines.append(f"\n{user_name(usermap, post['author'])} ({date}):\n")
        lines.append(post["body"].strip())
    return "\n".join(lines)
 
 
def send(subject: str, body: str) -> None:
    """Send a UTF-8 plain text mail to myself."""
    message = EmailMessage()
    message["From"] = TO
    message["To"] = TO
    message["Subject"] = subject
    message.set_content(body)
    subprocess.run(
        ["/usr/sbin/sendmail", "-t", "-oi"], input=message.as_bytes(), check=True
    )
 
 
def main() -> None:
    reply = api("thread_index")
    threads = reply["data"]
    current = {thread["thread_id"]: thread["last_mod"] for thread in threads}
 
    if not STATE.exists():
        STATE.write_text(json.dumps(current))
        return
 
    previous = json.loads(STATE.read_text())
    STATE.write_text(json.dumps(current))
 
    changed = sorted(
        (
            thread
            for thread in threads
            if thread["last_mod"] > previous.get(thread["thread_id"], 0)
        ),
        key=lambda thread: thread["last_mod"],
    )
    sections = [
        section
        for thread in changed
        if (
            section := format_thread(
                thread["thread_id"], previous.get(thread["thread_id"], 0)
            )
        )
    ]
    if not sections:
        return
 
    send(
        f"bbj: novedades en {len(sections)} hilo(s)",
        "\n\n\n".join(sections) + "\n",
    )
 
 
if __name__ == "__main__":
    main()

Este sitio web utiliza cookies para guardar datos esenciales de su actividad, como su autenticación. Al entrar acepta el uso de cookies.

Más información