def announce(text, cred): matrix = MatrixHttpApi(cred.get("url", "https://matrix.org"), token=cred['access_token']) for room in cred['rooms']: roomid = matrix.get_room_id(room) matrix.join_room(roomid) if not cred.get('mock', False): matrix.send_message(roomid, text)
def _get_matrix(): try: return g.matrix except AttributeError: g.matrix = MatrixHttpApi('https://matrix.org', token=current_app.config['MATRIX_TOKEN']) return g.matrix
def __init__(self, token, server, roomid): self.server = server self.roomid = roomid self.token = token self.APIWrapper = MatrixHttpApi("https://{}".format(self.server), token=self.token) self.next_batch = self.APIWrapper.sync().get("next_batch") print("client initialized")
def announce(text, token, room=None): from matrix_client.api import MatrixHttpApi matrix = MatrixHttpApi("https://matrix.org", token=token) matrix.sync() roomid = matrix.get_room_id(room) matrix.join_room(roomid) matrix.send_message(roomid, text)
def __init__(self, settings): self.sync_token = None self.logger = utils.get_logger() self.cache = utils.create_cache(settings) self.cache_timeout = int(settings["memcached"]["timeout"]) self.settings = settings self.period = settings["DEFAULT"]["period"] self.uri = settings["matrix"]["uri"] self.username = settings["matrix"]["username"].lower() self.password = settings["matrix"]["password"] self.room_ids = settings["matrix"]["rooms"] self.domain = self.settings["matrix"]["domain"] self.only_local_domain = self.settings["matrix"]["only_local_domain"] self.subscriptions_room_ids = settings["subscriptions"].keys() self.revokations_rooms_ids = settings["revokations"].keys() self.allowed_join_rooms_ids = filter(lambda x: x != 'default', settings["allowed-join"].keys()) self.default_allowed_join_rooms = settings["allowed-join"]["default"] self.client = MatrixClient(self.uri) self.token = self.client.login_with_password(username=self.username, password=self.password) self.api = MatrixHttpApi(self.uri, token=self.token) self.rooms = [] self.room_aliases = {} self.plugins = [] for plugin in settings['plugins'].itervalues(): mod = __import__(plugin['module'], fromlist=[plugin['class']]) klass = getattr(mod, plugin['class']) self.plugins.append(klass(self, plugin['settings']))
def main(config): # setup api/endpoint matrix = MatrixHttpApi(config.base_url, config.token) log.debug("Setting up plugins...") plugins = [ SmartHomePlugin # TimePlugin, # Base64Plugin, # GuessNumberPlugin, # #JiraPlugin, # UrlPlugin, # #GithubPlugin, # #JenkinsPlugin, # PrometheusPlugin, ] # setup engine engine = Engine(matrix, config) for plugin in plugins: engine.add_plugin(plugin) engine.setup() while True: try: log.info("Listening for incoming events.") engine.event_loop() except Exception as e: log.error("Ruh roh: %s", e) time.sleep(5) log.info("Terminating.")
def main(config): # setup api/endpoint matrix = MatrixHttpApi(config.base_url, config.token) log.debug("Setting up plugins...") plugins = [ ToDoPlugin, UrlPlugin, GuessNumberPlugin, ] # setup engine engine = Engine(matrix, config) for plugin in plugins: engine.add_plugin(plugin) engine.setup() while True: try: log.info("Listening for incoming events.") engine.event_loop() except Exception as e: log.error("Ruh roh: %s", e) time.sleep(5)
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 __init__(self): self.BOTUSERNAME = "******" self.BOTPASSWORD = "******" self.BOTSERVO = "matrix.org" self.RID = "!RnpiUpFIsfzZfHdHQf:matrix.org" self.realRID = "!obQcCWaLRAUgiGBvMg:postmarketos.org" self.MainClient = MatrixClient("https://" + self.BOTSERVO) self.token = self.MainClient.login_with_password( username=self.BOTUSERNAME, password=self.BOTPASSWORD) self.APIWrapper = MatrixHttpApi("https://" + self.BOTSERVO, token=self.token) self.target_room = Room(self.MainClient, self.RID) print("ready")
def __init__(self, settings): self.sync_token = None self.logger = utils.get_logger() self.settings = settings self.period = settings["DEFAULT"]["period"] self.uri = settings["matrix"]["uri"] self.username = settings["matrix"]["username"].lower() self.password = settings["matrix"]["password"] self.room_ids = settings["matrix"]["rooms"] self.domain = self.settings["matrix"]["domain"] self.subscriptions_room_ids = settings["subscriptions"]["rooms"] self.revokations_rooms_ids = settings["revokations"]["rooms"] self.client = MatrixClient(self.uri) self.token = self.client.login_with_password(username=self.username, password=self.password) self.api = MatrixHttpApi(self.uri, token=self.token)
def _get_messages(request, sync_token, direction): storage = get_messages(request) for message in storage: user_name = message print("MESSAGE : ", message) print("_get_message username: "******" : ", direction) messages.add_message(request, messages.INFO, user_name) sys.stdout.flush() session = Session.objects.get(matrix_user_name=user_name.message) api = MatrixHttpApi(session.matrix_server, token=session.matrix_token) synced = api.get_room_messages(api.get_room_id(session.matrix_room_name), session.matrix_sync_token, direction, limit=session.message_count) session.matrix_sync_token = synced[sync_token] session.save() room_topic = api.get_room_topic(api.get_room_id( session.matrix_room_name))['topic'] synced['chunk'] = _parse_messages(synced['chunk']) return synced
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 __init__(self, host=bothost, user=botuser, pwd=botpwd, room=botroom): print("Logging to matrix server...") self.chatclient = MatrixClient(host) try: self.chattoken = self.chatclient.login(username=user, password=pwd, sync=True) except MatrixRequestError as e: print(e) if e.code == 403: print("Bad username or password.") sys.exit(4) else: print("Check your sever details are correct.") sys.exit(2) except MissingSchema as e: print("Bad URL format.") print(e) sys.exit(3) self.chatapi = MatrixHttpApi(host, self.chattoken) print("Login OK") ### handle messages print("Setting up listener") try: room = self.chatclient.join_room(room) except MatrixRequestError as e: print(e) if e.code == 400: print("Room ID/Alias in the wrong format") sys.exit(11) else: print("Couldn't find room.") sys.exit(12) room.add_listener(self.on_message) self.listener_thread_id = self.chatclient.start_listener_thread() print('Listener set.. OK!')
def connect(self): ''' log in to the server and get connected rooms''' password = self.config['bot']['password'] username = self.username server = self.config['bot']['host'] room_id = self.config['bot']['room'] try: BOT_LOG.debug("Trying to log in as %s pw: %s", self.username, "".join(['*' for p in password])) token = self.client.login(username, password) BOT_LOG.debug("Got Token %s..%s", token[0:3], token[-3:-1]) except MatrixRequestError as error: BOT_LOG.error("Login Failed: Code: %s, Content: %s", error.code, error.content) #this is a second connection with different interface BOT_LOG.debug("Creating matrix API endpoint") self.api = MatrixHttpApi(server, token) if str(room_id).startswith('!'): self.current_room = room_id else: self.current_room = self.get_room_id_by_name(room_id) BOT_LOG.debug("Joining room with id %s", self.current_room) self.api.join_room(self.current_room) BOT_LOG.debug("Getting member info") self.members = self.api.get_room_members(self.current_room) BOT_LOG.debug( "Members in room: %s", ",".join([ a['sender'] if 'sender' in a.keys() else "" for a in self.members['chunk'] ])) rooms = [] for _, room in self.client.get_rooms().items(): rooms.append(room) self.all_rooms = VirtualRoom(rooms)
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'}
def serve_once(self): def dispatch_event(event): log.info("Received event: %s" % event) if event['type'] == "m.room.member": if event['membership'] == "invite" and event[ 'state_key'] == self._client.user_id: room_id = event['room_id'] self._client.join_room(room_id) log.info("Auto-joined room: %s" % room_id) if event['type'] == "m.room.message" and event[ 'sender'] != self._client.user_id: sender = event['sender'] room_id = event['room_id'] body = event['content']['body'] log.info("Received message from %s in room %s" % (sender, room_id)) # msg = Message(body) # msg.frm = MatrixPerson(self._client, sender, room_id) # msg.to = MatrixPerson(self._client, self._client.user_id, room_id) # self.callback_message(msg) msg = self.build_message(body) room = MatrixRoom(room_id) msg.frm = MatrixRoomOccupant(self._api, room, sender) msg.to = room self.callback_message(msg) self.reset_reconnection_count() self.connect_callback() self._client = MatrixClient(self._homeserver) try: self._token = self._client.register_with_password( self._username, self._password, ) except MatrixRequestError as e: if e.code == 400: try: self._token = self._client.login_with_password( self._username, self._password, ) except MatrixRequestError: log.fatal(""" Incorrect username or password specified in config.BOT_IDENTITY['username'] or config.BOT_IDENTITY['password']. """) sys.exit(1) self._api = MatrixHttpApi(self._homeserver, self._token) self.bot_identifier = MatrixPerson(self._api) self._client.add_listener(dispatch_event) try: while True: self._client.listen_for_events() except KeyboardInterrupt: log.info("Interrupt received, shutting down...") return True finally: self.disconnect_callback()
def chat(request, update=""): user_name = None storage = get_messages(request) for message in storage: user_name = message print("MESSAGE : ", message) if user_name != None: print("username: "******"LOGIN VARS") print("session.matrix_user_name ", session.matrix_user_name) print("session.matrix_room_name ", session.matrix_room_name) print("session.matrix_server ", session.matrix_server) print("session.message_count ", session.message_count) print("session.show_images ", session.show_images) sys.stdout.flush() api = MatrixHttpApi(session.matrix_server, token=session.matrix_token) print("GET_MEMBERSHIP") api.join_room(api.get_room_id(session.matrix_room_name)) else: return HttpResponseRedirect('/') if request.method == 'POST': #If the user hit send button try: print("Posting chat") sys.stdout.flush() chat_form = ChatForm(request.POST) if chat_form.is_valid(): response = api.send_message( api.get_room_id(session.matrix_room_name), chat_form.cleaned_data['text_entered']) chat_form = ChatForm() room_topic = api.get_room_topic( api.get_room_id(session.matrix_room_name))['topic'] messages.add_message(request, messages.INFO, session.matrix_user_name) synced = _get_messages(request, sync_token="end", direction='f') session.messages = json.dumps(synced['chunk'] + jsonDec.decode(session.messages)) session.save() return render( request, 'client_app/chat.html', { 'chat_form': chat_form, 'name': session.matrix_user_name, 'messages': jsonDec.decode(session.messages), 'room': session.matrix_room_name, 'topic': room_topic, 'show_images': session.show_images }) except MatrixRequestError as e: print(str(e)) sys.stdout.flush() form = NameForm(request.POST) return render(request, 'client_app/login.html', { 'form': form, 'login_error': True, 'error_text': str(e) }) else: return render( request, 'client_app/chat.html', { 'chat_form': chat_form, 'name': session.matrix_user_name, 'messages': jsonDec.decode(session.messages), 'room': session.matrix_room_name, 'topic': room_topic, 'show_images': session.show_images }) if update == "": #If not asking for an update, get first sync to server try: chat_form = ChatForm() synced = api.sync() room_topic = api.get_room_topic( api.get_room_id(session.matrix_room_name))['topic'] session.matrix_sync_token = synced["next_batch"] messages.add_message(request, messages.INFO, session.matrix_user_name) synced = _get_messages(request, sync_token="start", direction='b') session.messages = json.dumps(synced['chunk']) session.save() except MatrixRequestError as e: print(str(e)) sys.stdout.flush() form = NameForm(request.POST) return render(request, 'client_app/login.html', { 'form': form, 'login_error': True }) else: return render( request, 'client_app/chat.html', { 'chat_form': chat_form, 'name': session.matrix_user_name, 'messages': jsonDec.decode(session.messages), 'room': session.matrix_room_name, 'topic': room_topic, 'show_images': session.show_images }) else: # update is requested so return next messages using sync token from initial sync chat_form = ChatForm() room_topic = api.get_room_topic( api.get_room_id(session.matrix_room_name))['topic'] messages.add_message(request, messages.INFO, session.matrix_user_name) synced = _get_messages(request, sync_token="end", direction='f') session.messages = json.dumps(synced['chunk'] + jsonDec.decode(session.messages)) session.save() return render( request, 'client_app/chat.html', { 'chat_form': chat_form, 'name': session.matrix_user_name, 'messages': jsonDec.decode(session.messages), 'room': session.matrix_room_name, 'topic': room_topic, 'show_images': session.show_images })
def index(request): if request.method == 'POST': print("POST form") form = NameForm(request.POST) if form.is_valid(): #for s in list(Session.objects.all()): #print(s.matrix_user_name) #Get username from db or create it, and fill out the information from the form #Add user_name to message to pass to chat view so it knows which session to open messages.add_message(request, messages.INFO, form.cleaned_data['your_name']) if not Session.objects.filter( matrix_user_name=form.cleaned_data['your_name']): print("CREATE SESSION") session = Session.objects.create( matrix_user_name=form.cleaned_data['your_name'], matrix_room_name=form.cleaned_data['room'], matrix_server=form.cleaned_data['server'], message_count=form.cleaned_data['message_count'], show_images=form.cleaned_data['show_images']) session.save() sys.stdout.flush() else: print("OPEN SESSION") session = Session.objects.get( matrix_user_name=form.cleaned_data['your_name']) session.matrix_user_name = form.cleaned_data['your_name'] session.matrix_room_name = form.cleaned_data['room'] session.matrix_server = form.cleaned_data['server'] session.message_count = form.cleaned_data['message_count'] session.show_images = form.cleaned_data['show_images'] session.save() sys.stdout.flush() try: print("LOGIN VARS") print("session.matrix_user_name ", session.matrix_user_name) print("form.cleaned_data['your_name'] ", form.cleaned_data['your_name']) print("session.matrix_room_name ", session.matrix_room_name) print("form.cleaned_data['room'] ", form.cleaned_data['room']) print("session.matrix_server ", session.matrix_server) print("form.cleaned_data['server'] ", form.cleaned_data['server']) print("session.message_count ", session.message_count) print("form.cleaned_data['message_count'] ", form.cleaned_data['message_count']) print("session.show_images ", session.show_images) print("form.cleaned_data['show_images'] ", form.cleaned_data['show_images']) print("session_token: ", str(session.matrix_token)) print("Logging in to matrix") sys.stdout.flush() api = MatrixHttpApi(session.matrix_server) response = api.login('m.login.password', user=form.cleaned_data['your_name'], password=form.cleaned_data['your_pass']) session.matrix_token = response["access_token"] session.save() print("session_token: ", str(session.matrix_token)) sys.stdout.flush() except MatrixRequestError as e: #return HttpResponseForbidden() return render(request, 'client_app/login.html', { 'form': form, 'login_error': True, 'error_text': str(e) }) else: return HttpResponseRedirect('/chat') else: #GET page returns form with initial values form = NameForm( initial={ "room": "#cosmic_horror:matrix.org", "server": "https://matrix.org", "message_count": 1000 }) return render(request, 'client_app/login.html', { 'form': form, 'login_error': False })
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)
settings = yaml.load(stream) except IOError as e: sys.exit("no settings.yaml found!") # CONSTANTS DOMAIN = settings['DOMAIN'] SERVICES = settings['SERVICES'] ROOMS = settings['ROOMS'] TOKEN = settings['TOKEN'] def online(service): stat = os.system('systemctl is-active --quiet {}'.format(service)) if not stat: return True return False matrix = MatrixHttpApi(DOMAIN, token=TOKEN) status = False for service in SERVICES: if not online(service): status = True message = "Service: '{}' is offline".format(service) print(message) for room in ROOMS: matrix.join_room(room) response = matrix.send_message(room, message) if not status: print("everything is fine")
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), } )
def matrix_sender(homeserver: str, token: str, room: str): """ Matrix sender wrapper: execute func, send a Matrix message with the end status (sucessfully finished or crashed) at the end. Also send a Matrix message before executing func. `homeserver`: str The homeserver address which was used to register the BOT. It is e.g. 'https://matrix-client.matrix.org'. It can be also looked up in Riot by looking in the riot settings, "Help & About" at the bottom. Specifying the schema (`http` or `https`) is required. `token`: str The access TOKEN of the user that will send the messages. It can be obtained in Riot by looking in the riot settings, "Help & About" , down the bottom is: Access Token:<click to reveal> `room`: str The alias of the room to which messages will be send by the BOT. After creating a room, an alias can be set. In Riot, this can be done by opening the room settings under 'Room Addresses'. """ matrix = MatrixHttpApi(homeserver, token=token) room_id = matrix.get_room_id(room) def decorator_sender(func): @functools.wraps(func) def wrapper_sender(*args, **kwargs): start_time = datetime.datetime.now() host_name = socket.gethostname() func_name = func.__name__ # Handling distributed training edge case. # In PyTorch, the launch of `torch.distributed.launch` sets up a RANK environment variable for each process. # This can be used to detect the master process. # See https://github.com/pytorch/pytorch/blob/master/torch/distributed/launch.py#L211 # Except for errors, only the master process will send notifications. if 'RANK' in os.environ: master_process = (int(os.environ['RANK']) == 0) host_name += ' - RANK: %s' % os.environ['RANK'] else: master_process = True if master_process: contents = [ 'Your training has started 🎬', 'Machine name: %s' % host_name, 'Main call: %s' % func_name, 'Starting date: %s' % start_time.strftime(DATE_FORMAT) ] text = '\n'.join(contents) matrix.send_message(room_id, text) try: value = func(*args, **kwargs) if master_process: end_time = datetime.datetime.now() elapsed_time = end_time - start_time contents = [ "Your training is complete 🎉", 'Machine name: %s' % host_name, 'Main call: %s' % func_name, 'Starting date: %s' % start_time.strftime(DATE_FORMAT), 'End date: %s' % end_time.strftime(DATE_FORMAT), 'Training duration: %s' % str(elapsed_time) ] try: str_value = str(value) contents.append('Main call returned value: %s' % str_value) except: contents.append( 'Main call returned value: %s' % "ERROR - Couldn't str the returned value.") text = '\n'.join(contents) matrix.send_message(room_id, text) return value except Exception as ex: end_time = datetime.datetime.now() elapsed_time = end_time - start_time contents = [ "Your training has crashed ☠️", 'Machine name: %s' % host_name, 'Main call: %s' % func_name, 'Starting date: %s' % start_time.strftime(DATE_FORMAT), 'Crash date: %s' % end_time.strftime(DATE_FORMAT), 'Crashed training duration: %s\n\n' % str(elapsed_time), "Here's the error:", '%s\n\n' % ex, "Traceback:", '%s' % traceback.format_exc() ] text = '\n'.join(contents) matrix.send_message(room_id, text) raise ex return wrapper_sender return decorator_sender
from auth import url, host, room, token import pprint from matrix_client.api import MatrixHttpApi from matrix_client.api import MatrixRequestError pp = pprint.PrettyPrinter(indent=4) pp = pp.pprint matrix = MatrixHttpApi(host, token=token) try: # pp(matrix.get_room_state(room)) msg = input("Message : ") print(msg) print(matrix.send_message(room, msg)) except MatrixRequestError as e: print(e) if e.code == 400: print("Room ID/Alias in the wrong format") else: print("Couldn't find room.")
if homeserver.endswith('/'): homeserver = homeserver[:-1] if username.startswith('@'): username = username[1:] if username.find(':') > 0: username = username.split(':')[0] matrix = None for retry in range(0, 4): try: client = MatrixClient(homeserver) token = client.login(username, password) matrix = MatrixHttpApi(homeserver, token) break except MatrixHttpLibError: sys.stderr.write('Connection failed, retrying...\n') time.sleep(0.25) if matrix == None: sys.stderr.write('Could not connect to homeserver. Message not sent.\n') sys.exit(-2) try: client.rooms[room_id].send_text(message) except: sys.stderr.write('Failed to send message to room.\n') sys.exit(-3)
def startup(config): # setup api/endpoint login = config.json['user_id'][1:].split(":")[0] if not config.json['token']: matrix = MatrixHttpApi(config.json['url']) matrix.validate_certificate(config.json['cert_verify']) try: res = matrix.login(login_type="m.login.password", user=login, password=config.json['password']) except MatrixRequestError as err: log.error("Login error: %r" % err) exit() log.debug("Login result: %r" % res) config.json['token'] = res["access_token"] matrix.token = config.json['token'] else: matrix = MatrixHttpApi(config.json['url'], config.json['token']) matrix.validate_certificate(config.json['cert_verify']) config.save() # Update Display Name if needed cur_dn = matrix.get_display_name(config.json['user_id']) if not login == cur_dn: matrix.set_display_name(config.json['user_id'], login) # root path for plugin search and locale load config.rootf = os.path.dirname(os.path.abspath(matrix_bot.__file__)) log.debug("Matrix_bot root folder: %s" % config.rootf) log.debug("Matrix_bot configuration: %s" % json.dumps(config.json, indent=4, sort_keys=True)) # setup engine engine = Engine(matrix, config) # Dytnamic plugin load from plugins folder osppath = os.path.join(config.rootf, "plugins") lst = os.listdir(osppath) for fil in lst: name, ext = os.path.splitext(fil) if (not os.path.isdir(os.path.join(osppath, fil)) and not fil[0] == "_" and ext in (".py")): try: mod = __import__("matrix_bot.plugins." + name, fromlist=["*"]) for cls in inspect.getmembers(mod, inspect.isclass): if hasattr(cls[1], "name"): if not config.json['plugins'] or cls[ 1].name in config.json['plugins']: engine.add_plugin(cls[1]) log.info("Load plugin %s (%s) from %s" % (cls[1].name, cls[0], os.path.join("plugins", fil))) else: log.info( "Skip plugin %s (%s) from %s - not listed in config" % (cls[1].name, cls[0], os.path.join("plugins", fil))) except ImportError as err: log.error("Plugin module %s import error: %r" % ("plugins." + fil, err)) engine.setup() while True: try: log.info("Listening for incoming events.") engine.event_loop() except Exception as e: log.error("Ruh roh: %s", e) time.sleep(5) log.info("Terminating.")
def matrix_sender(homeserver: str, token: str, room: str): """ Matrix sender wrapper: execute func, send a Matrix message with the end status (sucessfully finished or crashed) at the end. Also send a Matrix message before executing func. `homeserver`: str The homeserver address which was used to register the BOT. It is e.g. 'https://matrix-client.matrix.org'. It can be also looked up in Riot by looking in the riot settings, "Help & About" at the bottom. Specifying the schema (`http` or `https`) is required. `token`: str The access TOKEN of the user that will send the messages. It can be obtained in Riot by looking in the riot settings, "Help & About" , down the bottom is: Access Token:<click to reveal> `room`: str The alias of the room to which messages will be send by the BOT. After creating a room, an alias can be set. In Riot, this can be done by opening the room settings under 'Room Addresses'. """ matrix = MatrixHttpApi(homeserver, token=token) room_id = matrix.get_room_id(room) def decorator_sender(func): def send_message(text, room_id=room_id): matrix.send_message(room_id, text) @functools.wraps(func) def wrapper_sender(*args, **kwargs): start_time = datetime.datetime.now() host_name = socket.gethostname() func_name = func.__name__ text = "" if include_details: text += f'{func_name} called on {host_name} at {start_time.strftime(DATE_FORMAT)}' if message: text += f'{func_name}: {message}' if not include_details else f'\nMessage: {message}' if notify_end: text += '\nWe\'ll let you know when it\'s done.' send_message(text=text) try: value = func(*args, **kwargs) if notify_end: end_time = datetime.datetime.now() elapsed_time = end_time - start_time text = "" text += f'✅ {func_name} finished on {host_name} at {end_time.strftime(DATE_FORMAT)}' text += f'\nDuration: {elapsed_time}' try: str_value = str(value) text += f'\nReturned value: {str_value}' except: text += f'\nReturned value: ERROR - Couldn\'t parse the returned value.' send_message(text=text) return value except Exception as ex: end_time = datetime.datetime.now() elapsed_time = end_time - start_time contents = [f"☠️ {func_name} has crashed on {host_name} at {end_time.strftime(DATE_FORMAT)}", "Here's the error:", '%s\n\n' % ex, "Traceback:", '%s' % traceback.format_exc()] text = '\n'.join(contents) send_message(text=text) raise ex return wrapper_sender return decorator_sender
def send_message_riot(message, token, room, server='https://matrix.org'): matrix = MatrixHttpApi(server, token=token) response = matrix.send_message(room, message)