INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Deletes created pool ledger configuration.
async def delete_pool_ledger_config(config_name: str) -> None: """ Deletes created pool ledger configuration. :param config_name: Name of the pool ledger configuration to delete. :return: Error code """ logger = logging.getLogger(__name__) logger.debug("delete_pool_ledger_config: >>> confi...
Set PROTOCOL_VERSION to specific version.
async def set_protocol_version(protocol_version: int) -> None: """ Set PROTOCOL_VERSION to specific version. There is a global property PROTOCOL_VERSION that used in every request to the pool and specified version of Indy Node which Libindy works. By default PROTOCOL_VERSION=1. :param protocol...
Opens a search handle within the storage wallet.
async def open_search(type_: str, query: dict, options: dict): """ Opens a search handle within the storage wallet. :param type_: String :param query: dictionary :param options: dictionary Example: query_json = {"tagName1": "str1"} type_ = 'TestType' ...
Searches for next n record from an open search handle
async def search_next_records(handle: int, count: int): """ Searches for next n record from an open search handle :param handle: int :param count: int Example: query_json = {"tagName1": "str1"} type_ = 'TestType' search_handle = await Wallet.open_search(...
Retrieves a record from the wallet storage.: param type_: String: param id: String: param options: String Example: import json await Wallet. add_record ( { id: RecordId tags: json. dumps ( { tag1: unencrypted value1 ~encryptedTag this value is encrypted integerTag 1 } ) type_: TestType value: RecordValue } ) options = ...
async def get_record(type_: str, id: str, options: str): """ Retrieves a record from the wallet storage. :param type_: String :param id: String :param options: String Example: import json await Wallet.add_record({ 'id': 'RecordId', ...
Delete a record from the storage wallet.
async def delete_record(type_: str, id: str): """ Delete a record from the storage wallet. :param type_: :param id: Example: await Wallet.add_record({ 'id': 'RecordId', 'tags': json.dumps({ 'tag1': 'unencrypted value1', ...
Retrieves from the ledger token info associated with the wallet.: param handle: Example: payment_handle = 0// payment handle is always 0 for now. info = await Wallet. get_token_info ( payment_handle ): return:
async def get_token_info(handle: int) -> str: """ Retrieves from the ledger token info associated with the wallet. :param handle: Example: payment_handle = 0 // payment handle is always 0, for now. info = await Wallet.get_token_info(payment_handle) :return: ...
Creates a payment address inside the wallet.: param seed: String Example: address = await Wallet. create_payment_address ( 00000000000000000000000001234567 ): return: String
async def create_payment_address(seed: str = None) -> str: """ Creates a payment address inside the wallet. :param seed: String Example: address = await Wallet.create_payment_address('00000000000000000000000001234567') :return: String """ logger = logging....
Determines whether a payment address is valid or not: param address: String Example: address = await Wallet. create_payment_address ( 00000000000000000000000001234567 ) b = await Wallet. validate_payment_address ( address ): return: Boolean
async def validate_payment_address(address: str) -> None: """ Determines whether a payment address is valid or not :param address: String Example: address = await Wallet.create_payment_address('00000000000000000000000001234567') b = await Wallet.validate_payment_address(a...
Sends tokens to an address payment_handle is always 0: param payment_handle: Integer: param tokens: Integer: param address: String Example: payment_handle = 0 amount = 1000 address = await Wallet. create_payment_address ( 00000000000000000000000001234567 ) await Wallet. send_tokens ( payment_handle amount address ): re...
async def send_tokens(payment_handle: int, tokens: int, address: str) -> str: """ Sends tokens to an address payment_handle is always 0 :param payment_handle: Integer :param tokens: Integer :param address: String Example: payment_handle = 0 amount ...
Exports opened wallet: param path: Path to export wallet to User s File System.: param backupKey: String representing the User s Key for securing ( encrypting ) the exported Wallet.: return: Error code - success indicates that the wallet was successfully exported.
async def export(path, backup_key): """ Exports opened wallet :param path: Path to export wallet to User's File System. :param backupKey: String representing the User's Key for securing (encrypting) the exported Wallet. :return: Error code - success indicates that the wal...
Imports wallet from file with given key. Cannot be used if wallet is already opened ( Especially if vcx_init has already been used ).: param config: Can be same config that is passed to vcx_init. Must include: { wallet_name: wallet_key: exported_wallet_path: backup_key: }: return: Error code - success indicates that th...
async def import_wallet(config): """ Imports wallet from file with given key. Cannot be used if wallet is already opened (Especially if vcx_init has already been used). :param config: Can be same config that is passed to vcx_init. Must include: '{"wallet_name":"","wallet_key":"",...
Update a non - secret wallet record value
async def update_wallet_record_value(wallet_handle: int, type_: str, id_: str, value: str) -> None: """ Update a non-secret wallet record value :param wallet_handle: wallet handler (created by ope...
Get an wallet record by id
async def get_wallet_record(wallet_handle: int, type_: str, id: str, options_json: str) -> str: """ Get an wallet record by id :param wallet_handle: wallet handler (created by open_wallet). :param type_: allows to separ...
Search for wallet records
async def open_wallet_search(wallet_handle: int, type_: str, query_json: str, options_json: str) -> int: """ Search for wallet records :param wallet_handle: wallet handler (created by open_wallet). :param type_: allo...
Fetch next records for wallet search.
async def fetch_wallet_search_next_records(wallet_handle: int, wallet_search_handle: int, count: int) -> str: """ Fetch next records for wallet search. :param wallet_handle: wallet handler (created by open_wallet). :p...
Close wallet search ( make search handle invalid )
async def close_wallet_search(wallet_search_handle: int) -> None: """ Close wallet search (make search handle invalid) :param wallet_search_handle: wallet wallet handle (created by open_wallet_search) :return: None """ logger = logging.getLogger(__name__) logger.debug("close_wallet_search:...
Returns a decorator registering a mark class in the mark type registry.
def register_mark(key=None): """Returns a decorator registering a mark class in the mark type registry. If no key is provided, the class name is used as a key. A key is provided for each core bqplot mark so that the frontend can use this key regardless of the kernel language. """ def wrap(mark)...
Return the list of scales corresponding to a given dimension.
def _get_dimension_scales(self, dimension, preserve_domain=False): """ Return the list of scales corresponding to a given dimension. The preserve_domain optional argument specifies whether one should filter out the scales for which preserve_domain is set to True. """ if ...
Validates the scales based on the mark s scaled attributes metadata.
def _validate_scales(self, proposal): """ Validates the `scales` based on the mark's scaled attributes metadata. First checks for missing scale and then for 'rtype' compatibility. """ # Validate scales' 'rtype' versus data attribute 'rtype' decoration # At this stage it ...
Returns a decorator registering an axis class in the axis type registry.
def register_axis(key=None): """Returns a decorator registering an axis class in the axis type registry. If no key is provided, the class name is used as a key. A key is provided for each core bqplot axis so that the frontend can use this key regardless of the kernel language. """ def wrap(axis...
Decorator registering an interaction class in the registry.
def register_interaction(key=None): """Decorator registering an interaction class in the registry. If no key is provided, the class name is used as a key. A key is provided for each core bqplot interaction type so that the frontend can use this key regardless of the kernal language. """ def wra...
Helper function for panning and zooming over a set of marks.
def panzoom(marks): """Helper function for panning and zooming over a set of marks. Creates and returns a panzoom interaction with the 'x' and 'y' dimension scales of the specified marks. """ return PanZoom(scales={ 'x': sum([mark._get_dimension_scales('x', preserve_domain=True) for mar...
Returns a decorator to register a scale type in the scale type registry.
def register_scale(key=None): """Returns a decorator to register a scale type in the scale type registry. If no key is provided, the class name is used as a key. A key is provided for each core bqplot scale type so that the frontend can use this key regardless of the kernal language. """ de...
Install the bqplot nbextension. Parameters ----------
def install(user=False, symlink=False, overwrite=False, **kwargs): """Install the bqplot nbextension. Parameters ---------- user: bool Install for current user instead of system-wide. symlink: bool Symlink instead of copy (for development). overwrite: bool Overwrite...
Determine whether v can be hashed.
def hashable(data, v): """Determine whether `v` can be hashed.""" try: data[v] except (TypeError, KeyError, IndexError): return False return True
Shows the current context figure in the output area.
def show(key=None, display_toolbar=True): """Shows the current context figure in the output area. Parameters ---------- key : hashable, optional Any variable that can be used as a key for a dictionary. display_toolbar: bool (default: True) If True, a toolbar for different mouse int...
Creates figures and switches between figures.
def figure(key=None, fig=None, **kwargs): """Creates figures and switches between figures. If a ``bqplot.Figure`` object is provided via the fig optional argument, this figure becomes the current context figure. Otherwise: - If no key is provided, a new empty context figure is created. - If a...
Closes and unregister the context figure corresponding to the key.
def close(key): """Closes and unregister the context figure corresponding to the key. Parameters ---------- key: hashable Any variable that can be used as a key for a dictionary """ figure_registry = _context['figure_registry'] if key not in figure_registry: return if ...
Helper function to handle data keyword argument
def _process_data(*kwarg_names): """Helper function to handle data keyword argument """ def _data_decorator(func): @functools.wraps(func) def _mark_with_data(*args, **kwargs): data = kwargs.pop('data', None) if data is None: return func(*args, **kwargs...
Creates and switches between context scales.
def scales(key=None, scales={}): """Creates and switches between context scales. If no key is provided, a new blank context is created. If a key is provided for which a context already exists, the existing context is set as the current context. If a key is provided and no corresponding context ex...
Set the domain bounds of the scale associated with the provided key.
def set_lim(min, max, name): """Set the domain bounds of the scale associated with the provided key. Parameters ---------- name: hashable Any variable that can be used as a key for a dictionary Raises ------ KeyError When no context figure is associated with the provided ke...
Draws axes corresponding to the scales of a given mark.
def axes(mark=None, options={}, **kwargs): """Draws axes corresponding to the scales of a given mark. It also returns a dictionary of drawn axes. If the mark is not provided, the last drawn mark is used. Parameters ---------- mark: Mark or None (default: None) The mark to inspect to cr...
Helper function to set labels for an axis
def _set_label(label, mark, dim, **kwargs): """Helper function to set labels for an axis """ if mark is None: mark = _context['last_mark'] if mark is None: return {} fig = kwargs.get('figure', current_figure()) scales = mark.scales scale_metadata = mark.scales_metadata.get(di...
Sets the value of the grid_lines for the axis to the passed value. The default value is solid.
def grids(fig=None, value='solid'): """Sets the value of the grid_lines for the axis to the passed value. The default value is `solid`. Parameters ---------- fig: Figure or None(default: None) The figure for which the axes should be edited. If the value is None, the current figure i...
Sets the title for the current figure.
def title(label, style=None): """Sets the title for the current figure. Parameters ---------- label : str The new title for the current figure. style: dict The CSS style to be applied to the figure title """ fig = current_figure() fig.title = label if style is not No...
Draws a horizontal line at the given level.
def hline(level, **kwargs): """Draws a horizontal line at the given level. Parameters ---------- level: float The level at which to draw the horizontal line. preserve_domain: boolean (default: False) If true, the line does not affect the domain of the 'y' scale. """ kwargs.s...
Returns a kwarg dict suitable for a ColorScale
def _process_cmap(cmap): ''' Returns a kwarg dict suitable for a ColorScale ''' option = {} if isinstance(cmap, str): option['scheme'] = cmap elif isinstance(cmap, list): option['colors'] = cmap else: raise ValueError('''`cmap` must be a string (name of a color scheme...
Set the color map of the current color scale.
def set_cmap(cmap): ''' Set the color map of the current 'color' scale. ''' scale = _context['scales']['color'] for k, v in _process_cmap(cmap).items(): setattr(scale, k, v) return scale
Draw the mark of specified mark type.
def _draw_mark(mark_type, options={}, axes_options={}, **kwargs): """Draw the mark of specified mark type. Parameters ---------- mark_type: type The type of mark to be drawn options: dict (default: {}) Options for the scales to be created. If a scale labeled 'x' is required ...
Infers the x for a line if no x is provided.
def _infer_x_for_line(y): """ Infers the x for a line if no x is provided. """ array_shape = shape(y) if len(array_shape) == 0: return [] if len(array_shape) == 1: return arange(array_shape[0]) if len(array_shape) > 1: return arange(array_shape[1])
Draw lines in the current context figure.
def plot(*args, **kwargs): """Draw lines in the current context figure. Signature: `plot(x, y, **kwargs)` or `plot(y, **kwargs)`, depending of the length of the list of positional arguments. In the case where the `x` array is not provided. Parameters ---------- x: numpy.ndarray or list, 1d...
Draw an image in the current context figure. Parameters ---------- image: image data Image data depending on the passed format can be one of: - an instance of an ipywidgets Image - a file name - a raw byte string format: { widget filename... } Type of the input argument. If not widget or filename must be a format suppo...
def imshow(image, format, **kwargs): """Draw an image in the current context figure. Parameters ---------- image: image data Image data, depending on the passed format, can be one of: - an instance of an ipywidgets Image - a file name - a raw byte string f...
Draw OHLC bars or candle bars in the current context figure.
def ohlc(*args, **kwargs): """Draw OHLC bars or candle bars in the current context figure. Signature: `ohlc(x, y, **kwargs)` or `ohlc(y, **kwargs)`, depending of the length of the list of positional arguments. In the case where the `x` array is not provided Parameters ---------- x: numpy.n...
Draw a scatter in the current context figure.
def scatter(x, y, **kwargs): """Draw a scatter in the current context figure. Parameters ---------- x: numpy.ndarray, 1d The x-coordinates of the data points. y: numpy.ndarray, 1d The y-coordinates of the data points. options: dict (default: {}) Options for the scales t...
Draw a histogram in the current context figure.
def hist(sample, options={}, **kwargs): """Draw a histogram in the current context figure. Parameters ---------- sample: numpy.ndarray, 1d The sample for which the histogram must be generated. options: dict (default: {}) Options for the scales to be created. If a scale labeled 'coun...
Draw a histogram in the current context figure. Parameters ---------- sample: numpy. ndarray 1d The sample for which the histogram must be generated. options: dict ( default: {} ) Options for the scales to be created. If a scale labeled x is required for that mark options [ x ] contains optional keyword arguments for t...
def bin(sample, options={}, **kwargs): """Draw a histogram in the current context figure. Parameters ---------- sample: numpy.ndarray, 1d The sample for which the histogram must be generated. options: dict (default: {}) Options for the scales to be created. If a scale labeled 'x' ...
Draws a bar chart in the current context figure.
def bar(x, y, **kwargs): """Draws a bar chart in the current context figure. Parameters ---------- x: numpy.ndarray, 1d The x-coordinates of the data points. y: numpy.ndarray, 1d The y-coordinates of the data pints. options: dict (default: {}) Options for the scales to ...
Draws a boxplot in the current context figure.
def boxplot(x, y, **kwargs): """Draws a boxplot in the current context figure. Parameters ---------- x: numpy.ndarray, 1d The x-coordinates of the data points. y: numpy.ndarray, 2d The data from which the boxes are to be created. Each row of the data corresponds to one box ...
Draw a map in the current context figure.
def geo(map_data, **kwargs): """Draw a map in the current context figure. Parameters ---------- map_data: string or bqplot.map (default: WorldMap) Name of the map or json file required for the map data. options: dict (default: {}) Options for the scales to be created. If a scale lab...
Add the interaction for the specified type.
def _add_interaction(int_type, **kwargs): """Add the interaction for the specified type. If a figure is passed using the key-word argument `figure` it is used. Else the context figure is used. If a list of marks are passed using the key-word argument `marks` it is used. Else the latest mark that is...
Create a selector of the specified type.
def _create_selector(int_type, func, trait, **kwargs): """Create a selector of the specified type. Also attaches the function `func` as an `on_trait_change` listener for the trait `trait` of the selector. This is an internal function which should not be called by the user. Parameters --------...
Clears the current context figure of all marks axes and grid lines.
def clear(): """Clears the current context figure of all marks axes and grid lines.""" fig = _context['figure'] if fig is not None: fig.marks = [] fig.axes = [] setattr(fig, 'axis_registry', {}) _context['scales'] = {} key = _context['current_key'] if key is n...
Sets the current global context dictionary. All the attributes to be set should be set. Otherwise it will result in unpredictable behavior.
def set_context(context): """Sets the current global context dictionary. All the attributes to be set should be set. Otherwise, it will result in unpredictable behavior.""" global _context _context = {k: v for k, v in context.items()}
Returns the dimension for the name of the trait for the specified mark.
def _get_attribute_dimension(trait_name, mark_type=None): """Returns the dimension for the name of the trait for the specified mark. If `mark_type` is `None`, then the `trait_name` is returned as is. Returns `None` if the `trait_name` is not valid for `mark_type`. """ if(mark_type is None): ...
Applies the specified properties to the widget.
def _apply_properties(widget, properties={}): """Applies the specified properties to the widget. `properties` is a dictionary with key value pairs corresponding to the properties to be applied to the widget. """ with widget.hold_sync(): for key, value in properties.items(): seta...
Return line style color and marker type from specified marker string.
def _get_line_styles(marker_str): """Return line style, color and marker type from specified marker string. For example, if ``marker_str`` is 'g-o' then the method returns ``('solid', 'green', 'circle')``. """ def _extract_marker_value(marker_str, code_dict): """Extracts the marker value fr...
Create a self iterator and collect it into a TotalList ( a normal list with a. total attribute ).
async def collect(self): """ Create a `self` iterator and collect it into a `TotalList` (a normal list with a `.total` attribute). """ result = helpers.TotalList() async for message in self: result.append(message) result.total = self.total ret...
#full: Advises to read Accessing the full API in the docs.
async def handler(event): """#full: Advises to read "Accessing the full API" in the docs.""" await asyncio.wait([ event.delete(), event.respond(READ_FULL, reply_to=event.reply_to_msg_id) ])
#search query: Searches for query in the method reference.
async def handler(event): """#search query: Searches for "query" in the method reference.""" query = urllib.parse.quote(event.pattern_match.group(1)) await asyncio.wait([ event.delete(), event.respond(SEARCH.format(query), reply_to=event.reply_to_msg_id) ])
#docs or #ref query: Like #search but shows the query.
async def handler(event): """#docs or #ref query: Like #search but shows the query.""" q1 = event.pattern_match.group(1) q2 = urllib.parse.quote(q1) await asyncio.wait([ event.delete(), event.respond(DOCS.format(q1, q2), reply_to=event.reply_to_msg_id) ])
#rtd: Tells the user to please read the docs.
async def handler(event): """#rtd: Tells the user to please read the docs.""" rtd = RTFD if event.pattern_match.group(1) else RTD await asyncio.wait([ event.delete(), event.respond(rtd, reply_to=event.reply_to_msg_id) ])
#client or #msg query: Looks for the given attribute in RTD.
async def handler(event): """#client or #msg query: Looks for the given attribute in RTD.""" await event.delete() await event.respond( get_docs_message(kind=event.pattern_match.group(1), query=event.pattern_match.group(2)), reply_to=event.reply_to_msg_id )
#ot #offtopic: Tells the user to move to
async def handler(event): """#ot, #offtopic: Tells the user to move to @TelethonOffTopic.""" await asyncio.wait([ event.delete(), event.respond(OFFTOPIC[event.chat_id], reply_to=event.reply_to_msg_id) ])
#learn or #python: Tells the user to learn some Python first.
async def handler(event): """#learn or #python: Tells the user to learn some Python first.""" await asyncio.wait([ event.delete(), event.respond( LEARN_PYTHON, reply_to=event.reply_to_msg_id, link_preview=False) ])
Builds a: tl ReplyInlineMarkup or: tl: ReplyKeyboardMarkup for the given buttons or does nothing if either no buttons are provided or the provided argument is already a reply markup.
def build_reply_markup(self, buttons, inline_only=False): """ Builds a :tl`ReplyInlineMarkup` or :tl:`ReplyKeyboardMarkup` for the given buttons, or does nothing if either no buttons are provided or the provided argument is already a reply markup. This will add any event handler...
Pretty formats the given object as a string which is returned. If indent is None a single line will be returned.
def pretty_format(obj, indent=None): """ Pretty formats the given object as a string which is returned. If indent is None, a single line will be returned. """ if indent is None: if isinstance(obj, TLObject): obj = obj.to_dict() if isinstan...
Write bytes by using Telegram guidelines
def serialize_bytes(data): """Write bytes by using Telegram guidelines""" if not isinstance(data, bytes): if isinstance(data, str): data = data.encode('utf-8') else: raise TypeError( 'bytes or str expected, not {}'.format(type(d...
Represent the current TLObject as JSON.
def to_json(self, fp=None, default=_json_default, **kwargs): """ Represent the current `TLObject` as JSON. If ``fp`` is given, the JSON will be dumped to said file pointer, otherwise a JSON string will be returned. Note that bytes and datetimes cannot be represented in ...
Helper method to replace entities [ i ] to mention user or do nothing if it can t be found.
async def _replace_with_mention(self, entities, i, user): """ Helper method to replace ``entities[i]`` to mention ``user``, or do nothing if it can't be found. """ try: entities[i] = types.InputMessageEntityMentionName( entities[i].offset, entities[i]....
Returns a ( parsed message entities ) tuple depending on parse_mode.
async def _parse_message_text(self, message, parse_mode): """ Returns a (parsed message, entities) tuple depending on ``parse_mode``. """ if parse_mode is (): parse_mode = self._parse_mode else: parse_mode = utils.sanitize_parse_mode(parse_mode) i...
Extracts the response message known a request and Update result. The request may also be the ID of the message to match.
def _get_response_message(self, request, result, input_chat): """ Extracts the response message known a request and Update result. The request may also be the ID of the message to match. If ``request is None`` this method returns ``{id: message}``. If ``request.random_id`` is a...
Returns sender but will make an API call to find the sender unless it s already cached.
async def get_sender(self): """ Returns `sender`, but will make an API call to find the sender unless it's already cached. """ # ``sender.min`` is present both in :tl:`User` and :tl:`Channel`. # It's a flag that will be set if only minimal information is # availab...
This: tl: InputPeer is the input version of the user/ channel who sent the message. Similarly to input_chat this doesn t have things like username or similar but still useful in some cases.
def input_sender(self): """ This :tl:`InputPeer` is the input version of the user/channel who sent the message. Similarly to `input_chat`, this doesn't have things like username or similar, but still useful in some cases. Note that this might not be available if the library can'...
Returns input_sender but will make an API call to find the input sender unless it s already cached.
async def get_input_sender(self): """ Returns `input_sender`, but will make an API call to find the input sender unless it's already cached. """ if self.input_sender is None and self._sender_id: await self._refetch_sender() return self._input_sender
Decorator method to * register * event handlers. This is the client - less add_event_handler <telethon. client. updates. UpdateMethods. add_event_handler > variant.
def register(event=None): """ Decorator method to *register* event handlers. This is the client-less `add_event_handler <telethon.client.updates.UpdateMethods.add_event_handler>` variant. Note that this method only registers callbacks as handlers, and does not attach them to any client. This is...
Inverse operation of register ( though not a decorator ). Client - less remove_event_handler <telethon. client. updates. UpdateMethods. remove_event_handler > variant. ** Note that this won t remove handlers from the client ** because it simply can t so you would generally use this before adding the handlers to the cli...
def unregister(callback, event=None): """ Inverse operation of `register` (though not a decorator). Client-less `remove_event_handler <telethon.client.updates.UpdateMethods.remove_event_handler>` variant. **Note that this won't remove handlers from the client**, because it simply can't, so you w...
Parses the given markdown message and returns its stripped representation plus a list of the MessageEntity s that were found.
def parse(message, delimiters=None, url_re=None): """ Parses the given markdown message and returns its stripped representation plus a list of the MessageEntity's that were found. :param message: the message with markdown-like syntax to be parsed. :param delimiters: the delimiters to be used, {deli...
Performs the reverse operation to. parse () effectively returning markdown - like syntax given a normal text and its MessageEntity s.
def unparse(text, entities, delimiters=None, url_fmt=None): """ Performs the reverse operation to .parse(), effectively returning markdown-like syntax given a normal text and its MessageEntity's. :param text: the text to be reconverted into markdown. :param entities: the MessageEntity's applied to ...
Calculates the new nonce hash based on the current attributes.
def calc_new_nonce_hash(self, new_nonce, number): """ Calculates the new nonce hash based on the current attributes. :param new_nonce: the new nonce to be hashed. :param number: number to prepend before the hash. :return: the hash for the given new nonce. """ new...
Return the variable length bytes corresponding to the given int
def get_byte_array(integer): """Return the variable length bytes corresponding to the given int""" # Operate in big endian (unlike most of Telegram API) since: # > "...pq is a representation of a natural number # (in binary *big endian* format)..." # > "...current value of dh_prime equals # ...
Given a RSA key computes its fingerprint like Telegram does.
def _compute_fingerprint(key): """ Given a RSA key, computes its fingerprint like Telegram does. :param key: the Crypto.RSA key. :return: its 8-bytes-long fingerprint. """ n = TLObject.serialize_bytes(get_byte_array(key.n)) e = TLObject.serialize_bytes(get_byte_array(key.e)) # Telegram ...
Adds a new public key to be used when encrypting new data is needed
def add_key(pub): """Adds a new public key to be used when encrypting new data is needed""" global _server_keys key = rsa.PublicKey.load_pkcs1(pub) _server_keys[_compute_fingerprint(key)] = key
Encrypts the given data known the fingerprint to be used in the way Telegram requires us to do so ( sha1 ( data ) + data + padding )
def encrypt(fingerprint, data): """ Encrypts the given data known the fingerprint to be used in the way Telegram requires us to do so (sha1(data) + data + padding) :param fingerprint: the fingerprint of the RSA key. :param data: the data to be encrypted. :return: the cipher text, or Non...
Sends a message in the context of this conversation. Shorthand for telethon. client. messages. MessageMethods. send_message with entity already set.
async def send_message(self, *args, **kwargs): """ Sends a message in the context of this conversation. Shorthand for `telethon.client.messages.MessageMethods.send_message` with ``entity`` already set. """ message = await self._client.send_message( self._input...
Marks as read the latest received message if message is None. Otherwise marks as read until the given message ( or message ID ).
def mark_read(self, message=None): """ Marks as read the latest received message if ``message is None``. Otherwise, marks as read until the given message (or message ID). This is equivalent to calling `client.send_read_acknowledge <telethon.client.messages.MessageMethods.send_re...
Returns a coroutine that will resolve once a response arrives.
async def get_response(self, message=None, *, timeout=None): """ Returns a coroutine that will resolve once a response arrives. Args: message (`Message <telethon.tl.custom.message.Message>` | `int`, optional): The message (or the message ID) for which a response ...
Returns a coroutine that will resolve once a reply ( that is a message being a reply ) arrives. The arguments are the same as those for get_response.
async def get_reply(self, message=None, *, timeout=None): """ Returns a coroutine that will resolve once a reply (that is, a message being a reply) arrives. The arguments are the same as those for `get_response`. """ return await self._get_message( message, se...
Gets the next desired message under the desired condition.
def _get_message( self, target_message, indices, pending, timeout, condition): """ Gets the next desired message under the desired condition. Args: target_message (`object`): The target message for which we want to find another response th...
Awaits for an edit after the last message to arrive. The arguments are the same as those for get_response.
async def get_edit(self, message=None, *, timeout=None): """ Awaits for an edit after the last message to arrive. The arguments are the same as those for `get_response`. """ start_time = time.time() target_id = self._get_message_id(message) target_date = self._ed...
Awaits for the sent message to be read. Note that receiving a response doesn t imply the message was read and this action will also trigger even without a response.
async def wait_read(self, message=None, *, timeout=None): """ Awaits for the sent message to be read. Note that receiving a response doesn't imply the message was read, and this action will also trigger even without a response. """ start_time = time.time() future ...
Waits for a custom event to occur. Timeouts still apply.
async def wait_event(self, event, *, timeout=None): """ Waits for a custom event to occur. Timeouts still apply. Unless you're certain that your code will run fast enough, generally you should get a "handle" of this special coroutine before acting. Generally, you should do this:...
Convenience method to interactively connect and sign in if required also taking into consideration that 2FA may be enabled in the account.
def start( self, phone=lambda: input('Please enter your phone (or bot token): '), password=lambda: getpass.getpass('Please enter your password: '), *, bot_token=None, force_sms=False, code_callback=None, first_name='New User', last_name='', max_att...
Helper method to both parse and validate phone and its hash.
def _parse_phone_and_hash(self, phone, phone_hash): """ Helper method to both parse and validate phone and its hash. """ phone = utils.parse_phone(phone) or self._phone if not phone: raise ValueError( 'Please make sure to call send_code_request first.'...
Starts or completes the sign in process with the given phone number or code that Telegram sent.
async def sign_in( self, phone=None, code=None, *, password=None, bot_token=None, phone_code_hash=None): """ Starts or completes the sign in process with the given phone number or code that Telegram sent. Args: phone (`str` | `int`): T...
Signs up to Telegram if you don t have an account yet. You must call. send_code_request ( phone ) first.
async def sign_up(self, code, first_name, last_name='', *, phone=None, phone_code_hash=None): """ Signs up to Telegram if you don't have an account yet. You must call .send_code_request(phone) first. **By using this method you're agreeing to Telegram's Term...
Callback called whenever the login or sign up process completes.
def _on_login(self, user): """ Callback called whenever the login or sign up process completes. Returns the input user parameter. """ self._bot = bool(user.bot) self._self_input_peer = utils.get_input_peer(user, allow_self=False) self._authorized = True ...
Sends a code request to the specified phone number.
async def send_code_request(self, phone, *, force_sms=False): """ Sends a code request to the specified phone number. Args: phone (`str` | `int`): The phone to which the code will be sent. force_sms (`bool`, optional): Whether to force se...
Logs out Telegram and deletes the current *. session file.
async def log_out(self): """ Logs out Telegram and deletes the current ``*.session`` file. Returns: ``True`` if the operation was successful. """ try: await self(functions.auth.LogOutRequest()) except errors.RPCError: return False ...
Changes the 2FA settings of the logged in user according to the passed parameters. Take note of the parameter explanations.
async def edit_2fa( self, current_password=None, new_password=None, *, hint='', email=None, email_code_callback=None): """ Changes the 2FA settings of the logged in user, according to the passed parameters. Take note of the parameter explanations. Note that this ...