docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Generate the payload to send. Args: command(str): The type of command. This is one of the entries from payload_dict data(dict, optional): The data to be send. This is what will be passed via the 'dps' entry
def generate_payload(self, command, data=None): json_data = payload_dict[self.dev_type][command]['command'] if 'gwId' in json_data: json_data['gwId'] = self.id if 'devId' in json_data: json_data['devId'] = self.id if 'uid' in json_data: json_...
237,679
Set status of the device to 'on' or 'off'. Args: on(bool): True for 'on', False for 'off'. switch(int): The switch to set
def set_status(self, on, switch=1): # open device, send request, then close connection if isinstance(switch, int): switch = str(switch) # index and payload is a string payload = self.generate_payload(SET, {switch:on}) #print('payload %r' % payload) data = s...
237,682
Set a timer. Args: num_secs(int): Number of seconds
def set_timer(self, num_secs): # FIXME / TODO support schemas? Accept timer id number as parameter? # Dumb heuristic; Query status, pick last device id as that is probably the timer status = self.status() devices = status['dps'] devices_numbers = list(devices.keys()) ...
237,683
Converts the hexvalue used by tuya for colour representation into an RGB value. Args: hexvalue(string): The hex representation generated by BulbDevice._rgb_to_hexvalue()
def _hexvalue_to_rgb(hexvalue): r = int(hexvalue[0:2], 16) g = int(hexvalue[2:4], 16) b = int(hexvalue[4:6], 16) return (r, g, b)
237,687
Converts the hexvalue used by tuya for colour representation into an HSV value. Args: hexvalue(string): The hex representation generated by BulbDevice._rgb_to_hexvalue()
def _hexvalue_to_hsv(hexvalue): h = int(hexvalue[7:10], 16) / 360 s = int(hexvalue[10:12], 16) / 255 v = int(hexvalue[12:14], 16) / 255 return (h, s, v)
237,688
Set colour of an rgb bulb. Args: r(int): Value for the colour red as int from 0-255. g(int): Value for the colour green as int from 0-255. b(int): Value for the colour blue as int from 0-255.
def set_colour(self, r, g, b): if not 0 <= r <= 255: raise ValueError("The value for red needs to be between 0 and 255.") if not 0 <= g <= 255: raise ValueError("The value for green needs to be between 0 and 255.") if not 0 <= b <= 255: raise ValueErr...
237,689
Set white coloured theme of an rgb bulb. Args: brightness(int): Value for the brightness (25-255). colourtemp(int): Value for the colour temperature (0-255).
def set_white(self, brightness, colourtemp): if not 25 <= brightness <= 255: raise ValueError("The brightness needs to be between 25 and 255.") if not 0 <= colourtemp <= 255: raise ValueError("The colour temperature needs to be between 0 and 255.") payload = sel...
237,690
Set the brightness value of an rgb bulb. Args: brightness(int): Value for the brightness (25-255).
def set_brightness(self, brightness): if not 25 <= brightness <= 255: raise ValueError("The brightness needs to be between 25 and 255.") payload = self.generate_payload(SET, {self.DPS_INDEX_BRIGHTNESS: brightness}) data = self._send_receive(payload) return data
237,691
Set the colour temperature of an rgb bulb. Args: colourtemp(int): Value for the colour temperature (0-255).
def set_colourtemp(self, colourtemp): if not 0 <= colourtemp <= 255: raise ValueError("The colour temperature needs to be between 0 and 255.") payload = self.generate_payload(SET, {self.DPS_INDEX_COLOURTEMP: colourtemp}) data = self._send_receive(payload) return dat...
237,692
Creates a :class:`Flow` instance from a Google client secrets file. Args: client_secrets_file (str): The path to the client secrets .json file. scopes (Sequence[str]): The list of scopes to request during the flow. kwargs: Any additional param...
def from_client_secrets_file(cls, client_secrets_file, scopes, **kwargs): with open(client_secrets_file, 'r') as json_file: client_config = json.load(json_file) return cls.from_client_config(client_config, scopes=scopes, **kwargs)
238,070
WSGI Callable. Args: environ (Mapping[str, Any]): The WSGI environment. start_response (Callable[str, list]): The WSGI start_response callable. Returns: Iterable[bytes]: The response body.
def __call__(self, environ, start_response): start_response('200 OK', [('Content-type', 'text/plain')]) self.last_request_uri = wsgiref.util.request_uri(environ) return [self._success_message.encode('utf-8')]
238,075
Create a registry object. Arguments: default_opener (str, optional): The protocol to use, if one is not supplied. The default is to use 'osfs', so that the FS URL is treated as a system path if no protocol is given. load_extern (bool, optional): Set to `T...
def __init__(self, default_opener="osfs", load_extern=False): # type: (Text, bool) -> None self.default_opener = default_opener self.load_extern = load_extern self._protocols = {}
238,079
Install an opener. Arguments: opener (`Opener`): an `Opener` instance, or a callable that returns an opener instance. Note: May be used as a class decorator. For example:: registry = Registry() @registry.install cl...
def install(self, opener): # type: (Union[Type[Opener], Opener, Callable[[], Opener]]) -> None _opener = opener if isinstance(opener, Opener) else opener() assert isinstance(_opener, Opener), "Opener instance required" assert _opener.protocols, "must list one or more protocols" ...
238,080
Get the opener class associated to a given protocol. Arguments: protocol (str): A filesystem protocol. Returns: Opener: an opener instance. Raises: ~fs.opener.errors.UnsupportedProtocol: If no opener could be found for the given protocol. ...
def get_opener(self, protocol): # type: (Text) -> Opener protocol = protocol or self.default_opener if self.load_extern: entry_point = next( pkg_resources.iter_entry_points("fs.opener", protocol), None ) else: entry_point = No...
238,082
Copy a file from one filesystem to another. If the destination exists, and is a file, it will be first truncated. Arguments: src_fs (FS or str): Source filesystem (instance or URL). src_path (str): Path to a file on the source filesystem. dst_fs (FS or str): Destination filesystem (ins...
def copy_file( src_fs, # type: Union[FS, Text] src_path, # type: Text dst_fs, # type: Union[FS, Text] dst_path, # type: Text ): # type: (...) -> None with manage_fs(src_fs, writeable=False) as _src_fs: with manage_fs(dst_fs, create=True) as _dst_fs: if _src_fs is _ds...
238,090
Low level copy, that doesn't call manage_fs or lock. If the destination exists, and is a file, it will be first truncated. This method exists to optimize copying in loops. In general you should prefer `copy_file`. Arguments: src_fs (FS): Source filesystem. src_path (str): Path to a fi...
def copy_file_internal( src_fs, # type: FS src_path, # type: Text dst_fs, # type: FS dst_path, # type: Text ): # type: (...) -> None if src_fs is dst_fs: # Same filesystem, so we can do a potentially optimized # copy src_fs.copy(src_path, dst_path, overwrite=True...
238,091
Copy directories (but not files) from ``src_fs`` to ``dst_fs``. Arguments: src_fs (FS or str): Source filesystem (instance or URL). dst_fs (FS or str): Destination filesystem (instance or URL). walker (~fs.walk.Walker, optional): A walker object that will be used to scan for fil...
def copy_structure( src_fs, # type: Union[FS, Text] dst_fs, # type: Union[FS, Text] walker=None, # type: Optional[Walker] ): # type: (...) -> None walker = walker or Walker() with manage_fs(src_fs) as _src_fs: with manage_fs(dst_fs, create=True) as _dst_fs: with _src_...
238,093
Compare a glob pattern with a path (case sensitive). Arguments: pattern (str): A glob pattern. path (str): A path. Returns: bool: ``True`` if the path matches the pattern. Example: >>> from fs.glob import match >>> match("**/*.py", "/fs/glob.py") True
def match(pattern, path): # type: (str, str) -> bool try: levels, recursive, re_pattern = _PATTERN_CACHE[(pattern, True)] except KeyError: levels, recursive, re_pattern = _translate_glob(pattern, case_sensitive=True) _PATTERN_CACHE[(pattern, True)] = (levels, recursive, re_patte...
238,141
Move a file from one filesystem to another. Arguments: src_fs (FS or str): Source filesystem (instance or URL). src_path (str): Path to a file on ``src_fs``. dst_fs (FS or str); Destination filesystem (instance or URL). dst_path (str): Path to a file on ``dst_fs``.
def move_file( src_fs, # type: Union[Text, FS] src_path, # type: Text dst_fs, # type: Union[Text, FS] dst_path, # type: Text ): # type: (...) -> None with manage_fs(src_fs) as _src_fs: with manage_fs(dst_fs, create=True) as _dst_fs: if _src_fs is _dst_fs: ...
238,150
Move a directory from one filesystem to another. Arguments: src_fs (FS or str): Source filesystem (instance or URL). src_path (str): Path to a directory on ``src_fs`` dst_fs (FS or str): Destination filesystem (instance or URL). dst_path (str): Path to a directory on ``dst_fs``. ...
def move_dir( src_fs, # type: Union[Text, FS] src_path, # type: Text dst_fs, # type: Union[Text, FS] dst_path, # type: Text workers=0, # type: int ): # type: (...) -> None def src(): return manage_fs(src_fs, writeable=False) def dst(): return manage_fs(dst_fs,...
238,151
Get intermediate paths from the root to the given path. Arguments: path (str): A PyFilesystem path reverse (bool): Reverses the order of the paths (default `False`). Returns: list: A list of paths. Example: >>> recursepath('a/b/c') ['/', '/a', '/a/b', '...
def recursepath(path, reverse=False): # type: (Text, bool) -> List[Text] if path in "/": return ["/"] path = abspath(normpath(path)) + "/" paths = ["/"] find = path.find append = paths.append pos = 1 len_path = len(path) while pos < len_path: pos = find("/", p...
238,153
Join any number of paths together. Arguments: *paths (str): Paths to join, given as positional arguments. Returns: str: The joined path. Example: >>> join('foo', 'bar', 'baz') 'foo/bar/baz' >>> join('foo/bar', '../baz') 'foo/baz' >>> join('foo/bar',...
def join(*paths): # type: (*Text) -> Text absolute = False relpaths = [] # type: List[Text] for p in paths: if p: if p[0] == "/": del relpaths[:] absolute = True relpaths.append(p) path = normpath("/".join(relpaths)) if absol...
238,154
Join two paths together. This is faster than :func:`~fs.path.join`, but only works when the second path is relative, and there are no back references in either path. Arguments: path1 (str): A PyFilesytem path. path2 (str): A PyFilesytem path. Returns: str: The joint path. ...
def combine(path1, path2): # type: (Text, Text) -> Text if not path1: return path2.lstrip() return "{}/{}".format(path1.rstrip("/"), path2.lstrip("/"))
238,155
Split a path in to its component parts. Arguments: path (str): Path to split in to parts. Returns: list: List of components Example: >>> parts('/foo/bar/baz') ['/', 'foo', 'bar', 'baz']
def parts(path): # type: (Text) -> List[Text] _path = normpath(path) components = _path.strip("/") _parts = ["/" if _path.startswith("/") else "./"] if components: _parts += components.split("/") return _parts
238,156
Split the extension from the path. Arguments: path (str): A path to split. Returns: (str, str): A tuple containing the path and the extension. Example: >>> splitext('baz.txt') ('baz', '.txt') >>> splitext('foo/bar/baz.txt') ('foo/bar/baz', '.txt') >...
def splitext(path): # type: (Text) -> Tuple[Text, Text] parent_path, pathname = split(path) if pathname.startswith(".") and pathname.count(".") == 1: return path, "" if "." not in pathname: return path, "" pathname, ext = pathname.rsplit(".", 1) path = join(parent_path, path...
238,157
Check if ``path1`` is a base of ``path2``. Arguments: path1 (str): A PyFilesytem path. path2 (str): A PyFilesytem path. Returns: bool: `True` if ``path2`` starts with ``path1`` Example: >>> isbase('foo/bar', 'foo/bar/baz/egg.txt') True
def isbase(path1, path2): # type: (Text, Text) -> bool _path1 = forcedir(abspath(path1)) _path2 = forcedir(abspath(path2)) return _path2.startswith(_path1)
238,158
Get the final path of ``path2`` that isn't in ``path1``. Arguments: path1 (str): A PyFilesytem path. path2 (str): A PyFilesytem path. Returns: str: the final part of ``path2``. Example: >>> frombase('foo/bar/', 'foo/bar/baz/egg') 'baz/egg'
def frombase(path1, path2): # type: (Text, Text) -> Text if not isparent(path1, path2): raise ValueError("path1 must be a prefix of path2") return path2[len(path1) :]
238,160
Return a path relative from a given base path. Insert backrefs as appropriate to reach the path from the base. Arguments: base (str): Path to a directory. path (str): Path to make relative. Returns: str: the path to ``base`` from ``path``. >>> relativefrom("foo/bar", "baz/ind...
def relativefrom(base, path): # type: (Text, Text) -> Text base_parts = list(iteratepath(base)) path_parts = list(iteratepath(path)) common = 0 for component_a, component_b in zip(base_parts, path_parts): if component_a != component_b: break common += 1 return ...
238,161
Test whether a name matches a wildcard pattern. Arguments: pattern (str): A wildcard pattern, e.g. ``"*.py"``. name (str): A filename. Returns: bool: `True` if the filename matches the pattern.
def match(pattern, name): # type: (Text, Text) -> bool try: re_pat = _PATTERN_CACHE[(pattern, True)] except KeyError: res = "(?ms)" + _translate(pattern) + r'\Z' _PATTERN_CACHE[(pattern, True)] = re_pat = re.compile(res) return re_pat.match(name) is not None
238,170
Test whether a name matches a wildcard pattern (case insensitive). Arguments: pattern (str): A wildcard pattern, e.g. ``"*.py"``. name (bool): A filename. Returns: bool: `True` if the filename matches the pattern.
def imatch(pattern, name): # type: (Text, Text) -> bool try: re_pat = _PATTERN_CACHE[(pattern, False)] except KeyError: res = "(?ms)" + _translate(pattern, case_sensitive=False) + r'\Z' _PATTERN_CACHE[(pattern, False)] = re_pat = re.compile(res, re.IGNORECASE) return re_pat....
238,171
Test if a name matches any of a list of patterns. Will return `True` if ``patterns`` is an empty list. Arguments: patterns (list): A list of wildcard pattern, e.g ``["*.py", "*.pyc"]`` name (str): A filename. Returns: bool: `True` if the name matches at least one of th...
def match_any(patterns, name): # type: (Iterable[Text], Text) -> bool if not patterns: return True return any(match(pattern, name) for pattern in patterns)
238,172
Test if a name matches any of a list of patterns (case insensitive). Will return `True` if ``patterns`` is an empty list. Arguments: patterns (list): A list of wildcard pattern, e.g ``["*.py", "*.pyc"]`` name (str): A filename. Returns: bool: `True` if the name matches...
def imatch_any(patterns, name): # type: (Iterable[Text], Text) -> bool if not patterns: return True return any(imatch(pattern, name) for pattern in patterns)
238,173
Translate a wildcard pattern to a regular expression. There is no way to quote meta-characters. Arguments: pattern (str): A wildcard pattern. case_sensitive (bool): Set to `False` to use a case insensitive regex (default `True`). Returns: str: A regex equivalent to the...
def _translate(pattern, case_sensitive=True): # type: (Text, bool) -> Text if not case_sensitive: pattern = pattern.lower() i, n = 0, len(pattern) res = "" while i < n: c = pattern[i] i = i + 1 if c == "*": res = res + "[^/]*" elif c == "?": ...
238,175
Get the delegate FS for a given path. Arguments: path (str): A path. Returns: (FS, str): a tuple of ``(<fs>, <path>)`` for a mounted filesystem, or ``(None, None)`` if no filesystem is mounted on the given ``path``.
def _delegate(self, path): # type: (Text) -> Tuple[FS, Text] _path = forcedir(abspath(normpath(path))) is_mounted = _path.startswith for mount_path, fs in self.mounts: if is_mounted(mount_path): return fs, _path[len(mount_path) :].rstrip("/") ...
238,177
Mounts a host FS object on a given path. Arguments: path (str): A path within the MountFS. fs (FS or str): A filesystem (instance or URL) to mount.
def mount(self, path, fs): # type: (Text, Union[FS, Text]) -> None if isinstance(fs, text_type): from .opener import open_fs fs = open_fs(fs) if not isinstance(fs, FS): raise TypeError("fs argument must be an FS object or a FS URL") if fs i...
238,178
Get a tuple of (name, fs) that the given path would map to. Arguments: path (str): A path on the filesystem. mode (str): An `io.open` mode.
def which(self, path, mode="r"): # type: (Text, Text) -> Tuple[Optional[Text], Optional[FS]] if check_writable(mode): return self._write_fs_name, self.write_fs for name, fs in self.iterate_fs(): if fs.exists(path): return name, fs return N...
238,218
Check ``mode`` parameter of `~fs.base.FS.openbin` is valid. Arguments: mode (str): Mode parameter. Raises: `ValueError` if mode is not valid.
def validate_openbin_mode(mode, _valid_chars=frozenset("rwxab+")): # type: (Text, Union[Set[Text], FrozenSet[Text]]) -> None if "t" in mode: raise ValueError("text mode not valid in openbin") if not mode: raise ValueError("mode must not be empty") if mode[0] not in "rwxa": r...
238,268
Parse a Filesystem URL and return a `ParseResult`. Arguments: fs_url (str): A filesystem URL. Returns: ~fs.opener.parse.ParseResult: a parse result instance. Raises: ~fs.errors.ParseError: if the FS URL is not valid.
def parse_fs_url(fs_url): # type: (Text) -> ParseResult match = _RE_FS_URL.match(fs_url) if match is None: raise ParseError("{!r} is not a fs2 url".format(fs_url)) fs_name, credentials, url1, url2, path = match.groups() if not credentials: username = None # type: Optional[Text...
238,284
Check if a filename should be included. Override to exclude files from the walk. Arguments: fs (FS): A filesystem instance. info (Info): A resource info object. Returns: bool: `True` if the file should be included.
def check_file(self, fs, info): # type: (FS, Info) -> bool if self.exclude is not None and fs.match(self.exclude, info.name): return False return fs.match(self.filter, info.name)
238,298
Get an iterator of `Info` objects for a directory path. Arguments: fs (FS): A filesystem instance. dir_path (str): A path to a directory on the filesystem. namespaces (list): A list of additional namespaces to include in the `Info` objects. Returns: ...
def _scan( self, fs, # type: FS dir_path, # type: Text namespaces=None, # type: Optional[Collection[Text]] ): # type: (...) -> Iterator[Info] try: for info in fs.scandir(dir_path, namespaces=namespaces): yield info excep...
238,299
Walk a filesystem, yielding absolute paths to files. Arguments: fs (FS): A filesystem instance. path (str): A path to a directory on the filesystem. Yields: str: absolute path to files on the filesystem found recursively within the given directory.
def files(self, fs, path="/"): # type: (FS, Text) -> Iterator[Text] _combine = combine for _path, info in self._iter_walk(fs, path=path): if info is not None and not info.is_dir: yield _combine(_path, info.name)
238,301
Walk a filesystem, yielding tuples of ``(<path>, <info>)``. Arguments: fs (FS): A filesystem instance. path (str): A path to a directory on the filesystem. namespaces (list, optional): A list of additional namespaces to add to the `Info` objects. Yie...
def info( self, fs, # type: FS path="/", # type: Text namespaces=None, # type: Optional[Collection[Text]] ): # type: (...) -> Iterator[Tuple[Text, Info]] _combine = combine _walk = self._iter_walk(fs, path=path, namespaces=namespaces) for _...
238,302
Remove all empty parents. Arguments: fs (FS): A filesystem instance. path (str): Path to a directory on the filesystem.
def remove_empty(fs, path): # type: (FS, Text) -> None path = abspath(normpath(path)) try: while path not in ("", "/"): fs.removedir(path) path = dirname(path) except DirectoryNotEmpty: pass
238,311
Copy data from one file object to another. Arguments: src_file (io.IOBase): File open for reading. dst_file (io.IOBase): File open for writing. chunk_size (int): Number of bytes to copy at a time (or `None` to use sensible default).
def copy_file_data(src_file, dst_file, chunk_size=None): # type: (IO, IO, Optional[int]) -> None _chunk_size = 1024 * 1024 if chunk_size is None else chunk_size read = src_file.read write = dst_file.write # The 'or None' is so that it works with binary and text files for chunk in iter(lambd...
238,312
Get a list of non-existing intermediate directories. Arguments: fs (FS): A filesystem instance. dir_path (str): A path to a new directory on the filesystem. Returns: list: A list of non-existing paths. Raises: ~fs.errors.DirectoryExpected: If a path component r...
def get_intermediate_dirs(fs, dir_path): # type: (FS, Text) -> List[Text] intermediates = [] with fs.lock(): for path in recursepath(abspath(dir_path), reverse=True): try: resource = fs.getinfo(path) except ResourceNotFound: intermediates....
238,313
Return class described by given topic. Args: topic: A string describing a class. Returns: A class. Raises: TopicResolutionError: If there is no such class.
def resolve_topic(topic): try: module_name, _, class_name = topic.partition('#') module = importlib.import_module(module_name) except ImportError as e: raise TopicResolutionError("{}: {}".format(topic, e)) try: cls = resolve_attr(module, class_name) except AttributeE...
239,624
A recursive version of getattr for navigating dotted paths. Args: obj: An object for which we want to retrieve a nested attribute. path: A dot separated string containing zero or more attribute names. Returns: The attribute referred to by obj.a1.a2.a3... Raises: AttributeE...
def resolve_attr(obj, path): if not path: return obj head, _, tail = path.partition('.') head_obj = getattr(obj, head) return resolve_attr(head_obj, tail)
239,625
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"): return self.client.api.send_message_event( self.room_id, "m.room.message", self.get_html_content(html, body, msgtype))
239,735
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): return self.client.api.send_content( self.room_id, url, name, "m.file", extra_information=fileinfo )
239,741
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): return self.client.api.send_content( self.room_id, url, name, "m.image", extra_information=imageinfo )
239,743
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): return self.client.api.send_location(self.room_id, geo_uri, name, thumb_url, thumb_info)
239,744
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): return self.client.api.send_content(self.room_id, url, name, "m.video", extra_information=videoinfo)
239,745
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): return self.client.api.send_content(self.room_id, url, name, "m.audio", extra_information=audioinfo)
239,746
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): listener_id = uuid4() self.listeners.append( { 'uid': listener_id, 'callback': callback, 'event_type': event_type } ) return listener_id
239,748
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): listener_id = uuid4() self.ephemeral_listeners.append( { 'uid': listener_id, 'callback': callback, 'event_type': event_type } ) return listener_id
239,750
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=""): try: self.client.api.kick_user(self.room_id, user_id) return True except MatrixRequestError: return False
239,755
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=""): return self.client.api.send_state_event( self.room_id, event_type, content, state_key )
239,759
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): res = self.client.api.get_room_messages(self.room_id, self.prev_batch, direction="b", limit=limit) events = res["chunk"] if not reverse: events = reversed(events) ...
239,766
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): try: content = self.client.api.get_power_levels(self.room_id) if users_default: content["users_default"] = users_default if users: if "users" in content: ...
239,767
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): join_rule = "invite" if invite_only else "public" try: self.client.api.set_join_rule(self.room_id, join_rule) self.invite_only = invite_only return True except MatrixRequestError: return False
239,769
.. warning:: Deprecated. Use sync instead. Perform /initialSync. Args: limit (int): The limit= param to provide.
def initial_sync(self, limit=1): warnings.warn("initial_sync is deprecated. Use sync instead.", DeprecationWarning) return self._send("GET", "/initialSync", query_params={"limit": limit})
239,783
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): request = { # non-integer timeouts appear to cause issues "timeout": int(timeout_ms) } if since: request["since"] = since if filter:...
239,784
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): content = { "type": login_type } for key in kwargs: if kwargs[key]: content[key] = kwargs[key] return self._send("POST", "/login", content)
239,786
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 ): content = { "visibility": "public" if is_public else "private" } if alia...
239,787
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): if not room_id_or_alias: raise MatrixError("No alias or room ID to join.") path = "/join/%s" % quote(room_id_or_alias) return self._send("POST", path)
239,788
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): warnings.warn("event_stream is deprecated. Use sync instead.", DeprecationWarning) path = "/events" return self._send( "GET", path, query_params={ "timeout": timeout, "fr...
239,789
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): path = "/rooms/%s/state/%s" % ( quote(room_id), quote(event_type), ) if state_key: path += "/%s" % (quote(state_key)) params = {} if t...
239,790
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): return self._send("GET", "/rooms/{}/state/{}".format(quote(room_id), event_type))
239,791
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): if not txn_id: txn_id = self._make_txn_id() path = "/rooms/%s/send/%s/%s" % ( quote(room_id), quote(event_type), quote(str(txn_id)), ) par...
239,792
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): if not txn_id: txn_id = self._make_txn_id() path = '/rooms/%s/redact/%s/%s' % ( room_id, event_id, txn_id ) content = {} if reason: content['reason']...
239,793
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): content_pack = { "geo_uri": geo_uri, "msgtype": "m.location", "body": name, } if thumb_url: content_pack["thumbnail_url...
239,795
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): return self.send_message_event( room_id, "m.room.message", self.get_text_body(text_content, msgtype), timestamp=timestamp )
239,796
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): return self.send_message_event( room_id, "m.room.message", self.get_emote_body(text_content), timestamp=timestamp )
239,797
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): body = { "msgtype": "m.notice", "body": text_content } return self.send_message_event(room_id, "m.room.message", body, timestamp=timestamp)
239,798
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): query = { "roomId": room_id, "from": token, "dir": direction, "limit": limit, } if to: query["to"] = to return self._send("GET", "/rooms/{}/me...
239,799
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): body = { "name": name } return self.send_state_event(room_id, "m.room.name", body, timestamp=timestamp)
239,800
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): body = { "topic": topic } return self.send_state_event(room_id, "m.room.topic", body, timestamp=timestamp)
239,801
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): body = { "user_id": user_id } return self._send("POST", "/rooms/" + room_id + "/invite", body)
239,803
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): if profile is None: profile = {} body = { "membership": membership, "reason": reason } if 'displayname' in profile: ...
239,805
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=""): body = { "user_id": user_id, "reason": reason } return self._send("POST", "/rooms/" + room_id + "/ban", body)
239,806
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): body = { "user_id": user_id } return self._send("POST", "/rooms/" + room_id + "/unban", body)
239,807
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): query_params = {} if not allow_remote: query_params["allow_remote"] = False if mxcurl.startswith('mxc://'): return self._send( "GET", mxcurl[6:], api_path="/_matrix/media/r0/down...
239,818
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): params = {'url': url} if ts: params['ts'] = ts return self._send( "GET", "", query_params=params, api_path="/_matrix/media/r0/preview_url" )
239,820
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): content = self._send("GET", "/directory/room/{}".format(quote(room_alias))) return content.get("room_id", None)
239,821
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): data = { "room_id": room_id } return self._send("PUT", "/directory/room/{}".format(quote(room_alias)), content=data)
239,822
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): content = { "join_rule": join_rule } return self.send_state_event(room_id, "m.room.join_rules", content)
239,823
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): content = { "guest_access": guest_access } return self.send_state_event(room_id, "m.room.guest_access", content)
239,824
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): content = { "display_name": display_name } return self._send("PUT", "/devices/%s" % device_id, content=content)
239,825
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): content = { "auth": auth_body } return self._send("DELETE", "/devices/%s" % device_id, content=content)
239,826
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): content = { "auth": auth_body, "devices": devices } return self._send("POST", "/delete_devices", content=content)
239,827
Claims one-time keys for use in pre-key messages. Args: key_request (dict): The keys to be claimed. Format should be <user_id>: { <device_id>: <algorithm> }. timeout (int): Optional. The time (in milliseconds) to wait when downloading keys from remote ser...
def claim_keys(self, key_request, timeout=None): content = {"one_time_keys": key_request} if timeout: content["timeout"] = timeout return self._send("POST", "/keys/claim", content=content)
239,830
Gets a list of users who have updated their device identity keys. Args: from_token (str): The desired start point of the list. Should be the next_batch field from a response to an earlier call to /sync. to_token (str): The desired end point of the list. Should be the nex...
def key_changes(self, from_token, to_token): params = {"from": from_token, "to": to_token} return self._send("GET", "/keys/changes", query_params=params)
239,831
Sends send-to-device events to a set of client devices. Args: event_type (str): The type of event to send. messages (dict): The messages to send. Format should be <user_id>: {<device_id>: <event_content>}. The device ID may also be '*', meaning all known ...
def send_to_device(self, event_type, messages, txn_id=None): txn_id = txn_id if txn_id else self._make_txn_id() return self._send( "PUT", "/sendToDevice/{}/{}".format(event_type, txn_id), content={"messages": messages} )
239,832
Register for a new account on this HS. Args: username (str): Account username password (str): Account password Returns: str: Access Token Raises: MatrixRequestError
def register_with_password(self, username, password): response = self.api.register( auth_body={"type": "m.login.dummy"}, kind='user', username=username, password=password, ) return self._post_registration(response)
239,836
Deprecated. Use ``login`` with ``sync=False``. Login to the homeserver. Args: username (str): Account username password (str): Account password Returns: str: Access token Raises: MatrixRequestError
def login_with_password_no_sync(self, username, password): warn("login_with_password_no_sync is deprecated. Use login with sync=False.", DeprecationWarning) return self.login(username, password, sync=False)
239,838
Deprecated. Use ``login`` with ``sync=True``. Login to the homeserver. Args: username (str): Account username password (str): Account password limit (int): Deprecated. How many messages to return when syncing. This will be replaced by a filter API in...
def login_with_password(self, username, password, limit=10): warn("login_with_password is deprecated. Use login with sync=True.", DeprecationWarning) return self.login(username, password, limit, sync=True)
239,839
Create a new room on the homeserver. Args: alias (str): The canonical_alias of the room. is_public (bool): The public/private visibility of the room. invitees (str[]): A set of user ids to invite into the room. Returns: Room Raises: ...
def create_room(self, alias=None, is_public=False, invitees=None): response = self.api.create_room(alias=alias, is_public=is_public, invitees=invitees) return self._mkroom(response["room_id"])
239,841
Join a room. Args: room_id_or_alias (str): Room ID or an alias. Returns: Room Raises: MatrixRequestError
def join_room(self, room_id_or_alias): response = self.api.join_room(room_id_or_alias) room_id = ( response["room_id"] if "room_id" in response else room_id_or_alias ) return self._mkroom(room_id)
239,842
Add a listener that will send a callback when the client recieves an event. Args: callback (func(roomchunk)): 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...
def add_listener(self, callback, event_type=None): listener_uid = uuid4() # TODO: listeners should be stored in dict and accessed/deleted directly. Add # convenience method such that MatrixClient.listeners.new(Listener(...)) performs # MatrixClient.listeners[uuid4()] = Listener(...
239,843
Add a presence listener that will send a callback when the client receives a presence update. Args: callback (func(roomchunk)): Callback called when a presence update arrives. Returns: uuid.UUID: Unique id of the listener, can be used to identify the listener.
def add_presence_listener(self, callback): listener_uid = uuid4() self.presence_listeners[listener_uid] = callback return listener_uid
239,844