77 lines
2.3 KiB
Python
77 lines
2.3 KiB
Python
|
import os
|
||
|
import hjson
|
||
|
|
||
|
from matrix_client.client import MatrixClient
|
||
|
|
||
|
from .api import CustomMatrixHttpApi
|
||
|
from .room import CustomRoom
|
||
|
|
||
|
MESSAGES_DIR = os.path.join(os.path.dirname(__file__), 'messages')
|
||
|
MESSAGES_LOCATION = MESSAGES_DIR + '/messages.dutch.hjson'
|
||
|
|
||
|
class CustomMatrixClient(MatrixClient):
|
||
|
def __init__(self, base_url, token=None):
|
||
|
super().__init__(base_url, token)
|
||
|
|
||
|
self.api = CustomMatrixHttpApi(base_url, token)
|
||
|
|
||
|
# Load messages
|
||
|
with open(MESSAGES_LOCATION) as hjson_data:
|
||
|
self.messages = hjson.load(hjson_data)
|
||
|
|
||
|
|
||
|
def _mkroom(self, room_id):
|
||
|
room = CustomRoom(self, room_id)
|
||
|
|
||
|
self.rooms[room_id] = room
|
||
|
return self.rooms[room_id]
|
||
|
|
||
|
def create_direct_room(self, invitees=None):
|
||
|
content = {
|
||
|
"visibility": "private",
|
||
|
"is_direct": True,
|
||
|
"invite": [invitees]
|
||
|
}
|
||
|
|
||
|
room_dict = self.api._send("POST", "/createRoom", content)
|
||
|
|
||
|
return self._mkroom(room_dict["room_id"])
|
||
|
|
||
|
|
||
|
def send_message_private_public(self, room, event, message):
|
||
|
"""This method takes a room, event, and message and makes sure
|
||
|
that the message is sent in a private room and not in a public
|
||
|
room. If no private room exists, it will create a private room
|
||
|
with the sender of the event.
|
||
|
"""
|
||
|
|
||
|
orig_room = room
|
||
|
found_room = False
|
||
|
|
||
|
for room_id, room in self.rooms.items():
|
||
|
joined_members = room.get_joined_members()
|
||
|
|
||
|
# Check for rooms with only two members
|
||
|
if len(joined_members) == 2:
|
||
|
# Check if sender is in that room
|
||
|
for member in joined_members:
|
||
|
if event['sender'] == member.user_id:
|
||
|
found_room = True
|
||
|
|
||
|
if found_room:
|
||
|
# If the flag is set, we do not need to check further rooms
|
||
|
break
|
||
|
|
||
|
# Send help message to an existing room or to a new room
|
||
|
if found_room:
|
||
|
room.send_html(message)
|
||
|
else:
|
||
|
room = self.create_direct_room(event['sender']);
|
||
|
room.send_html(message)
|
||
|
|
||
|
if room != orig_room:
|
||
|
display_name_sender = self.api.get_display_name(event['sender'])
|
||
|
orig_room.send_text(self.messages['private_message'].format(
|
||
|
display_name_sender))
|
||
|
|