"""Sends a direct message from a Slack app's bot to one user, through Slack's Web API. The `notifier` setting `slack` picks it.""" import dataclasses import html import pathlib import typing from failure import Failure from rest_client.json_request import Http, MessageOf from rest_client import json_request from rest_client.env_file import read_env KEYS = ("SLACK_TOKEN", "SLACK_RECIPIENT") # Slack's one host for every workspace. API = "https://slack.com/api" # 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: token: str recipient: str def read_config(path: pathlib.Path) -> Config | Failure: """The 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 return Config(*(values[key] for key in KEYS)) def send(config: Config, message: str, http: Http) -> Failure | None: """Posts message to the recipient's member ID, which Slack opens as a DM from the app's bot; the bot needs the `chat:write` scope. Slack reads `&`, `<` and `>` as control characters, so they are escaped as its docs ask.""" answer = http("POST", f"{API}/chat.postMessage", config.token, {"channel": config.recipient, "text": html.escape(message, quote=False)}) if isinstance(answer, Failure): return answer if isinstance(answer, dict) and answer.get("ok") is True: return None # Slack answers 200 with `ok` false and a short code, such as `channel_not_found` or `invalid_auth`. error = answer.get("error") if isinstance(answer, dict) else None return Failure(f"POST /api/chat.postMessage refused the message: {error if isinstance(error, str) and error else 'no error code'}") # request is json_request.http_json, but in the test of what this hands it. def http_json(method: str, url: str, token: str, body: object, request: typing.Callable[[str, str, str, object, int, MessageOf], object] = json_request.http_json) -> 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 request(method, url, f"Bearer {token}", body, TIMEOUT, error_message) def error_message(answer: object) -> str: """Slack's error code in the JSON of an error answer; empty where it holds none.""" error = answer.get("error") if isinstance(answer, dict) else None return error if isinstance(error, str) else ""