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)
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 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)
class MatrixEngine(object): chatapi = '' chatclient = '' chattoken = '' listener_thread_id = 0 new_msg_queue = [] new_msg_senders = [] 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 sendmsg(self, msg, chatid=botroom): room = self.chatclient.join_room(chatid) response = self.chatapi.send_message(chatid, msg) def sendhtml(self, msg, chatid=botroom): room = self.chatclient.join_room(chatid) room.send_html(msg) def create_room(self, alias): ex_room = matrix_mongo.matrix_chats.find_one({"alias": alias}) if ex_room: room_id = ex_room['room_id'] room = self.chatclient.join_room(room_id) room.invite_user(ebuser) else: try: aldt = datetime.datetime.strftime(datetime.datetime.now(), '%Y%m%d%H%M%S') new_room = self.chatclient.create_room(alias=alias + "_" + aldt, is_public=False, invitees=[ebuser]) room_id = new_room.room_id dtime = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S') chatdata = { "created_date": dtime, "alias": alias, "room_alias": alias + "_" + aldt, "room_id": room_id, "room_data": room } recordID = matrix_mongo.matrix_chats.insert_one(chatdata) except MatrixRequestError as e: print(str(e)) return room_id def sendfile(self, filename, chatid=botroom): room = self.chatclient.join_room(chatid) with open(filename, 'rb') as datafile: data = datafile.read() uri = self.chatclient.upload(content=data, content_type='image/jpg') print(uri) filedate = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S') room.send_image( uri, filedate + '_' + filename.replace('/', '_') + '.jpg') def on_message(self, room, event): try: # Called when a message is recieved. if event['type'] == "m.room.member": if event['membership'] == "join": # print("{0} joined".format(event['content']['displayname'])) dtime = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S') print(dtime + " new user joined to the room ") elif event['type'] == "m.room.message": if event['content']['msgtype'] == "m.text": # print("{0}: {1}".format(event['sender'], event['content']['body'])) dtime = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S') print(dtime + "| '" + event['content']['body'] + "' msg received from " + event['sender']) if event['sender'] != "@mybot:matrix.org": self.new_msg_senders.append(event['sender']) self.new_msg_queue.append(event['content']['body']) else: print('new event in room:' + event['type']) except Exception as e: print('error @ on_message: ' + str(e)) def parsemsg(self): for i in range(len(self.new_msg_queue)): origMsg = self.new_msg_queue[i] sender = self.new_msg_senders[i] msg = origMsg.lower() print("PARSER: '" + origMsg + "' msg received from " + sender) def doshit(): print('shit done') if msg == "test": doshit() elif msg == "msg": sendmsg("your msg responded!") elif msg == "html": sendhtml("your <b>html</b> message <h1>responded</h1>!") else: print("message not understood") self.new_msg_queue.remove(origMsg) self.new_msg_senders.remove(sender)
class MatrixBackend(ErrBot): def __init__(self, config): super().__init__(config) if not hasattr(config, 'MATRIX_HOMESERVER'): log.fatal(""" You need to specify a homeserver to connect to in config.MATRIX_HOMESERVER. For example: MATRIX_HOMESERVER = "https://matrix.org" """) sys.exit(1) self._homeserver = config.MATRIX_HOMESERVER self._username = config.BOT_IDENTITY['username'] self._password = config.BOT_IDENTITY['password'] self._api = None self._token = None 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 or e.code == 403: 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 rooms(self): rooms = [] raw_rooms = self._client.get_rooms() for rid, robject in raw_rooms: # TODO: Get the canonical alias rather than the first one from # `Room.aliases`. log.debug('Found room %s (aka %s)' % (rid, rid.aliases[0])) def send_message(self, mess): super().send_message(mess) room_id = mess.to.room.id text_content = item_url = mess.body if item_url.startswith("http://") or item_url.startswith("https://"): if item_url.endswith("gif"): self._api.send_content(room_id, item_url, "image", "m.image") return # text_content = Markdown().convert(mess.body) self._api.send_message(room_id, text_content) def connect_callback(self): super().connect_callback() def build_identifier(self, txtrep): raise Exception( "XXX" ) def build_reply(self, mess, text=None, private=False): log.info("build_reply") response = self.build_message(text) response.frm = self.bot_identifier response.to = mess.frm return response def change_presence(self, status: str = '', message: str = ''): raise Exception( "XXX" ) @property def mode(self): return 'matrix' def query_room(self, room): raise Exception( "XXX" )
class MatrixBackend(ErrBot): def __init__(self, config): super().__init__(config) if not hasattr(config, 'MATRIX_HOMESERVER'): log.fatal(""" You need to specify a homeserver to connect to in config.MATRIX_HOMESERVER. For example: MATRIX_HOMESERVER = "https://matrix.org" """) sys.exit(1) self._homeserver = config.MATRIX_HOMESERVER self._username = config.BOT_IDENTITY['username'] self._password = config.BOT_IDENTITY['password'] self._api = None self._token = None 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 rooms(self): rooms = [] raw_rooms = self._client.get_rooms() for rid, robject in raw_rooms: # TODO: Get the canonical alias rather than the first one from # `Room.aliases`. log.debug('Found room %s (aka %s)' % (rid, rid.aliases[0])) def send_message(self, mess): super().send_message(mess) room_id = mess.to.room.id text_content = item_url = mess.body if item_url.startswith("http://") or item_url.startswith("https://"): if item_url.endswith("gif"): self._api.send_content(room_id, item_url, "image", "m.image") return # text_content = Markdown().convert(mess.body) self._api.send_message(room_id, text_content) def connect_callback(self): super().connect_callback() def build_identifier(self, txtrep): raise Exception("XXX") def build_reply(self, mess, text=None, private=False): log.info("build_reply") response = self.build_message(text) response.frm = self.bot_identifier response.to = mess.frm return response def change_presence(self, status: str = '', message: str = ''): raise Exception("XXX") @property def mode(self): return 'matrix' def query_room(self, room): raise Exception("XXX")
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")
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.")
class MatrixBot: """The main bot, connecting to the server and handling plugins""" def __init__(self, config): self.username = config['bot']['username'] server = config['bot']['host'] self.fullname = "@" + str( self.username).lower() + ':' + urlparse(server).hostname self.plugins = [] self.api = None self.current_room = "" self.members = [] self.all_rooms = None self.config = config # Connect to server BOT_LOG.debug("creating matrix client for server %s", server) self.client = MatrixClient(server) 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 init_scheduler(self): ''' initialize a thread that handles the event loop for the scheduler for all plugins''' BOT_LOG.debug("Spinning up scheduler thread") self.schedule = schedule self.killswitch = Event() self.killswitch.clear() self.thread = Thread(target=self.schedule_loop, args=(self.killswitch, )) #self.thread.daemon = True self.thread.start() def stop_scheduler(self): ''' wind down the scheduler thread gracefully before exit''' BOT_LOG.debug("Trying to end scheduler thread ..") self.killswitch.set() self.thread.join() BOT_LOG.debug("..successful") def schedule_loop(self, stop_event): ''' this event loop is run inside the scheduler thread''' BOT_LOG.debug("Scheduler thread started successfully") while not stop_event.is_set(): #BOT_LOG.debug("Scheduler loop runs") self.schedule.run_pending() sleep(10) def add_plugin(self, plugin): """Puts a plugin in the internal list where it will be registered as a listener""" self.plugins.append(plugin) def get_room_id_by_name(self, name): """Translate human-readable room name into internal room id""" BOT_LOG.debug("Getting room ID for name '%s'", name) if str(name).startswith('#'): rid = self.api.get_room_id(name) else: rid = self.api.get_room_id('#' + name) if rid is None: BOT_LOG.warning("Room name '%s' not found", name) rid = "" return rid def send(self, text): """Sending initial message to room to announce startup""" BOT_LOG.debug("Sending sample text to room") self.api.send_message(self.current_room, text) def start_polling(self): """Starts syncing and polling for new messages in a new thread""" # Starts polling for messages self.client.start_listener_thread() return self.client.sync_thread def register_listeners(self): ''' register the added plugins as listeners into the rooms the bot si connected to''' rooms = [] for room_id, room in self.client.get_rooms().items(): BOT_LOG.debug("Registering plugins in room %s (%s)", room.name, room_id) rooms.append(room) for plugin in self.plugins: room.add_listener(plugin.handle_message)
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 send_message_riot(message, token, room, server='https://matrix.org'): matrix = MatrixHttpApi(server, token=token) response = matrix.send_message(room, message)