Implemented event callbacks

This commit is contained in:
2026-08-18 03:14:37 +03:00
parent 8c1399d781
commit c519ae379d
2 changed files with 30 additions and 8 deletions

View File

@@ -9,12 +9,12 @@ from pathlib import Path
import config import config
import util import util
#import bot
#import logic
from new_bot import MatrixBot from new_bot import MatrixBot
from bot_types import MatrixBotConfig from bot_types import MatrixBotConfig
import nio.events
from datatypes import AppConfig from datatypes import AppConfig
async def main() -> None: async def main() -> None:
@@ -42,6 +42,7 @@ async def main() -> None:
storage_directory=Path(cfg.store_dir) storage_directory=Path(cfg.store_dir)
) )
bot = MatrixBot(matrix_bot_config) bot = MatrixBot(matrix_bot_config)
bot.add_event_callback(None, nio.events.Event)
# start the app # start the app
bot.start() bot.start()

View File

@@ -8,11 +8,13 @@ import json
import os import os
import re import re
from urllib.parse import urlparse from urllib.parse import urlparse
from typing import Any from typing import Any, Callable, Awaitable
from nio import AsyncClient, AsyncClientConfig, SyncResponse from nio import AsyncClient, AsyncClientConfig, SyncResponse
from nio import LoginResponse, LoginError, WhoamiResponse, WhoamiError from nio import LoginResponse, LoginError, WhoamiResponse, WhoamiError
import nio.events
from bot_types import * from bot_types import *
@@ -129,6 +131,18 @@ class MatrixBot:
print("--- A password is required (btw you might use MATRIX_PASSWORD envvar) ---") print("--- A password is required (btw you might use MATRIX_PASSWORD envvar) ---")
return await aioconsole.ainput("Password: ") return await aioconsole.ainput("Password: ")
@staticmethod
async def _debug_event_callback(*args, **kwargs) -> None:
"""Just prints types of arguments"""
try:
print(f"_debug_event_callback ({len(args)} args, {len(kwargs)} kwargs)")
for a in args:
print(f" - {type(a)}")
for k in kwargs:
print(f" * {k} = {kwargs[k]}")
except:
traceback.print_exc()
async def _write_next_batch(self, next_batch: str) -> None: async def _write_next_batch(self, next_batch: str) -> None:
"""Writes `next_batch` value to disk.""" """Writes `next_batch` value to disk."""
@@ -286,8 +300,6 @@ class MatrixBot:
# we should stop when this task stops # we should stop when this task stops
self._logger.debug("_background_coroutine is started") self._logger.debug("_background_coroutine is started")
stop_wait_task = asyncio.create_task(self._stop_event.wait()) stop_wait_task = asyncio.create_task(self._stop_event.wait())
self._client = self._build_client(self._config)
self._setup_client_callbacks()
# perform login # perform login
login_task = asyncio.create_task(self._client_login()) login_task = asyncio.create_task(self._client_login())
try: try:
@@ -324,14 +336,16 @@ class MatrixBot:
# check if config is valid # check if config is valid
self._validate_bot_config(config) # may raise an Exception self._validate_bot_config(config) # may raise an Exception
# save the config # save the config
self._config = config self._config: MatrixBotConfig = config
# create the logger # create the logger
self._logger = logging.getLogger(self._build_matrix_username(config)) self._logger = logging.getLogger(self._build_matrix_username(config))
self._logger.setLevel(logging.DEBUG) self._logger.setLevel(logging.DEBUG)
# create the client
self._client: AsyncClient = self._build_client(self._config)
self._setup_client_callbacks()
# prepare some private data # prepare some private data
self._background_task: asyncio.Task | None = None self._background_task: asyncio.Task | None = None
self._client: AsyncClient = None # type: ignore
self._last_next_batch_dump: float = 0.0 self._last_next_batch_dump: float = 0.0
self._last_next_batch: str | None = None self._last_next_batch: str | None = None
self._cb_password = self._default_password_callback self._cb_password = self._default_password_callback
@@ -361,3 +375,10 @@ class MatrixBot:
traceback.print_exc() traceback.print_exc()
self._stop_event = None self._stop_event = None
self._background_task = None self._background_task = None
def add_event_callback(self, callback: Callable[[Any], Awaitable[None]] | None, event_class: nio.events.Event) -> None:
"""Added event callback for events of specified class.
Use `None` instead of callback to print parameter types you need to use in your callback."""
if callback is None:
callback = self._debug_event_callback
self._client.add_event_callback(callback, event_class) # type: ignore