Skip to content

netresearch/matrix-skill / skills/matrix-communication

matrix-communication

Unverified

Use when communicating via Matrix chat, notifying teams, or managing E2EE. Triggers on #room:server references, Matrix URLs, and chat requests.

FileKindSize
README.mdmarkdown2.9 KB
SKILL.mdskill md6.7 KB
evals/evals.jsonconfig12.6 KB
references/agent-governance.mdmarkdown2.0 KB
references/api-reference.mdmarkdown7.3 KB
references/command-reference.mdmarkdown8.9 KB
references/e2ee-guide.mdmarkdown17.2 KB
references/hookshot-integration.mdmarkdown10.7 KB
references/messaging-guide.mdmarkdown13.8 KB
references/no-editorializing.mdmarkdown331 B
references/setup-guide.mdmarkdown13.8 KB
references/troubleshooting.mdmarkdown7.8 KB
scripts/_lib/__init__.pyscript3.6 KB
scripts/_lib/backup_mac.pyscript1.2 KB
scripts/_lib/config.pyscript4.6 KB
scripts/_lib/daemon_client.pyscript3.0 KB
scripts/_lib/deps.pyscript1.9 KB
scripts/_lib/downloads.pyscript1.1 KB
scripts/_lib/e2ee.pyscript13.2 KB
scripts/_lib/formatting.pyscript14.4 KB
scripts/_lib/http.pyscript4.8 KB
scripts/_lib/reactions.pyscript2.9 KB
scripts/_lib/roomlog.pyscript13.7 KB
scripts/_lib/rooms.pyscript15.5 KB
scripts/_lib/secret_input.pyscript2.0 KB
scripts/_lib/test_backup_mac.pyscript1.5 KB
scripts/_lib/test_config.pyscript7.1 KB
scripts/_lib/test_daemon_client.pyscript5.9 KB
scripts/_lib/test_downloads.pyscript2.3 KB
scripts/_lib/test_e2ee.pyscript14.3 KB
scripts/_lib/test_formatting.pyscript15.5 KB
scripts/_lib/test_http.pyscript4.1 KB
scripts/_lib/test_reactions.pyscript15.2 KB
scripts/_lib/test_roomlog.pyscript20.2 KB
scripts/_lib/test_rooms.pyscript13.7 KB
scripts/_lib/test_secret_input.pyscript2.2 KB
scripts/_lib/test_trust.pyscript8.3 KB
scripts/_lib/trust.pyscript5.3 KB
scripts/_lib/utils.pyscript1.7 KB
scripts/matrix-create-room.pyexecutablescript4.7 KB
scripts/matrix-doctor.pyexecutablescript22.2 KB
scripts/matrix-download-e2ee.pyexecutablescript7.7 KB
scripts/matrix-e2ee-setup.pyexecutablescript9.2 KB
scripts/matrix-e2ee-verify.pyexecutablescript29.2 KB
scripts/matrix-edit-e2ee.pyexecutablescript7.9 KB
scripts/matrix-edit.pyexecutablescript5.3 KB
scripts/matrix-fetch-keys.pyexecutablescript9.1 KB
scripts/matrix-invite.pyexecutablescript3.0 KB
scripts/matrix-key-backup.pyexecutablescript21.3 KB
scripts/matrix-power-level.pyexecutablescript7.0 KB
scripts/matrix-react.pyexecutablescript14.1 KB
scripts/matrix-read-e2ee.pyexecutablescript12.8 KB
scripts/matrix-read.pyexecutablescript4.7 KB
scripts/matrix-redact.pyexecutablescript5.0 KB
scripts/matrix-resolve.pyexecutablescript1.7 KB
scripts/matrix-rooms.pyexecutablescript3.8 KB
scripts/matrix-send-e2ee.pyexecutablescript19.4 KB
scripts/matrix-send.pyexecutablescript9.4 KB
scripts/matrix-watch.pyexecutablescript5.3 KB
scripts/matrix-watchd.pyexecutablescript23.5 KB
scripts/test_matrix_doctor.pyscript14.2 KB
scripts/test_matrix_read_e2ee.pyscript2.7 KB

scripts/matrix-fetch-keys.py

View on GitHub
#!/usr/bin/env -S uv run --script
# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: Netresearch DTT GmbH
# /// script
# requires-python = ">=3.11"
# dependencies = ["matrix-nio[e2e]<0.26"]
# ///
"""
Fetch missing room keys by requesting them from other devices.

When you can't decrypt old messages, this script:
1. Reads room history
2. Detects encrypted events that can't be decrypted
3. Requests keys from other verified devices
4. Syncs to receive forwarded keys
5. Saves keys to local store

Usage:
    matrix-fetch-keys.py ROOM [--limit N] [--sync-time S]
"""

import argparse
import asyncio
import os
import sys
import time

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from _lib import (
    find_room_in_nio_client,
    get_store_path,
    load_config,
    load_credentials,
    normalize_room_input,
    restore_login_checked,
)
from nio import (
    AsyncClient,
    AsyncClientConfig,
    ForwardedRoomKeyEvent,
    MegolmEvent,
    RoomKeyEvent,
    RoomKeyRequestResponse,
    RoomMessagesResponse,
    RoomResolveAliasResponse,
    UnknownToDeviceEvent,
)

sys.stdout.reconfigure(line_buffering=True)
sys.stderr.reconfigure(line_buffering=True)


class KeyFetcher:
    def __init__(self, client, debug=False):
        self.client = client
        self.debug = debug
        self.requested_sessions = set()
        self.received_keys = 0
        self.decryption_failures = 0

    def _debug(self, msg):
        if self.debug:
            print(f"[DEBUG] {msg}")

    async def handle_key_event(self, event):
        """Handle incoming key events."""
        if isinstance(event, (ForwardedRoomKeyEvent, RoomKeyEvent)):
            self.received_keys += 1
            room_id = getattr(event, "room_id", "unknown")
            session_id = getattr(event, "session_id", "unknown")
            print(f"  šŸ“Ø Received key: {room_id[:20]}... / {session_id[:20]}...")

        elif isinstance(event, UnknownToDeviceEvent) and hasattr(event, "source"):
            event_type = event.source.get("type", "")
            if "room_key" in event_type.lower():
                self.received_keys += 1
                content = event.source.get("content", {})
                room_id = content.get("room_id", "unknown")
                session_id = content.get("session_id", "unknown")
                print(
                    f"  šŸ“Ø Received key ({event_type}): {room_id[:20]}... / {session_id[:20]}..."
                )

    async def request_key_for_event(self, event: MegolmEvent) -> bool:
        """Request key for an undecryptable event."""
        session_key = (event.room_id, event.session_id)

        if session_key in self.requested_sessions:
            self._debug(f"Already requested: {event.session_id[:20]}")
            return False

        self.requested_sessions.add(session_key)
        self.decryption_failures += 1

        try:
            result = await self.client.request_room_key(event)
            if isinstance(result, RoomKeyRequestResponse):
                self._debug(f"Key request sent for session {event.session_id[:20]}")
                return True
            else:
                self._debug(f"Key request failed: {result}")
                return False
        except Exception as e:  # noqa: BLE001  # intentional fail-soft: error surfaced to caller, not re-raised
            self._debug(f"Key request error: {e}")
            return False

    async def fetch_room_history(self, room_id: str, limit: int = 100):
        """Fetch room history and request keys for undecryptable events."""
        print(f"\nFetching {limit} messages from room...")

        # Get messages
        result = await self.client.room_messages(
            room_id,
            start="",  # From latest
            limit=limit,
        )

        if not isinstance(result, RoomMessagesResponse):
            print(f"Error fetching messages: {result}")
            return

        encrypted_count = 0
        decrypted_count = 0
        request_count = 0

        for event in result.chunk:
            if isinstance(event, MegolmEvent):
                encrypted_count += 1
                # This is an undecrypted event - request the key
                if await self.request_key_for_event(event):
                    request_count += 1
            elif (
                hasattr(event, "source")
                and event.source.get("type") == "m.room.encrypted"
            ):
                # Decrypted successfully
                decrypted_count += 1

        print(f"  Messages: {len(result.chunk)}")
        print(f"  Encrypted (need keys): {encrypted_count}")
        print(f"  Decrypted (have keys): {decrypted_count}")
        print(f"  Key requests sent: {request_count}")


async def main():
    parser = argparse.ArgumentParser(description="Fetch missing room keys")
    parser.add_argument("room", help="Room name, ID, or alias")
    parser.add_argument("--limit", type=int, default=100, help="Messages to scan")
    parser.add_argument(
        "--sync-time", type=int, default=60, help="Seconds to wait for keys"
    )
    parser.add_argument("--debug", action="store_true", help="Debug output")
    args = parser.parse_args()

    config = load_config(require_user_id=True)
    creds = load_credentials()

    if not creds:
        print("No credentials. Run matrix-e2ee-setup.py first.", file=sys.stderr)
        return 1

    store_path = get_store_path()
    client_config = AsyncClientConfig(store_sync_tokens=True, encryption_enabled=True)
    client = AsyncClient(
        homeserver=config["homeserver"],
        user=config["user_id"],
        device_id=creds["device_id"],
        store_path=str(store_path),
        config=client_config,
    )

    fetcher = KeyFetcher(client, debug=args.debug)

    try:
        restore_login_checked(
            client, config["user_id"], creds["device_id"], creds["access_token"]
        )
        if client.store:
            client.load_store()

        # Register handlers
        client.add_to_device_callback(fetcher.handle_key_event, ForwardedRoomKeyEvent)
        client.add_to_device_callback(fetcher.handle_key_event, RoomKeyEvent)
        client.add_to_device_callback(fetcher.handle_key_event, UnknownToDeviceEvent)

        # Initial sync
        print("Initial sync...")
        await client.sync(timeout=10000)

        # Upload keys
        if client.should_upload_keys:
            await client.keys_upload()

        # Resolve room with the synced client, like the other E2EE scripts:
        # an E2EE setup may have no access_token in the config for the HTTP
        # lookup to use.
        args.room = normalize_room_input(args.room)
        if args.room.startswith("#") and ":" not in args.room:
            # Bare alias without server part: a name to look up, as before
            args.room = args.room.lstrip("#")
        room_id = args.room
        if args.room.startswith("#"):
            response = await client.room_resolve_alias(args.room)
            if not isinstance(response, RoomResolveAliasResponse):
                print(f"Could not resolve room alias: {response}", file=sys.stderr)
                return 1
            room_id = response.room_id
        elif not args.room.startswith("!"):
            room_id = find_room_in_nio_client(client.rooms, args.room)
            if not room_id:
                print(
                    f"Could not find room '{args.room}' (none or several match). "
                    "Use 'matrix-rooms.py' to list rooms.",
                    file=sys.stderr,
                )
                return 1

        room = client.rooms.get(room_id)
        room_name = room.display_name if room else room_id
        print(f"Room: {room_name}")

        # Fetch history and request keys
        await fetcher.fetch_room_history(room_id, args.limit)

        if fetcher.decryption_failures == 0:
            print("\nāœ… No missing keys - all messages decryptable!")
            return 0

        # Sync to receive keys
        print(f"\nWaiting {args.sync_time}s for keys from other devices...")
        print("(Ensure you have other verified devices online)")

        start_time = time.time()
        last_count = 0
        while time.time() - start_time < args.sync_time:
            await client.sync(timeout=5000)
            elapsed = int(time.time() - start_time)

            if fetcher.received_keys > last_count:
                last_count = fetcher.received_keys
            elif elapsed % 15 == 0 and elapsed > 0:
                print(f"  [{elapsed}s] Received {fetcher.received_keys} keys...")

        print("\n=== Results ===")
        print(f"Key requests sent: {len(fetcher.requested_sessions)}")
        print(f"Keys received: {fetcher.received_keys}")

        if fetcher.received_keys > 0:
            print(f"\nāœ… Received {fetcher.received_keys} keys!")
            print("Run matrix-read-e2ee.py to read messages now.")
        else:
            print("\nāš ļø  No keys received.")
            print("Possible reasons:")
            print("  - Device not verified in Element")
            print("  - Other devices offline or don't share keys")
            print("  - Try: Element → Settings → Security → enable key sharing")

    finally:
        await client.close()

    return 0


if __name__ == "__main__":
    sys.exit(asyncio.run(main()))
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 197kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall