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 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)
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")
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 })