bot.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. """A small, opinionated framework for building bots on Chatto.
  2. Chatto 0.5.0 introduced *bot accounts*: user identities flagged as bots that
  3. authenticate with a **key** (e.g. ``cht_BK_...``) rather than a
  4. username/password. The key is used **directly as a bearer token** — there is
  5. no ``/auth/login`` round-trip — and it resolves to a ``User`` with a
  6. capability grant set.
  7. This module turns :class:`chattolib.client.ChattoClient` into the standard
  8. library for bots by adding three things on top of the raw client:
  9. * **Key-based login** — :meth:`Bot.login` builds an authenticated client from
  10. a bot key in one call.
  11. * **An event dispatcher** — :meth:`Bot.run` opens the realtime stream and
  12. routes incoming events (messages, reactions, mentions, presence, typing,
  13. room changes) to the async handlers you register.
  14. * **Flattened verbs** — :meth:`Bot.say`, :meth:`Bot.reply`,
  15. :meth:`Bot.react`, :method:`Bot.set_status`, :meth:`Bot.join_room`,
  16. :meth:`Bot.create_room`, and friends, so a bot's "brain" reads like
  17. natural language instead of protobuf plumbing.
  18. In the protocol-4 realtime channel, live events are thin, caller-scoped hints
  19. (identifiers rather than full resources). Where a handler needs the full
  20. resource (e.g. the body of a posted message), the bot hydrates it on demand
  21. through the corresponding ConnectRPC.
  22. A minimal bot::
  23. import asyncio
  24. from chattolib.bot import Bot
  25. async def on_message(event):
  26. if event.body.startswith("!hello"):
  27. await event.bot.reply(event, "hi!")
  28. async def main():
  29. async with await Bot.login("cht_BK_...") as bot:
  30. bot.on("message", on_message)
  31. await bot.run()
  32. asyncio.run(main())
  33. Requires the ``chattolib[realtime]`` extra for the live stream.
  34. """
  35. from __future__ import annotations
  36. import asyncio
  37. import contextlib
  38. from collections.abc import Awaitable, Callable
  39. from dataclasses import dataclass
  40. from typing import Any
  41. from chattolib import _pb # noqa: F401 — installs the generated pb import path
  42. from chattolib._pb.chatto.api.v1 import presence_pb2
  43. from chattolib.client import ChattoClient
  44. from chattolib.exceptions import ChattoError
  45. from chattolib.realtime import (
  46. ChattoRealtimeCloseError,
  47. ChattoRealtimeError,
  48. RealtimeConnection,
  49. RealtimeEvent,
  50. stream_events,
  51. )
  52. from chattolib.types import (
  53. Message,
  54. PresenceStatus,
  55. Room,
  56. RoomGroup,
  57. RoomWithViewerState,
  58. User,
  59. )
  60. def _presence(value: Any) -> PresenceStatus:
  61. """Coerce a protobuf presence value (int or enum) to a PresenceStatus."""
  62. name = value.name if hasattr(value, "name") else presence_pb2.PresenceStatus.Name(int(value))
  63. # The protobuf name is the *value* of our StrEnum (e.g. "PRESENCE_STATUS_ONLINE"),
  64. # so look it up by value, not by member name.
  65. for member in PresenceStatus:
  66. if member.value == name:
  67. return member
  68. return PresenceStatus.UNSPECIFIED
  69. __all__ = [
  70. "Bot",
  71. "BotError",
  72. "BotEvent",
  73. "BotMessageEvent",
  74. "BotPresenceEvent",
  75. "BotReactionEvent",
  76. "BotRoomEvent",
  77. "BotTypingEvent",
  78. "BotUserEvent",
  79. ]
  80. # Oneof ``event`` cases that map onto a :class:`BotRoomEvent`.
  81. _ROOM_EVENT_KINDS = frozenset(
  82. {
  83. "room_created",
  84. "room_updated",
  85. "room_deleted",
  86. "room_archived",
  87. "room_unarchived",
  88. "room_universal_changed",
  89. "room_slow_mode_changed",
  90. "room_threading_mode_changed",
  91. "user_joined_room",
  92. "user_left_room",
  93. }
  94. )
  95. # Oneof ``event`` cases that map onto a :class:`BotUserEvent`.
  96. _USER_EVENT_KINDS = frozenset(
  97. {"user_account_created", "user_profile_changed", "user_account_deleted"}
  98. )
  99. class BotError(ChattoError):
  100. """Raised for bot-framework-level errors (bad handlers, bad keys, ...)."""
  101. # ---------------------------------------------------------------------------
  102. # Event types
  103. # ---------------------------------------------------------------------------
  104. @dataclass
  105. class BotEvent:
  106. """Base class for every event the dispatcher delivers to a handler.
  107. ``bot`` is the owning :class:`Bot`, so a handler can act on the event
  108. (e.g. ``await event.bot.reply(event, "...")``) without closing over
  109. globals.
  110. """
  111. bot: Bot
  112. kind: str
  113. async def _noop(self) -> None: # pragma: no cover - interface
  114. ...
  115. @dataclass
  116. class BotMessageEvent(BotEvent):
  117. """A new message in a room the bot can see.
  118. ``message`` is the full :class:`Message`, hydrated from the server when
  119. this event was dispatched. ``actor`` is the author's :class:`User` when
  120. it could be resolved; otherwise ``None``.
  121. """
  122. message: Message
  123. actor: User | None = None
  124. @property
  125. def room_id(self) -> str:
  126. return self.message.room_id
  127. @property
  128. def body(self) -> str | None:
  129. return self.message.body
  130. @property
  131. def is_mention(self) -> bool:
  132. """True when this message mentions the bot (best-effort)."""
  133. me = self.bot.user
  134. if me is None or not self.message.body:
  135. return False
  136. return f"@{me.login}" in self.message.body or me.display_name in self.message.body
  137. @dataclass
  138. class BotReactionEvent(BotEvent):
  139. """A reaction was added to (or removed from) a message."""
  140. room_id: str
  141. message_event_id: str
  142. emoji: str
  143. user_id: str
  144. added: bool = True
  145. @dataclass
  146. class BotPresenceEvent(BotEvent):
  147. """A user's presence status changed."""
  148. user_id: str
  149. status: PresenceStatus
  150. @dataclass
  151. class BotTypingEvent(BotEvent):
  152. """A user started (or stopped) typing in a room/thread."""
  153. room_id: str
  154. thread_root_event_id: str | None = None
  155. @dataclass
  156. class BotRoomEvent(BotEvent):
  157. """A room lifecycle change (created, updated, archived, member join/...)."""
  158. room: Room | None = None
  159. detail: str = "" # e.g. "created", "updated", "archived", "user_joined_room"
  160. @dataclass
  161. class BotUserEvent(BotEvent):
  162. """A user account was created, changed, or deleted."""
  163. user: User | None = None
  164. removed: bool = False
  165. # ---------------------------------------------------------------------------
  166. # The Bot
  167. # ---------------------------------------------------------------------------
  168. Handler = Callable[[BotEvent], Awaitable[None]]
  169. class Bot:
  170. """A Chatto bot: an authenticated client plus an event dispatcher and a
  171. set of convenience verbs.
  172. Create one with :meth:`login` (from a bot key) or :meth:`from_client`
  173. (wrapping an already-authenticated :class:`ChattoClient`).
  174. """
  175. def __init__(
  176. self,
  177. client: ChattoClient,
  178. *,
  179. base_url: str | None = None,
  180. ) -> None:
  181. self._client = client
  182. self._base_url = base_url or client.base_url
  183. self._user: User | None = None
  184. self._handlers: dict[str, list[Handler]] = {}
  185. self._connection: RealtimeConnection | None = None
  186. self._running = False
  187. # -- construction ------------------------------------------------------
  188. @classmethod
  189. async def login(
  190. cls,
  191. key: str,
  192. *,
  193. base_url: str | None = None,
  194. ) -> Bot:
  195. """Authenticate a bot with its **key**.
  196. The key (e.g. ``cht_BK_...``) is used directly as the bearer token —
  197. no username/password. ``base_url`` defaults to the public Chatto
  198. server; pass it to target a self-hosted or preview deployment.
  199. """
  200. if base_url is None:
  201. base_url = ChattoClient.DEFAULT_BASE_URL
  202. client = ChattoClient(token=key, base_url=base_url)
  203. bot = cls(client, base_url=base_url)
  204. await bot._probe_identity()
  205. return bot
  206. @classmethod
  207. def from_client(cls, client: ChattoClient) -> Bot:
  208. """Wrap an already-authenticated client (e.g. a human login)."""
  209. return cls(client)
  210. async def _probe_identity(self) -> None:
  211. """Resolve the bot's own identity and warn (not fail) if not a bot."""
  212. try:
  213. self._user = await self._client.me()
  214. except ChattoError:
  215. self._user = None
  216. return
  217. if self._user is not None and not self._user.is_bot:
  218. # Not fatal — a human client can drive the same verbs — but surface
  219. # it so a misconfigured key is obvious.
  220. import warnings
  221. warnings.warn(
  222. f"Bot key authenticated as {self._user.login!r}, which is not "
  223. "flagged is_bot. It will still work, but this is usually a "
  224. "misconfigured key.",
  225. stacklevel=2,
  226. )
  227. # -- identity ----------------------------------------------------------
  228. @property
  229. def client(self) -> ChattoClient:
  230. """The underlying :class:`ChattoClient` for any RPC not wrapped here."""
  231. return self._client
  232. @property
  233. def base_url(self) -> str:
  234. return self._base_url
  235. @property
  236. def user(self) -> User | None:
  237. """The bot's own :class:`User` profile, once known."""
  238. return self._user
  239. @property
  240. def login_name(self) -> str | None:
  241. return self._user.login if self._user else None
  242. @property
  243. def display_name(self) -> str | None:
  244. return self._user.display_name if self._user else None
  245. # -- lifecycle ---------------------------------------------------------
  246. async def __aenter__(self) -> Bot:
  247. return self
  248. async def __aexit__(self, *exc: Any) -> None:
  249. await self.close()
  250. async def close(self) -> None:
  251. if self._connection is not None:
  252. with contextlib.suppress(Exception):
  253. await self._connection.close()
  254. self._connection = None
  255. self._running = False
  256. await self._client.close()
  257. # -- event registration ------------------------------------------------
  258. def on(self, kind: str, handler: Handler) -> Handler:
  259. """Register ``handler`` for events of ``kind``.
  260. ``kind`` is one of: ``message``, ``reaction``, ``presence``,
  261. ``typing``, ``room``, ``user``, ``*`` (all events). ``handler`` is an
  262. ``async def`` taking a single :class:`BotEvent`. Returns the handler
  263. so ``on`` can be used as a decorator.
  264. """
  265. self._handlers.setdefault(kind, []).append(handler)
  266. return handler
  267. def off(self, kind: str, handler: Handler) -> None:
  268. with contextlib.suppress(ValueError):
  269. self._handlers[kind].remove(handler)
  270. async def _dispatch(self, event: BotEvent) -> None:
  271. handlers = list(self._handlers.get(event.kind, [])) + list(self._handlers.get("*", []))
  272. for handler in handlers:
  273. try:
  274. await handler(event)
  275. except Exception: # noqa: BLE001 - one bad handler must not kill the loop
  276. import logging
  277. logging.exception("bot handler for %r raised", event.kind)
  278. # -- verbs: messaging --------------------------------------------------
  279. async def say(self, room_id: str, body: str = "", *, join_if_needed: bool = True) -> Message:
  280. """Post a message to a room. Returns the created :class:`Message`.
  281. With ``join_if_needed`` (the default), the bot joins the room first if
  282. it isn't already a member — so a bot that wants to be present
  283. everywhere can simply ``await bot.say(room_id, ...)`` without a
  284. separate join step. Pass ``join_if_needed=False`` to instead surface
  285. the server's ``permission_denied`` if the bot can't post.
  286. """
  287. try:
  288. return await self._client.post_message(room_id, body)
  289. except ChattoError as exc:
  290. if not join_if_needed or "not a member" not in str(exc):
  291. raise
  292. await self._client.join_room(room_id)
  293. return await self._client.post_message(room_id, body)
  294. async def reply(
  295. self,
  296. target: BotMessageEvent | Message,
  297. body: str,
  298. *,
  299. also_send_to_channel: bool = False,
  300. ) -> Message:
  301. """Reply to a message (or a :class:`BotMessageEvent`) in its room/thread."""
  302. if isinstance(target, BotMessageEvent):
  303. target = target.message
  304. return await self._client.post_message(
  305. target.room_id,
  306. body,
  307. thread_root_event_id=target.thread_root_event_id,
  308. in_reply_to=target.id,
  309. also_send_to_channel=also_send_to_channel,
  310. )
  311. async def react(self, room_id: str, message_event_id: str, emoji: str) -> bool:
  312. """Add an emoji reaction to a message."""
  313. return await self._client.add_reaction(room_id, message_event_id, emoji)
  314. async def unreact(self, room_id: str, message_event_id: str, emoji: str) -> bool:
  315. """Remove one of the bot's emoji reactions from a message."""
  316. return await self._client.remove_reaction(room_id, message_event_id, emoji)
  317. # -- verbs: presence & status -----------------------------------------
  318. async def set_presence(self, status: PresenceStatus) -> PresenceStatus:
  319. """Set the bot's presence (``ONLINE`` / ``AWAY`` / ``DO_NOT_DISTURB``)."""
  320. return await self._client.set_presence(status)
  321. async def set_status(self, emoji: str, text: str) -> dict[str, Any]:
  322. """Set the bot's custom status (e.g. a "working on X" note)."""
  323. return await self._client.set_custom_status(emoji, text)
  324. async def clear_status(self) -> dict[str, Any]:
  325. """Clear the bot's custom status."""
  326. return await self._client.delete_custom_status()
  327. # -- verbs: rooms ------------------------------------------------------
  328. async def join_room(self, room_id: str) -> Room:
  329. """Join a room. Returns the joined :class:`Room`."""
  330. return await self._client.join_room(room_id)
  331. async def join_room_group(self, group_id: str) -> list[str]:
  332. """Join **all** the rooms in a room group in one call.
  333. Mirrors the Chatto UI's one-click "join group" action. Returns the
  334. list of room IDs the bot is now a member of as a result.
  335. """
  336. return await self._client.join_room_group(group_id)
  337. async def list_room_groups(self) -> list[RoomGroup]:
  338. """List the room groups (and the rooms each contains) the bot can see."""
  339. return await self._client.list_room_groups()
  340. async def join_all_rooms(self) -> list[str]:
  341. """Join every room the bot can see, grouped the way the UI does.
  342. Joins each room group in one call (so a bot becomes a member of all
  343. the rooms in a group at once), then joins any ungrouped rooms
  344. individually. Returns the room IDs the bot is now a member of.
  345. """
  346. joined: list[str] = []
  347. groups = await self.list_room_groups()
  348. grouped_room_ids: set[str] = set()
  349. for group in groups:
  350. for rws in group.rooms:
  351. if rws.room is not None:
  352. grouped_room_ids.add(rws.room.id)
  353. try:
  354. joined.extend(await self.join_room_group(group.id))
  355. except ChattoError:
  356. # A group the bot can't join is skipped, not fatal.
  357. continue
  358. # Rooms that are not part of any group.
  359. for rws in await self.list_rooms():
  360. if rws.room is None or rws.room.id in grouped_room_ids:
  361. continue
  362. if rws.viewer_state.is_member:
  363. continue
  364. try:
  365. joined.append((await self.join_room(rws.room.id)).id)
  366. except ChattoError:
  367. continue
  368. return joined
  369. async def leave_room(self, room_id: str) -> None:
  370. """Leave a room."""
  371. await self._client.leave_room(room_id)
  372. async def create_room(
  373. self,
  374. name: str,
  375. group_id: str,
  376. *,
  377. description: str = "",
  378. universal: bool = False,
  379. ) -> Room:
  380. """Create a room in a room group."""
  381. return await self._client.create_room(
  382. name, group_id, description=description, universal=universal
  383. )
  384. async def list_rooms(self) -> list[RoomWithViewerState]:
  385. """List the rooms the bot is a member of."""
  386. return await self._client.list_rooms()
  387. async def mark_read(self, room_id: str) -> None:
  388. """Mark a room as read (clears its unread state for the bot)."""
  389. await self._client.mark_room_as_read(room_id)
  390. # -- the run loop ------------------------------------------------------
  391. async def run(
  392. self,
  393. *,
  394. resume_cursor: str | None = None,
  395. until: asyncio.Event | None = None,
  396. ) -> None:
  397. """Connect the realtime stream and dispatch events until it closes.
  398. Reconnects automatically (resuming from the last received
  399. ``resume_cursor``) when the server sends a reconnectable close frame.
  400. When the server terminates the session (or sends a non-reconnectable
  401. close), the loop stops. Pass ``until`` to stop on an external signal.
  402. """
  403. self._running = True
  404. cursor = resume_cursor
  405. while self._running:
  406. if until is not None and until.is_set():
  407. break
  408. try:
  409. async for frame in stream_events(self._client, resume_cursor=cursor):
  410. if until is not None and until.is_set():
  411. break
  412. if isinstance(frame, RealtimeEvent):
  413. if frame.cursor:
  414. cursor = frame.cursor
  415. await self._handle_live(frame)
  416. except ChattoRealtimeCloseError as close:
  417. if not close.reconnect:
  418. # Session terminated or otherwise unrecoverable: stop.
  419. self._running = False
  420. break
  421. # Reconnectable close: loop again, resuming from the cursor.
  422. continue
  423. except ChattoRealtimeError:
  424. raise
  425. self._running = False
  426. # -- live-event dispatch -----------------------------------------------
  427. async def _handle_live(self, frame: RealtimeEvent) -> None:
  428. kind = frame.kind
  429. if kind == "presence_changed":
  430. await self._dispatch(
  431. BotPresenceEvent(
  432. bot=self,
  433. kind="presence",
  434. user_id=frame.actor_id or "",
  435. status=_presence(frame.payload.status),
  436. )
  437. )
  438. elif kind == "user_typing":
  439. payload = frame.payload
  440. await self._dispatch(
  441. BotTypingEvent(
  442. bot=self,
  443. kind="typing",
  444. room_id=payload.room_id,
  445. thread_root_event_id=payload.thread_root_event_id or None,
  446. )
  447. )
  448. elif kind in ("reaction_added", "reaction_removed"):
  449. payload = frame.payload
  450. await self._dispatch(
  451. BotReactionEvent(
  452. bot=self,
  453. kind="reaction",
  454. room_id=payload.room_id,
  455. message_event_id=payload.message_event_id,
  456. emoji=payload.emoji,
  457. user_id=frame.actor_id or "",
  458. added=kind == "reaction_added",
  459. )
  460. )
  461. elif kind == "message_posted":
  462. await self._on_message_posted(frame)
  463. elif kind in _ROOM_EVENT_KINDS:
  464. await self._on_room_event(frame)
  465. elif kind in _USER_EVENT_KINDS:
  466. await self._on_user_event(frame)
  467. async def _on_message_posted(self, frame: RealtimeEvent) -> None:
  468. # Protocol-4 events are thin hints; hydrate the full message so the
  469. # handler gets a usable :class:`Message` (including the body).
  470. payload = frame.payload
  471. msg: Message | None = None
  472. with contextlib.suppress(ChattoError):
  473. msg = await self._client.get_message(payload.room_id, frame.id)
  474. if msg is None:
  475. return
  476. await self._dispatch(BotMessageEvent(bot=self, kind="message", message=msg, actor=None))
  477. async def _on_room_event(self, frame: RealtimeEvent) -> None:
  478. payload = frame.payload
  479. room_id = getattr(payload, "room_id", "")
  480. if not room_id:
  481. return
  482. extra: dict[str, Any] = {}
  483. if frame.kind == "room_created":
  484. name = getattr(payload, "name", "")
  485. if name:
  486. extra["name"] = name
  487. room = Room.parse({"id": room_id, **extra})
  488. await self._dispatch(BotRoomEvent(bot=self, kind="room", room=room, detail=frame.kind))
  489. async def _on_user_event(self, frame: RealtimeEvent) -> None:
  490. user_id = getattr(frame.payload, "user_id", "") or frame.actor_id or ""
  491. removed = frame.kind == "user_account_deleted"
  492. await self._dispatch(
  493. BotUserEvent(
  494. bot=self,
  495. kind="user",
  496. user=User.parse({"id": user_id}) if user_id else None,
  497. removed=removed,
  498. )
  499. )