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)
This commit is contained in:
@@ -23,7 +23,7 @@ install the latest stable version of the library:
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
apt install libmagic1-dev libolm-dev
|
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`
|
`libmagic1-dev` is needed for automatic file MIME type detection, `libolm-dev`
|
||||||
|
|||||||
@@ -13,11 +13,21 @@ from mab import *
|
|||||||
|
|
||||||
from _environment import check_environment
|
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:
|
async def on_specific_reaction(ctx: EventContext, vars: ContextVars) -> None:
|
||||||
"""This callback is called when a specific reaction is added."""
|
"""This callback is called when a specific reaction is added."""
|
||||||
sender = vars[CTX_REACTION].sender
|
sender = vars[CTX_REACTION].sender
|
||||||
reaction = vars[CTX_REACTION].reaction
|
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(
|
await ctx.bot.send.text(
|
||||||
ctx.room,
|
ctx.room,
|
||||||
response
|
response
|
||||||
@@ -27,7 +37,8 @@ async def on_reaction(ctx: EventContext, vars: ContextVars) -> None:
|
|||||||
"""This callback is called when a reaction is added."""
|
"""This callback is called when a reaction is added."""
|
||||||
sender = vars[CTX_REACTION].sender
|
sender = vars[CTX_REACTION].sender
|
||||||
reaction = vars[CTX_REACTION].reaction
|
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(
|
await ctx.bot.send.text(
|
||||||
ctx.room,
|
ctx.room,
|
||||||
response
|
response
|
||||||
@@ -35,6 +46,7 @@ async def on_reaction(ctx: EventContext, vars: ContextVars) -> None:
|
|||||||
|
|
||||||
async def on_message(ctx: EventContext, vars: ContextVars) -> None:
|
async def on_message(ctx: EventContext, vars: ContextVars) -> None:
|
||||||
"""This callback is called when a message is received."""
|
"""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, "👀")
|
await ctx.bot.send.reaction(ctx.room, vars[CTX_ROOM_EVENT].event_id, "👀")
|
||||||
|
|
||||||
async def main() -> None:
|
async def main() -> None:
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "mab"
|
name = "mab"
|
||||||
version = "0.7.0"
|
version = "0.7.1"
|
||||||
authors = [
|
authors = [
|
||||||
{ name = "Tyukalov Nikita", email = "nikita@tyukalov.su" }
|
{ name = "Tyukalov Nikita", email = "nikita@tyukalov.su" }
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ from ..types import MatrixBotConfig
|
|||||||
class _Database:
|
class _Database:
|
||||||
"""Database interface"""
|
"""Database interface"""
|
||||||
|
|
||||||
SCHEMA_VERSION = 2
|
SCHEMA_VERSION = 3
|
||||||
"""Version of the database schema"""
|
"""Version of the database schema"""
|
||||||
|
|
||||||
async def _create_tables(self) -> None:
|
async def _create_tables(self) -> None:
|
||||||
@@ -28,6 +28,12 @@ class _Database:
|
|||||||
"room_id TEXT UNIQUE ON CONFLICT REPLACE,"
|
"room_id TEXT UNIQUE ON CONFLICT REPLACE,"
|
||||||
"timestamp INTEGER"
|
"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")
|
self._logger.debug(f"Creating the tables")
|
||||||
@@ -102,6 +108,35 @@ class _Database:
|
|||||||
await cursor.fetchall()
|
await cursor.fetchall()
|
||||||
self._logger.debug(f"Updated property `{name}`")
|
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:
|
async def join_timestamp_get(self, room_id: str) -> int | None:
|
||||||
"""Returns the server timestamp when the room was joined (or None)."""
|
"""Returns the server timestamp when the room was joined (or None)."""
|
||||||
if self._conn is None:
|
if self._conn is None:
|
||||||
|
|||||||
@@ -128,6 +128,24 @@ class MatrixBot:
|
|||||||
finally:
|
finally:
|
||||||
await self.stop()
|
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
|
@property
|
||||||
def client(self) -> AsyncClient:
|
def client(self) -> AsyncClient:
|
||||||
"""
|
"""
|
||||||
|
|||||||
Reference in New Issue
Block a user