"""Connect an XMPP account to a Python handler: serve(jid, password, handler).""" from __future__ import annotations import asyncio import logging import re import sys from typing import Callable, Optional from xml.etree import ElementTree as ET _MARK = "{xmpp-cli-bridge}mark" # tags our replies so bounces back to us are dropped from slixmpp import ClientXMPP Handler = Callable[[str, str], Optional[str]] # control chars are illegal in XML 1.0; sending them kills the stream _XML_BAD = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\ud800-\udfff]") logger = logging.getLogger(__name__) class _Bridge(ClientXMPP): def __init__(self, jid: str, password: str, handler: Handler) -> None: super().__init__(jid, password) self._handler = handler self.add_event_handler("session_start", self._on_start) self.add_event_handler("message", self._on_message) async def _on_start(self, _event) -> None: logger.info("connected as %s", self.boundjid.bare) self.send_presence() async def _on_message(self, msg) -> None: if msg["type"] in ("groupchat", "error") or not msg["body"]: logger.debug("ignoring %s message from %s", msg["type"], msg["from"]) return if msg.xml.find(_MARK) is not None: # our own reply, bounced back return logger.info("message from %s: %.200r", msg["from"], str(msg["body"])) try: loop = asyncio.get_running_loop() reply = await loop.run_in_executor( None, self._handler, str(msg["body"]), str(msg["from"]) ) except Exception as exc: reply = f"error: {exc}" if reply is not None: # ESC (0x1b) etc. are illegal XML; sending them kills the stream # (seen live: pass ls output -> server ) out = msg.reply(_XML_BAD.sub("", str(reply))) ET.SubElement(out.xml, _MARK) out.send() logger.info("reply sent to %s (%d chars)", msg["from"], len(out["body"])) def serve(jid: str, password: str, handler: Handler) -> None: """Log in and dispatch messages to handler(body, sender_jid) -> reply or None. Blocks until Ctrl-C; handler runs in a worker thread so it may block. """ # one line per event on stdout; the child's stderr still goes to the # terminal, so the two don't interleave logging.basicConfig( stream=sys.stdout, level=logging.INFO, format="%(asctime)s %(message)s" ) async def _run() -> None: bot = _Bridge(jid, password, handler) bot.connect() try: await bot.disconnected finally: bot.disconnect() try: asyncio.run(_run()) except KeyboardInterrupt: pass