bot.py 22 KB

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