"""Sends a direct message from a Mattermost bot to one user, through Mattermost's REST API v4.""" import dataclasses import http.client import json import pathlib import typing import urllib.error import urllib.parse import urllib.request from failure import Failure KEYS = ("MATTERMOST_URL", "MATTERMOST_TOKEN", "MATTERMOST_RECIPIENT") # Seconds each connect and each read may wait, so an unreachable server holds loop-claude's interrupt only briefly. TIMEOUT = 10 # Sends a request, the body as JSON where there is one, and returns the JSON answer, or a Failure saying why there is none. Http = typing.Callable[[str, str, str, object], object] class NoRedirect(urllib.request.HTTPRedirectHandler): """Refuses every redirect, which Mattermost's API never sends: urllib would resend the token to the new location, even one off https.""" def redirect_request(self, *args: typing.Any, **kwargs: typing.Any) -> None: return None OPENER = urllib.request.build_opener(NoRedirect) @dataclasses.dataclass(frozen=True) class Config: url: str token: str recipient: str def env_file(home: pathlib.Path) -> pathlib.Path: return home / ".claude" / ".env" def read_config(path: pathlib.Path) -> Config | Failure: """The server, bot token and recipient that path's KEY=value lines hold.""" try: mode = path.stat().st_mode text = path.read_text(encoding="utf-8") except FileNotFoundError: return Failure(f"{path} does not exist; it needs {', '.join(KEYS[:-1])} and {KEYS[-1]}") except (OSError, UnicodeDecodeError) as failure: return Failure(f"cannot read {path}: {failure}") if mode & 0o077: return Failure(f"{path} holds the bot's token, so only its owner may read it; run chmod 600 {path}") values = parse_env(text) if missing := [key for key in KEYS if not values.get(key)]: return Failure(f"{path} lacks {' and '.join(missing)}") url, token, recipient = (values[key] for key in KEYS) if not url.startswith("https://"): return Failure(f"{path} → MATTERMOST_URL must start with https://, so the token is never sent in the clear") return Config(url.rstrip("/"), token, recipient) def parse_env(text: str) -> dict[str, str]: values = {} for line in text.splitlines(): key, equals, value = line.partition("=") if not equals or key.lstrip().startswith("#"): continue value = value.strip() if len(value) >= 2 and value[0] == value[-1] and value[0] in "'\"": value = value[1:-1] values[key.strip()] = value return values def send(config: Config, message: str, http: Http) -> Failure | None: api = f"{config.url}/api/v4" bot = id_of(http("GET", f"{api}/users/me", config.token, None), "GET /api/v4/users/me") if isinstance(bot, Failure): return bot recipient = id_of(http("GET", f"{api}/users/username/{urllib.parse.quote(config.recipient)}", config.token, None), f"GET /api/v4/users/username/{config.recipient}") if isinstance(recipient, Failure): return recipient channel = id_of(http("POST", f"{api}/channels/direct", config.token, [bot, recipient]), "POST /api/v4/channels/direct") if isinstance(channel, Failure): return channel posted = id_of(http("POST", f"{api}/posts", config.token, {"channel_id": channel, "message": message}), "POST /api/v4/posts") return posted if isinstance(posted, Failure) else None def id_of(answer: object, request: str) -> str | Failure: if isinstance(answer, Failure): return answer found = answer.get("id") if isinstance(answer, dict) else None return found if isinstance(found, str) and found else Failure(f"{request} answered without an id") def http_json(method: str, url: str, token: str, body: object) -> object: """The JSON that url answers; a Failure naming the server where it cannot be reached, and the request where it answers an error, breaks HTTP or answers something other than JSON.""" request_name = f"{method} {urllib.parse.urlsplit(url).path}" data = None if body is None else json.dumps(body).encode() request = urllib.request.Request(url, data, {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}, method=method) try: with OPENER.open(request, timeout=TIMEOUT) as response: raw = response.read() except urllib.error.HTTPError as failure: with failure: return Failure(f"{request_name} answered {failure.code}: {error_message(failure) or failure.reason}") except http.client.HTTPException as failure: return Failure(f"{request_name} got a broken answer: {failure!r}") except (OSError, ValueError) as failure: server = urllib.parse.urlunsplit(urllib.parse.urlsplit(url)[:2] + ("", "", "")) return Failure(f"cannot reach {server}: {getattr(failure, 'reason', failure)}") try: return json.loads(raw) except ValueError: return Failure(f"{request_name} answered with something other than JSON") def error_message(failure: urllib.error.HTTPError) -> str: """Mattermost's message in an error answer; empty where the body is cut short, breaks HTTP or holds none.""" try: answer = json.loads(failure.read()) except (http.client.HTTPException, OSError, ValueError): return "" message = answer.get("message") if isinstance(answer, dict) else None return message if isinstance(message, str) else "" def dm(text: str, home: pathlib.Path, http: Http) -> Failure | None: """Sends text as home's .claude/.env configures it. A machine without that file hasn't asked for DMs, so there the DM is skipped.""" path = env_file(home) if not path.exists(): return None config = read_config(path) return config if isinstance(config, Failure) else send(config, text, http)