90 lines
4.0 KiB
Python
90 lines
4.0 KiB
Python
"""Sends a direct message from a Mattermost bot to one user, through Mattermost's REST API v4."""
|
|
import dataclasses
|
|
import pathlib
|
|
import typing
|
|
import urllib.parse
|
|
|
|
from failure import Failure
|
|
from rest_client import json_request
|
|
from project_config.main import located
|
|
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
|
|
|
|
# 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]
|
|
|
|
|
|
@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, 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 ""
|
|
|
|
|
|
def dm(text: str, directory: str | None, home: pathlib.Path, http: Http) -> Failure | None:
|
|
"""Sends text to the recipient that the project's env file names. The project is the one whose checkout holds directory, and its config names the file.
|
|
|
|
The DM is skipped where the config sets no env-file, since the project hasn't asked for DMs. It is skipped too where no config can be read: loop-claude has stopped with that reason, and without a config there is no file to read the recipient from."""
|
|
project = located(directory, home)
|
|
if isinstance(project, Failure) or project.env_file is None:
|
|
return None
|
|
config = read_config(project.env_file)
|
|
return config if isinstance(config, Failure) else send(config, text, http)
|
|
|
|
|
|
def config_of(directory: str | None, home: pathlib.Path) -> Config | Failure:
|
|
"""The server, token and recipient in the env file that the config of the project holding directory names."""
|
|
project = located(directory, home)
|
|
if isinstance(project, Failure):
|
|
return project
|
|
if project.env_file is None:
|
|
return Failure(f"{project.folder / 'config.toml'} sets no `env-file`; set it to the file that holds {', '.join(KEYS[:-1])} and {KEYS[-1]}")
|
|
return read_config(project.env_file)
|