diff --git a/matrix_bot_api/matrix_bot_api.py b/matrix_bot_api/matrix_bot_api.py index 962fcc7..bc126d0 100644 --- a/matrix_bot_api/matrix_bot_api.py +++ b/matrix_bot_api/matrix_bot_api.py @@ -1,6 +1,7 @@ import traceback import re from matrix_client.client import MatrixClient +from matrix_client.room import Room from matrix_client.api import MatrixRequestError @@ -10,7 +11,10 @@ class MatrixBotAPI: # password - Matrix password # server - Matrix server url : port # rooms - List of rooms ids to operate in, or None to accept all rooms - def __init__(self, username, password, server, rooms=None): + # exclusive_rooms - If True (the default), only the specified rooms will be + # used, else they will simply be joined. + def __init__(self, username, password, server, + rooms=None, exclusive_rooms=True): self.username = username # Authenticate with given credentials @@ -25,25 +29,36 @@ def __init__(self, username, password, server, rooms=None): print("Invalid server URL") traceback.print_exc() - # Store allowed rooms - self.rooms = rooms - # Store empty list of handlers self.handlers = [] # If rooms is None, we should listen for invites and automatically accept them if rooms is None: self.client.add_invite_listener(self.handle_invite) - self.rooms = [] - - # Add all rooms we're currently in to self.rooms and add their callbacks - for room_id, room in self.client.get_rooms().items(): - room.add_listener(self.handle_message) - self.rooms.append(room_id) else: + old_rooms = self.client.get_rooms() + new_rooms = [] # Add the message callback for all specified rooms - for room in self.rooms: - room.add_listener(self.handle_message) + for room in rooms: + if isinstance(room, str): + room = Room(self.client, room) + new_rooms.append(room) + # Remove existing rooms which were not specified explicitly + new_ids = [r.room_id for r in new_rooms] + if exclusive_rooms: + rooms_to_leave = [] + for room_id, room in old_rooms.items(): + if not room_id in new_ids: + rooms_to_leave.append(room) + for room in rooms_to_leave: + room.leave() + + # Store clean list of allowed rooms + self.rooms = [] + # Add all rooms we're currently in to self.rooms and add their callbacks + for room_id, room in self.client.get_rooms().items(): + room.add_listener(self.handle_message) + self.rooms.append(room_id) def add_handler(self, handler): self.handlers.append(handler)