simplex-chat-python: add python library (#6954)

* docs: simplex-chat-python design and implementation plan

* bots: Python wire types codegen

* simplex-chat-python: package scaffold

* simplex-chat-python: native libsimplex loader

* simplex-chat-python: async FFI wrappers

* simplex-chat-python: ChatApi with 49 api methods

* simplex-chat-python: Bot class with decorators and dispatch

* simplex-chat-python: install CLI, example bot, README

* simplex-chat-python: audit fixes

* bots: regenerate API docs and types

Catches up the markdown, TypeScript and Python codegen outputs with two
upstream schema changes:

- APIConnectPlan.connectionLink became optional (from sh/python-lib audit
  fixes); cmdString and EBNF syntax now reflect optional parameter.
- APIAddGroupRelays command and CRGroupRelaysAdded/CRGroupRelaysAddFailed
  responses added in #6917 (relay management). The TS and markdown outputs
  were regenerated when #6917 landed but the Python types module only got
  the new entries with this regeneration.

* core: refresh SQLite query plans after relay_inactive_at migration

The M20260507_relay_inactive_at migration (#6917 / #6952) shifted the
query plans that 'Save query plans' verifies. Regenerated via the test
that owns those snapshots; no behavioral change.

* bots: keep APIConnectPlan connectionLink as required parameter

The prior audit-fixes commit changed the syntax expression to `Optional ...`
because the Haskell field is `connectionLink :: Maybe AConnectionLink`.
That misrepresents the API contract: the `Maybe` is purely an internal
signal for link-parsing failure (the handler returns `CEInvalidConnReq`
on `Nothing`), not API-level optionality. Callers MUST always pass a
connection link.

Revert the syntax expression to `Param "connectionLink"` and add a
comment so the intent is preserved next time someone audits.

Regenerates COMMANDS.md, commands.ts and _commands.py to match.
This commit is contained in:
sh
2026-05-12 11:32:01 +00:00
committed by GitHub
parent 5d597faf7e
commit e63c403623
38 changed files with 12051 additions and 49 deletions
@@ -0,0 +1,59 @@
"""SimpleX Chat — Python client library for chat bots."""
from ._version import __version__
from .api import ChatApi, ChatCommandError, ConnReqType, Db, PostgresDb, SqliteDb
from .bot import (
Bot,
BotCommand,
BotProfile,
ChatMessage,
CommandHandler,
EventHandler,
FileMessage,
ImageMessage,
LinkMessage,
Message,
MessageHandler,
Middleware,
ParsedCommand,
ReportMessage,
TextMessage,
UnknownMessage,
VideoMessage,
VoiceMessage,
)
from .core import ChatAPIError, ChatInitError, CryptoArgs, MigrationConfirmation
from . import util as util # re-export the util namespace
__all__ = [
"__version__",
"Bot",
"BotCommand",
"BotProfile",
"ChatAPIError",
"ChatApi",
"ChatCommandError",
"ChatInitError",
"ChatMessage",
"CommandHandler",
"ConnReqType",
"CryptoArgs",
"Db",
"EventHandler",
"FileMessage",
"ImageMessage",
"LinkMessage",
"Message",
"MessageHandler",
"Middleware",
"MigrationConfirmation",
"ParsedCommand",
"PostgresDb",
"ReportMessage",
"SqliteDb",
"TextMessage",
"UnknownMessage",
"VideoMessage",
"VoiceMessage",
"util",
]
@@ -0,0 +1,35 @@
"""CLI: ``python -m simplex_chat install [--backend=sqlite|postgres]``."""
from __future__ import annotations
import argparse
import sys
from . import _native
def main(argv: list[str] | None = None) -> int:
p = argparse.ArgumentParser(prog="simplex_chat")
sub = p.add_subparsers(dest="command", required=True)
install = sub.add_parser("install", help="Pre-fetch libsimplex into the user cache")
install.add_argument(
"--backend",
choices=["sqlite", "postgres"],
default="sqlite",
help="which libsimplex variant to download (default: sqlite)",
)
args = p.parse_args(argv)
# `args.command` is always set: `add_subparsers(required=True)` makes
# argparse exit before reaching this point if no subcommand is given.
assert args.command == "install"
try:
path = _native._resolve_libs_dir(args.backend)
print(f"libsimplex installed at: {path}")
return 0
except Exception as e:
print(f"install failed: {e}", file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main())
@@ -0,0 +1,257 @@
"""Native libsimplex loader: platform detection, lazy download, ctypes setup.
Internal — users interact with `Bot` / `ChatApi`, never with this module.
"""
from __future__ import annotations
import ctypes
import errno
import os
import platform
import sys
import tempfile
import threading
import urllib.request
import zipfile
from ctypes import POINTER, c_char_p, c_int, c_uint8, c_void_p
from pathlib import Path
from typing import Literal
from ._version import LIBS_VERSION
Backend = Literal["sqlite", "postgres"]
_GITHUB_REPO = "simplex-chat/simplex-chat-libs"
_PLATFORM_MAP = {
"linux": ("linux", {"x86_64": "x86_64", "aarch64": "aarch64"}),
"darwin": ("macos", {"x86_64": "x86_64", "arm64": "aarch64"}),
"win32": ("windows", {"AMD64": "x86_64", "x86_64": "x86_64"}),
}
_LIBNAME = {"linux": "libsimplex.so", "darwin": "libsimplex.dylib", "win32": "libsimplex.dll"}
SUPPORTED = (
"linux-x86_64",
"linux-aarch64",
"macos-x86_64",
"macos-aarch64",
"windows-x86_64",
)
def _platform_tag() -> str:
info = _PLATFORM_MAP.get(sys.platform)
if not info:
raise RuntimeError(f"Unsupported platform: {sys.platform}")
sysname, archs = info
arch = archs.get(platform.machine())
if not arch:
raise RuntimeError(f"Unsupported architecture: {sys.platform}/{platform.machine()}")
tag = f"{sysname}-{arch}"
if tag not in SUPPORTED:
raise RuntimeError(f"Unsupported combination: {tag}; supported: {SUPPORTED}")
return tag
def _libname() -> str:
return _LIBNAME[sys.platform]
def _libs_url(backend: Backend) -> str:
suffix = "-postgres" if backend == "postgres" else ""
return (
f"https://github.com/{_GITHUB_REPO}/releases/download/"
f"v{LIBS_VERSION}/simplex-chat-libs-{_platform_tag()}{suffix}.zip"
)
def _cache_root() -> Path:
if sys.platform == "darwin":
return Path.home() / "Library" / "Caches" / "simplex-chat"
if sys.platform == "win32":
return Path(os.environ["LOCALAPPDATA"]) / "simplex-chat"
base = os.environ.get("XDG_CACHE_HOME") or str(Path.home() / ".cache")
return Path(base) / "simplex-chat"
def _resolve_libs_dir(backend: Backend) -> Path:
if override := os.environ.get("SIMPLEX_LIBS_DIR"):
return Path(override)
if backend == "postgres" and _platform_tag() != "linux-x86_64":
raise RuntimeError(
"postgres backend is only supported on linux-x86_64; "
f"current platform is {_platform_tag()}"
)
target = _cache_root() / f"v{LIBS_VERSION}" / backend
if not (target / _libname()).exists():
_download(target, backend)
return target
_DOWNLOAD_CHUNK = 1 << 16 # 64 KiB
def _stream_to_file(url: str, dest: Path, *, timeout: float = 60.0) -> None:
"""Stream `url` → `dest`, printing a carriage-return progress bar.
`timeout` is per-request; we don't touch `socket.setdefaulttimeout`
so other socket users in the same process aren't affected.
"""
with urllib.request.urlopen(url, timeout=timeout) as resp: # noqa: S310 - https://github.com/...
total = int(resp.headers.get("Content-Length") or 0)
received = 0
with dest.open("wb") as out:
while chunk := resp.read(_DOWNLOAD_CHUNK):
out.write(chunk)
received += len(chunk)
if total > 0:
pct = min(100, received * 100 // total)
msg = f"\r download: {received >> 20} / {total >> 20} MiB ({pct}%)"
else:
msg = f"\r download: {received >> 20} MiB"
print(msg, end="", file=sys.stderr, flush=True)
print("", file=sys.stderr, flush=True) # newline after final progress line
def _download(target: Path, backend: Backend) -> None:
"""Download libs zip → atomic rename into `target`. Concurrent processes safe.
Atomicity strategy: each process extracts to its own sibling tempdir on the same
filesystem, then `os.rename` the `libs/` subdir to `target`. POSIX `os.rename`
onto a NON-EXISTENT path is atomic; if the target exists (another process won
the race), `os.rename` fails on most platforms — we then verify the winner has
what we need and proceed. NEVER rmtree the target: that creates a TOCTOU
window where another process is reading/loading the file we're deleting.
"""
target.parent.mkdir(parents=True, exist_ok=True)
url = _libs_url(backend)
print(
f"Downloading libsimplex ({_platform_tag()}, {backend}) v{LIBS_VERSION} from {url} ...",
file=sys.stderr,
flush=True,
)
with tempfile.TemporaryDirectory(dir=target.parent) as tmp:
zip_path = Path(tmp) / "libs.zip"
_stream_to_file(url, zip_path, timeout=60.0)
with zipfile.ZipFile(zip_path) as zf:
zf.extractall(tmp)
# zip layout: <tmp>/libs/libsimplex.* + libHS*.*
extracted_libs = Path(tmp) / "libs"
if not extracted_libs.is_dir():
raise RuntimeError(f"libs/ missing from {_libs_url(backend)}")
try:
os.rename(extracted_libs, target)
except OSError as e:
# EEXIST / ENOTEMPTY mean another process won the race — fall through
# and check that the winner left a usable libsimplex behind. Anything
# else (ENOSPC, EACCES, EROFS, Windows codes mapped to None) is a real
# failure and must propagate. Same VERSION cached → same content →
# safe to proceed once we've confirmed the file is there.
if e.errno not in (errno.EEXIST, errno.ENOTEMPTY):
raise
if not (target / _libname()).exists():
raise RuntimeError(
f"another process partially populated {target} but libsimplex "
f"is missing; remove the directory manually and retry"
) from e
_lock = threading.Lock()
_lib: ctypes.CDLL | None = None
_libc: ctypes.CDLL | None = None
_backend: Backend | None = None
def _load_libc() -> ctypes.CDLL:
if sys.platform == "win32":
return ctypes.CDLL("msvcrt")
return ctypes.CDLL(None) # libc on POSIX is the process's own symbol table
def _setup_signatures(lib: ctypes.CDLL) -> None:
"""Declare argtypes/restype for the 8 chat_* functions exported by libsimplex.
All result strings come back as raw c_void_p so the caller can free them
after copying — matches HandleCResult in cpp/simplex.cc:157-165.
"""
lib.chat_migrate_init.argtypes = [c_char_p, c_char_p, c_char_p, POINTER(c_void_p)]
lib.chat_migrate_init.restype = c_void_p
lib.chat_close_store.argtypes = [c_void_p]
lib.chat_close_store.restype = c_void_p
lib.chat_send_cmd.argtypes = [c_void_p, c_char_p]
lib.chat_send_cmd.restype = c_void_p
lib.chat_recv_msg_wait.argtypes = [c_void_p, c_int]
lib.chat_recv_msg_wait.restype = c_void_p
# chat_write_file's payload is treated read-only by libsimplex; passing
# `bytes` via c_char_p avoids the from_buffer_copy doubling. ctypes pins
# the bytes buffer for the duration of the call.
lib.chat_write_file.argtypes = [c_void_p, c_char_p, c_char_p, c_int]
lib.chat_write_file.restype = c_void_p
lib.chat_read_file.argtypes = [c_char_p, c_char_p, c_char_p]
lib.chat_read_file.restype = POINTER(c_uint8)
lib.chat_encrypt_file.argtypes = [c_void_p, c_char_p, c_char_p]
lib.chat_encrypt_file.restype = c_void_p
lib.chat_decrypt_file.argtypes = [c_char_p, c_char_p, c_char_p, c_char_p]
lib.chat_decrypt_file.restype = c_void_p
def _hs_init(lib: ctypes.CDLL) -> None:
"""Initialize the Haskell runtime exactly once. Mirrors cpp/simplex.cc:13-32."""
if sys.platform == "win32":
argv_strs = [b"simplex", b"+RTS", b"-A64m", b"-H64m", b"--install-signal-handlers=no"]
else:
argv_strs = [
b"simplex",
b"+RTS",
b"-A64m",
b"-H64m",
b"-xn",
b"--install-signal-handlers=no",
]
argc = c_int(len(argv_strs))
arr = (c_char_p * (len(argv_strs) + 1))(*argv_strs, None)
arr_ptr = ctypes.byref(ctypes.cast(arr, POINTER(c_char_p)))
lib.hs_init_with_rtsopts.argtypes = [POINTER(c_int), POINTER(POINTER(c_char_p))]
lib.hs_init_with_rtsopts.restype = None
lib.hs_init_with_rtsopts(ctypes.byref(argc), arr_ptr)
def lib_for(backend: Backend) -> ctypes.CDLL:
"""Resolve, load, and initialize libsimplex for the given backend.
Idempotent for the same backend; raises if called with a different backend.
Concurrent calls serialize on the module-level lock.
"""
global _lib, _libc, _backend
with _lock:
if _lib is not None:
if _backend != backend:
raise RuntimeError(
f"libsimplex already loaded with backend={_backend!r}; "
f"cannot switch to {backend!r} in the same process"
)
return _lib
libs_dir = _resolve_libs_dir(backend)
lib = ctypes.CDLL(str(libs_dir / _libname()))
_setup_signatures(lib)
_hs_init(lib)
_libc = _load_libc()
_lib = lib
_backend = backend
return lib
def libc() -> ctypes.CDLL:
"""libc — needed by `core` to free Haskell-allocated result strings."""
if _libc is None:
raise RuntimeError("lib_for() must be called before libc()")
return _libc
def lib() -> ctypes.CDLL:
"""Loaded libsimplex handle. Raises if `lib_for()` has not been called."""
if _lib is None:
raise RuntimeError("lib_for() must be called before lib()")
return _lib
@@ -0,0 +1,9 @@
"""Single source of truth for both the Python package version and the
simplex-chat-libs release tag we depend on.
Bump both together for normal releases. For wrapper-only fixes use a PEP 440
post-release: __version__ = "6.5.1.post1", LIBS_VERSION unchanged.
"""
__version__ = "6.5.1" # PEP 440 — read by hatchling for wheel metadata
LIBS_VERSION = "6.5.1" # simplex-chat-libs release tag (no 'v' prefix)
@@ -0,0 +1,704 @@
"""Low-level escape-hatch API. Most users go through `Bot` instead."""
from __future__ import annotations
import json
from dataclasses import dataclass
from typing import Any, Literal
from . import _native, core, util
from .core import MigrationConfirmation
from .types import CC, CEvt, CR, T
# Mirrors Node `ConnReqType` enum (api.ts:15-18) — the two possible outcomes
# of `api_connect` / `api_connect_active_user` depending on the link kind.
ConnReqType = Literal["invitation", "contact"]
@dataclass(slots=True)
class SqliteDb:
file_prefix: str
encryption_key: str | None = None
@dataclass(slots=True)
class PostgresDb:
connection_string: str
schema_prefix: str | None = None
Db = SqliteDb | PostgresDb
def _db_to_migrate_args(db: Db) -> tuple[str, str, _native.Backend]:
"""Returns (path-or-prefix, key-or-conn, backend)."""
if isinstance(db, SqliteDb):
return (db.file_prefix, db.encryption_key or "", "sqlite")
if isinstance(db, PostgresDb):
return (db.schema_prefix or "", db.connection_string, "postgres")
raise TypeError(f"Unknown db: {db!r}")
class ChatCommandError(Exception):
def __init__(self, message: str, response: CR.ChatResponse):
super().__init__(message)
self.response = response
class ChatApi:
def __init__(self, ctrl: int):
self._ctrl: int | None = ctrl
self._started = False
@classmethod
async def init(
cls,
db: Db,
confirm: MigrationConfirmation = MigrationConfirmation.YES_UP,
) -> "ChatApi":
path_or_prefix, key_or_conn, backend = _db_to_migrate_args(db)
# Trigger lazy lib load with the right backend BEFORE chat_migrate_init.
_native.lib_for(backend)
ctrl = await core.chat_migrate_init(path_or_prefix, key_or_conn, confirm)
return cls(ctrl)
@property
def ctrl(self) -> int:
"""Opaque controller pointer. Raises if `close()` has been called."""
if self._ctrl is None:
raise RuntimeError("ChatApi controller not initialized (close() called?)")
return self._ctrl
@property
def initialized(self) -> bool:
"""True until `close()` is called. Mirrors Node `ChatApi.initialized`."""
return self._ctrl is not None
@property
def started(self) -> bool:
"""True between `start_chat()` and the next `stop_chat()` / `close()`."""
return self._started
async def start_chat(self) -> None:
r = await self.send_chat_cmd(
CC.StartChat_cmd_string({"mainApp": True, "enableSndFiles": True})
)
if r.get("type") not in ("chatStarted", "chatRunning"):
raise ChatCommandError("error starting chat", r)
self._started = True
async def stop_chat(self) -> None:
r = await self.send_chat_cmd("/_stop")
if r.get("type") != "chatStopped":
raise ChatCommandError("error stopping chat", r)
self._started = False
async def close(self) -> None:
await core.chat_close_store(self.ctrl)
self._ctrl = None
self._started = False
async def send_chat_cmd(self, cmd: str) -> CR.ChatResponse:
return await core.chat_send_cmd(self.ctrl, cmd)
async def recv_chat_event(self, wait_us: int = 500_000) -> CEvt.ChatEvent | None:
return await core.chat_recv_msg_wait(self.ctrl, wait_us)
# ------------------------------------------------------------------ #
# Address commands
# ------------------------------------------------------------------ #
async def api_create_user_address(self, user_id: int) -> T.CreatedConnLink:
r = await self.send_chat_cmd(CC.APICreateMyAddress_cmd_string({"userId": user_id}))
if r["type"] == "userContactLinkCreated":
return r["connLinkContact"]
raise ChatCommandError("error creating user address", r)
async def api_delete_user_address(self, user_id: int) -> None:
r = await self.send_chat_cmd(CC.APIDeleteMyAddress_cmd_string({"userId": user_id}))
if r["type"] != "userContactLinkDeleted":
raise ChatCommandError("error deleting user address", r)
async def api_get_user_address(self, user_id: int) -> T.UserContactLink | None:
try:
r = await self.send_chat_cmd(CC.APIShowMyAddress_cmd_string({"userId": user_id}))
if r["type"] == "userContactLink":
return r["contactLink"]
raise ChatCommandError("error loading user address", r)
except core.ChatAPIError as e:
ce = e.chat_error
if (
ce is not None
and ce.get("type") == "errorStore"
and ce.get("storeError", {}).get("type") == "userContactLinkNotFound"
):
return None
raise
async def api_set_profile_address(
self, user_id: int, enable: bool
) -> T.UserProfileUpdateSummary:
r = await self.send_chat_cmd(
CC.APISetProfileAddress_cmd_string({"userId": user_id, "enable": enable})
)
if r["type"] == "userProfileUpdated":
return r["updateSummary"]
raise ChatCommandError("error setting profile address", r)
async def api_set_address_settings(self, user_id: int, settings: T.AddressSettings) -> None:
r = await self.send_chat_cmd(
CC.APISetAddressSettings_cmd_string({"userId": user_id, "settings": settings})
)
if r["type"] != "userContactLinkUpdated":
raise ChatCommandError("error changing user contact address settings", r)
# ------------------------------------------------------------------ #
# Message commands
# ------------------------------------------------------------------ #
async def api_send_messages(
self,
chat: list | T.ChatRef | T.ChatInfo,
messages: list[T.ComposedMessage],
live_message: bool = False,
) -> list[T.AChatItem]:
if isinstance(chat, list):
send_ref: T.ChatRef = {"chatType": chat[0], "chatId": chat[1]}
elif "chatType" in chat and "chatId" in chat:
send_ref = chat
else:
ref = util.chat_info_ref(chat)
if ref is None:
raise ValueError("api_send_messages: can't send messages to this chat")
send_ref = ref
r = await self.send_chat_cmd(
CC.APISendMessages_cmd_string(
{
"sendRef": send_ref,
"composedMessages": messages,
"liveMessage": live_message,
}
)
)
if r["type"] == "newChatItems":
return r["chatItems"]
raise ChatCommandError("unexpected response", r)
async def api_send_text_message(
self,
chat: list | T.ChatRef | T.ChatInfo,
text: str,
in_reply_to: int | None = None,
) -> list[T.AChatItem]:
msg: T.ComposedMessage = {"msgContent": {"type": "text", "text": text}, "mentions": {}}
if in_reply_to is not None:
msg["quotedItemId"] = in_reply_to
return await self.api_send_messages(chat, [msg])
async def api_send_text_reply(self, chat_item: T.AChatItem, text: str) -> list[T.AChatItem]:
return await self.api_send_text_message(
chat_item["chatInfo"], text, chat_item["chatItem"]["meta"]["itemId"]
)
async def api_update_chat_item(
self,
chat_type: T.ChatType,
chat_id: int,
chat_item_id: int,
msg_content: T.MsgContent,
live_message: bool = False,
) -> T.ChatItem:
r = await self.send_chat_cmd(
CC.APIUpdateChatItem_cmd_string(
{
"chatRef": {"chatType": chat_type, "chatId": chat_id},
"chatItemId": chat_item_id,
"liveMessage": live_message,
"updatedMessage": {"msgContent": msg_content, "mentions": {}},
}
)
)
if r["type"] == "chatItemUpdated":
return r["chatItem"]["chatItem"]
raise ChatCommandError("error updating chat item", r)
async def api_delete_chat_items(
self,
chat_type: T.ChatType,
chat_id: int,
chat_item_ids: list[int],
delete_mode: T.CIDeleteMode,
) -> list[T.ChatItemDeletion]:
r = await self.send_chat_cmd(
CC.APIDeleteChatItem_cmd_string(
{
"chatRef": {"chatType": chat_type, "chatId": chat_id},
"chatItemIds": chat_item_ids,
"deleteMode": delete_mode,
}
)
)
if r["type"] == "chatItemsDeleted":
return r["chatItemDeletions"]
raise ChatCommandError("error deleting chat item", r)
async def api_delete_member_chat_item(
self, group_id: int, chat_item_ids: list[int]
) -> list[T.ChatItemDeletion]:
r = await self.send_chat_cmd(
CC.APIDeleteMemberChatItem_cmd_string(
{"groupId": group_id, "chatItemIds": chat_item_ids}
)
)
if r["type"] == "chatItemsDeleted":
return r["chatItemDeletions"]
raise ChatCommandError("error deleting member chat item", r)
async def api_chat_item_reaction(
self,
chat_type: T.ChatType,
chat_id: int,
chat_item_id: int,
add: bool,
reaction: T.MsgReaction,
) -> T.ACIReaction:
r = await self.send_chat_cmd(
CC.APIChatItemReaction_cmd_string(
{
"chatRef": {"chatType": chat_type, "chatId": chat_id},
"chatItemId": chat_item_id,
"add": add,
"reaction": reaction,
}
)
)
if r["type"] == "chatItemReaction":
return r["reaction"]
raise ChatCommandError("error setting item reaction", r)
# ------------------------------------------------------------------ #
# File commands
# ------------------------------------------------------------------ #
async def api_receive_file(self, file_id: int) -> T.AChatItem:
r = await self.send_chat_cmd(
CC.ReceiveFile_cmd_string({"fileId": file_id, "userApprovedRelays": True})
)
if r["type"] == "rcvFileAccepted":
return r["chatItem"]
raise ChatCommandError("error receiving file", r)
async def api_cancel_file(self, file_id: int) -> None:
r = await self.send_chat_cmd(CC.CancelFile_cmd_string({"fileId": file_id}))
if r["type"] not in ("sndFileCancelled", "rcvFileCancelled"):
raise ChatCommandError("error canceling file", r)
# ------------------------------------------------------------------ #
# Group commands
# ------------------------------------------------------------------ #
async def api_add_member(
self, group_id: int, contact_id: int, member_role: T.GroupMemberRole
) -> T.GroupMember:
r = await self.send_chat_cmd(
CC.APIAddMember_cmd_string(
{"groupId": group_id, "contactId": contact_id, "memberRole": member_role}
)
)
if r["type"] == "sentGroupInvitation":
return r["member"]
raise ChatCommandError("error adding member", r)
async def api_join_group(self, group_id: int) -> T.GroupInfo:
r = await self.send_chat_cmd(CC.APIJoinGroup_cmd_string({"groupId": group_id}))
if r["type"] == "userAcceptedGroupSent":
return r["groupInfo"]
raise ChatCommandError("error joining group", r)
async def api_accept_member(
self, group_id: int, group_member_id: int, member_role: T.GroupMemberRole
) -> T.GroupMember:
r = await self.send_chat_cmd(
CC.APIAcceptMember_cmd_string(
{"groupId": group_id, "groupMemberId": group_member_id, "memberRole": member_role}
)
)
if r["type"] == "memberAccepted":
return r["member"]
raise ChatCommandError("error accepting member", r)
async def api_set_members_role(
self, group_id: int, group_member_ids: list[int], member_role: T.GroupMemberRole
) -> None:
r = await self.send_chat_cmd(
CC.APIMembersRole_cmd_string(
{"groupId": group_id, "groupMemberIds": group_member_ids, "memberRole": member_role}
)
)
if r["type"] != "membersRoleUser":
raise ChatCommandError("error setting members role", r)
async def api_block_members_for_all(
self, group_id: int, group_member_ids: list[int], blocked: bool
) -> None:
r = await self.send_chat_cmd(
CC.APIBlockMembersForAll_cmd_string(
{"groupId": group_id, "groupMemberIds": group_member_ids, "blocked": blocked}
)
)
if r["type"] != "membersBlockedForAllUser":
raise ChatCommandError("error blocking members", r)
async def api_remove_members(
self, group_id: int, member_ids: list[int], with_messages: bool = False
) -> list[T.GroupMember]:
r = await self.send_chat_cmd(
CC.APIRemoveMembers_cmd_string(
{"groupId": group_id, "groupMemberIds": member_ids, "withMessages": with_messages}
)
)
if r["type"] == "userDeletedMembers":
return r["members"]
raise ChatCommandError("error removing member", r)
async def api_leave_group(self, group_id: int) -> T.GroupInfo:
r = await self.send_chat_cmd(CC.APILeaveGroup_cmd_string({"groupId": group_id}))
if r["type"] == "leftMemberUser":
return r["groupInfo"]
raise ChatCommandError("error leaving group", r)
async def api_list_members(self, group_id: int) -> list[T.GroupMember]:
r = await self.send_chat_cmd(CC.APIListMembers_cmd_string({"groupId": group_id}))
if r["type"] == "groupMembers":
return r["group"]["members"]
raise ChatCommandError("error getting group members", r)
async def api_new_group(self, user_id: int, group_profile: T.GroupProfile) -> T.GroupInfo:
r = await self.send_chat_cmd(
CC.APINewGroup_cmd_string(
{"userId": user_id, "groupProfile": group_profile, "incognito": False}
)
)
if r["type"] == "groupCreated":
return r["groupInfo"]
raise ChatCommandError("error creating group", r)
async def api_update_group_profile(
self, group_id: int, group_profile: T.GroupProfile
) -> T.GroupInfo:
r = await self.send_chat_cmd(
CC.APIUpdateGroupProfile_cmd_string(
{"groupId": group_id, "groupProfile": group_profile}
)
)
if r["type"] == "groupUpdated":
return r["toGroup"]
raise ChatCommandError("error updating group", r)
# ------------------------------------------------------------------ #
# Group link commands
# ------------------------------------------------------------------ #
async def api_create_group_link(self, group_id: int, member_role: T.GroupMemberRole) -> str:
r = await self.send_chat_cmd(
CC.APICreateGroupLink_cmd_string({"groupId": group_id, "memberRole": member_role})
)
if r["type"] == "groupLinkCreated":
link = r["groupLink"]["connLinkContact"]
return link.get("connShortLink") or link["connFullLink"]
raise ChatCommandError("error creating group link", r)
async def api_set_group_link_member_role(
self, group_id: int, member_role: T.GroupMemberRole
) -> None:
r = await self.send_chat_cmd(
CC.APIGroupLinkMemberRole_cmd_string({"groupId": group_id, "memberRole": member_role})
)
if r["type"] != "groupLink":
raise ChatCommandError("error setting group link member role", r)
async def api_delete_group_link(self, group_id: int) -> None:
r = await self.send_chat_cmd(CC.APIDeleteGroupLink_cmd_string({"groupId": group_id}))
if r["type"] != "groupLinkDeleted":
raise ChatCommandError("error deleting group link", r)
async def api_get_group_link(self, group_id: int) -> T.GroupLink:
r = await self.send_chat_cmd(CC.APIGetGroupLink_cmd_string({"groupId": group_id}))
if r["type"] == "groupLink":
return r["groupLink"]
raise ChatCommandError("error getting group link", r)
async def api_get_group_link_str(self, group_id: int) -> str:
link = (await self.api_get_group_link(group_id))["connLinkContact"]
return link.get("connShortLink") or link["connFullLink"]
# ------------------------------------------------------------------ #
# Connection commands
# ------------------------------------------------------------------ #
async def api_create_link(self, user_id: int) -> str:
r = await self.send_chat_cmd(
CC.APIAddContact_cmd_string({"userId": user_id, "incognito": False})
)
if r["type"] == "invitation":
link = r["connLinkInvitation"]
return link.get("connShortLink") or link["connFullLink"]
raise ChatCommandError("error creating link", r)
async def api_connect_plan(
self, user_id: int, connection_link: str
) -> tuple[T.ConnectionPlan, T.CreatedConnLink]:
r = await self.send_chat_cmd(
CC.APIConnectPlan_cmd_string(
{"userId": user_id, "connectionLink": connection_link, "resolveKnown": False}
)
)
if r["type"] == "connectionPlan":
return (r["connectionPlan"], r["connLink"])
raise ChatCommandError("error getting connect plan", r)
async def api_connect(
self,
user_id: int,
incognito: bool,
prepared_link: T.CreatedConnLink | None = None,
) -> ConnReqType:
args: CC.APIConnect = {"userId": user_id, "incognito": incognito}
if prepared_link is not None:
args["preparedLink_"] = prepared_link
r = await self.send_chat_cmd(CC.APIConnect_cmd_string(args))
return self._handle_connect_result(r)
async def api_connect_active_user(self, conn_link: str) -> ConnReqType:
r = await self.send_chat_cmd(
CC.Connect_cmd_string({"incognito": False, "connLink_": conn_link})
)
return self._handle_connect_result(r)
def _handle_connect_result(self, r: CR.ChatResponse) -> ConnReqType:
if r["type"] == "sentConfirmation":
return "invitation"
if r["type"] == "sentInvitation":
return "contact"
if r["type"] == "contactAlreadyExists":
raise ChatCommandError("contact already exists", r)
raise ChatCommandError("connection error", r)
async def api_accept_contact_request(self, contact_req_id: int) -> T.Contact:
r = await self.send_chat_cmd(
CC.APIAcceptContact_cmd_string({"contactReqId": contact_req_id})
)
if r["type"] == "acceptingContactRequest":
return r["contact"]
raise ChatCommandError("error accepting contact request", r)
async def api_reject_contact_request(self, contact_req_id: int) -> None:
r = await self.send_chat_cmd(
CC.APIRejectContact_cmd_string({"contactReqId": contact_req_id})
)
if r["type"] != "contactRequestRejected":
raise ChatCommandError("error rejecting contact request", r)
# ------------------------------------------------------------------ #
# Chat commands
# ------------------------------------------------------------------ #
async def api_list_contacts(self, user_id: int) -> list[T.Contact]:
r = await self.send_chat_cmd(CC.APIListContacts_cmd_string({"userId": user_id}))
if r["type"] == "contactsList":
return r["contacts"]
raise ChatCommandError("error listing contacts", r)
async def api_list_groups(
self,
user_id: int,
contact_id: int | None = None,
search: str | None = None,
) -> list[T.GroupInfo]:
args: CC.APIListGroups = {"userId": user_id}
if contact_id is not None:
args["contactId_"] = contact_id
if search is not None:
args["search"] = search
r = await self.send_chat_cmd(CC.APIListGroups_cmd_string(args))
if r["type"] == "groupsList":
return r["groups"]
raise ChatCommandError("error listing groups", r)
async def api_get_chats(
self,
user_id: int,
pagination: T.PaginationByTime,
query: T.ChatListQuery | None = None,
pending_connections: bool = False,
) -> list[T.AChat]:
if query is None:
query = {"type": "filters", "favorite": False, "unread": False}
r = await self.send_chat_cmd(
CC.APIGetChats_cmd_string(
{
"userId": user_id,
"pendingConnections": pending_connections,
"pagination": pagination,
"query": query,
}
)
)
if r["type"] == "apiChats":
return r["chats"]
raise ChatCommandError("error getting chats", r)
async def api_delete_chat(
self,
chat_type: T.ChatType,
chat_id: int,
delete_mode: T.ChatDeleteMode | None = None,
) -> None:
if delete_mode is None:
delete_mode = {"type": "full", "notify": True}
r = await self.send_chat_cmd(
CC.APIDeleteChat_cmd_string(
{
"chatRef": {"chatType": chat_type, "chatId": chat_id},
"chatDeleteMode": delete_mode,
}
)
)
if chat_type == "direct" and r["type"] == "contactDeleted":
return
if chat_type == "group" and r["type"] == "groupDeletedUser":
return
raise ChatCommandError("error deleting chat", r)
async def api_set_group_custom_data(
self, group_id: int, custom_data: dict[str, object] | None = None
) -> None:
args: CC.APISetGroupCustomData = {"groupId": group_id}
if custom_data is not None:
args["customData"] = custom_data
r = await self.send_chat_cmd(CC.APISetGroupCustomData_cmd_string(args))
if r["type"] != "cmdOk":
raise ChatCommandError("error setting group custom data", r)
async def api_set_contact_custom_data(
self, contact_id: int, custom_data: dict[str, object] | None = None
) -> None:
args: CC.APISetContactCustomData = {"contactId": contact_id}
if custom_data is not None:
args["customData"] = custom_data
r = await self.send_chat_cmd(CC.APISetContactCustomData_cmd_string(args))
if r["type"] != "cmdOk":
raise ChatCommandError("error setting contact custom data", r)
async def api_set_auto_accept_member_contacts(self, user_id: int, on_off: bool) -> None:
r = await self.send_chat_cmd(
CC.APISetUserAutoAcceptMemberContacts_cmd_string({"userId": user_id, "onOff": on_off})
)
if r["type"] != "cmdOk":
raise ChatCommandError("error setting auto-accept member contacts", r)
async def api_get_chat(self, chat_type: T.ChatType, chat_id: int, count: int) -> dict[str, Any]:
ref = T.ChatType_cmd_string(chat_type) + str(chat_id)
r = await self.send_chat_cmd(f"/_get chat {ref} count={count}")
if r["type"] == "apiChat":
return r["chat"]
raise ChatCommandError("error getting chat", r)
# ------------------------------------------------------------------ #
# User profile commands
# ------------------------------------------------------------------ #
async def api_get_active_user(self) -> T.User | None:
try:
r = await self.send_chat_cmd(CC.ShowActiveUser_cmd_string({}))
if r["type"] == "activeUser":
return r["user"]
raise ChatCommandError("unexpected response", r)
except core.ChatAPIError as e:
ce = e.chat_error
if (
ce is not None
and ce.get("type") == "error"
and ce.get("errorType", {}).get("type") == "noActiveUser"
):
return None
raise
async def api_create_active_user(self, profile: T.Profile | None = None) -> T.User:
new_user: T.NewUser = {"pastTimestamp": False, "userChatRelay": False}
if profile is not None:
new_user["profile"] = profile
r = await self.send_chat_cmd(CC.CreateActiveUser_cmd_string({"newUser": new_user}))
if r["type"] == "activeUser":
return r["user"]
raise ChatCommandError("unexpected response", r)
async def api_list_users(self) -> list[T.UserInfo]:
r = await self.send_chat_cmd(CC.ListUsers_cmd_string({}))
if r["type"] == "usersList":
return r["users"]
raise ChatCommandError("error listing users", r)
async def api_set_active_user(self, user_id: int, view_pwd: str | None = None) -> T.User:
args: CC.APISetActiveUser = {"userId": user_id}
if view_pwd is not None:
args["viewPwd"] = view_pwd
r = await self.send_chat_cmd(CC.APISetActiveUser_cmd_string(args))
if r["type"] == "activeUser":
return r["user"]
raise ChatCommandError("error setting active user", r)
async def api_delete_user(
self, user_id: int, del_smp_queues: bool, view_pwd: str | None = None
) -> None:
args: CC.APIDeleteUser = {"userId": user_id, "delSMPQueues": del_smp_queues}
if view_pwd is not None:
args["viewPwd"] = view_pwd
r = await self.send_chat_cmd(CC.APIDeleteUser_cmd_string(args))
if r["type"] != "cmdOk":
raise ChatCommandError("error deleting user", r)
async def api_update_profile(
self, user_id: int, profile: T.Profile
) -> T.UserProfileUpdateSummary | None:
r = await self.send_chat_cmd(
CC.APIUpdateProfile_cmd_string({"userId": user_id, "profile": profile})
)
if r["type"] == "userProfileNoChange":
return None
if r["type"] == "userProfileUpdated":
return r["updateSummary"]
raise ChatCommandError("error updating profile", r)
async def api_set_contact_prefs(self, contact_id: int, preferences: T.Preferences) -> None:
r = await self.send_chat_cmd(
CC.APISetContactPrefs_cmd_string({"contactId": contact_id, "preferences": preferences})
)
if r["type"] != "contactPrefsUpdated":
raise ChatCommandError("error setting contact prefs", r)
# ------------------------------------------------------------------ #
# Member contact commands
# ------------------------------------------------------------------ #
async def api_create_member_contact(self, group_id: int, group_member_id: int) -> T.Contact:
r = await self.send_chat_cmd(f"/_create member contact #{group_id} {group_member_id}")
if r["type"] == "newMemberContact":
return r["contact"]
raise ChatCommandError("error creating member contact", r)
async def api_send_member_contact_invitation(
self,
contact_id: int,
message: T.MsgContent | str | None = None,
) -> T.Contact:
cmd = f"/_invite member contact @{contact_id}"
if message is not None:
if isinstance(message, str):
cmd += f" text {message}"
else:
cmd += f" json {json.dumps(message)}"
r = await self.send_chat_cmd(cmd)
if r["type"] == "newMemberContactSentInv":
return r["contact"]
raise ChatCommandError("error sending member contact invitation", r)
@@ -0,0 +1,707 @@
"""User-facing `Bot` API: decorators, filters, Message wrapper, lifecycle."""
from __future__ import annotations
import asyncio
import logging
import os
import signal as _signal
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from typing import Any, Generic, Literal, TypeVar, overload
from . import util
from .api import ChatApi, Db
from .core import MigrationConfirmation
from .filters import compile_message_filter
from .types import CEvt, T
log = logging.getLogger("simplex_chat")
C = TypeVar("C", bound="T.MsgContent")
@dataclass(slots=True)
class BotProfile:
display_name: str
full_name: str = ""
short_descr: str | None = None
image: str | None = None
@dataclass(slots=True)
class BotCommand:
keyword: str
label: str
@dataclass(slots=True, frozen=True)
class ParsedCommand:
keyword: str
args: str
@dataclass(slots=True, frozen=True)
class Message(Generic[C]):
chat_item: T.AChatItem
content: C
bot: "Bot"
@property
def chat_info(self) -> T.ChatInfo:
return self.chat_item["chatInfo"]
@property
def text(self) -> str | None:
c = self.content
if isinstance(c, dict):
return c.get("text") # type: ignore[return-value]
return None
async def reply(self, text: str) -> "Message[T.MsgContent]":
items = await self.bot.api.api_send_text_reply(self.chat_item, text)
ci = items[0]
content = ci["chatItem"]["content"]
# content is CIContent — snd variant has msgContent; cast for type safety.
msg_content: T.MsgContent = content["msgContent"] # type: ignore[index]
return Message(chat_item=ci, content=msg_content, bot=self.bot)
async def reply_content(self, content: T.MsgContent) -> "Message[T.MsgContent]":
items = await self.bot.api.api_send_messages(
self.chat_info, [{"msgContent": content, "mentions": {}}]
)
ci = items[0]
ci_content = ci["chatItem"]["content"]
msg_content: T.MsgContent = ci_content["msgContent"] # type: ignore[index]
return Message(chat_item=ci, content=msg_content, bot=self.bot)
# Concrete narrowed aliases — one per MsgContent_<tag> variant in _types.py.
TextMessage = Message[T.MsgContent_text]
LinkMessage = Message[T.MsgContent_link]
ImageMessage = Message[T.MsgContent_image]
VideoMessage = Message[T.MsgContent_video]
VoiceMessage = Message[T.MsgContent_voice]
FileMessage = Message[T.MsgContent_file]
ReportMessage = Message[T.MsgContent_report]
ChatMessage = Message[T.MsgContent_chat]
UnknownMessage = Message[T.MsgContent_unknown]
MessageHandler = Callable[[Message[Any]], Awaitable[None]]
CommandHandler = Callable[[Message[Any], ParsedCommand], Awaitable[None]]
EventHandler = Callable[[CEvt.ChatEvent], Awaitable[None]]
class Middleware:
"""Override `__call__` to wrap message handlers with cross-cutting logic.
`handler` is the next stage in the chain — call it with `(message, data)`
to continue, or skip the call to short-circuit. `data` is a per-dispatch
dict that middleware can use to pass values down the chain.
"""
async def __call__(
self,
handler: Callable[[Message[Any], dict[str, object]], Awaitable[None]],
message: Message[Any],
data: dict[str, object],
) -> None:
await handler(message, data)
class Bot:
def __init__(
self,
*,
profile: BotProfile,
db: Db,
welcome: str | T.MsgContent | None = None,
commands: list[BotCommand] | None = None,
confirm_migrations: MigrationConfirmation = MigrationConfirmation.YES_UP,
create_address: bool = True,
update_address: bool = True,
update_profile: bool = True,
auto_accept: bool = True,
business_address: bool = False,
allow_files: bool = False,
use_bot_profile: bool = True,
log_contacts: bool = True,
log_network: bool = False,
) -> None:
self._profile = profile
self._db = db
self._welcome = welcome
self._commands = commands or []
self._confirm_migrations = confirm_migrations
self._opts = {
"create_address": create_address,
"update_address": update_address,
"update_profile": update_profile,
"auto_accept": auto_accept,
"business_address": business_address,
"allow_files": allow_files,
"use_bot_profile": use_bot_profile,
"log_contacts": log_contacts,
"log_network": log_network,
}
self._api: ChatApi | None = None
self._serving = False
self._stop_event = asyncio.Event()
self._message_handlers: list[tuple[Callable[[Message[Any]], bool], MessageHandler]] = []
self._command_handlers: list[
tuple[tuple[str, ...], Callable[[Message[Any]], bool], CommandHandler]
] = []
self._event_handlers: dict[str, list[EventHandler]] = {}
self._middleware: list[Middleware] = []
# Track default-handler registration so __aenter__ on a re-used bot
# doesn't accumulate duplicate log/error handlers.
self._defaults_registered = False
@property
def api(self) -> ChatApi:
if self._api is None:
raise RuntimeError("Bot not initialized — call bot.run() or use `async with bot:`")
return self._api
# ------------------------------------------------------------------ #
# Decorators
# ------------------------------------------------------------------ #
@overload
def on_message(
self, *, content_type: Literal["text"], **rest: Any
) -> Callable[
[Callable[[TextMessage], Awaitable[None]]],
Callable[[TextMessage], Awaitable[None]],
]: ...
@overload
def on_message(
self, *, content_type: Literal["link"], **rest: Any
) -> Callable[
[Callable[[LinkMessage], Awaitable[None]]],
Callable[[LinkMessage], Awaitable[None]],
]: ...
@overload
def on_message(
self, *, content_type: Literal["image"], **rest: Any
) -> Callable[
[Callable[[ImageMessage], Awaitable[None]]],
Callable[[ImageMessage], Awaitable[None]],
]: ...
@overload
def on_message(
self, *, content_type: Literal["video"], **rest: Any
) -> Callable[
[Callable[[VideoMessage], Awaitable[None]]],
Callable[[VideoMessage], Awaitable[None]],
]: ...
@overload
def on_message(
self, *, content_type: Literal["voice"], **rest: Any
) -> Callable[
[Callable[[VoiceMessage], Awaitable[None]]],
Callable[[VoiceMessage], Awaitable[None]],
]: ...
@overload
def on_message(
self, *, content_type: Literal["file"], **rest: Any
) -> Callable[
[Callable[[FileMessage], Awaitable[None]]],
Callable[[FileMessage], Awaitable[None]],
]: ...
@overload
def on_message(
self, *, content_type: Literal["report"], **rest: Any
) -> Callable[
[Callable[[ReportMessage], Awaitable[None]]],
Callable[[ReportMessage], Awaitable[None]],
]: ...
@overload
def on_message(
self, *, content_type: Literal["chat"], **rest: Any
) -> Callable[
[Callable[[ChatMessage], Awaitable[None]]],
Callable[[ChatMessage], Awaitable[None]],
]: ...
@overload
def on_message(
self, *, content_type: Literal["unknown"], **rest: Any
) -> Callable[
[Callable[[UnknownMessage], Awaitable[None]]],
Callable[[UnknownMessage], Awaitable[None]],
]: ...
@overload
def on_message(self, **rest: Any) -> Callable[[MessageHandler], MessageHandler]: ...
def on_message(self, **filter_kw: Any) -> Callable[[MessageHandler], MessageHandler]:
predicate = compile_message_filter(filter_kw)
def deco(fn: MessageHandler) -> MessageHandler:
self._message_handlers.append((predicate, fn))
return fn
return deco
def on_command(
self, name: str | tuple[str, ...], **filter_kw: Any
) -> Callable[[CommandHandler], CommandHandler]:
names = (name,) if isinstance(name, str) else tuple(name)
predicate = compile_message_filter(filter_kw)
def deco(fn: CommandHandler) -> CommandHandler:
self._command_handlers.append((names, predicate, fn))
return fn
return deco
def on_event(self, event: CEvt.ChatEvent_Tag, /) -> Callable[[EventHandler], EventHandler]:
def deco(fn: EventHandler) -> EventHandler:
self._event_handlers.setdefault(event, []).append(fn)
return fn
return deco
def use(self, middleware: Middleware) -> None:
self._middleware.append(middleware)
# ------------------------------------------------------------------ #
# Lifecycle
# ------------------------------------------------------------------ #
async def __aenter__(self) -> "Bot":
# Order matters: libsimplex `/_start` requires an active user, so
# ensure (or create) the user first, THEN start the chat, THEN
# do address + profile sync. Mirrors Node bot.ts:48-64.
self._api = await ChatApi.init(self._db, self._confirm_migrations)
user = await self._ensure_active_user()
await self._api.start_chat()
await self._sync_address_and_profile(user)
self._register_log_handlers()
return self
async def __aexit__(self, *exc_info: object) -> None:
self.stop()
if self._api is not None:
try:
await self._api.stop_chat()
finally:
await self._api.close()
self._api = None
def run(self) -> None:
"""Blocking entry: runs serve_forever() with SIGINT/SIGTERM handlers installed.
Configures `logging.basicConfig(level=INFO)` if the root logger has no
handlers yet, so the bot's startup messages and the announced address
are visible without callers having to set up logging. Embedders that
manage logging themselves are unaffected (basicConfig is a no-op when
handlers already exist).
"""
if not logging.getLogger().handlers:
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s %(message)s",
)
async def _main() -> None:
async with self:
loop = asyncio.get_running_loop()
# First Ctrl+C → graceful stop (~500ms, bounded by the
# receive-loop poll interval). Second Ctrl+C → force-exit
# immediately (in case stop_chat / close hang on a wedged
# FFI call). Standard CLI UX (jupyter, ipython, …).
sigint_count = 0
def on_interrupt() -> None:
nonlocal sigint_count
sigint_count += 1
if sigint_count == 1:
log.info("stopping bot... (press Ctrl+C again to force exit)")
self.stop()
else:
os._exit(130) # 128 + SIGINT
if hasattr(_signal, "SIGINT"):
try:
loop.add_signal_handler(_signal.SIGINT, on_interrupt)
loop.add_signal_handler(_signal.SIGTERM, self.stop)
except NotImplementedError: # Windows
_signal.signal(_signal.SIGINT, lambda *_: on_interrupt())
await self.serve_forever()
asyncio.run(_main())
async def serve_forever(self) -> None:
if self._serving:
raise RuntimeError("already serving")
self._serving = True
self._stop_event.clear()
try:
await self._receive_loop()
finally:
self._serving = False
def stop(self) -> None:
self._stop_event.set()
async def _receive_loop(self) -> None:
# Catch broad Exception so a single malformed event or transient
# native error doesn't crash the whole bot. CancelledError must
# always re-raise so `bot.stop()` and asyncio cancellation work.
# `wait_us=500_000` (500ms) bounds the worst-case Ctrl+C latency:
# the C call blocks the worker thread until timeout, and the loop
# only checks `_stop_event` between polls.
while not self._stop_event.is_set():
try:
event = await self.api.recv_chat_event(wait_us=500_000)
except asyncio.CancelledError:
raise
except Exception:
log.exception("recv_chat_event failed")
# Bound the spin rate when the FFI is wedged on a persistent
# error (vs the timeout path, which already paces itself).
await asyncio.sleep(0.5)
continue
if event is None:
continue
try:
await self._dispatch_event(event)
except asyncio.CancelledError:
raise
except Exception:
log.exception("dispatch_event failed for tag=%s", event.get("type"))
# ------------------------------------------------------------------ #
# Dispatch
# ------------------------------------------------------------------ #
async def _dispatch_event(self, event: CEvt.ChatEvent) -> None:
tag = event["type"]
for h in self._event_handlers.get(tag, []):
try:
await h(event)
except Exception:
log.exception("on_event handler failed")
if tag == "newChatItems":
evt: CEvt.NewChatItems = event # type: ignore[assignment]
for ci in evt["chatItems"]:
content = ci["chatItem"]["content"]
if content["type"] != "rcvMsgContent":
continue
msg_content = content["msgContent"] # type: ignore[index]
msg: Message[T.MsgContent] = Message(chat_item=ci, content=msg_content, bot=self)
await self._dispatch_message(msg)
async def _dispatch_message(self, msg: Message[Any]) -> None:
# First-match-wins. The squaring bot's `@on_message(text=NUMBER_RE)`
# and catch-all `@on_message(content_type="text")` both match a number
# like "1"; we want only the first to fire. Registration order is the
# priority order — register the most-specific filters first.
#
# Slash-commands are tried first against command handlers; if no
# command handler matches, fall through to message handlers (so
# `@on_message` can still catch unknown slash-commands).
cmd = self._parse_command(msg)
if cmd is not None:
for names, predicate, handler in self._command_handlers:
if cmd.keyword in names and predicate(msg):
await self._invoke_command_with_middleware(handler, msg, cmd)
return
for predicate, handler in self._message_handlers:
if predicate(msg):
await self._invoke_with_middleware(handler, msg)
return
async def _invoke_with_middleware(self, handler: MessageHandler, message: Message[Any]) -> None:
# Fast path: most bots register no middleware. Skip the closure-chain
# construction and the empty-data dict on every dispatch.
if not self._middleware:
try:
await handler(message)
except Exception:
log.exception("message handler failed")
return
async def call(m: Message[Any], _data: dict[str, object]) -> None:
await handler(m)
chain: Callable[[Message[Any], dict[str, object]], Awaitable[None]] = call
for mw in reversed(self._middleware):
inner = chain
async def _wrapped(
m: Message[Any],
d: dict[str, object],
mw: Middleware = mw,
inner: Callable[[Message[Any], dict[str, object]], Awaitable[None]] = inner,
) -> None:
await mw(inner, m, d)
chain = _wrapped
try:
await chain(message, {})
except Exception:
log.exception("message handler failed")
async def _invoke_command_with_middleware(
self, handler: CommandHandler, message: Message[Any], cmd: ParsedCommand
) -> None:
if not self._middleware:
try:
await handler(message, cmd)
except Exception:
log.exception("command handler failed")
return
async def call(m: Message[Any], _data: dict[str, object]) -> None:
await handler(m, cmd)
chain: Callable[[Message[Any], dict[str, object]], Awaitable[None]] = call
for mw in reversed(self._middleware):
inner = chain
async def _wrapped(
m: Message[Any],
d: dict[str, object],
mw: Middleware = mw,
inner: Callable[[Message[Any], dict[str, object]], Awaitable[None]] = inner,
) -> None:
await mw(inner, m, d)
chain = _wrapped
try:
await chain(message, {})
except Exception:
log.exception("command handler failed")
@staticmethod
def _parse_command(msg: Message[Any]) -> ParsedCommand | None:
parsed = util.ci_bot_command(msg.chat_item["chatItem"])
if parsed is None:
return None
keyword, args = parsed
return ParsedCommand(keyword=keyword, args=args)
# ------------------------------------------------------------------ #
# Profile + address sync
# ------------------------------------------------------------------ #
async def _ensure_active_user(self) -> T.User:
"""Get or create the active user. Must run before `start_chat`.
Mirrors Node `createBotUser` (bot.ts:158-166). The chat controller
won't accept `/_start` without a user, so this phase has to land
before lifecycle proceeds.
"""
api = self.api
user = await api.api_get_active_user()
if user is None:
log.info("No active user in database, creating...")
user = await api.api_create_active_user(self._bot_profile_to_wire())
log.info("Bot user: %s", user["profile"]["displayName"])
return user
async def _sync_address_and_profile(self, user: T.User) -> None:
"""Address + profile sync. Runs after `start_chat` (mirrors bot.ts:57-63)."""
api = self.api
user_id = user["userId"]
# 2. Address (numbered to match bot.ts comments — phase 1 was user creation).
address = await api.api_get_user_address(user_id)
if address is None:
if self._opts["create_address"]:
log.info("Bot has no address, creating...")
await api.api_create_user_address(user_id)
address = await api.api_get_user_address(user_id)
if address is None:
raise RuntimeError("Failed reading newly created user address")
else:
log.warning("Bot has no address")
# Always announce the address — matches Node bot.ts:60.
link: str | None = None
if address is not None:
link = util.contact_address_str(address["connLinkContact"])
log.info("Bot address: %s", link)
# 3. Address settings (auto-accept + welcome message). Mirrors bot.ts:185-194.
# autoAccept present → accept; absent → no auto-accept (mirrors Node bot.ts).
if address is not None and self._opts["update_address"]:
desired: T.AddressSettings = {"businessAddress": self._opts["business_address"]}
if self._opts["auto_accept"]:
desired["autoAccept"] = {"acceptIncognito": False}
if self._welcome is not None:
desired["autoReply"] = (
{"type": "text", "text": self._welcome}
if isinstance(self._welcome, str)
else self._welcome
)
if address["addressSettings"] != desired:
log.info("Bot address settings changed, updating...")
await api.api_set_address_settings(user_id, desired)
# 4. Profile update. Mirrors Node `updateBotUserProfile` (bot.ts:199-214).
# Field-by-field comparison: user["profile"] is LocalProfile (has extra
# fields profileId, localAlias, preferences, peerType) so a full-dict
# equality would always differ.
new_profile = self._bot_profile_to_wire()
if link is not None and self._opts["use_bot_profile"]:
# Mirrors bot.ts:62 — embed the connection link in the bot's profile
# so contacts that resolve the bot via stored profile data see the
# current address.
new_profile["contactLink"] = link
cur = user["profile"]
changed = (
cur["displayName"] != new_profile["displayName"]
or cur.get("fullName", "") != new_profile.get("fullName", "")
or cur.get("shortDescr") != new_profile.get("shortDescr")
or cur.get("image") != new_profile.get("image")
or cur.get("preferences") != new_profile.get("preferences")
or cur.get("peerType") != new_profile.get("peerType")
or cur.get("contactLink") != new_profile.get("contactLink")
)
if changed and self._opts["update_profile"]:
log.info("Bot profile changed, updating...")
await api.api_update_profile(user_id, new_profile)
def _bot_profile_to_wire(self) -> T.Profile:
"""Construct wire-format Profile, applying bot conventions when use_bot_profile=True.
Mirrors Node mkBotProfile (bot.ts:88-102): bots get peerType="bot",
calls/voice prefs disabled, files gated on `allow_files`, and any
registered `commands` embedded in the profile preferences.
"""
p: T.Profile = {
"displayName": self._profile.display_name,
"fullName": self._profile.full_name,
}
if self._profile.short_descr is not None:
p["shortDescr"] = self._profile.short_descr
if self._profile.image is not None:
p["image"] = self._profile.image
if self._opts["use_bot_profile"]:
prefs: T.Preferences = {
"calls": {"allow": "no"},
"voice": {"allow": "no"},
"files": {"allow": "yes" if self._opts["allow_files"] else "no"},
}
if self._commands:
prefs["commands"] = [
{"type": "command", "keyword": c.keyword, "label": c.label}
for c in self._commands
]
p["preferences"] = prefs
p["peerType"] = "bot"
elif self._commands:
raise ValueError(
"use_bot_profile=False but commands were passed; commands are "
"only sent when use_bot_profile=True (they're embedded in the "
"user profile preferences)."
)
return p
# ------------------------------------------------------------------ #
# Log subscriptions (mirror Node subscribeLogEvents bot.ts:142-156)
# ------------------------------------------------------------------ #
def _register_log_handlers(self) -> None:
# Idempotent: a Bot reused across multiple `__aenter__` cycles must
# not stack duplicate log handlers. Always-on error handlers run
# regardless of log_contacts/log_network so messageError/chatError/
# chatErrors don't disappear into the void.
if self._defaults_registered:
return
self._defaults_registered = True
self._event_handlers.setdefault("messageError", []).append(self._log_message_error)
self._event_handlers.setdefault("chatError", []).append(self._log_chat_error)
self._event_handlers.setdefault("chatErrors", []).append(self._log_chat_errors)
if self._opts["log_contacts"]:
self._event_handlers.setdefault("contactConnected", []).append(
self._log_contact_connected
)
self._event_handlers.setdefault("contactDeletedByContact", []).append(
self._log_contact_deleted
)
if self._opts["log_network"]:
self._event_handlers.setdefault("hostConnected", []).append(self._log_host_connected)
self._event_handlers.setdefault("hostDisconnected", []).append(
self._log_host_disconnected
)
self._event_handlers.setdefault("subscriptionStatus", []).append(
self._log_subscription_status
)
@staticmethod
async def _log_contact_connected(evt: CEvt.ChatEvent) -> None:
log.info("%s connected", evt["contact"]["profile"]["displayName"]) # type: ignore[index]
@staticmethod
async def _log_contact_deleted(evt: CEvt.ChatEvent) -> None:
log.info(
"%s deleted connection with bot",
evt["contact"]["profile"]["displayName"], # type: ignore[index]
)
@staticmethod
async def _log_host_connected(evt: CEvt.ChatEvent) -> None:
log.info("connected server %s", evt["transportHost"]) # type: ignore[index]
@staticmethod
async def _log_host_disconnected(evt: CEvt.ChatEvent) -> None:
log.info("disconnected server %s", evt["transportHost"]) # type: ignore[index]
@staticmethod
async def _log_subscription_status(evt: CEvt.ChatEvent) -> None:
log.info(
"%d subscription(s) %s",
len(evt["connections"]), # type: ignore[index]
evt["subscriptionStatus"]["type"], # type: ignore[index]
)
@staticmethod
async def _log_message_error(evt: CEvt.ChatEvent) -> None:
log.warning("messageError: %s", evt.get("severity", "?")) # type: ignore[union-attr]
@staticmethod
async def _log_chat_error(evt: CEvt.ChatEvent) -> None:
err = evt.get("chatError") # type: ignore[union-attr]
log.error("chatError: %s", err.get("type") if isinstance(err, dict) else err)
@staticmethod
async def _log_chat_errors(evt: CEvt.ChatEvent) -> None:
errs = evt.get("chatErrors") or [] # type: ignore[union-attr]
log.error("chatErrors: %d errors", len(errs))
# Suppress unused-import warnings for re-exported names used only at type-check time.
__all__ = [
"Bot",
"BotCommand",
"BotProfile",
"ChatMessage",
"FileMessage",
"ImageMessage",
"LinkMessage",
"Message",
"MessageHandler",
"CommandHandler",
"EventHandler",
"Middleware",
"ParsedCommand",
"ReportMessage",
"TextMessage",
"UnknownMessage",
"VideoMessage",
"VoiceMessage",
]
@@ -0,0 +1,200 @@
"""Internal typed async wrapper around libsimplex's 8 C ABI functions.
Users interact with `Bot` / `ChatApi`. This module is exposed as
`simplex_chat.core` for tests and the api.ChatApi class only.
"""
from __future__ import annotations
import asyncio
import ctypes
import json
from enum import StrEnum
from typing import Any, TypedDict
from . import _native
from .types import T, CR, CEvt
class ChatAPIError(Exception):
"""Raised when chat_send_cmd / chat_recv_msg_wait returns a chat error."""
def __init__(self, message: str, chat_error: T.ChatError | None = None):
super().__init__(message)
self.chat_error = chat_error
class ChatInitError(Exception):
"""Raised when chat_migrate_init returns a DBMigrationResult error."""
def __init__(self, message: str, db_migration_error: dict[str, Any]):
super().__init__(message)
self.db_migration_error = db_migration_error
class MigrationConfirmation(StrEnum):
YES_UP = "yesUp"
YES_UP_DOWN = "yesUpDown"
CONSOLE = "console"
ERROR = "error"
class CryptoArgs(TypedDict): # wire-format JSON; camelCase fields
fileKey: str
fileNonce: str
def _read_and_free(ptr: int | None) -> str:
"""Copy a Haskell-allocated null-terminated UTF-8 string and free its buffer.
Mirrors HandleCResult in packages/simplex-chat-nodejs/cpp/simplex.cc:157-165.
"""
if not ptr:
raise RuntimeError("null pointer returned from libsimplex")
try:
return ctypes.string_at(ptr).decode("utf-8")
finally:
_native.libc().free(ctypes.c_void_p(ptr))
async def chat_send_cmd(ctrl: int, cmd: str) -> CR.ChatResponse:
def _call() -> str:
ptr = _native.lib().chat_send_cmd(ctrl, cmd.encode("utf-8"))
return _read_and_free(ptr)
raw = await asyncio.to_thread(_call)
parsed = json.loads(raw)
if "result" in parsed and isinstance(parsed["result"], dict):
return parsed["result"] # type: ignore[return-value]
err = parsed.get("error")
if isinstance(err, dict):
raise ChatAPIError(f"chat command error: {err.get('type')}", err) # type: ignore[arg-type]
raise ChatAPIError(f"invalid chat command result: {raw[:200]}")
async def chat_recv_msg_wait(ctrl: int, wait_us: int = 500_000) -> CEvt.ChatEvent | None:
def _call() -> str:
# On timeout, the C side returns a non-NULL pointer to a single NUL byte
# (see Mobile.hs `fromMaybe ""`), so `_read_and_free` returns "" — no
# NULL-pointer guard is needed here.
ptr = _native.lib().chat_recv_msg_wait(ctrl, wait_us)
return _read_and_free(ptr)
raw = await asyncio.to_thread(_call)
if not raw:
return None
parsed = json.loads(raw)
if "result" in parsed and isinstance(parsed["result"], dict):
return parsed["result"] # type: ignore[return-value]
err = parsed.get("error")
if isinstance(err, dict):
raise ChatAPIError(f"chat event error: {err.get('type')}", err) # type: ignore[arg-type]
raise ChatAPIError(f"invalid chat event: {raw[:200]}")
async def chat_migrate_init(db_path: str, db_key: str, confirm: MigrationConfirmation) -> int:
"""Initialize chat controller. Returns opaque ctrl pointer as Python int."""
def _call() -> tuple[int, str]:
ctrl = ctypes.c_void_p()
ptr = _native.lib().chat_migrate_init(
db_path.encode("utf-8"),
db_key.encode("utf-8"),
confirm.encode("utf-8"),
ctypes.byref(ctrl),
)
return (ctrl.value or 0, _read_and_free(ptr))
ctrl_val, raw = await asyncio.to_thread(_call)
parsed = json.loads(raw)
if parsed.get("type") == "ok":
if not ctrl_val:
# ABI invariant: type=="ok" → out-param written. Defensive guard so a
# broken libsimplex doesn't hand us a NULL controller that would only
# crash on first use much later.
raise RuntimeError("chat_migrate_init returned ok but did not set ctrl pointer")
return ctrl_val
raise ChatInitError(
"Database or migration error (see db_migration_error)",
parsed,
)
async def chat_close_store(ctrl: int) -> None:
def _call() -> str:
ptr = _native.lib().chat_close_store(ctrl)
return _read_and_free(ptr)
res = await asyncio.to_thread(_call)
if res:
raise RuntimeError(res)
async def chat_write_file(ctrl: int, path: str, data: bytes) -> CryptoArgs:
def _call() -> str:
ptr = _native.lib().chat_write_file(ctrl, path.encode("utf-8"), data, len(data))
return _read_and_free(ptr)
raw = await asyncio.to_thread(_call)
return _crypto_args_result(raw)
async def chat_read_file(path: str, args: CryptoArgs) -> bytes:
def _call() -> bytes:
ptr = _native.lib().chat_read_file(
path.encode("utf-8"),
args["fileKey"].encode("utf-8"),
args["fileNonce"].encode("utf-8"),
)
if not ptr:
raise RuntimeError("chat_read_file returned null")
addr = ctypes.cast(ptr, ctypes.c_void_p).value
assert addr is not None # `if not ptr` above already filtered NULL
try:
status = ctypes.cast(addr, ctypes.POINTER(ctypes.c_uint8))[0]
if status == 1:
msg = ctypes.string_at(addr + 1).decode("utf-8")
raise RuntimeError(msg)
if status != 0:
raise RuntimeError(f"unexpected status {status} from chat_read_file")
# `addr + 1` is unaligned for a uint32 read. On the supported platforms
# (linux-x86_64, linux-aarch64, macos-aarch64, windows-x86_64) this is
# silently handled; matches the Node.js binding (cpp/simplex.cc:344).
length = ctypes.cast(addr + 1, ctypes.POINTER(ctypes.c_uint32))[0]
return ctypes.string_at(addr + 5, length)
finally:
_native.libc().free(ctypes.c_void_p(addr))
return await asyncio.to_thread(_call)
async def chat_encrypt_file(ctrl: int, src: str, dst: str) -> CryptoArgs:
def _call() -> str:
ptr = _native.lib().chat_encrypt_file(ctrl, src.encode("utf-8"), dst.encode("utf-8"))
return _read_and_free(ptr)
return _crypto_args_result(await asyncio.to_thread(_call))
async def chat_decrypt_file(src: str, args: CryptoArgs, dst: str) -> None:
def _call() -> str:
ptr = _native.lib().chat_decrypt_file(
src.encode("utf-8"),
args["fileKey"].encode("utf-8"),
args["fileNonce"].encode("utf-8"),
dst.encode("utf-8"),
)
return _read_and_free(ptr)
res = await asyncio.to_thread(_call)
if res:
raise RuntimeError(res)
def _crypto_args_result(raw: str) -> CryptoArgs:
parsed = json.loads(raw)
if parsed.get("type") == "result":
return parsed["cryptoArgs"]
if parsed.get("type") == "error":
raise RuntimeError(parsed.get("writeError", "unknown write error"))
raise RuntimeError(f"unexpected result: {raw[:200]}")
@@ -0,0 +1,45 @@
"""Compile kwarg-based message filters into a single predicate."""
from __future__ import annotations
import re
from typing import Any, Callable
def compile_message_filter(kw: dict[str, Any]) -> Callable[[Any], bool]:
"""Compile filter kwargs into a single predicate function.
Multiple kwargs combine with AND; tuples within a kwarg combine with OR.
`when` is the last predicate evaluated.
"""
predicates: list[Callable[[Any], bool]] = []
if (ct := kw.get("content_type")) is not None:
ct_set = (ct,) if isinstance(ct, str) else tuple(ct)
predicates.append(lambda m: m.content.get("type") in ct_set)
if (t := kw.get("text")) is not None:
if isinstance(t, re.Pattern):
predicates.append(lambda m: bool(t.search(m.content.get("text", "") or "")))
else:
predicates.append(lambda m: m.content.get("text") == t)
if (cht := kw.get("chat_type")) is not None:
cht_set = (cht,) if isinstance(cht, str) else tuple(cht)
predicates.append(lambda m: m.chat_item["chatInfo"]["type"] in cht_set)
if (gid := kw.get("group_id")) is not None:
gid_set: tuple[int, ...] = (gid,) if isinstance(gid, int) else tuple(gid)
def gid_match(m: Any) -> bool:
ci = m.chat_item["chatInfo"]
return ci["type"] == "group" and ci["groupInfo"]["groupId"] in gid_set
predicates.append(gid_match)
if (when := kw.get("when")) is not None:
predicates.append(when)
if not predicates:
return lambda _m: True
return lambda m: all(p(m) for p in predicates)
@@ -0,0 +1,16 @@
"""SimpleX Chat wire types — auto-generated from Haskell.
Re-exports the four generated modules as namespaces:
- ``T`` — :mod:`._types` (records, enums, discriminated unions)
- ``CC`` — :mod:`._commands` (command TypedDicts + ``<Cmd>_cmd_string`` helpers)
- ``CR`` — :mod:`._responses` (``ChatResponse`` and member TypedDicts)
- ``CEvt`` — :mod:`._events` (``ChatEvent`` and member TypedDicts)
"""
from . import _commands as CC
from . import _events as CEvt
from . import _responses as CR
from . import _types as T
__all__ = ["T", "CC", "CR", "CEvt"]
@@ -0,0 +1,705 @@
# API Commands
# This file is generated automatically.
from __future__ import annotations
import json
from typing import NotRequired, TypedDict
from . import _types as T
from . import _responses as CR
# Address commands
# Bots can use these commands to automatically check and create address when initialized
# Create bot address.
# Network usage: interactive.
class APICreateMyAddress(TypedDict):
userId: int # int64
def APICreateMyAddress_cmd_string(self: APICreateMyAddress) -> str:
return '/_address ' + str(self['userId'])
APICreateMyAddress_Response = CR.UserContactLinkCreated | CR.ChatCmdError
# Delete bot address.
# Network usage: background.
class APIDeleteMyAddress(TypedDict):
userId: int # int64
def APIDeleteMyAddress_cmd_string(self: APIDeleteMyAddress) -> str:
return '/_delete_address ' + str(self['userId'])
APIDeleteMyAddress_Response = CR.UserContactLinkDeleted | CR.ChatCmdError
# Get bot address and settings.
# Network usage: no.
class APIShowMyAddress(TypedDict):
userId: int # int64
def APIShowMyAddress_cmd_string(self: APIShowMyAddress) -> str:
return '/_show_address ' + str(self['userId'])
APIShowMyAddress_Response = CR.UserContactLink | CR.ChatCmdError
# Add address to bot profile.
# Network usage: interactive.
class APISetProfileAddress(TypedDict):
userId: int # int64
enable: bool
def APISetProfileAddress_cmd_string(self: APISetProfileAddress) -> str:
return '/_profile_address ' + str(self['userId']) + ' ' + ('on' if self['enable'] else 'off')
APISetProfileAddress_Response = CR.UserProfileUpdated | CR.ChatCmdError
# Set bot address settings.
# Network usage: interactive.
class APISetAddressSettings(TypedDict):
userId: int # int64
settings: "T.AddressSettings"
def APISetAddressSettings_cmd_string(self: APISetAddressSettings) -> str:
return '/_address_settings ' + str(self['userId']) + ' ' + json.dumps(self['settings'])
APISetAddressSettings_Response = CR.UserContactLinkUpdated | CR.ChatCmdError
# Message commands
# Commands to send, update, delete, moderate messages and set message reactions
# Send messages.
# Network usage: background.
class APISendMessages(TypedDict):
sendRef: "T.ChatRef"
liveMessage: bool
ttl: NotRequired[int] # int
composedMessages: list["T.ComposedMessage"] # non-empty
def APISendMessages_cmd_string(self: APISendMessages) -> str:
return '/_send ' + T.ChatRef_cmd_string(self['sendRef']) + (' live=on' if self['liveMessage'] else '') + ((' ttl=' + str(self.get('ttl'))) if self.get('ttl') is not None else '') + ' json ' + json.dumps(self['composedMessages'])
APISendMessages_Response = CR.NewChatItems | CR.ChatCmdError
# Update message.
# Network usage: background.
class APIUpdateChatItem(TypedDict):
chatRef: "T.ChatRef"
chatItemId: int # int64
liveMessage: bool
updatedMessage: "T.UpdatedMessage"
def APIUpdateChatItem_cmd_string(self: APIUpdateChatItem) -> str:
return '/_update item ' + T.ChatRef_cmd_string(self['chatRef']) + ' ' + str(self['chatItemId']) + (' live=on' if self['liveMessage'] else '') + ' json ' + json.dumps(self['updatedMessage'])
APIUpdateChatItem_Response = CR.ChatItemUpdated | CR.ChatItemNotChanged | CR.ChatCmdError
# Delete message.
# Network usage: background.
class APIDeleteChatItem(TypedDict):
chatRef: "T.ChatRef"
chatItemIds: list[int] # int64, non-empty
deleteMode: "T.CIDeleteMode"
def APIDeleteChatItem_cmd_string(self: APIDeleteChatItem) -> str:
return '/_delete item ' + T.ChatRef_cmd_string(self['chatRef']) + ' ' + ','.join(map(str, self['chatItemIds'])) + ' ' + str(self['deleteMode'])
APIDeleteChatItem_Response = CR.ChatItemsDeleted | CR.ChatCmdError
# Moderate message. Requires Moderator role (and higher than message author's).
# Network usage: background.
class APIDeleteMemberChatItem(TypedDict):
groupId: int # int64
chatItemIds: list[int] # int64, non-empty
def APIDeleteMemberChatItem_cmd_string(self: APIDeleteMemberChatItem) -> str:
return '/_delete member item #' + str(self['groupId']) + ' ' + ','.join(map(str, self['chatItemIds']))
APIDeleteMemberChatItem_Response = CR.ChatItemsDeleted | CR.ChatCmdError
# Add/remove message reaction.
# Network usage: background.
class APIChatItemReaction(TypedDict):
chatRef: "T.ChatRef"
chatItemId: int # int64
add: bool
reaction: "T.MsgReaction"
def APIChatItemReaction_cmd_string(self: APIChatItemReaction) -> str:
return '/_reaction ' + T.ChatRef_cmd_string(self['chatRef']) + ' ' + str(self['chatItemId']) + ' ' + ('on' if self['add'] else 'off') + ' ' + json.dumps(self['reaction'])
APIChatItemReaction_Response = CR.ChatItemReaction | CR.ChatCmdError
# File commands
# Commands to receive and to cancel files. Files are sent as part of the message, there are no separate commands to send files.
# Receive file.
# Network usage: no.
class ReceiveFile(TypedDict):
fileId: int # int64
userApprovedRelays: bool
storeEncrypted: NotRequired[bool]
fileInline: NotRequired[bool]
filePath: NotRequired[str]
def ReceiveFile_cmd_string(self: ReceiveFile) -> str:
return '/freceive ' + str(self['fileId']) + (' approved_relays=on' if self['userApprovedRelays'] else '') + ((' encrypt=' + ('on' if self.get('storeEncrypted') else 'off')) if self.get('storeEncrypted') is not None else '') + ((' inline=' + ('on' if self.get('fileInline') else 'off')) if self.get('fileInline') is not None else '') + ((' ' + self.get('filePath')) if self.get('filePath') is not None else '')
ReceiveFile_Response = CR.RcvFileAccepted | CR.RcvFileAcceptedSndCancelled | CR.ChatCmdError
# Cancel file.
# Network usage: background.
class CancelFile(TypedDict):
fileId: int # int64
def CancelFile_cmd_string(self: CancelFile) -> str:
return '/fcancel ' + str(self['fileId'])
CancelFile_Response = CR.SndFileCancelled | CR.RcvFileCancelled | CR.ChatCmdError
# Group commands
# Commands to manage and moderate groups. These commands can be used with business chats as well - they are groups. E.g., a common scenario would be to add human agents to business chat with the customer who connected via business address.
# Add contact to group. Requires bot to have Admin role.
# Network usage: interactive.
class APIAddMember(TypedDict):
groupId: int # int64
contactId: int # int64
memberRole: "T.GroupMemberRole"
def APIAddMember_cmd_string(self: APIAddMember) -> str:
return '/_add #' + str(self['groupId']) + ' ' + str(self['contactId']) + ' ' + str(self['memberRole'])
APIAddMember_Response = CR.SentGroupInvitation | CR.ChatCmdError
# Join group.
# Network usage: interactive.
class APIJoinGroup(TypedDict):
groupId: int # int64
def APIJoinGroup_cmd_string(self: APIJoinGroup) -> str:
return '/_join #' + str(self['groupId'])
APIJoinGroup_Response = CR.UserAcceptedGroupSent | CR.ChatCmdError
# Accept group member. Requires Admin role.
# Network usage: background.
class APIAcceptMember(TypedDict):
groupId: int # int64
groupMemberId: int # int64
memberRole: "T.GroupMemberRole"
def APIAcceptMember_cmd_string(self: APIAcceptMember) -> str:
return '/_accept member #' + str(self['groupId']) + ' ' + str(self['groupMemberId']) + ' ' + str(self['memberRole'])
APIAcceptMember_Response = CR.MemberAccepted | CR.ChatCmdError
# Set members role. Requires Admin role.
# Network usage: background.
class APIMembersRole(TypedDict):
groupId: int # int64
groupMemberIds: list[int] # int64, non-empty
memberRole: "T.GroupMemberRole"
def APIMembersRole_cmd_string(self: APIMembersRole) -> str:
return '/_member role #' + str(self['groupId']) + ' ' + ','.join(map(str, self['groupMemberIds'])) + ' ' + str(self['memberRole'])
APIMembersRole_Response = CR.MembersRoleUser | CR.ChatCmdError
# Block members. Requires Moderator role.
# Network usage: background.
class APIBlockMembersForAll(TypedDict):
groupId: int # int64
groupMemberIds: list[int] # int64, non-empty
blocked: bool
def APIBlockMembersForAll_cmd_string(self: APIBlockMembersForAll) -> str:
return '/_block #' + str(self['groupId']) + ' ' + ','.join(map(str, self['groupMemberIds'])) + ' blocked=' + ('on' if self['blocked'] else 'off')
APIBlockMembersForAll_Response = CR.MembersBlockedForAllUser | CR.ChatCmdError
# Remove members. Requires Admin role.
# Network usage: background.
class APIRemoveMembers(TypedDict):
groupId: int # int64
groupMemberIds: list[int] # int64, non-empty
withMessages: bool
def APIRemoveMembers_cmd_string(self: APIRemoveMembers) -> str:
return '/_remove #' + str(self['groupId']) + ' ' + ','.join(map(str, self['groupMemberIds'])) + (' messages=on' if self['withMessages'] else '')
APIRemoveMembers_Response = CR.UserDeletedMembers | CR.ChatCmdError
# Leave group.
# Network usage: background.
class APILeaveGroup(TypedDict):
groupId: int # int64
def APILeaveGroup_cmd_string(self: APILeaveGroup) -> str:
return '/_leave #' + str(self['groupId'])
APILeaveGroup_Response = CR.LeftMemberUser | CR.ChatCmdError
# Get group members.
# Network usage: no.
class APIListMembers(TypedDict):
groupId: int # int64
def APIListMembers_cmd_string(self: APIListMembers) -> str:
return '/_members #' + str(self['groupId'])
APIListMembers_Response = CR.GroupMembers | CR.ChatCmdError
# Create group.
# Network usage: no.
class APINewGroup(TypedDict):
userId: int # int64
incognito: bool
groupProfile: "T.GroupProfile"
def APINewGroup_cmd_string(self: APINewGroup) -> str:
return '/_group ' + str(self['userId']) + (' incognito=on' if self['incognito'] else '') + ' ' + json.dumps(self['groupProfile'])
APINewGroup_Response = CR.GroupCreated | CR.ChatCmdError
# Create public group.
# Network usage: interactive.
class APINewPublicGroup(TypedDict):
userId: int # int64
incognito: bool
relayIds: list[int] # int64, non-empty
groupProfile: "T.GroupProfile"
def APINewPublicGroup_cmd_string(self: APINewPublicGroup) -> str:
return '/_public group ' + str(self['userId']) + (' incognito=on' if self['incognito'] else '') + ' ' + ','.join(map(str, self['relayIds'])) + ' ' + json.dumps(self['groupProfile'])
APINewPublicGroup_Response = CR.PublicGroupCreated | CR.PublicGroupCreationFailed | CR.ChatCmdError
# Get group relays.
# Network usage: no.
class APIGetGroupRelays(TypedDict):
groupId: int # int64
def APIGetGroupRelays_cmd_string(self: APIGetGroupRelays) -> str:
return '/_get relays #' + str(self['groupId'])
APIGetGroupRelays_Response = CR.GroupRelays | CR.ChatCmdError
# Add relays to group.
# Network usage: interactive.
class APIAddGroupRelays(TypedDict):
groupId: int # int64
relayIds: list[int] # int64, non-empty
def APIAddGroupRelays_cmd_string(self: APIAddGroupRelays) -> str:
return '/_add relays #' + str(self['groupId']) + ' ' + ','.join(map(str, self['relayIds']))
APIAddGroupRelays_Response = CR.GroupRelaysAdded | CR.GroupRelaysAddFailed | CR.ChatCmdError
# Update group profile.
# Network usage: background.
class APIUpdateGroupProfile(TypedDict):
groupId: int # int64
groupProfile: "T.GroupProfile"
def APIUpdateGroupProfile_cmd_string(self: APIUpdateGroupProfile) -> str:
return '/_group_profile #' + str(self['groupId']) + ' ' + json.dumps(self['groupProfile'])
APIUpdateGroupProfile_Response = CR.GroupUpdated | CR.ChatCmdError
# Group link commands
# These commands can be used by bots that manage multiple public groups
# Create group link.
# Network usage: interactive.
class APICreateGroupLink(TypedDict):
groupId: int # int64
memberRole: "T.GroupMemberRole"
def APICreateGroupLink_cmd_string(self: APICreateGroupLink) -> str:
return '/_create link #' + str(self['groupId']) + ' ' + str(self['memberRole'])
APICreateGroupLink_Response = CR.GroupLinkCreated | CR.ChatCmdError
# Set member role for group link.
# Network usage: no.
class APIGroupLinkMemberRole(TypedDict):
groupId: int # int64
memberRole: "T.GroupMemberRole"
def APIGroupLinkMemberRole_cmd_string(self: APIGroupLinkMemberRole) -> str:
return '/_set link role #' + str(self['groupId']) + ' ' + str(self['memberRole'])
APIGroupLinkMemberRole_Response = CR.GroupLink | CR.ChatCmdError
# Delete group link.
# Network usage: background.
class APIDeleteGroupLink(TypedDict):
groupId: int # int64
def APIDeleteGroupLink_cmd_string(self: APIDeleteGroupLink) -> str:
return '/_delete link #' + str(self['groupId'])
APIDeleteGroupLink_Response = CR.GroupLinkDeleted | CR.ChatCmdError
# Get group link.
# Network usage: no.
class APIGetGroupLink(TypedDict):
groupId: int # int64
def APIGetGroupLink_cmd_string(self: APIGetGroupLink) -> str:
return '/_get link #' + str(self['groupId'])
APIGetGroupLink_Response = CR.GroupLink | CR.ChatCmdError
# Connection commands
# These commands may be used to create connections. Most bots do not need to use them - bot users will connect via bot address with auto-accept enabled.
# Create 1-time invitation link.
# Network usage: interactive.
class APIAddContact(TypedDict):
userId: int # int64
incognito: bool
def APIAddContact_cmd_string(self: APIAddContact) -> str:
return '/_connect ' + str(self['userId']) + (' incognito=on' if self['incognito'] else '')
APIAddContact_Response = CR.Invitation | CR.ChatCmdError
# Determine SimpleX link type and if the bot is already connected via this link.
# Network usage: interactive.
class APIConnectPlan(TypedDict):
userId: int # int64
connectionLink: NotRequired[str]
resolveKnown: bool
linkOwnerSig: NotRequired["T.LinkOwnerSig"]
def APIConnectPlan_cmd_string(self: APIConnectPlan) -> str:
return '/_connect plan ' + str(self['userId']) + ' ' + self.get('connectionLink')
APIConnectPlan_Response = CR.ConnectionPlan | CR.ChatCmdError
# Connect via prepared SimpleX link. The link can be 1-time invitation link, contact address or group link.
# Network usage: interactive.
class APIConnect(TypedDict):
userId: int # int64
incognito: bool
preparedLink_: NotRequired["T.CreatedConnLink"]
def APIConnect_cmd_string(self: APIConnect) -> str:
return '/_connect ' + str(self['userId']) + ((' ' + T.CreatedConnLink_cmd_string(self.get('preparedLink_'))) if self.get('preparedLink_') is not None else '')
APIConnect_Response = CR.SentConfirmation | CR.ContactAlreadyExists | CR.SentInvitation | CR.ChatCmdError
# Connect via SimpleX link as string in the active user profile.
# Network usage: interactive.
class Connect(TypedDict):
incognito: bool
connLink_: NotRequired[str]
def Connect_cmd_string(self: Connect) -> str:
return '/connect' + ((' ' + self.get('connLink_')) if self.get('connLink_') is not None else '')
Connect_Response = CR.SentConfirmation | CR.ContactAlreadyExists | CR.SentInvitation | CR.ChatCmdError
# Accept contact request.
# Network usage: interactive.
class APIAcceptContact(TypedDict):
contactReqId: int # int64
def APIAcceptContact_cmd_string(self: APIAcceptContact) -> str:
return '/_accept ' + str(self['contactReqId'])
APIAcceptContact_Response = CR.AcceptingContactRequest | CR.ChatCmdError
# Reject contact request. The user who sent the request is **not notified**.
# Network usage: no.
class APIRejectContact(TypedDict):
contactReqId: int # int64
def APIRejectContact_cmd_string(self: APIRejectContact) -> str:
return '/_reject ' + str(self['contactReqId'])
APIRejectContact_Response = CR.ContactRequestRejected | CR.ChatCmdError
# Chat commands
# Commands to list and delete conversations.
# Get contacts.
# Network usage: no.
class APIListContacts(TypedDict):
userId: int # int64
def APIListContacts_cmd_string(self: APIListContacts) -> str:
return '/_contacts ' + str(self['userId'])
APIListContacts_Response = CR.ContactsList | CR.ChatCmdError
# Get groups.
# Network usage: no.
class APIListGroups(TypedDict):
userId: int # int64
contactId_: NotRequired[int] # int64
search: NotRequired[str]
def APIListGroups_cmd_string(self: APIListGroups) -> str:
return '/_groups ' + str(self['userId']) + ((' @' + str(self.get('contactId_'))) if self.get('contactId_') is not None else '') + ((' ' + self.get('search')) if self.get('search') is not None else '')
APIListGroups_Response = CR.GroupsList | CR.ChatCmdError
# Get chat previews. Supports time-based pagination — use this instead of APIListContacts / APIListGroups when scanning at scale (those load every record into memory and fail on large databases).
# Network usage: no.
class APIGetChats(TypedDict):
userId: int # int64
pendingConnections: bool
pagination: "T.PaginationByTime"
query: "T.ChatListQuery"
def APIGetChats_cmd_string(self: APIGetChats) -> str:
return '/_get chats ' + str(self['userId']) + (' pcc=on' if self['pendingConnections'] else '') + ' ' + T.PaginationByTime_cmd_string(self['pagination']) + ' ' + json.dumps(self['query'])
APIGetChats_Response = CR.ApiChats | CR.ChatCmdError
# Delete chat.
# Network usage: background.
class APIDeleteChat(TypedDict):
chatRef: "T.ChatRef"
chatDeleteMode: "T.ChatDeleteMode"
def APIDeleteChat_cmd_string(self: APIDeleteChat) -> str:
return '/_delete ' + T.ChatRef_cmd_string(self['chatRef']) + ' ' + T.ChatDeleteMode_cmd_string(self['chatDeleteMode'])
APIDeleteChat_Response = CR.ContactDeleted | CR.ContactConnectionDeleted | CR.GroupDeletedUser | CR.ChatCmdError
# Set group custom data.
# Network usage: no.
class APISetGroupCustomData(TypedDict):
groupId: int # int64
customData: NotRequired[dict[str, object]]
def APISetGroupCustomData_cmd_string(self: APISetGroupCustomData) -> str:
return '/_set custom #' + str(self['groupId']) + ((' ' + json.dumps(self.get('customData'))) if self.get('customData') is not None else '')
APISetGroupCustomData_Response = CR.CmdOk | CR.ChatCmdError
# Set contact custom data.
# Network usage: no.
class APISetContactCustomData(TypedDict):
contactId: int # int64
customData: NotRequired[dict[str, object]]
def APISetContactCustomData_cmd_string(self: APISetContactCustomData) -> str:
return '/_set custom @' + str(self['contactId']) + ((' ' + json.dumps(self.get('customData'))) if self.get('customData') is not None else '')
APISetContactCustomData_Response = CR.CmdOk | CR.ChatCmdError
# Set auto-accept member contacts.
# Network usage: no.
class APISetUserAutoAcceptMemberContacts(TypedDict):
userId: int # int64
onOff: bool
def APISetUserAutoAcceptMemberContacts_cmd_string(self: APISetUserAutoAcceptMemberContacts) -> str:
return '/_set accept member contacts ' + str(self['userId']) + ' ' + ('on' if self['onOff'] else 'off')
APISetUserAutoAcceptMemberContacts_Response = CR.CmdOk | CR.ChatCmdError
# User profile commands
# Most bots don't need to use these commands, as bot profile can be configured manually via CLI or desktop client. These commands can be used by bots that need to manage multiple user profiles (e.g., the profiles of support agents).
# Get active user profile.
# Network usage: no.
class ShowActiveUser(TypedDict):
pass
def ShowActiveUser_cmd_string(self: ShowActiveUser) -> str:
return '/user'
ShowActiveUser_Response = CR.ActiveUser | CR.ChatCmdError
# Create new user profile.
# Network usage: no.
class CreateActiveUser(TypedDict):
newUser: "T.NewUser"
def CreateActiveUser_cmd_string(self: CreateActiveUser) -> str:
return '/_create user ' + json.dumps(self['newUser'])
CreateActiveUser_Response = CR.ActiveUser | CR.ChatCmdError
# Get all user profiles.
# Network usage: no.
class ListUsers(TypedDict):
pass
def ListUsers_cmd_string(self: ListUsers) -> str:
return '/users'
ListUsers_Response = CR.UsersList | CR.ChatCmdError
# Set active user profile.
# Network usage: no.
class APISetActiveUser(TypedDict):
userId: int # int64
viewPwd: NotRequired[str]
def APISetActiveUser_cmd_string(self: APISetActiveUser) -> str:
return '/_user ' + str(self['userId']) + ((' ' + json.dumps(self.get('viewPwd'))) if self.get('viewPwd') is not None else '')
APISetActiveUser_Response = CR.ActiveUser | CR.ChatCmdError
# Delete user profile.
# Network usage: background.
class APIDeleteUser(TypedDict):
userId: int # int64
delSMPQueues: bool
viewPwd: NotRequired[str]
def APIDeleteUser_cmd_string(self: APIDeleteUser) -> str:
return '/_delete user ' + str(self['userId']) + ' del_smp=' + ('on' if self['delSMPQueues'] else 'off') + ((' ' + json.dumps(self.get('viewPwd'))) if self.get('viewPwd') is not None else '')
APIDeleteUser_Response = CR.CmdOk | CR.ChatCmdError
# Update user profile.
# Network usage: background.
class APIUpdateProfile(TypedDict):
userId: int # int64
profile: "T.Profile"
def APIUpdateProfile_cmd_string(self: APIUpdateProfile) -> str:
return '/_profile ' + str(self['userId']) + ' ' + json.dumps(self['profile'])
APIUpdateProfile_Response = CR.UserProfileUpdated | CR.UserProfileNoChange | CR.ChatCmdError
# Configure chat preference overrides for the contact.
# Network usage: background.
class APISetContactPrefs(TypedDict):
contactId: int # int64
preferences: "T.Preferences"
def APISetContactPrefs_cmd_string(self: APISetContactPrefs) -> str:
return '/_set prefs @' + str(self['contactId']) + ' ' + json.dumps(self['preferences'])
APISetContactPrefs_Response = CR.ContactPrefsUpdated | CR.ChatCmdError
# Chat management
# These commands should not be used with CLI-based bots
# Start chat controller.
# Network usage: no.
class StartChat(TypedDict):
mainApp: bool
enableSndFiles: bool
def StartChat_cmd_string(self: StartChat) -> str:
return '/_start'
StartChat_Response = CR.ChatStarted | CR.ChatRunning
# Stop chat controller.
# Network usage: no.
class APIStopChat(TypedDict):
pass
def APIStopChat_cmd_string(self: APIStopChat) -> str:
return '/_stop'
APIStopChat_Response = CR.ChatStopped
@@ -0,0 +1,379 @@
# API Events
# This file is generated automatically.
from __future__ import annotations
from typing import Literal, NotRequired, TypedDict
from . import _types as T
class ContactConnected(TypedDict):
type: Literal["contactConnected"]
user: "T.User"
contact: "T.Contact"
userCustomProfile: NotRequired["T.Profile"]
class ContactUpdated(TypedDict):
type: Literal["contactUpdated"]
user: "T.User"
fromContact: "T.Contact"
toContact: "T.Contact"
class ContactDeletedByContact(TypedDict):
type: Literal["contactDeletedByContact"]
user: "T.User"
contact: "T.Contact"
class ReceivedContactRequest(TypedDict):
type: Literal["receivedContactRequest"]
user: "T.User"
contactRequest: "T.UserContactRequest"
chat_: NotRequired["T.AChat"]
class NewMemberContactReceivedInv(TypedDict):
type: Literal["newMemberContactReceivedInv"]
user: "T.User"
contact: "T.Contact"
groupInfo: "T.GroupInfo"
member: "T.GroupMember"
class ContactSndReady(TypedDict):
type: Literal["contactSndReady"]
user: "T.User"
contact: "T.Contact"
class NewChatItems(TypedDict):
type: Literal["newChatItems"]
user: "T.User"
chatItems: list["T.AChatItem"]
class ChatItemReaction(TypedDict):
type: Literal["chatItemReaction"]
user: "T.User"
added: bool
reaction: "T.ACIReaction"
class ChatItemsDeleted(TypedDict):
type: Literal["chatItemsDeleted"]
user: "T.User"
chatItemDeletions: list["T.ChatItemDeletion"]
byUser: bool
timed: bool
class ChatItemUpdated(TypedDict):
type: Literal["chatItemUpdated"]
user: "T.User"
chatItem: "T.AChatItem"
class GroupChatItemsDeleted(TypedDict):
type: Literal["groupChatItemsDeleted"]
user: "T.User"
groupInfo: "T.GroupInfo"
chatItemIDs: list[int] # int64
byUser: bool
member_: NotRequired["T.GroupMember"]
class ChatItemsStatusesUpdated(TypedDict):
type: Literal["chatItemsStatusesUpdated"]
user: "T.User"
chatItems: list["T.AChatItem"]
class ReceivedGroupInvitation(TypedDict):
type: Literal["receivedGroupInvitation"]
user: "T.User"
groupInfo: "T.GroupInfo"
contact: "T.Contact"
fromMemberRole: "T.GroupMemberRole"
memberRole: "T.GroupMemberRole"
class UserJoinedGroup(TypedDict):
type: Literal["userJoinedGroup"]
user: "T.User"
groupInfo: "T.GroupInfo"
hostMember: "T.GroupMember"
class GroupUpdated(TypedDict):
type: Literal["groupUpdated"]
user: "T.User"
fromGroup: "T.GroupInfo"
toGroup: "T.GroupInfo"
member_: NotRequired["T.GroupMember"]
msgSigned: NotRequired["T.MsgSigStatus"]
class JoinedGroupMember(TypedDict):
type: Literal["joinedGroupMember"]
user: "T.User"
groupInfo: "T.GroupInfo"
member: "T.GroupMember"
class MemberRole(TypedDict):
type: Literal["memberRole"]
user: "T.User"
groupInfo: "T.GroupInfo"
byMember: "T.GroupMember"
member: "T.GroupMember"
fromRole: "T.GroupMemberRole"
toRole: "T.GroupMemberRole"
msgSigned: NotRequired["T.MsgSigStatus"]
class DeletedMember(TypedDict):
type: Literal["deletedMember"]
user: "T.User"
groupInfo: "T.GroupInfo"
byMember: "T.GroupMember"
deletedMember: "T.GroupMember"
withMessages: bool
msgSigned: NotRequired["T.MsgSigStatus"]
class LeftMember(TypedDict):
type: Literal["leftMember"]
user: "T.User"
groupInfo: "T.GroupInfo"
member: "T.GroupMember"
msgSigned: NotRequired["T.MsgSigStatus"]
class DeletedMemberUser(TypedDict):
type: Literal["deletedMemberUser"]
user: "T.User"
groupInfo: "T.GroupInfo"
member: "T.GroupMember"
withMessages: bool
msgSigned: NotRequired["T.MsgSigStatus"]
class GroupDeleted(TypedDict):
type: Literal["groupDeleted"]
user: "T.User"
groupInfo: "T.GroupInfo"
member: "T.GroupMember"
msgSigned: NotRequired["T.MsgSigStatus"]
class ConnectedToGroupMember(TypedDict):
type: Literal["connectedToGroupMember"]
user: "T.User"
groupInfo: "T.GroupInfo"
member: "T.GroupMember"
memberContact: NotRequired["T.Contact"]
class MemberAcceptedByOther(TypedDict):
type: Literal["memberAcceptedByOther"]
user: "T.User"
groupInfo: "T.GroupInfo"
acceptingMember: "T.GroupMember"
member: "T.GroupMember"
class MemberBlockedForAll(TypedDict):
type: Literal["memberBlockedForAll"]
user: "T.User"
groupInfo: "T.GroupInfo"
byMember: "T.GroupMember"
member: "T.GroupMember"
blocked: bool
msgSigned: NotRequired["T.MsgSigStatus"]
class GroupMemberUpdated(TypedDict):
type: Literal["groupMemberUpdated"]
user: "T.User"
groupInfo: "T.GroupInfo"
fromMember: "T.GroupMember"
toMember: "T.GroupMember"
class GroupLinkDataUpdated(TypedDict):
type: Literal["groupLinkDataUpdated"]
user: "T.User"
groupInfo: "T.GroupInfo"
groupLink: "T.GroupLink"
groupRelays: list["T.GroupRelay"]
relaysChanged: bool
class GroupRelayUpdated(TypedDict):
type: Literal["groupRelayUpdated"]
user: "T.User"
groupInfo: "T.GroupInfo"
member: "T.GroupMember"
groupRelay: "T.GroupRelay"
class RcvFileDescrReady(TypedDict):
type: Literal["rcvFileDescrReady"]
user: "T.User"
chatItem: "T.AChatItem"
rcvFileTransfer: "T.RcvFileTransfer"
rcvFileDescr: "T.RcvFileDescr"
class RcvFileComplete(TypedDict):
type: Literal["rcvFileComplete"]
user: "T.User"
chatItem: "T.AChatItem"
class SndFileCompleteXFTP(TypedDict):
type: Literal["sndFileCompleteXFTP"]
user: "T.User"
chatItem: "T.AChatItem"
fileTransferMeta: "T.FileTransferMeta"
class RcvFileStart(TypedDict):
type: Literal["rcvFileStart"]
user: "T.User"
chatItem: "T.AChatItem"
class RcvFileSndCancelled(TypedDict):
type: Literal["rcvFileSndCancelled"]
user: "T.User"
chatItem: "T.AChatItem"
rcvFileTransfer: "T.RcvFileTransfer"
class RcvFileAccepted(TypedDict):
type: Literal["rcvFileAccepted"]
user: "T.User"
chatItem: "T.AChatItem"
class RcvFileError(TypedDict):
type: Literal["rcvFileError"]
user: "T.User"
chatItem_: NotRequired["T.AChatItem"]
agentError: "T.AgentErrorType"
rcvFileTransfer: "T.RcvFileTransfer"
class RcvFileWarning(TypedDict):
type: Literal["rcvFileWarning"]
user: "T.User"
chatItem_: NotRequired["T.AChatItem"]
agentError: "T.AgentErrorType"
rcvFileTransfer: "T.RcvFileTransfer"
class SndFileError(TypedDict):
type: Literal["sndFileError"]
user: "T.User"
chatItem_: NotRequired["T.AChatItem"]
fileTransferMeta: "T.FileTransferMeta"
errorMessage: str
class SndFileWarning(TypedDict):
type: Literal["sndFileWarning"]
user: "T.User"
chatItem_: NotRequired["T.AChatItem"]
fileTransferMeta: "T.FileTransferMeta"
errorMessage: str
class AcceptingContactRequest(TypedDict):
type: Literal["acceptingContactRequest"]
user: "T.User"
contact: "T.Contact"
class AcceptingBusinessRequest(TypedDict):
type: Literal["acceptingBusinessRequest"]
user: "T.User"
groupInfo: "T.GroupInfo"
class ContactConnecting(TypedDict):
type: Literal["contactConnecting"]
user: "T.User"
contact: "T.Contact"
class BusinessLinkConnecting(TypedDict):
type: Literal["businessLinkConnecting"]
user: "T.User"
groupInfo: "T.GroupInfo"
hostMember: "T.GroupMember"
fromContact: "T.Contact"
class JoinedGroupMemberConnecting(TypedDict):
type: Literal["joinedGroupMemberConnecting"]
user: "T.User"
groupInfo: "T.GroupInfo"
hostMember: "T.GroupMember"
member: "T.GroupMember"
class SentGroupInvitation(TypedDict):
type: Literal["sentGroupInvitation"]
user: "T.User"
groupInfo: "T.GroupInfo"
contact: "T.Contact"
member: "T.GroupMember"
class GroupLinkConnecting(TypedDict):
type: Literal["groupLinkConnecting"]
user: "T.User"
groupInfo: "T.GroupInfo"
hostMember: "T.GroupMember"
class HostConnected(TypedDict):
type: Literal["hostConnected"]
protocol: str
transportHost: str
class HostDisconnected(TypedDict):
type: Literal["hostDisconnected"]
protocol: str
transportHost: str
class SubscriptionStatus(TypedDict):
type: Literal["subscriptionStatus"]
server: str
subscriptionStatus: "T.SubscriptionStatus"
connections: list[str]
class MessageError(TypedDict):
type: Literal["messageError"]
user: "T.User"
severity: str
errorMessage: str
class ChatError(TypedDict):
type: Literal["chatError"]
chatError: "T.ChatError"
class ChatErrors(TypedDict):
type: Literal["chatErrors"]
chatErrors: list["T.ChatError"]
ChatEvent = (
ContactConnected
| ContactUpdated
| ContactDeletedByContact
| ReceivedContactRequest
| NewMemberContactReceivedInv
| ContactSndReady
| NewChatItems
| ChatItemReaction
| ChatItemsDeleted
| ChatItemUpdated
| GroupChatItemsDeleted
| ChatItemsStatusesUpdated
| ReceivedGroupInvitation
| UserJoinedGroup
| GroupUpdated
| JoinedGroupMember
| MemberRole
| DeletedMember
| LeftMember
| DeletedMemberUser
| GroupDeleted
| ConnectedToGroupMember
| MemberAcceptedByOther
| MemberBlockedForAll
| GroupMemberUpdated
| GroupLinkDataUpdated
| GroupRelayUpdated
| RcvFileDescrReady
| RcvFileComplete
| SndFileCompleteXFTP
| RcvFileStart
| RcvFileSndCancelled
| RcvFileAccepted
| RcvFileError
| RcvFileWarning
| SndFileError
| SndFileWarning
| AcceptingContactRequest
| AcceptingBusinessRequest
| ContactConnecting
| BusinessLinkConnecting
| JoinedGroupMemberConnecting
| SentGroupInvitation
| GroupLinkConnecting
| HostConnected
| HostDisconnected
| SubscriptionStatus
| MessageError
| ChatError
| ChatErrors
)
ChatEvent_Tag = Literal["contactConnected", "contactUpdated", "contactDeletedByContact", "receivedContactRequest", "newMemberContactReceivedInv", "contactSndReady", "newChatItems", "chatItemReaction", "chatItemsDeleted", "chatItemUpdated", "groupChatItemsDeleted", "chatItemsStatusesUpdated", "receivedGroupInvitation", "userJoinedGroup", "groupUpdated", "joinedGroupMember", "memberRole", "deletedMember", "leftMember", "deletedMemberUser", "groupDeleted", "connectedToGroupMember", "memberAcceptedByOther", "memberBlockedForAll", "groupMemberUpdated", "groupLinkDataUpdated", "groupRelayUpdated", "rcvFileDescrReady", "rcvFileComplete", "sndFileCompleteXFTP", "rcvFileStart", "rcvFileSndCancelled", "rcvFileAccepted", "rcvFileError", "rcvFileWarning", "sndFileError", "sndFileWarning", "acceptingContactRequest", "acceptingBusinessRequest", "contactConnecting", "businessLinkConnecting", "joinedGroupMemberConnecting", "sentGroupInvitation", "groupLinkConnecting", "hostConnected", "hostDisconnected", "subscriptionStatus", "messageError", "chatError", "chatErrors"]
@@ -0,0 +1,360 @@
# API Responses
# This file is generated automatically.
from __future__ import annotations
from typing import Literal, NotRequired, TypedDict
from . import _types as T
class AcceptingContactRequest(TypedDict):
type: Literal["acceptingContactRequest"]
user: "T.User"
contact: "T.Contact"
class ActiveUser(TypedDict):
type: Literal["activeUser"]
user: "T.User"
class ChatItemNotChanged(TypedDict):
type: Literal["chatItemNotChanged"]
user: "T.User"
chatItem: "T.AChatItem"
class ChatItemReaction(TypedDict):
type: Literal["chatItemReaction"]
user: "T.User"
added: bool
reaction: "T.ACIReaction"
class ChatItemUpdated(TypedDict):
type: Literal["chatItemUpdated"]
user: "T.User"
chatItem: "T.AChatItem"
class ChatItemsDeleted(TypedDict):
type: Literal["chatItemsDeleted"]
user: "T.User"
chatItemDeletions: list["T.ChatItemDeletion"]
byUser: bool
timed: bool
class ChatRunning(TypedDict):
type: Literal["chatRunning"]
class ChatStarted(TypedDict):
type: Literal["chatStarted"]
class ChatStopped(TypedDict):
type: Literal["chatStopped"]
class CmdOk(TypedDict):
type: Literal["cmdOk"]
user_: NotRequired["T.User"]
class ChatCmdError(TypedDict):
type: Literal["chatCmdError"]
chatError: "T.ChatError"
class ConnectionPlan(TypedDict):
type: Literal["connectionPlan"]
user: "T.User"
connLink: "T.CreatedConnLink"
connectionPlan: "T.ConnectionPlan"
class ContactAlreadyExists(TypedDict):
type: Literal["contactAlreadyExists"]
user: "T.User"
contact: "T.Contact"
class ContactConnectionDeleted(TypedDict):
type: Literal["contactConnectionDeleted"]
user: "T.User"
connection: "T.PendingContactConnection"
class ContactDeleted(TypedDict):
type: Literal["contactDeleted"]
user: "T.User"
contact: "T.Contact"
class ContactPrefsUpdated(TypedDict):
type: Literal["contactPrefsUpdated"]
user: "T.User"
fromContact: "T.Contact"
toContact: "T.Contact"
class ContactRequestRejected(TypedDict):
type: Literal["contactRequestRejected"]
user: "T.User"
contactRequest: "T.UserContactRequest"
contact_: NotRequired["T.Contact"]
class ContactsList(TypedDict):
type: Literal["contactsList"]
user: "T.User"
contacts: list["T.Contact"]
class GroupDeletedUser(TypedDict):
type: Literal["groupDeletedUser"]
user: "T.User"
groupInfo: "T.GroupInfo"
msgSigned: bool
class GroupLink(TypedDict):
type: Literal["groupLink"]
user: "T.User"
groupInfo: "T.GroupInfo"
groupLink: "T.GroupLink"
class GroupLinkCreated(TypedDict):
type: Literal["groupLinkCreated"]
user: "T.User"
groupInfo: "T.GroupInfo"
groupLink: "T.GroupLink"
class GroupLinkDeleted(TypedDict):
type: Literal["groupLinkDeleted"]
user: "T.User"
groupInfo: "T.GroupInfo"
class GroupCreated(TypedDict):
type: Literal["groupCreated"]
user: "T.User"
groupInfo: "T.GroupInfo"
class PublicGroupCreated(TypedDict):
type: Literal["publicGroupCreated"]
user: "T.User"
groupInfo: "T.GroupInfo"
groupLink: "T.GroupLink"
groupRelays: list["T.GroupRelay"]
class PublicGroupCreationFailed(TypedDict):
type: Literal["publicGroupCreationFailed"]
user: "T.User"
addRelayResults: list["T.AddRelayResult"]
class GroupRelays(TypedDict):
type: Literal["groupRelays"]
user: "T.User"
groupInfo: "T.GroupInfo"
groupRelays: list["T.GroupRelay"]
class GroupRelaysAdded(TypedDict):
type: Literal["groupRelaysAdded"]
user: "T.User"
groupInfo: "T.GroupInfo"
groupLink: "T.GroupLink"
groupRelays: list["T.GroupRelay"]
class GroupRelaysAddFailed(TypedDict):
type: Literal["groupRelaysAddFailed"]
user: "T.User"
addRelayResults: list["T.AddRelayResult"]
class GroupMembers(TypedDict):
type: Literal["groupMembers"]
user: "T.User"
group: "T.Group"
class GroupUpdated(TypedDict):
type: Literal["groupUpdated"]
user: "T.User"
fromGroup: "T.GroupInfo"
toGroup: "T.GroupInfo"
member_: NotRequired["T.GroupMember"]
msgSigned: bool
class GroupsList(TypedDict):
type: Literal["groupsList"]
user: "T.User"
groups: list["T.GroupInfo"]
class Invitation(TypedDict):
type: Literal["invitation"]
user: "T.User"
connLinkInvitation: "T.CreatedConnLink"
connection: "T.PendingContactConnection"
class LeftMemberUser(TypedDict):
type: Literal["leftMemberUser"]
user: "T.User"
groupInfo: "T.GroupInfo"
class MemberAccepted(TypedDict):
type: Literal["memberAccepted"]
user: "T.User"
groupInfo: "T.GroupInfo"
member: "T.GroupMember"
class MembersBlockedForAllUser(TypedDict):
type: Literal["membersBlockedForAllUser"]
user: "T.User"
groupInfo: "T.GroupInfo"
members: list["T.GroupMember"]
blocked: bool
msgSigned: bool
class MembersRoleUser(TypedDict):
type: Literal["membersRoleUser"]
user: "T.User"
groupInfo: "T.GroupInfo"
members: list["T.GroupMember"]
toRole: "T.GroupMemberRole"
msgSigned: bool
class NewChatItems(TypedDict):
type: Literal["newChatItems"]
user: "T.User"
chatItems: list["T.AChatItem"]
class RcvFileAccepted(TypedDict):
type: Literal["rcvFileAccepted"]
user: "T.User"
chatItem: "T.AChatItem"
class RcvFileAcceptedSndCancelled(TypedDict):
type: Literal["rcvFileAcceptedSndCancelled"]
user: "T.User"
rcvFileTransfer: "T.RcvFileTransfer"
class RcvFileCancelled(TypedDict):
type: Literal["rcvFileCancelled"]
user: "T.User"
chatItem_: NotRequired["T.AChatItem"]
rcvFileTransfer: "T.RcvFileTransfer"
class SentConfirmation(TypedDict):
type: Literal["sentConfirmation"]
user: "T.User"
connection: "T.PendingContactConnection"
customUserProfile: NotRequired["T.Profile"]
class SentGroupInvitation(TypedDict):
type: Literal["sentGroupInvitation"]
user: "T.User"
groupInfo: "T.GroupInfo"
contact: "T.Contact"
member: "T.GroupMember"
class SentInvitation(TypedDict):
type: Literal["sentInvitation"]
user: "T.User"
connection: "T.PendingContactConnection"
customUserProfile: NotRequired["T.Profile"]
class SndFileCancelled(TypedDict):
type: Literal["sndFileCancelled"]
user: "T.User"
chatItem_: NotRequired["T.AChatItem"]
fileTransferMeta: "T.FileTransferMeta"
sndFileTransfers: list["T.SndFileTransfer"]
class UserAcceptedGroupSent(TypedDict):
type: Literal["userAcceptedGroupSent"]
user: "T.User"
groupInfo: "T.GroupInfo"
hostContact: NotRequired["T.Contact"]
class UserContactLink(TypedDict):
type: Literal["userContactLink"]
user: "T.User"
contactLink: "T.UserContactLink"
class UserContactLinkCreated(TypedDict):
type: Literal["userContactLinkCreated"]
user: "T.User"
connLinkContact: "T.CreatedConnLink"
class UserContactLinkDeleted(TypedDict):
type: Literal["userContactLinkDeleted"]
user: "T.User"
class UserContactLinkUpdated(TypedDict):
type: Literal["userContactLinkUpdated"]
user: "T.User"
contactLink: "T.UserContactLink"
class UserDeletedMembers(TypedDict):
type: Literal["userDeletedMembers"]
user: "T.User"
groupInfo: "T.GroupInfo"
members: list["T.GroupMember"]
withMessages: bool
msgSigned: bool
class UserProfileUpdated(TypedDict):
type: Literal["userProfileUpdated"]
user: "T.User"
fromProfile: "T.Profile"
toProfile: "T.Profile"
updateSummary: "T.UserProfileUpdateSummary"
class UserProfileNoChange(TypedDict):
type: Literal["userProfileNoChange"]
user: "T.User"
class UsersList(TypedDict):
type: Literal["usersList"]
users: list["T.UserInfo"]
class ApiChats(TypedDict):
type: Literal["apiChats"]
user: "T.User"
chats: list["T.AChat"]
ChatResponse = (
AcceptingContactRequest
| ActiveUser
| ChatItemNotChanged
| ChatItemReaction
| ChatItemUpdated
| ChatItemsDeleted
| ChatRunning
| ChatStarted
| ChatStopped
| CmdOk
| ChatCmdError
| ConnectionPlan
| ContactAlreadyExists
| ContactConnectionDeleted
| ContactDeleted
| ContactPrefsUpdated
| ContactRequestRejected
| ContactsList
| GroupDeletedUser
| GroupLink
| GroupLinkCreated
| GroupLinkDeleted
| GroupCreated
| PublicGroupCreated
| PublicGroupCreationFailed
| GroupRelays
| GroupRelaysAdded
| GroupRelaysAddFailed
| GroupMembers
| GroupUpdated
| GroupsList
| Invitation
| LeftMemberUser
| MemberAccepted
| MembersBlockedForAllUser
| MembersRoleUser
| NewChatItems
| RcvFileAccepted
| RcvFileAcceptedSndCancelled
| RcvFileCancelled
| SentConfirmation
| SentGroupInvitation
| SentInvitation
| SndFileCancelled
| UserAcceptedGroupSent
| UserContactLink
| UserContactLinkCreated
| UserContactLinkDeleted
| UserContactLinkUpdated
| UserDeletedMembers
| UserProfileUpdated
| UserProfileNoChange
| UsersList
| ApiChats
)
ChatResponse_Tag = Literal["acceptingContactRequest", "activeUser", "chatItemNotChanged", "chatItemReaction", "chatItemUpdated", "chatItemsDeleted", "chatRunning", "chatStarted", "chatStopped", "cmdOk", "chatCmdError", "connectionPlan", "contactAlreadyExists", "contactConnectionDeleted", "contactDeleted", "contactPrefsUpdated", "contactRequestRejected", "contactsList", "groupDeletedUser", "groupLink", "groupLinkCreated", "groupLinkDeleted", "groupCreated", "publicGroupCreated", "publicGroupCreationFailed", "groupRelays", "groupRelaysAdded", "groupRelaysAddFailed", "groupMembers", "groupUpdated", "groupsList", "invitation", "leftMemberUser", "memberAccepted", "membersBlockedForAllUser", "membersRoleUser", "newChatItems", "rcvFileAccepted", "rcvFileAcceptedSndCancelled", "rcvFileCancelled", "sentConfirmation", "sentGroupInvitation", "sentInvitation", "sndFileCancelled", "userAcceptedGroupSent", "userContactLink", "userContactLinkCreated", "userContactLinkDeleted", "userContactLinkUpdated", "userDeletedMembers", "userProfileUpdated", "userProfileNoChange", "usersList", "apiChats"]
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,128 @@
"""Reusable helpers for working with chat events, types, and message content.
Mirrors the Node `util.ts` exports provides the same primitives bot
authors typically reach for: command parsing, sender display strings,
message-content extraction, profile field cleanup, and ChatRef extraction
from a ChatInfo (handy when echoing into a different chat).
"""
from __future__ import annotations
import re
from typing import Any
from .types import T
def chat_info_ref(c_info: T.ChatInfo) -> T.ChatRef | None:
"""Extract a wire-format `ChatRef` from a `ChatInfo`.
Returns `None` for non-chat infos (contactRequest, contactConnection)
that can't be the target of `api_send_messages`. For groups, the
`memberSupport` scope is forwarded so messages land in the right
thread; other scopes are dropped (matches Node `util.chatInfoRef`).
"""
t = c_info["type"]
if t == "direct":
return {"chatType": "direct", "chatId": c_info["contact"]["contactId"]} # type: ignore[index]
if t == "group":
ref: T.ChatRef = {"chatType": "group", "chatId": c_info["groupInfo"]["groupId"]} # type: ignore[index]
scope = c_info.get("groupChatScope") # type: ignore[union-attr]
if scope and scope.get("type") == "memberSupport":
member = scope.get("groupMember_")
ms_scope: T.GroupChatScope_memberSupport = {"type": "memberSupport"}
if member is not None:
ms_scope["groupMemberId_"] = member["groupMemberId"]
ref["chatScope"] = ms_scope
return ref
return None
def chat_info_name(c_info: T.ChatInfo) -> str:
"""Display string for a chat: `@Alice`, `#GroupName`, `private notes`, etc."""
t = c_info["type"]
if t == "direct":
return f"@{c_info['contact']['profile']['displayName']}" # type: ignore[index]
if t == "group":
scope = c_info.get("groupChatScope") # type: ignore[union-attr]
if scope and scope.get("type") == "memberSupport":
member = scope.get("groupMember_")
scope_name = f" {member['memberProfile']['displayName']}" if member else ""
return f"#{c_info['groupInfo']['groupProfile']['displayName']}(support{scope_name})" # type: ignore[index]
return f"#{c_info['groupInfo']['groupProfile']['displayName']}" # type: ignore[index]
if t == "local":
return "private notes"
if t == "contactRequest":
return f"request from @{c_info['contactRequest']['profile']['displayName']}" # type: ignore[index]
if t == "contactConnection":
alias = c_info["contactConnection"].get("localAlias") # type: ignore[index]
return f"pending connection ({alias})" if alias else "pending connection"
return f"<{t}>"
def sender_name(c_info: T.ChatInfo, chat_dir: T.CIDirection) -> str:
"""Sender display: chat name plus group sender suffix when applicable."""
base = chat_info_name(c_info)
if chat_dir["type"] == "groupRcv":
sender = chat_dir["groupMember"]["memberProfile"]["displayName"] # type: ignore[index]
return f"{base} @{sender}"
return base
def contact_address_str(link: T.CreatedConnLink) -> str:
"""Prefer the short link, fall back to the full link."""
return link.get("connShortLink") or link["connFullLink"]
def from_local_profile(local: T.LocalProfile) -> T.Profile:
"""Strip extra LocalProfile fields (profileId, localAlias) and undefined values."""
p: dict[str, Any] = {}
for key in (
"displayName",
"fullName",
"shortDescr",
"image",
"contactLink",
"preferences",
"peerType",
):
v = local.get(key) # type: ignore[misc]
if v is not None:
p[key] = v
return p # type: ignore[return-value]
def ci_content_text(chat_item: T.ChatItem) -> str | None:
"""Extract the message text from a sent or received message item, if any."""
content = chat_item["content"]
if content["type"] in ("sndMsgContent", "rcvMsgContent"):
msg = content.get("msgContent", {}) # type: ignore[union-attr]
return msg.get("text")
return None
_BOT_COMMAND_RE = re.compile(r"^/([^\s]+)(.*)$")
def ci_bot_command(chat_item: T.ChatItem) -> tuple[str, str] | None:
"""Parse a `/keyword args...` slash-command from a chat item.
Returns `(keyword, trimmed_params)` or `None` if the message isn't a
slash command. Mirrors Node `util.ciBotCommand` semantics.
"""
text = ci_content_text(chat_item)
if not text:
return None
text = text.strip()
m = _BOT_COMMAND_RE.match(text)
if not m:
return None
return m.group(1), m.group(2).strip()
def reaction_text(reaction: T.ACIReaction) -> str:
"""Format an `ACIReaction` as the emoji character or tag string."""
r = reaction["chatReaction"]["reaction"] # type: ignore[index]
if r["type"] == "emoji":
return r["emoji"] # type: ignore[index]
return r.get("tag", "") # type: ignore[union-attr]