class Patroniser(Bouncer, PA): """Bot to do the needful""" client = None def __init__(self, username, password): self.client = MatrixClient('https://matrix.org') self.client.login_with_password_no_sync(username=username, password=password) def get_client(self): """Provide the matrix client for all the myriad purposes.""" return self.client
def claim_account(self, mxid, passgen_secret, new_password, display_name=None, password_function=passgen): """Claims an account by logging in with the genned password, setting a display name, and changing the password to a new password.""" matrix = MatrixClient(self._base_url) old_password = password_function(mxid, passgen_secret) try: matrix.login_with_password_no_sync(username=mxid, password=old_password) if display_name: matrix.api.set_display_name(matrix.user_id, display_name) body = { "auth": { "type": "m.login.password", "user": mxid, "password": old_password }, "new_password": new_password } matrix.api._send('POST', '/account/password', body, api_path='/_matrix/client/r0') return True except MatrixRequestError as exception: if exception.code == 403: raise PasswordAlreadyReset(exception) raise exception
def run_bot(homeserver, authorize, username, password): allowed_users = authorize shell_env = os.environ.copy() shell_env['TERM'] = 'vt100' child_pid, master = pty.fork() if child_pid == 0: # we are the child os.execlpe('sh', 'sh', shell_env) pin = os.fdopen(master, 'w') stop = threading.Event() client = MatrixClient(homeserver) client.login_with_password_no_sync(username, password) # listen for invites during initial event sync so we don't miss any client.add_invite_listener(lambda room_id, state: on_invite( client, room_id, state, allowed_users)) client.listen_for_events() # get rid of initial event sync client.add_listener(lambda event: on_message(event, pin, allowed_users), event_type='m.room.message') shell_stdout_handler_thread = threading.Thread(target=shell_stdout_handler, args=(master, client, stop)) shell_stdout_handler_thread.start() while True: try: client.listen_forever() except KeyboardInterrupt: stop.set() sys.exit(0) except requests.exceptions.Timeout: logger.warn("timeout. Trying again in 5s...") time.sleep(5) except requests.exceptions.ConnectionError as e: logger.warn(repr(e)) logger.warn("disconnected. Trying again in 5s...") time.sleep(5)
class JokeBot: bot_startcmd = '!joke' bot_display_name = 'JokeBot' auto_join_invited_rooms = True mcl = None init_done = False admin_ids = set() def __init__(self, filename=CONFIG_FILENAME): logging.debug('load config') config_dic = load_yaml_config(filename) matrix_server = config_dic['matrix_server'] login_with_token = False if matrix_server.get('token', ''): if not matrix_server.get('user_id', ''): matrix_server['user_id'] = config_dic['matrix_user'][ 'username'] login_with_token = True else: matrix_user = config_dic['matrix_user'] bot_startcmd = config_dic.get('bot_startcmd') if bot_startcmd: self.bot_startcmd = bot_startcmd bot_display_name = config_dic.get('bot_display_name') if bot_display_name: self.bot_display_name = bot_display_name self.auto_join_invited_rooms = config_dic.get( 'auto_join_invited_rooms', True) self.admin_ids = set(config_dic.get('admin_ids', [])) logging.debug('init bot') if login_with_token: logging.debug('init bot with token') self.mcl = MatrixClient(**matrix_server) else: logging.debug('init bot with password') self.mcl = MatrixClient(**matrix_server) self.mcl.login_with_password_no_sync(**matrix_user) m_user = self.mcl.get_user(self.mcl.user_id) if m_user.get_display_name() != self.bot_display_name: m_user.set_display_name(self.bot_display_name) self.mcl.add_invite_listener(self.process_invite) self.mcl.add_listener(self.process_message, 'm.room.message') self.init_done = True logging.info('bot initialization successful') def run(self): if self.init_done: logging.debug('run listen_forever') self.mcl.listen_forever() else: logging.warning('bot not initialized successful') def join_room(self, room_id): self.ignore_room_temporary( room_id ) # necessary while joining room because otherwise old messages would be processed try: logging.info('joining new room {}'.format(room_id)) room = self.mcl.join_room(room_id) room.send_text( "Welcome! I'm a joke bot. Type '{}' and I will tell you a joke." .format(self.bot_startcmd)) return True except: logging.exception( 'Exception while joining room {}'.format(room_id)) return False temp_ignored_rooms = set() def temp_ignore_room_thread(self, room_id): logging.debug('temporary ignoring room {}'.format(room_id)) self.temp_ignored_rooms.add(room_id) time.sleep(10) self.temp_ignored_rooms.remove(room_id) logging.debug('not ignoring room {} any more'.format(room_id)) def ignore_room_temporary(self, room_id): threading.Thread(target=self.temp_ignore_room_thread, args=[room_id], daemon=True).start() def leave_room(self, room_id): logging.debug('trying to leave room with id {}'.format(room_id)) leave_room = self.mcl.get_rooms().get(room_id, '') if not leave_room: logging.debug('bot not in room with id {}'.format(room_id)) return False if leave_room.leave(): logging.debug('leaving room {} was successful'.format(room_id)) return True else: logging.debug('failed to leave known room with id {}'.format( leave_room.room_id)) return False def process_invite(self, room_id, state=None): logging.debug('received invitation of {}'.format(room_id)) if self.auto_join_invited_rooms: self.join_room(room_id) def evaluate_bot_message(self, room, sender, msg): if msg.startswith('ctl'): logging.debug("received control message '{}' in room '{}'".format( msg, room.room_id)) if sender not in self.admin_ids: logging.debug( '{} has no permissions to send a ctl-message'.format( sender)) room.send_notice( '{} has no permissions to send a ctl-message'.format( sender)) return data = msg.split(' ')[1:] if len(data) == 2: if data[0] == 'join': if not self.join_room(data[1]): room.send_notice( 'something went wrong while joining room') elif data[0] == 'leave': if data[1] == 'this': data[1] = room.room_id if not self.leave_room(data[1]): room.send_notice('room could not be left') return logging.info('sending joke to room {}'.format(room.room_id)) answer = '...' data = msg.split(' ')[1:] # remove first empty string if len(data) == 0: answer = get_joke() elif len(data) == 1: answer = get_joke(data[0]) elif len(data) == 2: answer = get_joke(data[0], data[1]) logging.debug('starting room send text') room.send_text(answer) logging.debug('done room send text') def process_message(self, roomchunk): if roomchunk['sender'] == self.mcl.user_id: return if roomchunk['room_id'] in self.temp_ignored_rooms: logging.debug('ignoring room {} temporary'.format( roomchunk['room_id'])) return content = roomchunk['content'] if content['msgtype'] == 'm.text': msg = content['body'] if msg.startswith(self.bot_startcmd): room = self.mcl.get_rooms()[roomchunk['room_id']] msg = msg[len(self.bot_startcmd):] self.evaluate_bot_message(room, roomchunk['sender'], msg)
# 11 - Serverside Error import sys import samples_common from matrix_client.client import MatrixClient from matrix_client.api import MatrixRequestError from requests.exceptions import MissingSchema host, username, password = samples_common.get_user_details(sys.argv) client = MatrixClient(host) try: client.login_with_password_no_sync(username, password) 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) room = client.join_room(input("Room:")) displayname = input("Displayname:")
print("bisher generierte labels: " + str(last_label_key)) print("letzte gedruckte label id: " + padhexa(hex(last_label_key))) nextkey = last_label_key + 1 print("naechste freie label id: " + padhexa(hex(nextkey))) for i in range(nextkey, nextkey + new_keys): hexkey = padhexa(hex(i)) urldings = "https://inv.unhb.de/" + hexkey create_qrcode(urldings, hexkey) with open("lastkey.txt", "w") as outfile: outfile.write(hexkey) # Prepare MQTT client client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("localhost", 1883, 60) # Prepare Matrix Client matrix_client = MatrixClient(matrix_server) matrix_client.login_with_password_no_sync(matrix_bot_user, matrix_bot_passwd) matrix_room = matrix_client.join_room(matrix_roomid) matrix_room.send_state_event("m.room.avatar", matrix_unk_json) # Blocking call that processes network traffic, dispatches callbacks and # handles reconnecting. # Other loop*() functions are available that give a threaded interface and a # manual interface. client.loop_forever()