diff --git a/bot_types.py b/bot_types.py index bf76106..333264e 100644 --- a/bot_types.py +++ b/bot_types.py @@ -17,4 +17,7 @@ class MatrixBotConfig: """Path to the storage directory (will be created if needed)""" auto_verify_all_known_devices: bool = True - """Enable automatic verification of all known devices on related errors""" \ No newline at end of file + """Enable automatic verification of all known devices on related errors""" + + auto_join_any_room_on_invite: bool = True + """Enable automatic join for invites (implemented by automatically adding internal callback on bot creation)""" \ No newline at end of file diff --git a/new_bot.py b/new_bot.py index 8bec982..728f6a9 100644 --- a/new_bot.py +++ b/new_bot.py @@ -18,6 +18,9 @@ from nio import RoomSendResponse, RoomSendError from nio import OlmUnverifiedDeviceError +from nio import MatrixInvitedRoom, InviteMemberEvent +from nio import JoinResponse + import nio.events from bot_types import * @@ -225,13 +228,32 @@ class MatrixBot: except: traceback.print_exc() + async def _callback_autojoin(self, room: MatrixInvitedRoom, event: InviteMemberEvent): + try: + # event.state_key must be our username + if event.state_key != self._client.user_id: + return + # membership status must be invite + if event.membership != "invite": + return + result = await self._client.join(room.room_id) + if type(result) is JoinResponse: + self._logger.info(f"Autojoined the room {room.room_id}") + else: + self._logger.error(f"Can't autojoin the room {room.room_id}") + except: + self._logger.error(traceback.format_exc()) + # # LIFECYCLE # def _setup_client_callbacks(self) -> None: - # setup the callbacks + """Setup internal client callbacks""" self._client.add_response_callback(self._callback_sync, SyncResponse) # type: ignore + if self._config.auto_join_any_room_on_invite: + self._client.add_event_callback(self._callback_autojoin, InviteMemberEvent) # type: ignore + async def _client_login_session_data(self, session_data: dict[str, Any]) -> None: """Login using session data. Raises and exception on failure.""" self._logger.debug("Using stored session data to log in")