text
stringlengths
81
112k
Similar to :meth:`get_input_peer`, but for geo points def get_input_geo(geo): """Similar to :meth:`get_input_peer`, but for geo points""" try: if geo.SUBCLASS_OF_ID == 0x430d225: # crc32(b'InputGeoPoint'): return geo except AttributeError: _raise_cast_fail(geo, 'InputGeoPoint')...
Similar to :meth:`get_input_peer`, but for media. If the media is :tl:`InputFile` and ``is_photo`` is known to be ``True``, it will be treated as an :tl:`InputMediaUploadedPhoto`. Else, the rest of parameters will indicate how to treat it. def get_input_media( media, *, is_photo=False, att...
Similar to :meth:`get_input_peer`, but for input messages. def get_input_message(message): """Similar to :meth:`get_input_peer`, but for input messages.""" try: if isinstance(message, int): # This case is really common too return types.InputMessageID(message) elif message.SUBCLASS_...
Similar to :meth:`get_input_peer`, but for message IDs. def get_message_id(message): """Similar to :meth:`get_input_peer`, but for message IDs.""" if message is None: return None if isinstance(message, int): return message try: if message.SUBCLASS_OF_ID == 0x790009e3: ...
Get a list of attributes for the given file and the mime type as a tuple ([attribute], mime_type). def get_attributes(file, *, attributes=None, mime_type=None, force_document=False, voice_note=False, video_note=False, supports_streaming=False): """ Get a list of attrib...
Converts the given parse mode into an object with ``parse`` and ``unparse`` callable properties. def sanitize_parse_mode(mode): """ Converts the given parse mode into an object with ``parse`` and ``unparse`` callable properties. """ if not mode: return None if callable(mode): ...
Similar to :meth:`get_input_peer`, but for input messages. Note that this returns a tuple ``(dc_id, location)``, the ``dc_id`` being present if known. def get_input_location(location): """ Similar to :meth:`get_input_peer`, but for input messages. Note that this returns a tuple ``(dc_id, location...
Gets the extension for the given file, which can be either a str or an ``open()``'ed file (which has a ``.name`` attribute). def _get_extension(file): """ Gets the extension for the given file, which can be either a str or an ``open()``'ed file (which has a ``.name`` attribute). """ if isinstan...
Returns ``True`` if the file extension looks like an image file to Telegram. def is_image(file): """ Returns ``True`` if the file extension looks like an image file to Telegram. """ match = re.match(r'\.(png|jpe?g)', _get_extension(file), re.IGNORECASE) if match: return True else: ...
Parses the given phone, or returns ``None`` if it's invalid. def parse_phone(phone): """Parses the given phone, or returns ``None`` if it's invalid.""" if isinstance(phone, int): return str(phone) else: phone = re.sub(r'[+()\s-]', '', str(phone)) if phone.isdigit(): retu...
Parses the given username or channel access hash, given a string, username or URL. Returns a tuple consisting of both the stripped, lowercase username and whether it is a joinchat/ hash (in which case is not lowercase'd). Returns ``(None, False)`` if the ``username`` or link is not valid. def parse_us...
Gets the inner text that's surrounded by the given entities. For instance: text = 'hey!', entity = MessageEntityBold(2, 2) -> 'y!'. :param text: the original text. :param entities: the entity or entities that must be matched. :return: a single result or a list of the text surrounded by the entities...
Finds the ID of the given peer, and converts it to the "bot api" format so it the peer can be identified back. User ID is left unmodified, chat ID is negated, and channel ID is prefixed with -100. The original ID and the peer type class can be returned with a call to :meth:`resolve_id(marked_id)`. def...
Given a marked ID, returns the original ID and its :tl:`Peer` type. def resolve_id(marked_id): """Given a marked ID, returns the original ID and its :tl:`Peer` type.""" if marked_id >= 0: return marked_id, types.PeerUser # There have been report of chat IDs being 10000xyz, which means their # ...
Decodes run-length-encoded `data`. def _rle_decode(data): """ Decodes run-length-encoded `data`. """ if not data: return data new = b'' last = b'' for cur in data: if last == b'\0': new += last * cur last = b'' else: new += last ...
Decodes an url-safe base64-encoded string into its bytes by first adding the stripped necessary padding characters. This is the way Telegram shares binary data as strings, such as Bot API-style file IDs or invite links. Returns ``None`` if the input string was not valid. def _decode_telegram_base64(s...
Inverse for `_decode_telegram_base64`. def _encode_telegram_base64(string): """ Inverse for `_decode_telegram_base64`. """ try: return base64.urlsafe_b64encode(string).rstrip(b'=').decode('ascii') except (binascii.Error, ValueError, TypeError): return None
Given a Bot API-style `file_id`, returns the media it represents. If the `file_id` is not valid, ``None`` is returned instead. Note that the `file_id` does not have information such as image dimensions or file size, so these will be zero if present. For thumbnails, the photo ID and hash will always be...
Inverse operation for `resolve_bot_file_id`. The only parameters this method will accept are :tl:`Document` and :tl:`Photo`, and it will return a variable-length ``file_id`` string. If an invalid parameter is given, it will ``return None``. def pack_bot_file_id(file): """ Inverse operation for `r...
Resolves the given invite link. Returns a tuple of ``(link creator user id, global chat id, random int)``. Note that for broadcast channels, the link creator user ID will be zero to protect their identity. Normal chats and megagroup channels will have such ID. Note that the chat ID may not be accu...
Resolves an inline message ID. Returns a tuple of ``(message id, peer, dc id, access hash)`` The ``peer`` may either be a :tl:`PeerUser` referencing the user who sent the message via the bot in a private conversation or small group chat, or a :tl:`PeerChannel` if the message was sent in a channel. ...
Adds the JPG header and footer to a stripped image. Ported from https://github.com/telegramdesktop/tdesktop/blob/bec39d89e19670eb436dc794a8f20b657cb87c71/Telegram/SourceFiles/ui/image/image.cpp#L225 def stripped_photo_to_jpg(stripped): """ Adds the JPG header and footer to a stripped image. Ported fr...
Sends and receives the result for the given request. async def send(self, request): """ Sends and receives the result for the given request. """ body = bytes(request) msg_id = self._state._get_new_msg_id() await self._connection.send( struct.pack('<qqi', 0, m...
Get the relative path for the given path from the current file by working around https://bugs.python.org/issue20012. def _rel(self, path): """ Get the relative path for the given path from the current file by working around https://bugs.python.org/issue20012. """ return ...
Writes the head part for the generated document, with the given title and CSS def write_head(self, title, css_path, default_css): """Writes the head part for the generated document, with the given title and CSS """ self.title = title self.write( '''<!DO...
Sets the menu separator. Must be called before adding entries to the menu def set_menu_separator(self, img): """Sets the menu separator. Must be called before adding entries to the menu """ if img: self.menu_separator_tag = '<img src="{}" alt="/" />'.format( ...
Adds a menu entry, will create it if it doesn't exist yet def add_menu(self, name, link=None): """Adds a menu entry, will create it if it doesn't exist yet""" if self.menu_began: if self.menu_separator_tag: self.write(self.menu_separator_tag) else: # Firs...
Writes a title header in the document body, with an optional depth level def write_title(self, title, level=1, id=None): """Writes a title header in the document body, with an optional depth level """ if id: self.write('<h{lv} id="{id}">{title}</h{lv}>', ...
Writes the code for the given 'tlobject' properly formatted with hyperlinks def write_code(self, tlobject): """Writes the code for the given 'tlobject' properly formatted with hyperlinks """ self.write('<pre>---{}---\n', 'functions' if tlobject.is_functi...
Begins a table with the given 'column_count', required to automatically create the right amount of columns when adding items to the rows def begin_table(self, column_count): """Begins a table with the given 'column_count', required to automatically create the right amount of columns when ...
This will create a new row, or add text to the next column of the previously created, incomplete row, closing it if complete def add_row(self, text, link=None, bold=False, align=None): """This will create a new row, or add text to the next column of the previously created, incomplete row,...
Writes a button with 'text' which can be used to copy 'text_to_copy' to clipboard when it's clicked. def write_copy_button(self, text, text_to_copy): """Writes a button with 'text' which can be used to copy 'text_to_copy' to clipboard when it's clicked.""" self.write_copy_script =...
Ends the whole document. This should be called the last def end_body(self): """Ends the whole document. This should be called the last""" if self.write_copy_script: self.write( '<textarea id="c" class="invisible"></textarea>' '<script>' 'funct...
Wrapper around handle.write def write(self, s, *args, **kwargs): """Wrapper around handle.write""" if args or kwargs: self.handle.write(s.format(*args, **kwargs)) else: self.handle.write(s)
Iterator over the participants belonging to the specified chat. Args: entity (`entity`): The entity from which to retrieve the participants list. limit (`int`): Limits amount of participants fetched. search (`str`, optional): ...
Iterator over the admin log for the specified channel. Note that you must be an administrator of it to use this method. If none of the filters are present (i.e. they all are ``None``), *all* event types will be returned. If at least one of them is ``True``, only those that are true wil...
Returns a context-manager object to represent a "chat action". Chat actions indicate things like "user is typing", "user is uploading a photo", etc. Normal usage is as follows: .. code-block:: python async with client.action(chat, 'typing'): await asyncio.sleep(2) ...
Prepares a new CDN decrypter. :param client: a TelegramClient connected to the main servers. :param cdn_client: a new client connected to the CDN. :param cdn_redirect: the redirect file object that caused this call. :return: (CdnDecrypter, first chunk file data) async def prepare_decry...
Calls GetCdnFileRequest and decrypts its bytes. Also ensures that the file hasn't been tampered. :return: the CdnFile result. def get_file(self): """ Calls GetCdnFileRequest and decrypts its bytes. Also ensures that the file hasn't been tampered. :return: the CdnFile r...
Parses the given HTML message and returns its stripped representation plus a list of the MessageEntity's that were found. :param message: the message with HTML to be parsed. :return: a tuple consisting of (clean message, [message entities]). def parse(html): """ Parses the given HTML message and r...
Performs the reverse operation to .parse(), effectively returning HTML given a normal text and its MessageEntity's. :param text: the text to be reconverted into HTML. :param entities: the MessageEntity's applied to the text. :return: a HTML representation of the combination of both inputs. def unparse...
The ``bytes`` data for :tl:`KeyboardButtonCallback` objects. def data(self): """The ``bytes`` data for :tl:`KeyboardButtonCallback` objects.""" if isinstance(self.button, types.KeyboardButtonCallback): return self.button.data
The query ``str`` for :tl:`KeyboardButtonSwitchInline` objects. def inline_query(self): """The query ``str`` for :tl:`KeyboardButtonSwitchInline` objects.""" if isinstance(self.button, types.KeyboardButtonSwitchInline): return self.button.query
The url ``str`` for :tl:`KeyboardButtonUrl` objects. def url(self): """The url ``str`` for :tl:`KeyboardButtonUrl` objects.""" if isinstance(self.button, types.KeyboardButtonUrl): return self.button.url
Emulates the behaviour of clicking this button. If it's a normal :tl:`KeyboardButton` with text, a message will be sent, and the sent `telethon.tl.custom.message.Message` returned. If it's an inline :tl:`KeyboardButtonCallback` with text and data, it will be "clicked" and the :tl:`BotC...
Helper util to turn the input chat or chats into a set of IDs. async def _into_id_set(client, chats): """Helper util to turn the input chat or chats into a set of IDs.""" if chats is None: return None if not utils.is_list_like(chats): chats = (chats,) result = set() for chat in ch...
Decorator to rename cls.Event 'Event' as 'cls.Event def name_inner_event(cls): """Decorator to rename cls.Event 'Event' as 'cls.Event'""" if hasattr(cls, 'Event'): cls.Event._event_name = '{}.Event'.format(cls.__name__) else: warnings.warn('Class {} does not have a inner Event'.format(cls))...
Helper method to allow event builders to be resolved before usage async def resolve(self, client): """Helper method to allow event builders to be resolved before usage""" if self.resolved: return if not self._resolve_lock: self._resolve_lock = asyncio.Lock(loop=client.l...
If the ID of ``event._chat_peer`` isn't in the chats set (or it is but the set is a blacklist) returns ``None``, otherwise the event. The events must have been resolved before this can be called. def filter(self, event): """ If the ID of ``event._chat_peer`` isn't in the chats set (or ...
Returns ``(entity, input_entity)`` for the given entity ID. def _get_entity_pair(self, entity_id): """ Returns ``(entity, input_entity)`` for the given entity ID. """ entity = self._entities.get(entity_id) try: input_entity = utils.get_input_peer(entity) exce...
Must load all the entities it needs from cache, and return ``False`` if it could not find all of them. def _load_entities(self): """ Must load all the entities it needs from cache, and return ``False`` if it could not find all of them. """ if not self._chat_peer: ...
Get the difference for this `channel_id` if any, then load entities. Calls :tl:`updates.getDifference`, which fills the entities cache (always done by `__call__`) and lets us know about the full entities. async def _get_difference(self, channel_id, pts_date): """ Get the difference for...
Returns `chat`, but will make an API call to find the chat unless it's already cached. async def get_chat(self): """ Returns `chat`, but will make an API call to find the chat unless it's already cached. """ # See `get_sender` for information about 'min'. if (sel...
This :tl:`InputPeer` is the input version of the chat where the message was sent. Similarly to `input_sender`, 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 doesn't have enough information availabl...
Returns `input_chat`, but will make an API call to find the input chat unless it's already cached. async def get_input_chat(self): """ Returns `input_chat`, but will make an API call to find the input chat unless it's already cached. """ if self.input_chat is None and se...
True if the message was sent on a group or megagroup. def is_group(self): """True if the message was sent on a group or megagroup.""" if self._broadcast is None and self.chat: self._broadcast = getattr(self.chat, 'broadcast', None) return ( isinstance(self._chat_peer, (...
Generates a random long integer (8 bytes), which is optionally signed def generate_random_long(signed=True): """Generates a random long integer (8 bytes), which is optionally signed""" return int.from_bytes(os.urandom(8), signed=signed, byteorder='little')
Ensures that the parent directory exists def ensure_parent_dir_exists(file_path): """Ensures that the parent directory exists""" parent = os.path.dirname(file_path) if parent: os.makedirs(parent, exist_ok=True)
Strips whitespace from the given text modifying the provided entities. This assumes that there are no overlapping entities, that their length is greater or equal to one, and that their length is not out of bounds. def strip_text(text, entities): """ Strips whitespace from the given text modifying the ...
Helper to cancel one or more tasks gracefully, logging exceptions. async def _cancel(log, **tasks): """ Helper to cancel one or more tasks gracefully, logging exceptions. """ for name, task in tasks.items(): if not task: continue task.cancel() try: await...
Helps to cut boilerplate on async context managers that offer synchronous variants. def _sync_enter(self): """ Helps to cut boilerplate on async context managers that offer synchronous variants. """ if hasattr(self, 'loop'): loop = self.loop else: loop = self._client.loop ...
Generates the key data corresponding to the given nonce def generate_key_data_from_nonce(server_nonce, new_nonce): """Generates the key data corresponding to the given nonce""" server_nonce = server_nonce.to_bytes(16, 'little', signed=True) new_nonce = new_nonce.to_bytes(32, 'little', signed=True) hash...
Writes a string into the source code, applying indentation if required def write(self, string, *args, **kwargs): """Writes a string into the source code, applying indentation if required """ if self.on_new_line: self.on_new_line = False # We're not on a new li...
Writes a string into the source code _and_ appends a new line, applying indentation if required def writeln(self, string='', *args, **kwargs): """Writes a string into the source code _and_ appends a new line, applying indentation if required """ self.write(string + '\n', *...
Ends an indentation block, leaving an empty line afterwards def end_block(self): """Ends an indentation block, leaving an empty line afterwards""" self.current_indent -= 1 # If we did not add a new line automatically yet, now it's the time! if not self.auto_added_line: self...
Writes the source code corresponding to the given TLObject by making use of the ``builder`` `SourceBuilder`. Additional information such as file path depth and the ``Type: [Constructors]`` must be given for proper importing and documentation strings. def _write_source_code(tlobject, kind, builder, typ...
Writes the .__bytes__() code for the given argument :param builder: The source code builder :param arg: The argument to write :param args: All the other arguments in TLObject same __bytes__. This is required to determine the flags value :param name: The name of the argument. Defaults to...
Writes the read code for the given argument, setting the arg.name variable to its read value. :param builder: The source code builder :param arg: The argument to write :param args: All the other arguments in TLObject same on_send. This is required to determine the flags value :para...
Converts a Telegram's RPC Error to a Python error. :param rpc_error: the RpcError instance. :param request: the request that caused this error. :return: the RPCError as a Python exception that represents this error. def rpc_message_to_error(rpc_error, request): """ Converts a Telegram's RPC Error ...
Returns ``True`` if the button belongs to an inline keyboard. def _is_inline(button): """ Returns ``True`` if the button belongs to an inline keyboard. """ return isinstance(button, ( types.KeyboardButtonCallback, types.KeyboardButtonSwitchInline, typ...
Creates a new inline button. If `data` is omitted, the given `text` will be used as `data`. In any case `data` should be either ``bytes`` or ``str``. Note that the given `data` must be less or equal to 64 bytes. If more than 64 bytes are passed as data, ``ValueError`` is raised. def i...
Creates a new button to switch to inline query. If `query` is given, it will be the default text to be used when making the inline query. If ``same_peer is True`` the inline query will directly be set under the currently opened chat. Otherwise, the user will have to select a di...
Creates a new button with the given text. Args: resize (`bool`): If present, the entire keyboard will be reconfigured to be resized and be smaller if there are not many buttons. single_use (`bool`): If present, the entire keyboard will be...
Creates a new button that will request the user's location upon being clicked. ``resize``, ``single_use`` and ``selective`` are documented in `text`. def request_location(cls, text, *, resize=None, single_use=None, selective=None): """ Creates a new button that...
Creates a new button that will request the user's phone number upon being clicked. ``resize``, ``single_use`` and ``selective`` are documented in `text`. def request_phone(cls, text, *, resize=None, single_use=None, selective=None): """ Creates a new button that w...
Safe Print (handle UnicodeEncodeErrors on some terminals) def sprint(string, *args, **kwargs): """Safe Print (handle UnicodeEncodeErrors on some terminals)""" try: print(string, *args, **kwargs) except UnicodeEncodeError: string = string.encode('utf-8', errors='ignore')\ ...
Helper function to print titles to the console more nicely def print_title(title): """Helper function to print titles to the console more nicely""" sprint('\n') sprint('=={}=='.format('=' * len(title))) sprint('= {} ='.format(title)) sprint('=={}=='.format('=' * len(title)))
Python's ``input()`` is blocking, which means the event loop we set above can't be running while we're blocking there. This method will let the loop run while we wait for input. async def async_input(prompt): """ Python's ``input()`` is blocking, which means the event loop we set above can't be run...
Main loop of the TelegramClient, will wait for user action async def run(self): """Main loop of the TelegramClient, will wait for user action""" # Once everything is ready, we can add an event handler. # # Events are an abstraction over Telegram's "Updates" and # are much easie...
Sends the file located at path to the desired entity as a photo async def send_photo(self, path, entity): """Sends the file located at path to the desired entity as a photo""" await self.send_file( entity, path, progress_callback=self.upload_progress_callback ) p...
Sends the file located at path to the desired entity as a document async def send_document(self, path, entity): """Sends the file located at path to the desired entity as a document""" await self.send_file( entity, path, force_document=True, progress_callback=self.up...
Given a message ID, finds the media this message contained and downloads it. async def download_media_by_id(self, media_id): """Given a message ID, finds the media this message contained and downloads it. """ try: msg = self.found_media[int(media_id)] e...
Callback method for received events.NewMessage async def message_handler(self, event): """Callback method for received events.NewMessage""" # Note that message_handler is called when a Telegram update occurs # and an event is created. Telegram may not always send information # about th...
``ClassName -> class_name.html``. def _get_file_name(tlobject): """``ClassName -> class_name.html``.""" name = tlobject.name if isinstance(tlobject, TLObject) else tlobject # Courtesy of http://stackoverflow.com/a/1176023/4759433 s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) result = re.sub('([a-...
``TLObject -> from ... import ...``. def get_import_code(tlobject): """``TLObject -> from ... import ...``.""" kind = 'functions' if tlobject.is_function else 'types' ns = '.' + tlobject.namespace if tlobject.namespace else '' return 'from telethon.tl.{}{} import {}'\ .format(kind, ns, tlobject...
Creates and returns the path for the given TLObject at root. def _get_path_for(root, tlobject): """Creates and returns the path for the given TLObject at root.""" out_dir = root / ('methods' if tlobject.is_function else 'constructors') if tlobject.namespace: out_dir /= tlobject.namespace retur...
Similar to `_get_path_for` but for only type names. def _get_path_for_type(type_): """Similar to `_get_path_for` but for only type names.""" if type_.lower() in CORE_TYPES: return Path('index.html#%s' % type_.lower()) elif '.' in type_: namespace, name = type_.split('.') return Path...
Finds the <title> for the given HTML file, or (Unknown). def _find_title(html_file): """Finds the <title> for the given HTML file, or (Unknown).""" # TODO Is it necessary to read files like this? with html_file.open() as f: for line in f: if '<title>' in line: # + 7 to s...
Builds the menu used for the current ``DocumentWriter``. def _build_menu(docs): """ Builds the menu used for the current ``DocumentWriter``. """ paths = [] current = docs.filename while current != docs.root: current = current.parent paths.append(current) for path in revers...
Generates the index file for the specified folder def _generate_index(root, folder, paths, bots_index=False, bots_index_paths=()): """Generates the index file for the specified folder""" # Determine the namespaces listed here (as sub folders) # and the files (.html files) that we should...
Generates a proper description for the given argument. def _get_description(arg): """Generates a proper description for the given argument.""" desc = [] otherwise = False if arg.can_be_inferred: desc.append('If left unspecified, it will be inferred automatically.') otherwise = True ...
Copies the src file into dst applying the replacements dict def _copy_replace(src, dst, replacements): """Copies the src file into dst applying the replacements dict""" with src.open() as infile, dst.open('w') as outfile: outfile.write(re.sub( '|'.join(re.escape(k) for k in replacements), ...
Generates the documentation HTML files from from ``scheme.tl`` to ``/methods`` and ``/constructors``, etc. def _write_html_pages(root, tlobjects, methods, layer, input_res): """ Generates the documentation HTML files from from ``scheme.tl`` to ``/methods`` and ``/constructors``, etc. """ # Save...
Pre-create the required directory structure in `output_dir` for the input objects. def _create_structure(tlobjects, output_dir): """ Pre-create the required directory structure in `output_dir` for the input objects. """ types_ns = set() method_ns = set() for obj in tlobjects: if...
This method is trying to establish connection with one of the zookeeper nodes. Somehow strategy "fail earlier and retry more often" works way better comparing to the original strategy "try to connect with specified timeout". Since we want to try connect to zookeeper more often (with the...
Python3 raises `ValueError` if socket is closed, because fd == -1 def select(self, *args, **kwargs): """Python3 raises `ValueError` if socket is closed, because fd == -1""" try: return super(PatroniSequentialThreadingHandler, self).select(*args, **kwargs) except ValueError as e: ...
Kazoo is using Ping's to determine health of connection to zookeeper. If there is no response on Ping after Ping interval (1/2 from read_timeout) it will consider current connection dead and try to connect to another node. Without this "magic" it was taking up to 2/3 from session timeout (ttl) t...
It is not possible to change ttl (session_timeout) in zookeeper without destroying old session and creating the new one. This method returns `!True` if session_timeout has been changed (`restart()` has been called). def set_ttl(self, ttl): """It is not possible to change ttl (session_timeout) i...
Translate scope name to service name which can be used in dns. 230 = 253 - len('replica.') - len('.service.consul') def service_name_from_scope_name(scope_name): """Translate scope name to service name which can be used in dns. 230 = 253 - len('replica.') - len('.service.consul') """ def replace...
:returns: `!True` if it had to create new session def _do_refresh_session(self): """:returns: `!True` if it had to create new session""" if self._session and self._last_session_refresh + self._loop_wait > time.time(): return False if self._session: try: ...