Implemented event callbacks
This commit is contained in:
5
main.py
5
main.py
@@ -9,12 +9,12 @@ from pathlib import Path
|
||||
|
||||
import config
|
||||
import util
|
||||
#import bot
|
||||
#import logic
|
||||
|
||||
from new_bot import MatrixBot
|
||||
from bot_types import MatrixBotConfig
|
||||
|
||||
import nio.events
|
||||
|
||||
from datatypes import AppConfig
|
||||
|
||||
async def main() -> None:
|
||||
@@ -42,6 +42,7 @@ async def main() -> None:
|
||||
storage_directory=Path(cfg.store_dir)
|
||||
)
|
||||
bot = MatrixBot(matrix_bot_config)
|
||||
bot.add_event_callback(None, nio.events.Event)
|
||||
|
||||
# start the app
|
||||
bot.start()
|
||||
|
||||
33
new_bot.py
33
new_bot.py
@@ -8,11 +8,13 @@ import json
|
||||
import os
|
||||
import re
|
||||
from urllib.parse import urlparse
|
||||
from typing import Any
|
||||
from typing import Any, Callable, Awaitable
|
||||
|
||||
from nio import AsyncClient, AsyncClientConfig, SyncResponse
|
||||
from nio import LoginResponse, LoginError, WhoamiResponse, WhoamiError
|
||||
|
||||
import nio.events
|
||||
|
||||
from bot_types import *
|
||||
|
||||
|
||||
@@ -128,6 +130,18 @@ class MatrixBot:
|
||||
return os.environ["MATRIX_PASSWORD"]
|
||||
print("--- A password is required (btw you might use MATRIX_PASSWORD envvar) ---")
|
||||
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:
|
||||
@@ -286,8 +300,6 @@ class MatrixBot:
|
||||
# we should stop when this task stops
|
||||
self._logger.debug("_background_coroutine is started")
|
||||
stop_wait_task = asyncio.create_task(self._stop_event.wait())
|
||||
self._client = self._build_client(self._config)
|
||||
self._setup_client_callbacks()
|
||||
# perform login
|
||||
login_task = asyncio.create_task(self._client_login())
|
||||
try:
|
||||
@@ -324,14 +336,16 @@ class MatrixBot:
|
||||
# check if config is valid
|
||||
self._validate_bot_config(config) # may raise an Exception
|
||||
# save the config
|
||||
self._config = config
|
||||
self._config: MatrixBotConfig = config
|
||||
# create the logger
|
||||
self._logger = logging.getLogger(self._build_matrix_username(config))
|
||||
self._logger.setLevel(logging.DEBUG)
|
||||
# create the client
|
||||
self._client: AsyncClient = self._build_client(self._config)
|
||||
self._setup_client_callbacks()
|
||||
|
||||
# prepare some private data
|
||||
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: str | None = None
|
||||
self._cb_password = self._default_password_callback
|
||||
@@ -360,4 +374,11 @@ class MatrixBot:
|
||||
except:
|
||||
traceback.print_exc()
|
||||
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
|
||||
Reference in New Issue
Block a user