"""Sends a direct message from a Mattermost bot to one user, through Mattermost's REST API v4. The `notifier` setting `mattermost` picks it.""" import dataclasses import pathlib import urllib.parse from failure import Failure from rest_client.json_request import Http from rest_client import json_request from rest_client.env_file import read_env 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 @dataclasses.dataclass(frozen=True) class Config: url: str token: str recipient: str def read_config(path: pathlib.Path) -> Config | Failure: """The server, bot token and recipient that path's KEY=value lines hold.""" values = read_env(path, KEYS, "the bot's token") if isinstance(values, Failure): return values 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 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 to the bot's request, None where the answer has no body, or a Failure saying why there is none.""" return json_request.http_json(method, url, f"Bearer {token}", body, TIMEOUT, error_message) def error_message(answer: object) -> str: """Mattermost's message in the JSON of an error answer; empty where it holds none.""" message = answer.get("message") if isinstance(answer, dict) else None return message if isinstance(message, str) else ""