class Matrix: def __init__(self): logger.info('logging in to Matrix as %s', config.matrix.username) self._client = MatrixClient(config.matrix.server) self._token = self._client.login(username=config.matrix.username, password=config.matrix.password, sync=False) self._api = MatrixHttpApi(config.matrix.server, self._token) def send_text(self, room_id, text): self._api.send_message(room_id, text) def send_notice_html(self, room_id, text): content = dict( body=text, format='org.matrix.custom.html', formatted_body=text, msgtype=MsgType.NOTICE ) self._api.send_message_event(room_id, event_type='m.room.message', content=content) def send_text_html(self, room_id, text): content = dict( body=text, format='org.matrix.custom.html', formatted_body=text, msgtype=MsgType.TEXT ) self._api.send_message_event(room_id, event_type='m.room.message', content=content) def send_notice(self, room_id, text): self._api.send_notice(room_id, text)
class MatrixClient: """ Provides minimal interface to MatrixHttpApi and holds its state. :param server: Matrix server to use. :param token: Matrix token. :param room: Room id for sending data. """ def __init__(self, server: str, token: str, room: str): """Construct a new MatrixClient and init and sync MatrixHttpApi.""" self.server = server self.token = token self.room = room self.api = MatrixHttpApi(self.server, token=self.token) self.api.initial_sync() def send_event(self, event_type: str, content: dict): """Send an event of arbitrary type.""" return self.api.send_message_event(self.room, event_type, content) @staticmethod def get_token(server: str, user: str, password: str) -> str: """Get an access_token via password login.""" return MatrixHttpApi(server).login("m.login.password", user=user, password=password)
def handleNotification(): req = request.get_json() print(req) matrix = MatrixHttpApi(HOMESERVER, token=req['notification']['devices'][0]['pushkey']) print(matrix.send_message_event(room_id=ROOMID, event_type='net.terracrypt.matrix.push', content=req)) return jsonify({})
def send_message(matrix_room, message_plain, message): ''' One day ''' # Init matrix API matrix = MatrixHttpApi(settings.MATRIX_SERVER, token=settings.MATRIX_TOKEN) try: response = matrix.send_message_event( room_id=matrix_room, event_type="m.room.message", content={ "msgtype": "m.text", "format": "org.matrix.custom.html", "body": message_plain, "formatted_body": message, } ) except MatrixRequestError as ex: LOG.error('send_message_event failure %s', ex) return json.dumps({'success': False}), 417, {'ContentType':'application/json'} LOG.debug('Matrix Response: %s', response) return json.dumps({'success': True}), 200, {'ContentType':'application/json'}
Info: {HOSTOUTPUT} When: {LONGDATETIME} {COMMENT_PLAIN} {ICINGA_WEBURL}/monitoring/host/show?host={HOSTNAME} """.format(**DATA) # Message in markdown MSG_MD = """**<font color="{COLOR}">[{NOTIFICATIONTYPE}] Host {HOSTDISPLAYNAME} is {HOSTSTATE}</font>** > *Info:* > > {HOSTOUTPUT} {COMMENT_MD} > *{LONGDATETIME} - [Show in Icinga2]({ICINGA_WEBURL}/monitoring/host/show?host={HOSTNAME})* """.format(**DATA) # Init matrix API matrix = MatrixHttpApi(environ['MATRIX_SERVER'], token=environ['MATRIX_TOKEN']) # Send message in both formats to channel response = matrix.send_message_event( room_id=environ['MATRIX_CHANNEL'], event_type="m.room.message", content={ "msgtype": "m.text", "format": "org.matrix.custom.html", "body": MSG_PLAIN, "formatted_body": Markdown().convert(MSG_MD), } )
class MatrixLogHandler(logging.Handler): """Log handler to send records to a Matrix room. :param base_url: the base URL of the Matrix homeserver to use. This should not include the `_matrix/client/` part. :param room_id: the room ID to send the messages to. The account must be in the room and must have the sufficient power level to send messages. Note that this must be the room ID (!foo:bar.org), not an alias! :param username: a username to use for logging in if no access token was set :param password: a password to use for logging in if no access token was set :param token: a valid access token that can be used to identify the log handler to the Matrix homeserver. This is the recommended way for authorization. If not set, a username/password pair must be set so the handler can acquire an access token. :use_m_text: if `True`, the handler will send `m.text` messages instead of `m.notice` ones (which is intended for bots) :type base_url: str :type room_id: str :type username: str :type password: str :type token: str :type use_m_text: bool """ def __init__( self, base_url, room_id, username=None, password=None, token=None, use_m_text=False, format='[%(levelname)s] [%(asctime)s] [%(name)s] - %(message)s'): logging.Handler.__init__(self) self.base_url = base_url self.username = username self.password = password self.room_id = room_id self.token = token self.use_m_text = use_m_text self.matrix = MatrixHttpApi(base_url, token=self.token) self.formatter = logging.Formatter(format) def _login(self): if self.username is None or self.password is None: raise ValueError( 'Both username and password must be set if there is no token available!' ) response = self.matrix.login('m.login.password', user=self.username, password=self.password) self.token = response['access_token'] def _make_content(self, record): content = { 'msgtype': 'm.text' if self.use_m_text else 'm.notice', 'body': self.format(record), } return content def emit(self, record): content = self._make_content(record) try: if not self.token: self._login() self.matrix.send_message_event(self.room_id, 'm.room.message', content) except: self.handleError(record)