From b99b2fa9bf798ea530192625e7ada4a8e6445265 Mon Sep 17 00:00:00 2001 From: nikita Date: Sat, 5 Dec 2026 23:30:34 +0300 Subject: [PATCH] Added user key-value pairs in bot database. v0.7.1 - Bumped patch number - Added user key-value pairs to the built-in database - Updated reaction_bot example to use key-value pairs storage - Database schema version is 3 now (added a table for user kv pairs) --- README.md | 2 +- examples/reaction_bot.py | 16 ++++++++++++++-- pyproject.toml | 2 +- src/mab/bot/_database.py | 37 ++++++++++++++++++++++++++++++++++++- src/mab/bot/bot.py | 18 ++++++++++++++++++ 5 files changed, 70 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index a8ef0da..0ba323e 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ install the latest stable version of the library: ```bash apt install libmagic1-dev libolm-dev -python -m pip install git+https://git.tyukalov.su/nikita/mab@v0.7.0 +python -m pip install git+https://git.tyukalov.su/nikita/mab@v0.7.1 ``` `libmagic1-dev` is needed for automatic file MIME type detection, `libolm-dev` diff --git a/examples/reaction_bot.py b/examples/reaction_bot.py index 7fbd035..027a4cd 100644 --- a/examples/reaction_bot.py +++ b/examples/reaction_bot.py @@ -13,11 +13,21 @@ from mab import * from _environment import check_environment +async def bump_count(bot: MatrixBot) -> int: + """Bump count of reactions processed and return new value. Uses bot's + database for storage.""" + val = await bot.load_value("reactions_processed") + val = 0 if val is None else int.from_bytes(val) + val += 1 + await bot.save_value("reactions_processed", val.to_bytes(8)) + return val + async def on_specific_reaction(ctx: EventContext, vars: ContextVars) -> None: """This callback is called when a specific reaction is added.""" sender = vars[CTX_REACTION].sender reaction = vars[CTX_REACTION].reaction - response = f"(Specific reaction) {sender}: {reaction}" + count = await bump_count(ctx.bot) + response = f"(Specific reaction) {sender}: {reaction}. Total reactions processed: {count}" await ctx.bot.send.text( ctx.room, response @@ -27,7 +37,8 @@ async def on_reaction(ctx: EventContext, vars: ContextVars) -> None: """This callback is called when a reaction is added.""" sender = vars[CTX_REACTION].sender reaction = vars[CTX_REACTION].reaction - response = f"(Generic reaction) {sender}: {reaction}" + count = await bump_count(ctx.bot) + response = f"(Generic reaction) {sender}: {reaction}. Total reactions processed: {count}" await ctx.bot.send.text( ctx.room, response @@ -35,6 +46,7 @@ async def on_reaction(ctx: EventContext, vars: ContextVars) -> None: async def on_message(ctx: EventContext, vars: ContextVars) -> None: """This callback is called when a message is received.""" + await bump_count(ctx.bot) await ctx.bot.send.reaction(ctx.room, vars[CTX_ROOM_EVENT].event_id, "👀") async def main() -> None: diff --git a/pyproject.toml b/pyproject.toml index caeee29..410aebf 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "mab" -version = "0.7.0" +version = "0.7.1" authors = [ { name = "Tyukalov Nikita", email = "nikita@tyukalov.su" } ] diff --git a/src/mab/bot/_database.py b/src/mab/bot/_database.py index 5978954..b3012bf 100644 --- a/src/mab/bot/_database.py +++ b/src/mab/bot/_database.py @@ -9,7 +9,7 @@ from ..types import MatrixBotConfig class _Database: """Database interface""" - SCHEMA_VERSION = 2 + SCHEMA_VERSION = 3 """Version of the database schema""" async def _create_tables(self) -> None: @@ -28,6 +28,12 @@ class _Database: "room_id TEXT UNIQUE ON CONFLICT REPLACE," "timestamp INTEGER" ")" + ), + ( + "CREATE TABLE IF NOT EXISTS user_kv_pairs(" + "key TEXT UNIQUE ON CONFLICT REPLACE," + "value BLOB" + ")" ) ) self._logger.debug(f"Creating the tables") @@ -102,6 +108,35 @@ class _Database: await cursor.fetchall() self._logger.debug(f"Updated property `{name}`") + async def user_kv_get(self, key: str) -> bytes | None: + """Gets user key-value pair from the database. Returns None if it does + not exist.""" + if self._conn is None: + raise RuntimeError("No connection exists") + async with self._conn.execute("SELECT value FROM user_kv_pairs WHERE key=?", + (key,)) as cursor: + row = await cursor.fetchone() + if row is None: + return None + return row["value"] + + async def user_kv_set(self, key: str, value: bytes | None) -> bytes | None: + """Sets user key-value pair in the database. Use `None` to remove it. + Returns `value`.""" + if self._conn is None: + raise RuntimeError("No connection exists") + if value is not None: + async with self._conn.execute("REPLACE INTO user_kv_pairs(key, value) VALUES(?, ?)", + (key, value)) as cursor: + await cursor.fetchall() + self._logger.debug(f"Updated user key-value `{key}`") + else: + async with self._conn.execute("DELETE FROM user_kv_pairs WHERE key=?", + (key,)) as cursor: + await cursor.fetchall() + self._logger.debug(f"Removed user key-value `{key}`") + return value + async def join_timestamp_get(self, room_id: str) -> int | None: """Returns the server timestamp when the room was joined (or None).""" if self._conn is None: diff --git a/src/mab/bot/bot.py b/src/mab/bot/bot.py index e79e68f..b706638 100644 --- a/src/mab/bot/bot.py +++ b/src/mab/bot/bot.py @@ -128,6 +128,24 @@ class MatrixBot: finally: await self.stop() + async def save_value(self, key: str, value: bytes | None) -> bytes | None: + """Save key-value pair to the database. Save `None` to remove the key. + Returns `value`. + + Please use this feature for simple bots only. Prefer your own database + for higher efficiency. + """ + return await self._database.user_kv_set(key, value) + + async def load_value(self, key: str) -> bytes | None: + """Load key-value pair from the database. Returns `None` if the key + does not exist. + + Please use this feature for simple bots only. Prefer your own database + for higher efficiency. + """ + return await self._database.user_kv_get(key) + @property def client(self) -> AsyncClient: """