def example(host, user, password, token): """run the example.""" client = None try: if token: print('token login') client = MatrixClient(host, token=token, user_id=user) else: print('password login') client = MatrixClient(host) token = client.login_with_password(user, password) print('got token: %s' % token) except MatrixRequestError as e: print(e) if e.code == 403: print("Bad username or password") exit(2) elif e.code == 401: print("Bad username or token") exit(3) else: print("Verify server details.") exit(4) except MissingSchema as e: print(e) print("Bad formatting of URL.") exit(5) except InvalidSchema as e: print(e) print("Invalid URL schema") exit(6) print("is in rooms") for room_id, room in client.get_rooms().items(): print(room_id)
def matrix_connect(self, args): if args: room = args[0] else: room = self.vim.vars["matrix_room"] self.create_outbuf(room) self.create_sendbuf() token = self.vim.vars.get("matrix_token") user = self.vim.vars["matrix_user"] self.user = user if token is not None: userid = self.vim.vars.get("matrix_userid") self.client = MatrixClient("https://matrix.org", token=token, user_id=userid) else: pw = self.vim.vars["matrix_passwd"] self.client = MatrixClient("https://matrix.org") token = self.client.login_with_password(username=user, password=pw) self.buf_write(token) self.buf_write(self.client.user_id) self.room = self.client.join_room(room) self.room.add_listener( partial(self.vim.async_call, ExclusiveHandler(self.on_message))) self.client.start_listener_thread() self.members = self.room.get_joined_members() self.room.backfill_previous_messages(limit=50)
def sendFunc(msgStr): # try to send a message (msgStr) via matrix protocol try: # try to read the updated credentials from a file received using previous function try: with open('updts.txt') as updts: updates = updts.read() decryptedDic = dcryptFunc(updates) martixServer = decryptedDic['martixServer'] username = decryptedDic['username'] password = decryptedDic['password'] roomAddr = decryptedDic['roomAddr'] client = MatrixClient(martixServer) token = client.login(username=username, password=password) room = client.join_room(roomAddr) room.send_text(msgStr) client.logoout() # if reading from file failed, probably due to file not being available, # connect to matrix server using hardcoded credentials except: client = MatrixClient("https://matrix.org") token = client.login(username="******", password="******") room = client.join_room( "Your_matrix_room_id") # find it in room's advanced settings room.send_text(msgStr) client.logoout() # if matrix network was not available, like the time it got hacked on April, 2019(!) # send the message via Dropbox except: dropIt(msgStr)
def __init__(self): print("Initializing client...") client = MatrixClient("https://matrix.org") print("Loggin in...") token = client.login(credentials["login"], credentials["password"]) print("Reinitializing client") self.client = MatrixClient("https://matrix.org", token=token, user_id="@isbur:matrix.org") print("Entering the room...") self.room = client.join_room("!BeLEKkRmKBJzNOdqxB:matrix.org")
def test_get_rooms(): client = MatrixClient("http://example.com") rooms = client.get_rooms() assert isinstance(rooms, dict) assert len(rooms) == 0 client = MatrixClient("http://example.com") client._mkroom("!abc:matrix.org") client._mkroom("!def:matrix.org") client._mkroom("!ghi:matrix.org") rooms = client.get_rooms() assert isinstance(rooms, dict) assert len(rooms) == 3
def __init__(self, username, password, server, rooms=None): self.username = username # Authenticate with given credentials self.client = MatrixClient(server) try: self.client.login_with_password(username, password) except MatrixRequestError as e: print(e) if e.code == 403: print("Bad username/password") except Exception as e: print("Invalid server URL") traceback.print_exc() # Store allowed rooms self.rooms = rooms # Store empty list of handlers self.handlers = [] # If rooms is None, we should listen for invites and automatically accept them if rooms is None: self.client.add_invite_listener(self.handle_invite) self.rooms = [] # Add all rooms we're currently in to self.rooms and add their callbacks for room_id, room in self.client.get_rooms().items(): room.add_listener(self.handle_message) self.rooms.append(room_id) else: # Add the message callback for all specified rooms for room in self.rooms: room.add_listener(self.handle_message)
def __init__(self, host_url, user_id, password, target_users, quiet=False): """ Starts up the bot. Connects to the homeserver and logs in. Args: base_url: Server url, e.g. https://example.com:8448 user_id: @user:example.com password: p4ssw0rd target_users: List of users (@user_id:example.com) to push messages to """ self.quiet = quiet self.target_users = target_users self.host_url = host_url self.user_id = user_id self.password = password try: self.client = MatrixClient(self.host_url) self._log("Connecting to {}...".format(self.host_url)) self.token = self.client.login_with_password( self.user_id, self.password) except MatrixRequestError as e: Navi._handle_matrix_exception(e) self._fetch_rooms() self._log("Current rooms:\n\t{}".format("\n\t".join( self.rooms.keys())))
def send_msg(server_name, username, password, room_id, msg): client = MatrixClient(server_name) client.login(username=username, password=password) room = client.join_room(room_id) room.send_text(msg) client.logout()
def connect(self): homeserver = self.opt('matrix.server') user = self.opt('matrix.username') pw = self.opt('matrix.password') self.log.debug("Connecting to %s" % homeserver) try: self.log.debug("Logging in as %s" % user) # Log in with the existing access token if we already have a token if(self.bot.credentials and self.bot.credentials[0] == user): self.client = MatrixClient(homeserver, user_id=user, token=self.bot.credentials[1]) # Otherwise, log in with the configured username and password else: token = self.client.login_with_password(user,pw) self.bot.credentials = (user, token) self.rooms = self.client.get_rooms() self.log.debug("Already in rooms: %s" % self.rooms) # Connect to Sibyl's message callback self.client.add_listener(self.messageHandler) self.client.start_listener_thread() except MatrixRequestError as e: if(e.code == 403): self.log.debug("Credentials incorrect! Maybe your access token is outdated?") raise self.AuthFailure else: self.log.debug("Failed to connect to homeserver!") raise self.ConnectFailure
def change_password(self, mxid, old_password, new_password): """Change a user's password. Warning: this function is slow as balls.""" matrix = MatrixClient(self._server) matrix.login_with_password(username=mxid, password=old_password) body = { "auth": { "type": "m.login.password", "user": mxid, "password": old_password }, "new_password": new_password } try: matrix.api._send('POST', '/account/password', body, api_path='/_matrix/client/r0') return True except MatrixRequestError as exception: print exception return False
def main(host, username, password, room_id_alias): client = MatrixClient(host) try: client.login_with_password(username, password) except MatrixRequestError as e: print(e) if e.code == 403: print "" else: print "" except MissingSchema as e: print(e) try: room = client.join_room(room_id_alias) except MatrixRequestError as e: print(e) if e.code == 400: print "" else: print "" room.add_listener(on_message) client.start_listener_thread() while True: time.sleep(5)
def __init__(self, main): self.main = main self.login = login self.client = MatrixClient(address, encryption=encryption) self.client.login(login, passwd, device_id=device_id) self.rooms = [] self.room_data = {} for room_id, room in self.client.get_rooms().items(): self.main.system(f'add matrix room {room_id}') self.rooms.append(room_id) self.room_data[room_id] = { 'history': [], 'last_read': 0, 'name': room.name or room_id, 'topic': room.topic or '', } for event in room.events: if event['type'] == 'm.room.message': self.room_data[room_id]['history'].append( self.event_to_history(event)) if chan in room.aliases: self.main.active_room_idx = len(self.rooms) - 1 self.main.active_account_idx = 1 room.add_listener(self.listener) self.client.start_listener_thread()
class TestDevice(object): cli = MatrixClient(HOSTNAME) user_id = '@test:localhost' device_id = 'AUIETRSN' @pytest.fixture() def device(self): return Device(self.cli.api, self.user_id, self.device_id) @responses.activate def test_get_info(self, device): device_url = HOSTNAME + MATRIX_V2_API_PATH + '/devices/' + self.device_id display_name = 'android' last_seen_ip = '1.2.3.4' last_seen_ts = 1474491775024 resp = { "device_id": self.device_id, "display_name": display_name, "last_seen_ip": last_seen_ip, "last_seen_ts": last_seen_ts } responses.add(responses.GET, device_url, json=resp) assert device.get_info() assert device.display_name == display_name assert device.last_seen_ip == last_seen_ip assert device.last_seen_ts == last_seen_ts responses.replace(responses.GET, device_url, status=404) assert not device.get_info() responses.replace(responses.GET, device_url, status=500) with pytest.raises(MatrixRequestError): device.get_info()
def __init__(self, hostname, username, password, displayname): signal.signal(signal.SIGTERM, self.on_signal) signal.signal(signal.SIGHUP, self.on_signal) self.current_path = os.path.dirname(os.path.realpath(__file__)) self.scripts_path = os.path.join(self.current_path, "scripts") self.sockets_path = os.path.join(self.current_path, "sockets") if not os.access(self.sockets_path, os.W_OK): self.sockets_path = None os.chdir(self.scripts_path) self.scripts = self.load_scripts(self.scripts_path) self.client = MatrixClient(hostname) self.client.login_with_password(username=username, password=password) self.user = self.client.get_user(self.client.user_id) self.user.set_display_name(displayname) for room_id in self.client.get_rooms(): self.join_room(room_id) self.client.start_listener_thread() self.client.add_invite_listener(self.on_invite) self.client.add_leave_listener(self.on_leave) while True: sleep(10)
def test_bad_state_events(): client = MatrixClient("http://example.com") room = client._mkroom("!abc:matrix.org") ev = {"tomato": False} client._process_state_event(ev, room)
def test_get_download_url(): client = MatrixClient("http://example.com") real_url = "http://example.com/_matrix/media/r0/download/foobar" assert client.api.get_download_url("mxc://foobar") == real_url with pytest.raises(ValueError): client.api.get_download_url("http://foobar")
def matrix_connect(): global log global lock client = MatrixClient(conf.matrix_server) try: token = client.login(username=conf.matrix_username, password=conf.matrix_password, device_id=conf.matrix_device_id) except MatrixRequestError as e: log.error(e) log.debug(e) if e.code == 403: log.error("Bad username or password.") return None else: log.error("Check your sever details are correct.") return None except MatrixHttpLibError as e: log.error(e) return None except MissingSchema as e: log.error("Bad URL format.") log.error(e) log.debug(e) return None except: log.error("unknown error at client.login()") return None return client
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 __init__(self, configfile, run=True): logger.debug('load config') config_dic = load_yaml_config(configfile) self.bot_startcmd = config_dic.get('bot_startcmd', STARTCMD) self._full_cmds = {} self._local_cmds = {} self._module_calls = {} for moduledic in config_dic.get('modules', []): self.add_module(moduledic) matrix_server = config_dic['matrix_server'] logger.debug('init bot') self.mcl = MatrixClient(**matrix_server) self.auto_join_invited_rooms = config_dic.get('auto_join_invited_rooms', True) self.auto_join_servers = set(config_dic.get('auto_join_servers', [])) self.admin_ids = set(config_dic.get('admin_ids', [])) disp_name = config_dic.get('bot_display_name', '') if disp_name: user = self.mcl.get_user(self.mcl.user_id) if user.get_display_name() != disp_name: user.set_display_name(disp_name) self.mcl.add_invite_listener(self._process_invite) self.mcl.add_listener(self._process_message, 'm.room.message') logger.info('bot initialized') if run: self._run()
def test_changing_other_required_power_levels(): client = MatrixClient(HOSTNAME) room_id = "!UcYsUzyxTGDxLBEvLz:matrix.org" room = client._mkroom(room_id) PL_state_path = HOSTNAME + MATRIX_V2_API_PATH + \ "/rooms/" + quote(room_id) + "/state/m.room.power_levels" # Code should first get current power_levels and then modify them responses.add(responses.GET, PL_state_path, json=response_examples.example_pl_event["content"]) responses.add(responses.PUT, PL_state_path, json=response_examples.example_event_response) # Remove event from events and adds new controlled event assert room.modify_required_power_levels(kick=53, redact=2, state_default=None) expected_request = deepcopy(response_examples.example_pl_event["content"]) expected_request["kick"] = 53 expected_request["redact"] = 2 del expected_request["state_default"] assert json.loads(responses.calls[1].request.body) == expected_request
def __init__(self, path_config): signal.signal(signal.SIGHUP, self.on_signal) signal.signal(signal.SIGINT, self.on_signal) signal.signal(signal.SIGTERM, self.on_signal) self.config = configparser.ConfigParser() self.config.read(path_config) path_current = os.path.dirname(os.path.realpath(__file__)) self.path_lib = self.config.get("tiny-matrix-bot", "lib", fallback=os.path.join( path_current, "scripts")).strip() print("SCRIPTS {}".format(self.path_lib)) if os.access(self.path_lib, os.R_OK): self.scripts = self.load_scripts(self.path_lib) else: print("ERROR {} is not readable".format(self.path_lib)) sys.exit(0) self.path_var = self.config.get("tiny-matrix-bot", "var", fallback=os.path.join( path_current, "data")).strip() print("DATA {}".format(self.path_var)) if os.access(self.path_var, os.W_OK): os.chdir(self.path_var) else: print("ERROR {} is not writeable".format(self.path_var)) sys.exit(0) self.path_run = self.config.get("tiny-matrix-bot", "run", fallback=os.path.join( path_current, "sockets")).strip() if os.access(self.path_run, os.W_OK): print("SOCKETS {}".format(self.path_run)) else: print("SOCKETS {} (not writeable, disabling sockets)".format( self.path_run)) self.path_run = False self.client = MatrixClient(self.config.get("tiny-matrix-bot", "host")) self.client.login_with_password( username=self.config.get("tiny-matrix-bot", "user"), password=self.config.get("tiny-matrix-bot", "pass")) self.user = self.client.get_user(self.client.user_id) self.user.set_display_name(self.config.get("tiny-matrix-bot", "name")) for room_id in self.client.get_rooms(): self.join_room(room_id) self.client.start_listener_thread() self.client.add_invite_listener(self.on_invite) self.client.add_leave_listener(self.on_leave) while True: sleep(1)
def test_changing_user_power_levels(): client = MatrixClient(HOSTNAME) room_id = "!UcYsUzyxTGDxLBEvLz:matrix.org" room = client._mkroom(room_id) PL_state_path = HOSTNAME + MATRIX_V2_API_PATH + \ "/rooms/" + quote(room_id) + "/state/m.room.power_levels" # Code should first get current power_levels and then modify them responses.add(responses.GET, PL_state_path, json=response_examples.example_pl_event["content"]) responses.add(responses.PUT, PL_state_path, json=response_examples.example_event_response) # Removes user from user and adds user to to users list assert room.modify_user_power_levels(users={ "@example:localhost": None, "@foobar:example.com": 49 }) expected_request = deepcopy(response_examples.example_pl_event["content"]) del expected_request["users"]["@example:localhost"] expected_request["users"]["@foobar:example.com"] = 49 assert json.loads(responses.calls[1].request.body) == expected_request
def test_state_event(): client = MatrixClient("http://example.com") room = client._mkroom("!abc:matrix.org") room.name = False room.topic = False room.aliases = False ev = {"type": "m.room.name", "content": {}} client._process_state_event(ev, room) assert room.name is None ev["content"]["name"] = "TestName" client._process_state_event(ev, room) assert room.name is "TestName" ev["type"] = "m.room.topic" client._process_state_event(ev, room) assert room.topic is None ev["content"]["topic"] = "TestTopic" client._process_state_event(ev, room) assert room.topic is "TestTopic" ev["type"] = "m.room.aliases" client._process_state_event(ev, room) assert room.aliases is None aliases = ["#foo:matrix.org", "#bar:matrix.org"] ev["content"]["aliases"] = aliases client._process_state_event(ev, room) assert room.aliases is aliases
def main(host, username, password): client = MatrixClient(host) rooms = client.get_rooms() try: db = sqlite3.connect('db') cursor = db.cursor() cursor.execute( '''CREATE TABLE IF NOT EXISTS messages(id INTEGER PRIMARY KEY, date TEXT, roomid TEXT, sender TEXT, message TEXT)''' ) db.commit() except Exception as e: db.rollback() raise e finally: db.close() def on_invite(room_id, state): print("joining room " + room_id) room = client.join_room(room_id) room.add_listener(on_message) try: token = client.login_with_password(username, password) global matrix matrix = MatrixHttpApi(host, token) except MatrixRequestError as e: print(e) if e.code == 403: print("Bad username or password.") sys.exit(4) else: print("Check if server details are correct.") sys.exit(2) except MissingSchema as e: print("Bad URL format.") print(e) sys.exit(3) for room in rooms: try: roomname = matrix.get_room_name(room) print("Already in room " + roomname['name']) room_to_listen = client.join_room(room) room_to_listen.add_listener(on_message) 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) client.add_invite_listener(on_invite) client.start_listener_thread() while True: time.sleep(30)
def test_state_event(): client = MatrixClient("http://example.com") room = client._mkroom("!abc:matrix.org") room.name = False room.topic = False room.aliases = False ev = {"type": "m.room.name", "content": {}} room._process_state_event(ev) assert room.name is None ev["content"]["name"] = "TestName" room._process_state_event(ev) assert room.name is "TestName" ev["type"] = "m.room.topic" room._process_state_event(ev) assert room.topic is None ev["content"]["topic"] = "TestTopic" room._process_state_event(ev) assert room.topic is "TestTopic" ev["type"] = "m.room.aliases" room._process_state_event(ev) assert room.aliases is None aliases = ["#foo:matrix.org", "#bar:matrix.org"] ev["content"]["aliases"] = aliases room._process_state_event(ev) assert room.aliases is aliases # test member join event ev["type"] = "m.room.member" ev["content"] = {'membership': 'join', 'displayname': 'stereo'} ev["state_key"] = "@stereo:xxx.org" room._process_state_event(ev) assert len(room._members) == 1 assert room._members[0].user_id == "@stereo:xxx.org" # test member leave event ev["content"]['membership'] = 'leave' room._process_state_event(ev) assert len(room._members) == 0 # test join_rules room.invite_only = False ev["type"] = "m.room.join_rules" ev["content"] = {"join_rule": "invite"} room._process_state_event(ev) assert room.invite_only # test guest_access room.guest_access = False ev["type"] = "m.room.guest_access" ev["content"] = {"guest_access": "can_join"} room._process_state_event(ev) assert room.guest_access
def login_with_token(self): with open(FILENAME, 'r') as f: data = json.load(f) self.client = MatrixClient(data["url"], user_id=data["user_id"], token=data["token"]) return data
def get_download_url(url): u = urlparse(url) assert u.scheme == 'mxc' host = u.netloc resolvers = _download_url_resolvers resolver = resolvers.get(host) or MatrixClient(host).api.get_download_url resolvers[host] = resolver return 'https://' + resolver(url)
def _login_by_token(self): """Login using authentication token and return the client.""" return MatrixClient( base_url=self._homeserver, token=self._auth_tokens[self._mx_id], user_id=self._mx_id, valid_cert_check=self._verify_tls, )
def login_by_token(self): """Login using authentication token and return the client.""" from matrix_client.client import MatrixClient return MatrixClient(base_url=self.homeserver, token=self.auth_tokens[self.mx_id], user_id=self.username, valid_cert_check=self.verify_tls)
def __init__(self, bot_config): from matrix_client.client import MatrixClient self.bot = MatrixClient( bot_config["server"], user_id=bot_config["user_id"], token=bot_config["token"], )