INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Create features for all possible country labels, return as matrix for keras. Parameters ---------- loc: dict one entry from the list of locations and features that come out of make_country_features Returns -------- keras_inputs: dict with two keys, "label" a...
def make_country_matrix(self, loc): """ Create features for all possible country labels, return as matrix for keras. Parameters ---------- loc: dict one entry from the list of locations and features that come out of make_country_features Returns ----...
NLP a doc, find its entities, get their features, and return the model's country guess for each. Maybe use a better name. Parameters ----------- doc: str or spaCy the document to country-resolve the entities in Returns ------- proced: list of dict ...
def infer_country(self, doc): """NLP a doc, find its entities, get their features, and return the model's country guess for each. Maybe use a better name. Parameters ----------- doc: str or spaCy the document to country-resolve the entities in Returns ...
Convert a geonames admin1 code to the associated place name. Parameters --------- country_code2: string The two character country code admin1_code: string The admin1 code to be converted. (Admin1 is the highest subnational...
def get_admin1(self, country_code2, admin1_code): """ Convert a geonames admin1 code to the associated place name. Parameters --------- country_code2: string The two character country code admin1_code: string The admin1 code to...
Compute features for ranking results from ES/geonames Parameters ---------- proc : dict One dictionary from the list that comes back from geoparse or from make_country_features (doesn't matter) results : dict the response from a geonames query Returns ...
def features_for_rank(self, proc, results): """Compute features for ranking results from ES/geonames Parameters ---------- proc : dict One dictionary from the list that comes back from geoparse or from make_country_features (doesn't matter) results : dict ...
Sort the place features list by the score of its relevance.
def ranker(self, X, meta): """ Sort the place features list by the score of its relevance. """ # total score is just a sum of each row total_score = X.sum(axis=1).transpose() total_score = np.squeeze(np.asarray(total_score)) # matrix to array ranks = total_score....
Given a feature matrix, geonames data, and the original query, construct a prodigy task. Make meta nicely readable: "A town in Germany" Parameters ---------- X: matrix vector of features for ranking. Output of features_for_rank() meta: list of dictionaries ...
def format_for_prodigy(self, X, meta, placename, return_feature_subset=False): """ Given a feature matrix, geonames data, and the original query, construct a prodigy task. Make meta nicely readable: "A town in Germany" Parameters ---------- X: matrix ...
Pull out just the fields we want from a geonames entry To do: - switch to model picking Parameters ----------- res : dict ES/geonames result searchterm : str (not implemented). Needed for better results picking Returns -------- ...
def format_geonames(self, entry, searchterm=None): """ Pull out just the fields we want from a geonames entry To do: - switch to model picking Parameters ----------- res : dict ES/geonames result searchterm : str (not implemented...
Small helper function to delete the features from the final dictionary. These features are mostly interesting for debugging but won't be relevant for most users.
def clean_proced(self, proced): """Small helper function to delete the features from the final dictionary. These features are mostly interesting for debugging but won't be relevant for most users. """ for loc in proced: try: del loc['all_countries'] ...
Main geoparsing function. Text to extracted, resolved entities. Parameters ---------- doc : str or spaCy The document to be geoparsed. Can be either raw text or already spacy processed. In some cases, it makes sense to bulk parse using spacy's .pipe() before sending ...
def geoparse(self, doc, verbose=False): """Main geoparsing function. Text to extracted, resolved entities. Parameters ---------- doc : str or spaCy The document to be geoparsed. Can be either raw text or already spacy processed. In some cases, it makes sense to b...
Batch geoparsing function. Take in a list of text documents and return a list of lists of the geoparsed documents. The speed improvements come exclusively from using spaCy's `nlp.pipe`. Parameters ---------- text_list : list of strs List of documents. The documents should no...
def batch_geoparse(self, text_list): """ Batch geoparsing function. Take in a list of text documents and return a list of lists of the geoparsed documents. The speed improvements come exclusively from using spaCy's `nlp.pipe`. Parameters ---------- text_list : list of st...
Take in a line from the labeled json and return a vector of labels and a matrix of features for training. Two ways to get 0s: - marked as false by user - generated automatically from other entries when guess is correct Rather than iterating through entities, just get the number of the corr...
def entry_to_matrix(prodigy_entry): """ Take in a line from the labeled json and return a vector of labels and a matrix of features for training. Two ways to get 0s: - marked as false by user - generated automatically from other entries when guess is correct Rather than iterating t...
Refreshes the FindMyiPhoneService endpoint, This ensures that the location data is up-to-date.
def refresh_client(self): """ Refreshes the FindMyiPhoneService endpoint, This ensures that the location data is up-to-date. """ req = self.session.post( self._fmip_refresh_url, params=self.params, data=json.dumps( { ...
Returns status information for device. This returns only a subset of possible properties.
def status(self, additional=[]): """ Returns status information for device. This returns only a subset of possible properties. """ self.manager.refresh_client() fields = ['batteryLevel', 'deviceDisplayName', 'deviceStatus', 'name'] fields += additional properties...
Send a request to the device to play a sound. It's possible to pass a custom message by changing the `subject`.
def play_sound(self, subject='Find My iPhone Alert'): """ Send a request to the device to play a sound. It's possible to pass a custom message by changing the `subject`. """ data = json.dumps({ 'device': self.content['id'], 'subject': subject, 'client...
Send a request to the device to play a sound. It's possible to pass a custom message by changing the `subject`.
def display_message( self, subject='Find My iPhone Alert', message="This is a note", sounds=False ): """ Send a request to the device to play a sound. It's possible to pass a custom message by changing the `subject`. """ data = json.dumps( { ...
Send a request to the device to trigger 'lost mode'. The device will show the message in `text`, and if a number has been passed, then the person holding the device can call the number without entering the passcode.
def lost_device( self, number, text='This iPhone has been lost. Please call me.', newpasscode="" ): """ Send a request to the device to trigger 'lost mode'. The device will show the message in `text`, and if a number has been passed, then the person holding the devic...
Fetches a single event's details by specifying a pguid (a calendar) and a guid (an event's ID).
def get_event_detail(self, pguid, guid): """ Fetches a single event's details by specifying a pguid (a calendar) and a guid (an event's ID). """ params = dict(self.params) params.update({'lang': 'en-us', 'usertz': get_localzone().zone}) url = '%s/%s/%s' % (self._c...
Retrieves events for a given date range, by default, this month.
def events(self, from_dt=None, to_dt=None): """ Retrieves events for a given date range, by default, this month. """ self.refresh_client(from_dt, to_dt) return self.response['Event']
Retrieves calendars for this month
def calendars(self): """ Retrieves calendars for this month """ today = datetime.today() first_day, last_day = monthrange(today.year, today.month) from_dt = datetime(today.year, today.month, first_day) to_dt = datetime(today.year, today.month, last_day) pa...
This helper will output the idevice to a pickled file named after the passed filename. This allows the data to be used without resorting to screen / pipe scrapping.
def create_pickled_data(idevice, filename): """This helper will output the idevice to a pickled file named after the passed filename. This allows the data to be used without resorting to screen / pipe scrapping. """ data = {} for x in idevice.content: data[x] = idevice.content[x] l...
Main commandline entrypoint
def main(args=None): """Main commandline entrypoint""" if args is None: args = sys.argv[1:] parser = argparse.ArgumentParser( description="Find My iPhone CommandLine Tool") parser.add_argument( "--username", action="store", dest="username", default="", ...
Refreshes the ContactsService endpoint, ensuring that the contacts data is up-to-date.
def refresh_client(self, from_dt=None, to_dt=None): """ Refreshes the ContactsService endpoint, ensuring that the contacts data is up-to-date. """ params_contacts = dict(self.params) params_contacts.update({ 'clientVersion': '2.1', 'locale': 'en_US...
Handles authentication, and persists the X-APPLE-WEB-KB cookie so that subsequent logins will not cause additional e-mails from Apple.
def authenticate(self): """ Handles authentication, and persists the X-APPLE-WEB-KB cookie so that subsequent logins will not cause additional e-mails from Apple. """ logger.info("Authenticating as %s", self.user['apple_id']) data = dict(self.user) # We authent...
Returns devices trusted for two-step authentication.
def trusted_devices(self): """ Returns devices trusted for two-step authentication.""" request = self.session.get( '%s/listDevices' % self._setup_endpoint, params=self.params ) return request.json().get('devices')
Requests that a verification code is sent to the given device
def send_verification_code(self, device): """ Requests that a verification code is sent to the given device""" data = json.dumps(device) request = self.session.post( '%s/sendVerificationCode' % self._setup_endpoint, params=self.params, data=data ) ...
Verifies a verification code received on a trusted device
def validate_verification_code(self, device, code): """ Verifies a verification code received on a trusted device""" device.update({ 'verificationCode': code, 'trustBrowser': True }) data = json.dumps(device) try: request = self.session.post( ...
Return all devices.
def devices(self): """ Return all devices.""" service_root = self.webservices['findme']['url'] return FindMyiPhoneServiceManager( service_root, self.session, self.params )
Sends the request object using the specified pool. If a pool isn't specified this method blocks. Pools are useful because you can specify size and can hence limit concurrency.
def send(r, pool=None, stream=False): """Sends the request object using the specified pool. If a pool isn't specified this method blocks. Pools are useful because you can specify size and can hence limit concurrency.""" if pool is not None: return pool.spawn(r.send, stream=stream) return ge...
Concurrently converts a list of Requests to Responses. :param requests: a collection of Request objects. :param stream: If True, the content will not be downloaded immediately. :param size: Specifies the number of requests to make at a time. If None, no throttling occurs. :param exception_handler: Call...
def map(requests, stream=False, size=None, exception_handler=None, gtimeout=None): """Concurrently converts a list of Requests to Responses. :param requests: a collection of Request objects. :param stream: If True, the content will not be downloaded immediately. :param size: Specifies the number of req...
Concurrently converts a generator object of Requests to a generator of Responses. :param requests: a generator of Request objects. :param stream: If True, the content will not be downloaded immediately. :param size: Specifies the number of requests to make at a time. default is 2 :param exception_h...
def imap(requests, stream=False, size=2, exception_handler=None): """Concurrently converts a generator object of Requests to a generator of Responses. :param requests: a generator of Request objects. :param stream: If True, the content will not be downloaded immediately. :param size: Specifies the ...
Prepares request based on parameter passed to constructor and optional ``kwargs```. Then sends request and saves response to :attr:`response` :returns: ``Response``
def send(self, **kwargs): """ Prepares request based on parameter passed to constructor and optional ``kwargs```. Then sends request and saves response to :attr:`response` :returns: ``Response`` """ merged_kwargs = {} merged_kwargs.update(self.kwargs) mer...
Set user profile within a room. This sets displayname and avatar_url for the logged in user only in a specific room. It does not change the user's global user profile.
def set_user_profile(self, displayname=None, avatar_url=None, reason="Changing room profile information"): """Set user profile within a room. This sets displayname and avatar_url for the logged in user only in a specific...
Calculates the display name for a room.
def display_name(self): """Calculates the display name for a room.""" if self.name: return self.name elif self.canonical_alias: return self.canonical_alias # Member display names without me members = [u.get_display_name(self) for u in self.get_joined_memb...
Send a plain text message to the room.
def send_text(self, text): """Send a plain text message to the room.""" return self.client.api.send_message(self.room_id, text)
Send an html formatted message. Args: html (str): The html formatted message to be sent. body (str): The unformatted body of the message to be sent.
def send_html(self, html, body=None, msgtype="m.text"): """Send an html formatted message. Args: html (str): The html formatted message to be sent. body (str): The unformatted body of the message to be sent. """ return self.client.api.send_message_event( ...
Send an emote (/me style) message to the room.
def send_emote(self, text): """Send an emote (/me style) message to the room.""" return self.client.api.send_emote(self.room_id, text)
Send a pre-uploaded file to the room. See http://matrix.org/docs/spec/r0.2.0/client_server.html#m-file for fileinfo. Args: url (str): The mxc url of the file. name (str): The filename of the image. fileinfo (): Extra information about the file
def send_file(self, url, name, **fileinfo): """Send a pre-uploaded file to the room. See http://matrix.org/docs/spec/r0.2.0/client_server.html#m-file for fileinfo. Args: url (str): The mxc url of the file. name (str): The filename of the image. filei...
Send a notice (from bot) message to the room.
def send_notice(self, text): """Send a notice (from bot) message to the room.""" return self.client.api.send_notice(self.room_id, text)
Send a pre-uploaded image to the room. See http://matrix.org/docs/spec/r0.0.1/client_server.html#m-image for imageinfo Args: url (str): The mxc url of the image. name (str): The filename of the image. imageinfo (): Extra information about the image.
def send_image(self, url, name, **imageinfo): """Send a pre-uploaded image to the room. See http://matrix.org/docs/spec/r0.0.1/client_server.html#m-image for imageinfo Args: url (str): The mxc url of the image. name (str): The filename of the image. ...
Send a location to the room. See http://matrix.org/docs/spec/client_server/r0.2.0.html#m-location for thumb_info Args: geo_uri (str): The geo uri representing the location. name (str): Description for the location. thumb_url (str): URL to the thumbnail of th...
def send_location(self, geo_uri, name, thumb_url=None, **thumb_info): """Send a location to the room. See http://matrix.org/docs/spec/client_server/r0.2.0.html#m-location for thumb_info Args: geo_uri (str): The geo uri representing the location. name (str): Desc...
Send a pre-uploaded video to the room. See http://matrix.org/docs/spec/client_server/r0.2.0.html#m-video for videoinfo Args: url (str): The mxc url of the video. name (str): The filename of the video. videoinfo (): Extra information about the video.
def send_video(self, url, name, **videoinfo): """Send a pre-uploaded video to the room. See http://matrix.org/docs/spec/client_server/r0.2.0.html#m-video for videoinfo Args: url (str): The mxc url of the video. name (str): The filename of the video. ...
Send a pre-uploaded audio to the room. See http://matrix.org/docs/spec/client_server/r0.2.0.html#m-audio for audioinfo Args: url (str): The mxc url of the audio. name (str): The filename of the audio. audioinfo (): Extra information about the audio.
def send_audio(self, url, name, **audioinfo): """Send a pre-uploaded audio to the room. See http://matrix.org/docs/spec/client_server/r0.2.0.html#m-audio for audioinfo Args: url (str): The mxc url of the audio. name (str): The filename of the audio. ...
Redacts the message with specified event_id for the given reason. See https://matrix.org/docs/spec/r0.0.1/client_server.html#id112
def redact_message(self, event_id, reason=None): """Redacts the message with specified event_id for the given reason. See https://matrix.org/docs/spec/r0.0.1/client_server.html#id112 """ return self.client.api.redact_event(self.room_id, event_id, reason)
Add a callback handler for events going to this room. Args: callback (func(room, event)): Callback called when an event arrives. event_type (str): The event_type to filter for. Returns: uuid.UUID: Unique id of the listener, can be used to identify the listener.
def add_listener(self, callback, event_type=None): """Add a callback handler for events going to this room. Args: callback (func(room, event)): Callback called when an event arrives. event_type (str): The event_type to filter for. Returns: uuid.UUID: Unique i...
Remove listener with given uid.
def remove_listener(self, uid): """Remove listener with given uid.""" self.listeners[:] = (listener for listener in self.listeners if listener['uid'] != uid)
Add a callback handler for ephemeral events going to this room. Args: callback (func(room, event)): Callback called when an ephemeral event arrives. event_type (str): The event_type to filter for. Returns: uuid.UUID: Unique id of the listener, can be used to identify...
def add_ephemeral_listener(self, callback, event_type=None): """Add a callback handler for ephemeral events going to this room. Args: callback (func(room, event)): Callback called when an ephemeral event arrives. event_type (str): The event_type to filter for. Returns: ...
Remove ephemeral listener with given uid.
def remove_ephemeral_listener(self, uid): """Remove ephemeral listener with given uid.""" self.ephemeral_listeners[:] = (listener for listener in self.ephemeral_listeners if listener['uid'] != uid)
Invite a user to this room. Returns: boolean: Whether invitation was sent.
def invite_user(self, user_id): """Invite a user to this room. Returns: boolean: Whether invitation was sent. """ try: self.client.api.invite_user(self.room_id, user_id) return True except MatrixRequestError: return False
Kick a user from this room. Args: user_id (str): The matrix user id of a user. reason (str): A reason for kicking the user. Returns: boolean: Whether user was kicked.
def kick_user(self, user_id, reason=""): """Kick a user from this room. Args: user_id (str): The matrix user id of a user. reason (str): A reason for kicking the user. Returns: boolean: Whether user was kicked. """ try: self.cli...
Leave the room. Returns: boolean: Leaving the room was successful.
def leave(self): """Leave the room. Returns: boolean: Leaving the room was successful. """ try: self.client.api.leave_room(self.room_id) del self.client.rooms[self.room_id] return True except MatrixRequestError: return ...
Updates self.name and returns True if room name has changed.
def update_room_name(self): """Updates self.name and returns True if room name has changed.""" try: response = self.client.api.get_room_name(self.room_id) if "name" in response and response["name"] != self.name: self.name = response["name"] return ...
Return True if room name successfully changed.
def set_room_name(self, name): """Return True if room name successfully changed.""" try: self.client.api.set_room_name(self.room_id, name) self.name = name return True except MatrixRequestError: return False
Send a state event to the room. Args: event_type (str): The type of event that you are sending. content (): An object with the content of the message. state_key (str, optional): A unique key to identify the state.
def send_state_event(self, event_type, content, state_key=""): """Send a state event to the room. Args: event_type (str): The type of event that you are sending. content (): An object with the content of the message. state_key (str, optional): A unique key to identif...
Updates self.topic and returns True if room topic has changed.
def update_room_topic(self): """Updates self.topic and returns True if room topic has changed.""" try: response = self.client.api.get_room_topic(self.room_id) if "topic" in response and response["topic"] != self.topic: self.topic = response["topic"] ...
Set room topic. Returns: boolean: True if the topic changed, False if not
def set_room_topic(self, topic): """Set room topic. Returns: boolean: True if the topic changed, False if not """ try: self.client.api.set_room_topic(self.room_id, topic) self.topic = topic return True except MatrixRequestError: ...
Get aliases information from room state. Returns: boolean: True if the aliases changed, False if not
def update_aliases(self): """Get aliases information from room state. Returns: boolean: True if the aliases changed, False if not """ try: response = self.client.api.get_room_state(self.room_id) for chunk in response: if "content" in c...
Add an alias to the room and return True if successful.
def add_room_alias(self, room_alias): """Add an alias to the room and return True if successful.""" try: self.client.api.set_room_alias(self.room_id, room_alias) return True except MatrixRequestError: return False
Returns list of joined members (User objects).
def get_joined_members(self): """Returns list of joined members (User objects).""" if self._members: return list(self._members.values()) response = self.client.api.get_room_members(self.room_id) for event in response["chunk"]: if event["content"]["membership"] == ...
Backfill handling of previous messages. Args: reverse (bool): When false messages will be backfilled in their original order (old to new), otherwise the order will be reversed (new to old). limit (int): Number of messages to go back.
def backfill_previous_messages(self, reverse=False, limit=10): """Backfill handling of previous messages. Args: reverse (bool): When false messages will be backfilled in their original order (old to new), otherwise the order will be reversed (new to old). limit (...
Modify the power level for a subset of users Args: users(dict): Power levels to assign to specific users, in the form {"@name0:host0": 10, "@name1:host1": 100, "@name3:host3", None} A level of None causes the user to revert to the default level as spe...
def modify_user_power_levels(self, users=None, users_default=None): """Modify the power level for a subset of users Args: users(dict): Power levels to assign to specific users, in the form {"@name0:host0": 10, "@name1:host1": 100, "@name3:host3", None} A leve...
Modifies room power level requirements. Args: events(dict): Power levels required for sending specific event types, in the form {"m.room.whatever0": 60, "m.room.whatever2": None}. Overrides events_default and state_default for the specified events. A ...
def modify_required_power_levels(self, events=None, **kwargs): """Modifies room power level requirements. Args: events(dict): Power levels required for sending specific event types, in the form {"m.room.whatever0": 60, "m.room.whatever2": None}. Overrides eve...
Set how the room can be joined. Args: invite_only(bool): If True, users will have to be invited to join the room. If False, anyone who knows the room link can join. Returns: True if successful, False if not
def set_invite_only(self, invite_only): """Set how the room can be joined. Args: invite_only(bool): If True, users will have to be invited to join the room. If False, anyone who knows the room link can join. Returns: True if successful, False if not ...
Set whether guests can join the room and return True if successful.
def set_guest_access(self, allow_guests): """Set whether guests can join the room and return True if successful.""" guest_access = "can_join" if allow_guests else "forbidden" try: self.client.api.set_guest_access(self.room_id, guest_access) self.guest_access = allow_guest...
Enables encryption in the room. NOTE: Once enabled, encryption cannot be disabled. Returns: True if successful, False if not
def enable_encryption(self): """Enables encryption in the room. NOTE: Once enabled, encryption cannot be disabled. Returns: True if successful, False if not """ try: self.send_state_event("m.room.encryption", {"algorithm": "...
run the example.
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) toke...
Main entry.
def main(): """Main entry.""" parser = argparse.ArgumentParser() parser.add_argument("--host", type=str, required=True) parser.add_argument("--user", type=str, required=True) parser.add_argument("--password", type=str) parser.add_argument("--token", type=str) args = parser.parse_args() i...
.. warning:: Deprecated. Use sync instead. Perform /initialSync. Args: limit (int): The limit= param to provide.
def initial_sync(self, limit=1): """ .. warning:: Deprecated. Use sync instead. Perform /initialSync. Args: limit (int): The limit= param to provide. """ warnings.warn("initial_sync is deprecated. Use sync instead.", DeprecationWarning) ...
Perform a sync request. Args: since (str): Optional. A token which specifies where to continue a sync from. timeout_ms (int): Optional. The time in milliseconds to wait. filter (int|str): Either a Filter ID or a JSON string. full_state (bool): Return the full sta...
def sync(self, since=None, timeout_ms=30000, filter=None, full_state=None, set_presence=None): """ Perform a sync request. Args: since (str): Optional. A token which specifies where to continue a sync from. timeout_ms (int): Optional. The time in milliseconds to wai...
Performs /register. Args: auth_body (dict): Authentication Params. kind (str): Specify kind of account to register. Can be 'guest' or 'user'. bind_email (bool): Whether to use email in registration and authentication. username (str): The localpart of a Matrix ID....
def register(self, auth_body=None, kind="user", bind_email=None, username=None, password=None, device_id=None, initial_device_display_name=None, inhibit_login=None): """Performs /register. Args: auth_body (dict): Authentication Params. kind (str...
Perform /login. Args: login_type (str): The value for the 'type' key. **kwargs: Additional key/values to add to the JSON submitted.
def login(self, login_type, **kwargs): """Perform /login. Args: login_type (str): The value for the 'type' key. **kwargs: Additional key/values to add to the JSON submitted. """ content = { "type": login_type } for key in kwargs: ...
Perform /createRoom. Args: alias (str): Optional. The room alias name to set for this room. name (str): Optional. Name for new room. is_public (bool): Optional. The public/private visibility. invitees (list<str>): Optional. The list of user IDs to invite. ...
def create_room( self, alias=None, name=None, is_public=False, invitees=None, federate=None ): """Perform /createRoom. Args: alias (str): Optional. The room alias name to set for this...
Performs /join/$room_id Args: room_id_or_alias (str): The room ID or room alias to join.
def join_room(self, room_id_or_alias): """Performs /join/$room_id Args: room_id_or_alias (str): The room ID or room alias to join. """ if not room_id_or_alias: raise MatrixError("No alias or room ID to join.") path = "/join/%s" % quote(room_id_or_alias) ...
Perform PUT /rooms/$room_id/state/$event_type Args: room_id(str): The room ID to send the state event in. event_type(str): The state event type to send. content(dict): The JSON content to send. state_key(str): Optional. The state key for the event. ti...
def send_state_event(self, room_id, event_type, content, state_key="", timestamp=None): """Perform PUT /rooms/$room_id/state/$event_type Args: room_id(str): The room ID to send the state event in. event_type(str): The state event type to send. ...
Deprecated. Use sync instead. Performs /events Args: from_token (str): The 'from' query parameter. timeout (int): Optional. The 'timeout' query parameter.
def event_stream(self, from_token, timeout=30000): """ Deprecated. Use sync instead. Performs /events Args: from_token (str): The 'from' query parameter. timeout (int): Optional. The 'timeout' query parameter. """ warnings.warn("event_stream is deprecated...
Perform GET /rooms/$room_id/state/$event_type Args: room_id(str): The room ID. event_type (str): The type of the event. Raises: MatrixRequestError(code=404) if the state event is not found.
def get_state_event(self, room_id, event_type): """Perform GET /rooms/$room_id/state/$event_type Args: room_id(str): The room ID. event_type (str): The type of the event. Raises: MatrixRequestError(code=404) if the state event is not found. """ ...
Perform PUT /rooms/$room_id/send/$event_type Args: room_id (str): The room ID to send the message event in. event_type (str): The event type to send. content (dict): The JSON content to send. txn_id (int): Optional. The transaction ID to use. timestam...
def send_message_event(self, room_id, event_type, content, txn_id=None, timestamp=None): """Perform PUT /rooms/$room_id/send/$event_type Args: room_id (str): The room ID to send the message event in. event_type (str): The event type to send. ...
Perform PUT /rooms/$room_id/redact/$event_id/$txn_id/ Args: room_id(str): The room ID to redact the message event in. event_id(str): The event id to redact. reason (str): Optional. The reason the message was redacted. txn_id(int): Optional. The transaction ID to ...
def redact_event(self, room_id, event_id, reason=None, txn_id=None, timestamp=None): """Perform PUT /rooms/$room_id/redact/$event_id/$txn_id/ Args: room_id(str): The room ID to redact the message event in. event_id(str): The event id to redact. reason (str): Optional...
Send m.location message event Args: room_id (str): The room ID to send the event in. geo_uri (str): The geo uri representing the location. name (str): Description for the location. thumb_url (str): URL to the thumbnail of the location. thumb_info (dic...
def send_location(self, room_id, geo_uri, name, thumb_url=None, thumb_info=None, timestamp=None): """Send m.location message event Args: room_id (str): The room ID to send the event in. geo_uri (str): The geo uri representing the location. name ...
Perform PUT /rooms/$room_id/send/m.room.message Args: room_id (str): The room ID to send the event in. text_content (str): The m.text body to send. timestamp (int): Set origin_server_ts (For application services only)
def send_message(self, room_id, text_content, msgtype="m.text", timestamp=None): """Perform PUT /rooms/$room_id/send/m.room.message Args: room_id (str): The room ID to send the event in. text_content (str): The m.text body to send. timestamp (int): Set origin_server_...
Perform PUT /rooms/$room_id/send/m.room.message with m.emote msgtype Args: room_id (str): The room ID to send the event in. text_content (str): The m.emote body to send. timestamp (int): Set origin_server_ts (For application services only)
def send_emote(self, room_id, text_content, timestamp=None): """Perform PUT /rooms/$room_id/send/m.room.message with m.emote msgtype Args: room_id (str): The room ID to send the event in. text_content (str): The m.emote body to send. timestamp (int): Set origin_serve...
Perform PUT /rooms/$room_id/send/m.room.message with m.notice msgtype Args: room_id (str): The room ID to send the event in. text_content (str): The m.notice body to send. timestamp (int): Set origin_server_ts (For application services only)
def send_notice(self, room_id, text_content, timestamp=None): """Perform PUT /rooms/$room_id/send/m.room.message with m.notice msgtype Args: room_id (str): The room ID to send the event in. text_content (str): The m.notice body to send. timestamp (int): Set origin_se...
Perform GET /rooms/{roomId}/messages. Args: room_id (str): The room's id. token (str): The token to start returning events from. direction (str): The direction to return events from. One of: ["b", "f"]. limit (int): The maximum number of events to return. ...
def get_room_messages(self, room_id, token, direction, limit=10, to=None): """Perform GET /rooms/{roomId}/messages. Args: room_id (str): The room's id. token (str): The token to start returning events from. direction (str): The direction to return events from. One o...
Perform PUT /rooms/$room_id/state/m.room.name Args: room_id (str): The room ID name (str): The new room name timestamp (int): Set origin_server_ts (For application services only)
def set_room_name(self, room_id, name, timestamp=None): """Perform PUT /rooms/$room_id/state/m.room.name Args: room_id (str): The room ID name (str): The new room name timestamp (int): Set origin_server_ts (For application services only) """ body = { ...
Perform PUT /rooms/$room_id/state/m.room.topic Args: room_id (str): The room ID topic (str): The new room topic timestamp (int): Set origin_server_ts (For application services only)
def set_room_topic(self, room_id, topic, timestamp=None): """Perform PUT /rooms/$room_id/state/m.room.topic Args: room_id (str): The room ID topic (str): The new room topic timestamp (int): Set origin_server_ts (For application services only) """ body ...
Perform PUT /rooms/$room_id/state/m.room.power_levels Note that any power levels which are not explicitly specified in the content arg are reset to default values. Args: room_id (str): The room ID content (dict): The JSON content to send. See example content below. ...
def set_power_levels(self, room_id, content): """Perform PUT /rooms/$room_id/state/m.room.power_levels Note that any power levels which are not explicitly specified in the content arg are reset to default values. Args: room_id (str): The room ID content (dict): ...
Perform POST /rooms/$room_id/invite Args: room_id (str): The room ID user_id (str): The user ID of the invitee
def invite_user(self, room_id, user_id): """Perform POST /rooms/$room_id/invite Args: room_id (str): The room ID user_id (str): The user ID of the invitee """ body = { "user_id": user_id } return self._send("POST", "/rooms/" + room_id ...
Calls set_membership with membership="leave" for the user_id provided
def kick_user(self, room_id, user_id, reason=""): """Calls set_membership with membership="leave" for the user_id provided """ self.set_membership(room_id, user_id, "leave", reason)
Perform PUT /rooms/$room_id/state/m.room.member/$user_id Args: room_id (str): The room ID user_id (str): The user ID membership (str): New membership value reason (str): The reason timestamp (int): Set origin_server_ts (For application services only)
def set_membership(self, room_id, user_id, membership, reason="", profile=None, timestamp=None): """Perform PUT /rooms/$room_id/state/m.room.member/$user_id Args: room_id (str): The room ID user_id (str): The user ID membership (str): New membe...
Perform POST /rooms/$room_id/ban Args: room_id (str): The room ID user_id (str): The user ID of the banee(sic) reason (str): The reason for this ban
def ban_user(self, room_id, user_id, reason=""): """Perform POST /rooms/$room_id/ban Args: room_id (str): The room ID user_id (str): The user ID of the banee(sic) reason (str): The reason for this ban """ body = { "user_id": user_id, ...
Download raw media from provided mxc URL. Args: mxcurl (str): mxc media URL. allow_remote (bool): indicates to the server that it should not attempt to fetch the media if it is deemed remote. Defaults to true if not provided.
def media_download(self, mxcurl, allow_remote=True): """Download raw media from provided mxc URL. Args: mxcurl (str): mxc media URL. allow_remote (bool): indicates to the server that it should not attempt to fetch the media if it is deemed remote. Defaults ...
Perform POST /rooms/$room_id/unban Args: room_id (str): The room ID user_id (str): The user ID of the banee(sic)
def unban_user(self, room_id, user_id): """Perform POST /rooms/$room_id/unban Args: room_id (str): The room ID user_id (str): The user ID of the banee(sic) """ body = { "user_id": user_id } return self._send("POST", "/rooms/" + room_id...
Download raw media thumbnail from provided mxc URL. Args: mxcurl (str): mxc media URL width (int): desired thumbnail width height (int): desired thumbnail height method (str): thumb creation method. Must be in ['scale', 'crop']. Default 'scale'. ...
def get_thumbnail(self, mxcurl, width, height, method='scale', allow_remote=True): """Download raw media thumbnail from provided mxc URL. Args: mxcurl (str): mxc media URL width (int): desired thumbnail width height (int): desired thumbnail height method ...
Get preview for URL. Args: url (str): URL to get a preview ts (double): The preferred point in time to return a preview for. The server may return a newer version if it does not have the requested version available.
def get_url_preview(self, url, ts=None): """Get preview for URL. Args: url (str): URL to get a preview ts (double): The preferred point in time to return a preview for. The server may return a newer version if it does not have the requested ...
Get room id from its alias. Args: room_alias (str): The room alias name. Returns: Wanted room's id.
def get_room_id(self, room_alias): """Get room id from its alias. Args: room_alias (str): The room alias name. Returns: Wanted room's id. """ content = self._send("GET", "/directory/room/{}".format(quote(room_alias))) return content.get("room_id"...
Set alias to room id Args: room_id (str): The room id. room_alias (str): The room wanted alias name.
def set_room_alias(self, room_id, room_alias): """Set alias to room id Args: room_id (str): The room id. room_alias (str): The room wanted alias name. """ data = { "room_id": room_id } return self._send("PUT", "/directory/room/{}".for...
Set the rule for users wishing to join the room. Args: room_id(str): The room to set the rules for. join_rule(str): The chosen rule. One of: ["public", "knock", "invite", "private"]
def set_join_rule(self, room_id, join_rule): """Set the rule for users wishing to join the room. Args: room_id(str): The room to set the rules for. join_rule(str): The chosen rule. One of: ["public", "knock", "invite", "private"] """ content = { ...
Set the guest access policy of the room. Args: room_id(str): The room to set the rules for. guest_access(str): Wether guests can join. One of: ["can_join", "forbidden"]
def set_guest_access(self, room_id, guest_access): """Set the guest access policy of the room. Args: room_id(str): The room to set the rules for. guest_access(str): Wether guests can join. One of: ["can_join", "forbidden"] """ content = { ...
Update the display name of a device. Args: device_id (str): The device ID of the device to update. display_name (str): New display name for the device.
def update_device_info(self, device_id, display_name): """Update the display name of a device. Args: device_id (str): The device ID of the device to update. display_name (str): New display name for the device. """ content = { "display_name": display_n...
Deletes the given device, and invalidates any access token associated with it. NOTE: This endpoint uses the User-Interactive Authentication API. Args: auth_body (dict): Authentication params. device_id (str): The device ID of the device to delete.
def delete_device(self, auth_body, device_id): """Deletes the given device, and invalidates any access token associated with it. NOTE: This endpoint uses the User-Interactive Authentication API. Args: auth_body (dict): Authentication params. device_id (str): The device ...
Bulk deletion of devices. NOTE: This endpoint uses the User-Interactive Authentication API. Args: auth_body (dict): Authentication params. devices (list): List of device ID"s to delete.
def delete_devices(self, auth_body, devices): """Bulk deletion of devices. NOTE: This endpoint uses the User-Interactive Authentication API. Args: auth_body (dict): Authentication params. devices (list): List of device ID"s to delete. """ content = { ...