CtrlK
BlogDocsLog inGet started
Tessl Logo
PluginPublic

jbaruch/nanoclaw-core

Core behavioral rules and skills for NanoClaw personal assistant agents. Always-on rules for communication, verification, memory, and formatting.

Quality

89%

Does it follow best practices?

Run evals on this skill

Adds up to 20 points to the overall score

View guide
SecuritybySnyk

Low

Low-risk findings worth noting

Overview
Quality
Evals
Security
Files

resolve-telegram-link.pyskills/query-history/scripts/

#!/usr/bin/env python3
"""Resolve an existing message in the current Telegram supergroup, read-only."""

import argparse
import json
import os
import re
import sqlite3
import sys
from contextlib import closing
from pathlib import Path

MESSAGE_ID = re.compile(r"[1-9][0-9]*")
SUPERGROUP = re.compile(r"tg:-100([1-9][0-9]*)")


def resolve(conn: sqlite3.Connection, chat: str, reference: str) -> dict:
    group = SUPERGROUP.fullmatch(chat)
    if group is None:
        raise ValueError("Use this lookup in the current Telegram supergroup.")
    matches = conn.execute(
        """SELECT DISTINCT id LIKE 'owner-answer:%', telegram_message_id,
                  CASE WHEN id LIKE 'owner-answer:%' THEN reply_to_message_id END,
                  thread_id, substr(content, 1, 160)
             FROM messages WHERE chat_jid = ? AND (id = ? OR telegram_message_id = ?)
            LIMIT 2""",
        (chat, reference, reference),
    ).fetchall()
    if len(matches) != 1:
        raise ValueError("The reference does not identify one message in the current chat.")
    is_answer, platform_id, reply_to, thread, preview = matches[0]
    button = bool(is_answer)
    if button:
        card = conn.execute(
            """SELECT DISTINCT telegram_message_id, thread_id, substr(content, 1, 160)
                 FROM messages WHERE chat_jid = ? AND telegram_message_id = ? LIMIT 2""",
            (chat, reply_to),
        ).fetchall()
        if len(card) != 1:
            raise ValueError("Could not find the original button card in the current chat.")
        platform_id, thread, preview = card[0]
    if platform_id is None or not MESSAGE_ID.fullmatch(platform_id):
        raise ValueError("The message has no verified Telegram ID.")
    if thread is not None and not MESSAGE_ID.fullmatch(thread):
        raise ValueError("The message has no valid Telegram topic ID.")
    topic = f"{thread}/" if thread and thread != "1" else ""
    return {
        "url": f"https://t.me/c/{group[1]}/{topic}{platform_id}",
        "chat_jid": chat,
        "topic": thread,
        "preview": preview or "",
        "linked_button_card": button,
    }


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("message_id")
    args = parser.parse_args()
    path = Path(os.environ.get("NANOCLAW_DB", "/workspace/store/messages.db"))
    chat = os.environ.get("NANOCLAW_CHAT_JID", "")
    try:
        with closing(sqlite3.connect(path.resolve().as_uri() + "?mode=ro", uri=True)) as conn:
            result = resolve(conn, chat, args.message_id)
    except (OSError, sqlite3.Error):
        print("Check that NANOCLAW_DB points to the mounted message store.", file=sys.stderr)
        print(json.dumps({"error": "Cannot read the host message store."}))
        return 1
    except ValueError as error:
        print(f"{error} Look up the original message in this Telegram chat.", file=sys.stderr)
        print(json.dumps({"error": str(error)}))
        return 1
    print(json.dumps(result, ensure_ascii=False))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

README.md

tile.json