Skip to content

netresearch/matrix-skill / skills/matrix-communication

matrix-communication

Flagged

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.mdmarkdown11.1 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-send.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 = []
# ///
"""Send a message to a Matrix room.

Usage:
    matrix-send.py ROOM MESSAGE [OPTIONS]
    matrix-send.py --help

Arguments:
    ROOM        Room identifier. Supports multiple formats:
                - Room ID: !abc123xyz (direct, fastest)
                - Room alias: #room:server (resolved via directory)
                - Room name: "agent-work" (looked up from joined rooms)
    MESSAGE     Message content (markdown supported)

Options:
    --format FORMAT   Message format: text or markdown [default: markdown]
    --emote           Send as /me action (m.emote)
    --notice          Send as m.notice — bot-flagged, suppressed from auto-reply
                      loops. Use for unattended automation. Mutually exclusive
                      with --emote.
    --thread EVENT    Reply in thread (event ID of thread root)
    --reply EVENT     Reply to message (event ID to reply to)
    --no-prefix       Don't add bot_prefix from config
    --json            Output as JSON
    --quiet           Minimal output
    --debug           Show debug information
    --help            Show this help

Effects (Element clients):
    Include emoji in message to trigger visual effects:
    party or tada = confetti, fireworks = fireworks, snowflake = snowfall

Examples:
    # Send by room name (easiest)
    matrix-send.py agent-work "Hello team!"

    # Send by room ID (from matrix-rooms.py output)
    matrix-send.py '!sZBoTOreI1z0BgHY-s2ZC9MV63B1orGFigPXvYMQ22E' "Hello!"

    # Send by alias
    matrix-send.py '#general:matrix.org' "Hello everyone!"
"""

import json
import os
import sys
import time

# Add script directory to path for _lib imports
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from _lib import (
    add_bot_prefix,
    clean_message,
    find_room_by_name,
    load_config,
    markdown_to_html,
    matrix_request,
    normalize_room_input,
    path_segment,
    resolve_room_alias,
)

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


def send_message(
    config: dict,
    room_id: str,
    message: str,
    format: str = "markdown",
    emote: bool = False,
    notice: bool = False,
    thread_id: str | None = None,
    reply_id: str | None = None,
) -> dict:
    """Send a message to a Matrix room.

    Args:
        config: Matrix config with homeserver and access_token
        room_id: Room ID to send to
        message: Message content
        format: "text" or "markdown"
        emote: If True, send as m.emote (/me action)
        notice: If True, send as m.notice (bot-flagged, no auto-reply loops)
        thread_id: Event ID of thread root (for thread replies)
        reply_id: Event ID to reply to

    msgtype precedence: notice > emote > text. The CLI enforces that callers
    pass only one of --notice or --emote via a mutually exclusive group.
    """
    txn_id = str(int(time.time() * 1000))

    if notice:
        msgtype = "m.notice"
    elif emote:
        msgtype = "m.emote"
    else:
        msgtype = "m.text"
    content = {"msgtype": msgtype, "body": message}

    if format == "markdown":
        html = markdown_to_html(message)
        if html != message:  # Only add HTML if there's actual formatting
            content["format"] = "org.matrix.custom.html"
            content["formatted_body"] = html

    # Thread reply (MSC3440)
    if thread_id:
        content["m.relates_to"] = {
            "rel_type": "m.thread",
            "event_id": thread_id,
            "is_falling_back": True,
        }
        # If also replying to a specific message in thread
        if reply_id and reply_id != thread_id:
            content["m.relates_to"]["m.in_reply_to"] = {"event_id": reply_id}
        else:
            content["m.relates_to"]["m.in_reply_to"] = {"event_id": thread_id}

    # Regular reply (not in thread)
    elif reply_id:
        content["m.relates_to"] = {"m.in_reply_to": {"event_id": reply_id}}

    return matrix_request(
        config,
        "PUT",
        f"/rooms/{path_segment(room_id)}/send/m.room.message/{txn_id}",
        content,
    )


def main():
    import argparse

    parser = argparse.ArgumentParser(description="Send a message to a Matrix room")
    parser.add_argument("room", help="Room ID (!id), alias (#room:server), or name")
    parser.add_argument("message", help="Message content (markdown supported)")
    parser.add_argument(
        "--format",
        choices=["text", "markdown"],
        default="markdown",
        help="Message format (default: markdown)",
    )
    msgtype_group = parser.add_mutually_exclusive_group()
    msgtype_group.add_argument(
        "--emote", action="store_true", help="Send as /me action (m.emote msgtype)"
    )
    msgtype_group.add_argument(
        "--notice",
        action="store_true",
        help="Send as m.notice — bot-flagged, suppressed from auto-reply loops. "
        "Use for unattended automation (release announcements, CI summaries).",
    )
    parser.add_argument(
        "--thread", metavar="EVENT_ID", help="Reply in thread (event ID of thread root)"
    )
    parser.add_argument(
        "--reply", metavar="EVENT_ID", help="Reply to message (event ID)"
    )
    parser.add_argument(
        "--no-prefix", action="store_true", help="Don't add bot_prefix from config"
    )
    parser.add_argument("--json", action="store_true", help="Output as JSON")
    parser.add_argument("--quiet", "-q", action="store_true", help="Minimal output")
    parser.add_argument("--debug", action="store_true", help="Show debug info")

    args = parser.parse_args()

    config = load_config()

    # Clean message from bash escaping artifacts
    message = clean_message(args.message)

    # Add bot prefix if configured (unless --no-prefix or emote)
    if not args.no_prefix and not args.emote and config.get("bot_prefix"):
        message = add_bot_prefix(message, config["bot_prefix"])

    # Resolve room to room ID
    room_input = normalize_room_input(clean_message(args.room))
    room_id = room_input

    if room_input.startswith("!"):
        # Direct room ID - use as-is
        room_id = room_input
        if args.debug:
            print(f"Using room ID directly: {room_id}", file=sys.stderr)

    elif room_input.startswith("#"):
        # Room alias - try to resolve
        try:
            room_id = resolve_room_alias(config, room_input)
            if args.debug:
                print(f"Resolved alias {room_input} -> {room_id}", file=sys.stderr)
        except ValueError:
            # Alias resolution failed - try name lookup as fallback
            alias_name = room_input.split(":")[0].lstrip("#")
            if args.debug:
                print(
                    f"Alias resolution failed, trying name lookup for '{alias_name}'",
                    file=sys.stderr,
                )

            found_id, matches = find_room_by_name(config, alias_name)
            if found_id:
                room_id = found_id
                if args.debug:
                    print(f"Found room by name: {room_id}", file=sys.stderr)
            else:
                error_msg = f"Could not resolve room '{room_input}'"
                if matches:
                    error_msg += ". Multiple matches found:\n"
                    for m in matches:
                        alias_str = f" ({m['alias']})" if m.get("alias") else ""
                        error_msg += f"  - {m['name']}{alias_str}: {m['room_id']}\n"
                else:
                    error_msg += ". Room not found in joined rooms."
                if args.json:
                    print(json.dumps({"error": error_msg}))
                else:
                    print(f"Error: {error_msg}", file=sys.stderr)
                sys.exit(1)

    else:
        # Plain name - look up by name
        if args.debug:
            print(f"Looking up room by name: '{room_input}'", file=sys.stderr)

        found_id, matches = find_room_by_name(config, room_input)
        if found_id:
            room_id = found_id
            if args.debug:
                print(f"Found room: {room_id}", file=sys.stderr)
        else:
            error_msg = f"Could not find room '{room_input}'"
            if matches:
                error_msg += ". Multiple matches found:\n"
                for m in matches:
                    alias_str = f" ({m['alias']})" if m.get("alias") else ""
                    error_msg += f"  - {m['name']}{alias_str}: {m['room_id']}\n"
            else:
                error_msg += ". Use 'matrix-rooms.py' to list available rooms."
            if args.json:
                print(json.dumps({"error": error_msg}))
            else:
                print(f"Error: {error_msg}", file=sys.stderr)
            sys.exit(1)

    # Send message
    result = send_message(
        config,
        room_id,
        message,
        args.format,
        emote=args.emote,
        notice=args.notice,
        thread_id=args.thread,
        reply_id=args.reply,
    )

    if "error" in result:
        if args.json:
            print(json.dumps(result))
        else:
            print(f"Error: {result['error']}", file=sys.stderr)
        sys.exit(1)

    if args.json:
        print(json.dumps(result))
    elif args.quiet:
        print(result.get("event_id", ""))
    else:
        print(f"Message sent to {args.room}")
        print(f"Event ID: {result.get('event_id')}")


if __name__ == "__main__":
    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