index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
711,908
pyrogram.types.messages_and_media.message
react
Bound method *react* of :obj:`~pyrogram.types.Message`. Use as a shortcut for: .. code-block:: python await client.send_reaction( chat_id=chat_id, message_id=message.id, emoji="🔥" ) Example: .. code-block:: python await message.react(emoji="🔥") Parameters: emoji (``str``, *optional*): Reaction emoji. Pass "" as emoji (default) to retract the reaction. big (``bool``, *optional*): Pass True to show a bigger and longer reaction. Defaults to False. Returns: ``bool``: On success, True is returned. Raises: RPCError: In case of a Telegram RPC error.
@property def html(self): return Parser.unparse(self, self.entities, True)
(self, emoji: str = '', big: bool = False) -> bool
711,909
pyrogram.types.messages_and_media.message
reply_text
Bound method *reply_text* of :obj:`~pyrogram.types.Message`. An alias exists as *reply*. Use as a shortcut for: .. code-block:: python await client.send_message( chat_id=message.chat.id, text="hello", reply_to_message_id=message.id ) Example: .. code-block:: python await message.reply_text("hello", quote=True) Parameters: text (``str``): Text of the message to be sent. quote (``bool``, *optional*): If ``True``, the message will be sent as a reply to this message. If *reply_to_message_id* is passed, this parameter will be ignored. Defaults to ``True`` in group chats and ``False`` in private chats. parse_mode (:obj:`~pyrogram.enums.ParseMode`, *optional*): By default, texts are parsed using both Markdown and HTML styles. You can combine both syntaxes together. entities (List of :obj:`~pyrogram.types.MessageEntity`): List of special entities that appear in message text, which can be specified instead of *parse_mode*. disable_web_page_preview (``bool``, *optional*): Disables link previews for links in this message. disable_notification (``bool``, *optional*): Sends the message silently. Users will receive a notification with no sound. reply_to_message_id (``int``, *optional*): If the message is a reply, ID of the original message. schedule_date (:py:obj:`~datetime.datetime`, *optional*): Date when the message will be automatically sent. protect_content (``bool``, *optional*): Protects the contents of the sent message from forwarding and saving. reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardRemove` | :obj:`~pyrogram.types.ForceReply`, *optional*): Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. Returns: On success, the sent Message is returned. Raises: RPCError: In case of a Telegram RPC error.
@property def html(self): return Parser.unparse(self, self.entities, True)
(self, text: str, quote: bool = None, parse_mode: Optional[pyrogram.enums.parse_mode.ParseMode] = None, entities: List[pyrogram.types.messages_and_media.message_entity.MessageEntity] = None, disable_web_page_preview: bool = None, disable_notification: bool = None, reply_to_message_id: int = None, schedule_date: datetime.datetime = None, protect_content: bool = None, reply_markup=None) -> pyrogram.types.messages_and_media.message.Message
711,910
pyrogram.types.messages_and_media.message
reply_animation
Bound method *reply_animation* :obj:`~pyrogram.types.Message`. Use as a shortcut for: .. code-block:: python await client.send_animation( chat_id=message.chat.id, animation=animation ) Example: .. code-block:: python await message.reply_animation(animation) Parameters: animation (``str``): Animation to send. Pass a file_id as string to send an animation that exists on the Telegram servers, pass an HTTP URL as a string for Telegram to get an animation from the Internet, or pass a file path as string to upload a new animation that exists on your local machine. quote (``bool``, *optional*): If ``True``, the message will be sent as a reply to this message. If *reply_to_message_id* is passed, this parameter will be ignored. Defaults to ``True`` in group chats and ``False`` in private chats. caption (``str``, *optional*): Animation caption, 0-1024 characters. parse_mode (:obj:`~pyrogram.enums.ParseMode`, *optional*): By default, texts are parsed using both Markdown and HTML styles. You can combine both syntaxes together. caption_entities (List of :obj:`~pyrogram.types.MessageEntity`): List of special entities that appear in the caption, which can be specified instead of *parse_mode*. has_spoiler (``bool``, *optional*): Pass True if the animation needs to be covered with a spoiler animation. duration (``int``, *optional*): Duration of sent animation in seconds. width (``int``, *optional*): Animation width. height (``int``, *optional*): Animation height. thumb (``str``, *optional*): Thumbnail of the animation file sent. The thumbnail should be in JPEG format and less than 200 KB in size. A thumbnail's width and height should not exceed 320 pixels. Thumbnails can't be reused and can be only uploaded as a new file. disable_notification (``bool``, *optional*): Sends the message silently. Users will receive a notification with no sound. reply_to_message_id (``int``, *optional*): If the message is a reply, ID of the original message. reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardRemove` | :obj:`~pyrogram.types.ForceReply`, *optional*): Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. progress (``Callable``, *optional*): Pass a callback function to view the file transmission progress. The function must take *(current, total)* as positional arguments (look at Other Parameters below for a detailed description) and will be called back each time a new file chunk has been successfully transmitted. progress_args (``tuple``, *optional*): Extra custom arguments for the progress callback function. You can pass anything you need to be available in the progress callback scope; for example, a Message object or a Client instance in order to edit the message with the updated progress status. Other Parameters: current (``int``): The amount of bytes transmitted so far. total (``int``): The total size of the file. *args (``tuple``, *optional*): Extra custom arguments as defined in the ``progress_args`` parameter. You can either keep ``*args`` or add every single extra argument in your function signature. Returns: On success, the sent :obj:`~pyrogram.types.Message` is returned. In case the upload is deliberately stopped with :meth:`~pyrogram.Client.stop_transmission`, None is returned instead. Raises: RPCError: In case of a Telegram RPC error.
@property def html(self): return Parser.unparse(self, self.entities, True)
(self, animation: Union[str, BinaryIO], quote: bool = None, caption: str = '', parse_mode: Optional[pyrogram.enums.parse_mode.ParseMode] = None, caption_entities: List[pyrogram.types.messages_and_media.message_entity.MessageEntity] = None, has_spoiler: bool = None, duration: int = 0, width: int = 0, height: int = 0, thumb: str = None, disable_notification: bool = None, reply_markup: Union[pyrogram.types.bots_and_keyboards.inline_keyboard_markup.InlineKeyboardMarkup, pyrogram.types.bots_and_keyboards.reply_keyboard_markup.ReplyKeyboardMarkup, pyrogram.types.bots_and_keyboards.reply_keyboard_remove.ReplyKeyboardRemove, pyrogram.types.bots_and_keyboards.force_reply.ForceReply] = None, reply_to_message_id: int = None, progress: Callable = None, progress_args: tuple = ()) -> pyrogram.types.messages_and_media.message.Message
711,911
pyrogram.types.messages_and_media.message
reply_audio
Bound method *reply_audio* of :obj:`~pyrogram.types.Message`. Use as a shortcut for: .. code-block:: python await client.send_audio( chat_id=message.chat.id, audio=audio ) Example: .. code-block:: python await message.reply_audio(audio) Parameters: audio (``str``): Audio file to send. Pass a file_id as string to send an audio file that exists on the Telegram servers, pass an HTTP URL as a string for Telegram to get an audio file from the Internet, or pass a file path as string to upload a new audio file that exists on your local machine. quote (``bool``, *optional*): If ``True``, the message will be sent as a reply to this message. If *reply_to_message_id* is passed, this parameter will be ignored. Defaults to ``True`` in group chats and ``False`` in private chats. caption (``str``, *optional*): Audio caption, 0-1024 characters. parse_mode (:obj:`~pyrogram.enums.ParseMode`, *optional*): By default, texts are parsed using both Markdown and HTML styles. You can combine both syntaxes together. caption_entities (List of :obj:`~pyrogram.types.MessageEntity`): List of special entities that appear in the caption, which can be specified instead of *parse_mode*. duration (``int``, *optional*): Duration of the audio in seconds. performer (``str``, *optional*): Performer. title (``str``, *optional*): Track name. thumb (``str``, *optional*): Thumbnail of the music file album cover. The thumbnail should be in JPEG format and less than 200 KB in size. A thumbnail's width and height should not exceed 320 pixels. Thumbnails can't be reused and can be only uploaded as a new file. disable_notification (``bool``, *optional*): Sends the message silently. Users will receive a notification with no sound. reply_to_message_id (``int``, *optional*): If the message is a reply, ID of the original message. reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardRemove` | :obj:`~pyrogram.types.ForceReply`, *optional*): Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. progress (``Callable``, *optional*): Pass a callback function to view the file transmission progress. The function must take *(current, total)* as positional arguments (look at Other Parameters below for a detailed description) and will be called back each time a new file chunk has been successfully transmitted. progress_args (``tuple``, *optional*): Extra custom arguments for the progress callback function. You can pass anything you need to be available in the progress callback scope; for example, a Message object or a Client instance in order to edit the message with the updated progress status. Other Parameters: current (``int``): The amount of bytes transmitted so far. total (``int``): The total size of the file. *args (``tuple``, *optional*): Extra custom arguments as defined in the ``progress_args`` parameter. You can either keep ``*args`` or add every single extra argument in your function signature. Returns: On success, the sent :obj:`~pyrogram.types.Message` is returned. In case the upload is deliberately stopped with :meth:`~pyrogram.Client.stop_transmission`, None is returned instead. Raises: RPCError: In case of a Telegram RPC error.
@property def html(self): return Parser.unparse(self, self.entities, True)
(self, audio: Union[str, BinaryIO], quote: bool = None, caption: str = '', parse_mode: Optional[pyrogram.enums.parse_mode.ParseMode] = None, caption_entities: List[pyrogram.types.messages_and_media.message_entity.MessageEntity] = None, duration: int = 0, performer: str = None, title: str = None, thumb: str = None, disable_notification: bool = None, reply_to_message_id: int = None, reply_markup: Union[pyrogram.types.bots_and_keyboards.inline_keyboard_markup.InlineKeyboardMarkup, pyrogram.types.bots_and_keyboards.reply_keyboard_markup.ReplyKeyboardMarkup, pyrogram.types.bots_and_keyboards.reply_keyboard_remove.ReplyKeyboardRemove, pyrogram.types.bots_and_keyboards.force_reply.ForceReply] = None, progress: Callable = None, progress_args: tuple = ()) -> pyrogram.types.messages_and_media.message.Message
711,912
pyrogram.types.messages_and_media.message
reply_cached_media
Bound method *reply_cached_media* of :obj:`~pyrogram.types.Message`. Use as a shortcut for: .. code-block:: python await client.send_cached_media( chat_id=message.chat.id, file_id=file_id ) Example: .. code-block:: python await message.reply_cached_media(file_id) Parameters: file_id (``str``): Media to send. Pass a file_id as string to send a media that exists on the Telegram servers. quote (``bool``, *optional*): If ``True``, the message will be sent as a reply to this message. If *reply_to_message_id* is passed, this parameter will be ignored. Defaults to ``True`` in group chats and ``False`` in private chats. caption (``bool``, *optional*): Media caption, 0-1024 characters. parse_mode (:obj:`~pyrogram.enums.ParseMode`, *optional*): By default, texts are parsed using both Markdown and HTML styles. You can combine both syntaxes together. caption_entities (List of :obj:`~pyrogram.types.MessageEntity`): List of special entities that appear in the caption, which can be specified instead of *parse_mode*. disable_notification (``bool``, *optional*): Sends the message silently. Users will receive a notification with no sound. reply_to_message_id (``int``, *optional*): If the message is a reply, ID of the original message. reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardRemove` | :obj:`~pyrogram.types.ForceReply`, *optional*): Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. Returns: On success, the sent :obj:`~pyrogram.types.Message` is returned. Raises: RPCError: In case of a Telegram RPC error.
@property def html(self): return Parser.unparse(self, self.entities, True)
(self, file_id: str, quote: bool = None, caption: str = '', parse_mode: Optional[pyrogram.enums.parse_mode.ParseMode] = None, caption_entities: List[pyrogram.types.messages_and_media.message_entity.MessageEntity] = None, disable_notification: bool = None, reply_to_message_id: int = None, reply_markup: Union[pyrogram.types.bots_and_keyboards.inline_keyboard_markup.InlineKeyboardMarkup, pyrogram.types.bots_and_keyboards.reply_keyboard_markup.ReplyKeyboardMarkup, pyrogram.types.bots_and_keyboards.reply_keyboard_remove.ReplyKeyboardRemove, pyrogram.types.bots_and_keyboards.force_reply.ForceReply] = None) -> pyrogram.types.messages_and_media.message.Message
711,913
pyrogram.types.messages_and_media.message
reply_chat_action
Bound method *reply_chat_action* of :obj:`~pyrogram.types.Message`. Use as a shortcut for: .. code-block:: python from pyrogram import enums await client.send_chat_action( chat_id=message.chat.id, action=enums.ChatAction.TYPING ) Example: .. code-block:: python from pyrogram import enums await message.reply_chat_action(enums.ChatAction.TYPING) Parameters: action (:obj:`~pyrogram.enums.ChatAction`): Type of action to broadcast. Returns: ``bool``: On success, True is returned. Raises: RPCError: In case of a Telegram RPC error. ValueError: In case the provided string is not a valid chat action.
@property def html(self): return Parser.unparse(self, self.entities, True)
(self, action: pyrogram.enums.chat_action.ChatAction) -> bool
711,914
pyrogram.types.messages_and_media.message
reply_contact
Bound method *reply_contact* of :obj:`~pyrogram.types.Message`. Use as a shortcut for: .. code-block:: python await client.send_contact( chat_id=message.chat.id, phone_number=phone_number, first_name=first_name ) Example: .. code-block:: python await message.reply_contact("+1-123-456-7890", "Name") Parameters: phone_number (``str``): Contact's phone number. first_name (``str``): Contact's first name. quote (``bool``, *optional*): If ``True``, the message will be sent as a reply to this message. If *reply_to_message_id* is passed, this parameter will be ignored. Defaults to ``True`` in group chats and ``False`` in private chats. last_name (``str``, *optional*): Contact's last name. vcard (``str``, *optional*): Additional data about the contact in the form of a vCard, 0-2048 bytes disable_notification (``bool``, *optional*): Sends the message silently. Users will receive a notification with no sound. reply_to_message_id (``int``, *optional*): If the message is a reply, ID of the original message. reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardRemove` | :obj:`~pyrogram.types.ForceReply`, *optional*): Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. Returns: On success, the sent :obj:`~pyrogram.types.Message` is returned. Raises: RPCError: In case of a Telegram RPC error.
@property def html(self): return Parser.unparse(self, self.entities, True)
(self, phone_number: str, first_name: str, quote: bool = None, last_name: str = '', vcard: str = '', disable_notification: bool = None, reply_to_message_id: int = None, reply_markup: Union[pyrogram.types.bots_and_keyboards.inline_keyboard_markup.InlineKeyboardMarkup, pyrogram.types.bots_and_keyboards.reply_keyboard_markup.ReplyKeyboardMarkup, pyrogram.types.bots_and_keyboards.reply_keyboard_remove.ReplyKeyboardRemove, pyrogram.types.bots_and_keyboards.force_reply.ForceReply] = None) -> pyrogram.types.messages_and_media.message.Message
711,915
pyrogram.types.messages_and_media.message
reply_document
Bound method *reply_document* of :obj:`~pyrogram.types.Message`. Use as a shortcut for: .. code-block:: python await client.send_document( chat_id=message.chat.id, document=document ) Example: .. code-block:: python await message.reply_document(document) Parameters: document (``str``): File to send. Pass a file_id as string to send a file that exists on the Telegram servers, pass an HTTP URL as a string for Telegram to get a file from the Internet, or pass a file path as string to upload a new file that exists on your local machine. quote (``bool``, *optional*): If ``True``, the message will be sent as a reply to this message. If *reply_to_message_id* is passed, this parameter will be ignored. Defaults to ``True`` in group chats and ``False`` in private chats. thumb (``str``, *optional*): Thumbnail of the file sent. The thumbnail should be in JPEG format and less than 200 KB in size. A thumbnail's width and height should not exceed 320 pixels. Thumbnails can't be reused and can be only uploaded as a new file. caption (``str``, *optional*): Document caption, 0-1024 characters. parse_mode (:obj:`~pyrogram.enums.ParseMode`, *optional*): By default, texts are parsed using both Markdown and HTML styles. You can combine both syntaxes together. caption_entities (List of :obj:`~pyrogram.types.MessageEntity`): List of special entities that appear in the caption, which can be specified instead of *parse_mode*. file_name (``str``, *optional*): File name of the document sent. Defaults to file's path basename. force_document (``bool``, *optional*): Pass True to force sending files as document. Useful for video files that need to be sent as document messages instead of video messages. Defaults to False. disable_notification (``bool``, *optional*): Sends the message silently. Users will receive a notification with no sound. reply_to_message_id (``int``, *optional*): If the message is a reply, ID of the original message. schedule_date (:py:obj:`~datetime.datetime`, *optional*): Date when the message will be automatically sent. reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardRemove` | :obj:`~pyrogram.types.ForceReply`, *optional*): Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. progress (``Callable``, *optional*): Pass a callback function to view the file transmission progress. The function must take *(current, total)* as positional arguments (look at Other Parameters below for a detailed description) and will be called back each time a new file chunk has been successfully transmitted. progress_args (``tuple``, *optional*): Extra custom arguments for the progress callback function. You can pass anything you need to be available in the progress callback scope; for example, a Message object or a Client instance in order to edit the message with the updated progress status. Other Parameters: current (``int``): The amount of bytes transmitted so far. total (``int``): The total size of the file. *args (``tuple``, *optional*): Extra custom arguments as defined in the ``progress_args`` parameter. You can either keep ``*args`` or add every single extra argument in your function signature. Returns: On success, the sent :obj:`~pyrogram.types.Message` is returned. In case the upload is deliberately stopped with :meth:`~pyrogram.Client.stop_transmission`, None is returned instead. Raises: RPCError: In case of a Telegram RPC error.
@property def html(self): return Parser.unparse(self, self.entities, True)
(self, document: Union[str, BinaryIO], quote: bool = None, thumb: str = None, caption: str = '', parse_mode: Optional[pyrogram.enums.parse_mode.ParseMode] = None, caption_entities: List[pyrogram.types.messages_and_media.message_entity.MessageEntity] = None, file_name: str = None, force_document: bool = None, disable_notification: bool = None, reply_to_message_id: int = None, schedule_date: datetime.datetime = None, reply_markup: Union[pyrogram.types.bots_and_keyboards.inline_keyboard_markup.InlineKeyboardMarkup, pyrogram.types.bots_and_keyboards.reply_keyboard_markup.ReplyKeyboardMarkup, pyrogram.types.bots_and_keyboards.reply_keyboard_remove.ReplyKeyboardRemove, pyrogram.types.bots_and_keyboards.force_reply.ForceReply] = None, progress: Callable = None, progress_args: tuple = ()) -> pyrogram.types.messages_and_media.message.Message
711,916
pyrogram.types.messages_and_media.message
reply_game
Bound method *reply_game* of :obj:`~pyrogram.types.Message`. Use as a shortcut for: .. code-block:: python await client.send_game( chat_id=message.chat.id, game_short_name="lumberjack" ) Example: .. code-block:: python await message.reply_game("lumberjack") Parameters: game_short_name (``str``): Short name of the game, serves as the unique identifier for the game. Set up your games via Botfather. quote (``bool``, *optional*): If ``True``, the message will be sent as a reply to this message. If *reply_to_message_id* is passed, this parameter will be ignored. Defaults to ``True`` in group chats and ``False`` in private chats. disable_notification (``bool``, *optional*): Sends the message silently. Users will receive a notification with no sound. reply_to_message_id (``int``, *optional*): If the message is a reply, ID of the original message. reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup`, *optional*): An object for an inline keyboard. If empty, one ‘Play game_title’ button will be shown automatically. If not empty, the first button must launch the game. Returns: On success, the sent :obj:`~pyrogram.types.Message` is returned. Raises: RPCError: In case of a Telegram RPC error.
@property def html(self): return Parser.unparse(self, self.entities, True)
(self, game_short_name: str, quote: bool = None, disable_notification: bool = None, reply_to_message_id: int = None, reply_markup: Union[pyrogram.types.bots_and_keyboards.inline_keyboard_markup.InlineKeyboardMarkup, pyrogram.types.bots_and_keyboards.reply_keyboard_markup.ReplyKeyboardMarkup, pyrogram.types.bots_and_keyboards.reply_keyboard_remove.ReplyKeyboardRemove, pyrogram.types.bots_and_keyboards.force_reply.ForceReply] = None) -> pyrogram.types.messages_and_media.message.Message
711,917
pyrogram.types.messages_and_media.message
reply_inline_bot_result
Bound method *reply_inline_bot_result* of :obj:`~pyrogram.types.Message`. Use as a shortcut for: .. code-block:: python await client.send_inline_bot_result( chat_id=message.chat.id, query_id=query_id, result_id=result_id ) Example: .. code-block:: python await message.reply_inline_bot_result(query_id, result_id) Parameters: query_id (``int``): Unique identifier for the answered query. result_id (``str``): Unique identifier for the result that was chosen. quote (``bool``, *optional*): If ``True``, the message will be sent as a reply to this message. If *reply_to_message_id* is passed, this parameter will be ignored. Defaults to ``True`` in group chats and ``False`` in private chats. disable_notification (``bool``, *optional*): Sends the message silently. Users will receive a notification with no sound. reply_to_message_id (``bool``, *optional*): If the message is a reply, ID of the original message. Returns: On success, the sent Message is returned. Raises: RPCError: In case of a Telegram RPC error.
@property def html(self): return Parser.unparse(self, self.entities, True)
(self, query_id: int, result_id: str, quote: bool = None, disable_notification: bool = None, reply_to_message_id: int = None) -> pyrogram.types.messages_and_media.message.Message
711,918
pyrogram.types.messages_and_media.message
reply_location
Bound method *reply_location* of :obj:`~pyrogram.types.Message`. Use as a shortcut for: .. code-block:: python await client.send_location( chat_id=message.chat.id, latitude=latitude, longitude=longitude ) Example: .. code-block:: python await message.reply_location(latitude, longitude) Parameters: latitude (``float``): Latitude of the location. longitude (``float``): Longitude of the location. quote (``bool``, *optional*): If ``True``, the message will be sent as a reply to this message. If *reply_to_message_id* is passed, this parameter will be ignored. Defaults to ``True`` in group chats and ``False`` in private chats. disable_notification (``bool``, *optional*): Sends the message silently. Users will receive a notification with no sound. reply_to_message_id (``int``, *optional*): If the message is a reply, ID of the original message reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardRemove` | :obj:`~pyrogram.types.ForceReply`, *optional*): Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. Returns: On success, the sent :obj:`~pyrogram.types.Message` is returned. Raises: RPCError: In case of a Telegram RPC error.
@property def html(self): return Parser.unparse(self, self.entities, True)
(self, latitude: float, longitude: float, quote: bool = None, disable_notification: bool = None, reply_to_message_id: int = None, reply_markup: Union[pyrogram.types.bots_and_keyboards.inline_keyboard_markup.InlineKeyboardMarkup, pyrogram.types.bots_and_keyboards.reply_keyboard_markup.ReplyKeyboardMarkup, pyrogram.types.bots_and_keyboards.reply_keyboard_remove.ReplyKeyboardRemove, pyrogram.types.bots_and_keyboards.force_reply.ForceReply] = None) -> pyrogram.types.messages_and_media.message.Message
711,919
pyrogram.types.messages_and_media.message
reply_media_group
Bound method *reply_media_group* of :obj:`~pyrogram.types.Message`. Use as a shortcut for: .. code-block:: python await client.send_media_group( chat_id=message.chat.id, media=list_of_media ) Example: .. code-block:: python await message.reply_media_group(list_of_media) Parameters: media (``list``): A list containing either :obj:`~pyrogram.types.InputMediaPhoto` or :obj:`~pyrogram.types.InputMediaVideo` objects describing photos and videos to be sent, must include 2–10 items. quote (``bool``, *optional*): If ``True``, the message will be sent as a reply to this message. If *reply_to_message_id* is passed, this parameter will be ignored. Defaults to ``True`` in group chats and ``False`` in private chats. disable_notification (``bool``, *optional*): Sends the message silently. Users will receive a notification with no sound. reply_to_message_id (``int``, *optional*): If the message is a reply, ID of the original message. Returns: On success, a :obj:`~pyrogram.types.Messages` object is returned containing all the single messages sent. Raises: RPCError: In case of a Telegram RPC error.
@property def html(self): return Parser.unparse(self, self.entities, True)
(self, media: List[Union[pyrogram.types.input_media.input_media_photo.InputMediaPhoto, pyrogram.types.input_media.input_media_video.InputMediaVideo]], quote: bool = None, disable_notification: bool = None, reply_to_message_id: int = None) -> List[pyrogram.types.messages_and_media.message.Message]
711,920
pyrogram.types.messages_and_media.message
reply_photo
Bound method *reply_photo* of :obj:`~pyrogram.types.Message`. Use as a shortcut for: .. code-block:: python await client.send_photo( chat_id=message.chat.id, photo=photo ) Example: .. code-block:: python await message.reply_photo(photo) Parameters: photo (``str``): Photo to send. Pass a file_id as string to send a photo that exists on the Telegram servers, pass an HTTP URL as a string for Telegram to get a photo from the Internet, or pass a file path as string to upload a new photo that exists on your local machine. quote (``bool``, *optional*): If ``True``, the message will be sent as a reply to this message. If *reply_to_message_id* is passed, this parameter will be ignored. Defaults to ``True`` in group chats and ``False`` in private chats. caption (``str``, *optional*): Photo caption, 0-1024 characters. parse_mode (:obj:`~pyrogram.enums.ParseMode`, *optional*): By default, texts are parsed using both Markdown and HTML styles. You can combine both syntaxes together. caption_entities (List of :obj:`~pyrogram.types.MessageEntity`): List of special entities that appear in the caption, which can be specified instead of *parse_mode*. has_spoiler (``bool``, *optional*): Pass True if the photo needs to be covered with a spoiler animation. ttl_seconds (``int``, *optional*): Self-Destruct Timer. If you set a timer, the photo will self-destruct in *ttl_seconds* seconds after it was viewed. disable_notification (``bool``, *optional*): Sends the message silently. Users will receive a notification with no sound. reply_to_message_id (``int``, *optional*): If the message is a reply, ID of the original message. reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardRemove` | :obj:`~pyrogram.types.ForceReply`, *optional*): Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. progress (``Callable``, *optional*): Pass a callback function to view the file transmission progress. The function must take *(current, total)* as positional arguments (look at Other Parameters below for a detailed description) and will be called back each time a new file chunk has been successfully transmitted. progress_args (``tuple``, *optional*): Extra custom arguments for the progress callback function. You can pass anything you need to be available in the progress callback scope; for example, a Message object or a Client instance in order to edit the message with the updated progress status. Other Parameters: current (``int``): The amount of bytes transmitted so far. total (``int``): The total size of the file. *args (``tuple``, *optional*): Extra custom arguments as defined in the ``progress_args`` parameter. You can either keep ``*args`` or add every single extra argument in your function signature. Returns: On success, the sent :obj:`~pyrogram.types.Message` is returned. In case the upload is deliberately stopped with :meth:`~pyrogram.Client.stop_transmission`, None is returned instead. Raises: RPCError: In case of a Telegram RPC error.
@property def html(self): return Parser.unparse(self, self.entities, True)
(self, photo: Union[str, BinaryIO], quote: bool = None, caption: str = '', parse_mode: Optional[pyrogram.enums.parse_mode.ParseMode] = None, caption_entities: List[pyrogram.types.messages_and_media.message_entity.MessageEntity] = None, has_spoiler: bool = None, ttl_seconds: int = None, disable_notification: bool = None, reply_to_message_id: int = None, reply_markup: Union[pyrogram.types.bots_and_keyboards.inline_keyboard_markup.InlineKeyboardMarkup, pyrogram.types.bots_and_keyboards.reply_keyboard_markup.ReplyKeyboardMarkup, pyrogram.types.bots_and_keyboards.reply_keyboard_remove.ReplyKeyboardRemove, pyrogram.types.bots_and_keyboards.force_reply.ForceReply] = None, progress: Callable = None, progress_args: tuple = ()) -> pyrogram.types.messages_and_media.message.Message
711,921
pyrogram.types.messages_and_media.message
reply_poll
Bound method *reply_poll* of :obj:`~pyrogram.types.Message`. Use as a shortcut for: .. code-block:: python await client.send_poll( chat_id=message.chat.id, question="This is a poll", options=["A", "B", "C] ) Example: .. code-block:: python await message.reply_poll("This is a poll", ["A", "B", "C"]) Parameters: question (``str``): Poll question, 1-255 characters. options (List of ``str``): List of answer options, 2-10 strings 1-100 characters each. is_anonymous (``bool``, *optional*): True, if the poll needs to be anonymous. Defaults to True. type (:obj`~pyrogram.enums.PollType`, *optional*): Poll type, :obj:`~pyrogram.enums.PollType.QUIZ` or :obj:`~pyrogram.enums.PollType.REGULAR`. Defaults to :obj:`~pyrogram.enums.PollType.REGULAR`. allows_multiple_answers (``bool``, *optional*): True, if the poll allows multiple answers, ignored for polls in quiz mode. Defaults to False. correct_option_id (``int``, *optional*): 0-based identifier of the correct answer option, required for polls in quiz mode. explanation (``str``, *optional*): Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters with at most 2 line feeds after entities parsing. explanation_parse_mode (:obj:`~pyrogram.enums.ParseMode`, *optional*): By default, texts are parsed using both Markdown and HTML styles. You can combine both syntaxes together. explanation_entities (List of :obj:`~pyrogram.types.MessageEntity`): List of special entities that appear in the poll explanation, which can be specified instead of *parse_mode*. open_period (``int``, *optional*): Amount of time in seconds the poll will be active after creation, 5-600. Can't be used together with *close_date*. close_date (:py:obj:`~datetime.datetime`, *optional*): Point in time when the poll will be automatically closed. Must be at least 5 and no more than 600 seconds in the future. Can't be used together with *open_period*. is_closed (``bool``, *optional*): Pass True, if the poll needs to be immediately closed. This can be useful for poll preview. quote (``bool``, *optional*): If ``True``, the message will be sent as a reply to this message. If *reply_to_message_id* is passed, this parameter will be ignored. Defaults to ``True`` in group chats and ``False`` in private chats. disable_notification (``bool``, *optional*): Sends the message silently. Users will receive a notification with no sound. protect_content (``bool``, *optional*): Protects the contents of the sent message from forwarding and saving. reply_to_message_id (``int``, *optional*): If the message is a reply, ID of the original message. schedule_date (:py:obj:`~datetime.datetime`, *optional*): Date when the message will be automatically sent. reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardRemove` | :obj:`~pyrogram.types.ForceReply`, *optional*): Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. Returns: On success, the sent :obj:`~pyrogram.types.Message` is returned. Raises: RPCError: In case of a Telegram RPC error.
@property def html(self): return Parser.unparse(self, self.entities, True)
(self, question: str, options: List[str], is_anonymous: bool = True, type: pyrogram.enums.poll_type.PollType = pyrogram.enums.PollType.REGULAR, allows_multiple_answers: bool = None, correct_option_id: int = None, explanation: str = None, explanation_parse_mode: pyrogram.enums.parse_mode.ParseMode = None, explanation_entities: List[pyrogram.types.messages_and_media.message_entity.MessageEntity] = None, open_period: int = None, close_date: datetime.datetime = None, is_closed: bool = None, quote: bool = None, disable_notification: bool = None, protect_content: bool = None, reply_to_message_id: int = None, schedule_date: datetime.datetime = None, reply_markup: Union[pyrogram.types.bots_and_keyboards.inline_keyboard_markup.InlineKeyboardMarkup, pyrogram.types.bots_and_keyboards.reply_keyboard_markup.ReplyKeyboardMarkup, pyrogram.types.bots_and_keyboards.reply_keyboard_remove.ReplyKeyboardRemove, pyrogram.types.bots_and_keyboards.force_reply.ForceReply] = None) -> pyrogram.types.messages_and_media.message.Message
711,922
pyrogram.types.messages_and_media.message
reply_sticker
Bound method *reply_sticker* of :obj:`~pyrogram.types.Message`. Use as a shortcut for: .. code-block:: python await client.send_sticker( chat_id=message.chat.id, sticker=sticker ) Example: .. code-block:: python await message.reply_sticker(sticker) Parameters: sticker (``str``): Sticker to send. Pass a file_id as string to send a sticker that exists on the Telegram servers, pass an HTTP URL as a string for Telegram to get a .webp sticker file from the Internet, or pass a file path as string to upload a new sticker that exists on your local machine. quote (``bool``, *optional*): If ``True``, the message will be sent as a reply to this message. If *reply_to_message_id* is passed, this parameter will be ignored. Defaults to ``True`` in group chats and ``False`` in private chats. disable_notification (``bool``, *optional*): Sends the message silently. Users will receive a notification with no sound. reply_to_message_id (``int``, *optional*): If the message is a reply, ID of the original message. reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardRemove` | :obj:`~pyrogram.types.ForceReply`, *optional*): Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. progress (``Callable``, *optional*): Pass a callback function to view the file transmission progress. The function must take *(current, total)* as positional arguments (look at Other Parameters below for a detailed description) and will be called back each time a new file chunk has been successfully transmitted. progress_args (``tuple``, *optional*): Extra custom arguments for the progress callback function. You can pass anything you need to be available in the progress callback scope; for example, a Message object or a Client instance in order to edit the message with the updated progress status. Other Parameters: current (``int``): The amount of bytes transmitted so far. total (``int``): The total size of the file. *args (``tuple``, *optional*): Extra custom arguments as defined in the ``progress_args`` parameter. You can either keep ``*args`` or add every single extra argument in your function signature. Returns: On success, the sent :obj:`~pyrogram.types.Message` is returned. In case the upload is deliberately stopped with :meth:`~pyrogram.Client.stop_transmission`, None is returned instead. Raises: RPCError: In case of a Telegram RPC error.
@property def html(self): return Parser.unparse(self, self.entities, True)
(self, sticker: Union[str, BinaryIO], quote: bool = None, disable_notification: bool = None, reply_to_message_id: int = None, reply_markup: Union[pyrogram.types.bots_and_keyboards.inline_keyboard_markup.InlineKeyboardMarkup, pyrogram.types.bots_and_keyboards.reply_keyboard_markup.ReplyKeyboardMarkup, pyrogram.types.bots_and_keyboards.reply_keyboard_remove.ReplyKeyboardRemove, pyrogram.types.bots_and_keyboards.force_reply.ForceReply] = None, progress: Callable = None, progress_args: tuple = ()) -> pyrogram.types.messages_and_media.message.Message
711,924
pyrogram.types.messages_and_media.message
reply_venue
Bound method *reply_venue* of :obj:`~pyrogram.types.Message`. Use as a shortcut for: .. code-block:: python await client.send_venue( chat_id=message.chat.id, latitude=latitude, longitude=longitude, title="Venue title", address="Venue address" ) Example: .. code-block:: python await message.reply_venue(latitude, longitude, "Venue title", "Venue address") Parameters: latitude (``float``): Latitude of the venue. longitude (``float``): Longitude of the venue. title (``str``): Name of the venue. address (``str``): Address of the venue. quote (``bool``, *optional*): If ``True``, the message will be sent as a reply to this message. If *reply_to_message_id* is passed, this parameter will be ignored. Defaults to ``True`` in group chats and ``False`` in private chats. foursquare_id (``str``, *optional*): Foursquare identifier of the venue. foursquare_type (``str``, *optional*): Foursquare type of the venue, if known. (For example, "arts_entertainment/default", "arts_entertainment/aquarium" or "food/icecream".) disable_notification (``bool``, *optional*): Sends the message silently. Users will receive a notification with no sound. reply_to_message_id (``int``, *optional*): If the message is a reply, ID of the original message reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardRemove` | :obj:`~pyrogram.types.ForceReply`, *optional*): Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. Returns: On success, the sent :obj:`~pyrogram.types.Message` is returned. Raises: RPCError: In case of a Telegram RPC error.
@property def html(self): return Parser.unparse(self, self.entities, True)
(self, latitude: float, longitude: float, title: str, address: str, quote: bool = None, foursquare_id: str = '', foursquare_type: str = '', disable_notification: bool = None, reply_to_message_id: int = None, reply_markup: Union[pyrogram.types.bots_and_keyboards.inline_keyboard_markup.InlineKeyboardMarkup, pyrogram.types.bots_and_keyboards.reply_keyboard_markup.ReplyKeyboardMarkup, pyrogram.types.bots_and_keyboards.reply_keyboard_remove.ReplyKeyboardRemove, pyrogram.types.bots_and_keyboards.force_reply.ForceReply] = None) -> pyrogram.types.messages_and_media.message.Message
711,925
pyrogram.types.messages_and_media.message
reply_video
Bound method *reply_video* of :obj:`~pyrogram.types.Message`. Use as a shortcut for: .. code-block:: python await client.send_video( chat_id=message.chat.id, video=video ) Example: .. code-block:: python await message.reply_video(video) Parameters: video (``str``): Video to send. Pass a file_id as string to send a video that exists on the Telegram servers, pass an HTTP URL as a string for Telegram to get a video from the Internet, or pass a file path as string to upload a new video that exists on your local machine. quote (``bool``, *optional*): If ``True``, the message will be sent as a reply to this message. If *reply_to_message_id* is passed, this parameter will be ignored. Defaults to ``True`` in group chats and ``False`` in private chats. caption (``str``, *optional*): Video caption, 0-1024 characters. parse_mode (:obj:`~pyrogram.enums.ParseMode`, *optional*): By default, texts are parsed using both Markdown and HTML styles. You can combine both syntaxes together. caption_entities (List of :obj:`~pyrogram.types.MessageEntity`): List of special entities that appear in the caption, which can be specified instead of *parse_mode*. has_spoiler (``bool``, *optional*): Pass True if the video needs to be covered with a spoiler animation. ttl_seconds (``int``, *optional*): Self-Destruct Timer. If you set a timer, the video will self-destruct in *ttl_seconds* seconds after it was viewed. duration (``int``, *optional*): Duration of sent video in seconds. width (``int``, *optional*): Video width. height (``int``, *optional*): Video height. thumb (``str``, *optional*): Thumbnail of the video sent. The thumbnail should be in JPEG format and less than 200 KB in size. A thumbnail's width and height should not exceed 320 pixels. Thumbnails can't be reused and can be only uploaded as a new file. supports_streaming (``bool``, *optional*): Pass True, if the uploaded video is suitable for streaming. disable_notification (``bool``, *optional*): Sends the message silently. Users will receive a notification with no sound. reply_to_message_id (``int``, *optional*): If the message is a reply, ID of the original message. reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardRemove` | :obj:`~pyrogram.types.ForceReply`, *optional*): Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. progress (``Callable``, *optional*): Pass a callback function to view the file transmission progress. The function must take *(current, total)* as positional arguments (look at Other Parameters below for a detailed description) and will be called back each time a new file chunk has been successfully transmitted. progress_args (``tuple``, *optional*): Extra custom arguments for the progress callback function. You can pass anything you need to be available in the progress callback scope; for example, a Message object or a Client instance in order to edit the message with the updated progress status. Other Parameters: current (``int``): The amount of bytes transmitted so far. total (``int``): The total size of the file. *args (``tuple``, *optional*): Extra custom arguments as defined in the ``progress_args`` parameter. You can either keep ``*args`` or add every single extra argument in your function signature. Returns: On success, the sent :obj:`~pyrogram.types.Message` is returned. In case the upload is deliberately stopped with :meth:`~pyrogram.Client.stop_transmission`, None is returned instead. Raises: RPCError: In case of a Telegram RPC error.
@property def html(self): return Parser.unparse(self, self.entities, True)
(self, video: Union[str, BinaryIO], quote: bool = None, caption: str = '', parse_mode: Optional[pyrogram.enums.parse_mode.ParseMode] = None, caption_entities: List[pyrogram.types.messages_and_media.message_entity.MessageEntity] = None, has_spoiler: bool = None, ttl_seconds: int = None, duration: int = 0, width: int = 0, height: int = 0, thumb: str = None, supports_streaming: bool = True, disable_notification: bool = None, reply_to_message_id: int = None, reply_markup: Union[pyrogram.types.bots_and_keyboards.inline_keyboard_markup.InlineKeyboardMarkup, pyrogram.types.bots_and_keyboards.reply_keyboard_markup.ReplyKeyboardMarkup, pyrogram.types.bots_and_keyboards.reply_keyboard_remove.ReplyKeyboardRemove, pyrogram.types.bots_and_keyboards.force_reply.ForceReply] = None, progress: Callable = None, progress_args: tuple = ()) -> pyrogram.types.messages_and_media.message.Message
711,926
pyrogram.types.messages_and_media.message
reply_video_note
Bound method *reply_video_note* of :obj:`~pyrogram.types.Message`. Use as a shortcut for: .. code-block:: python await client.send_video_note( chat_id=message.chat.id, video_note=video_note ) Example: .. code-block:: python await message.reply_video_note(video_note) Parameters: video_note (``str``): Video note to send. Pass a file_id as string to send a video note that exists on the Telegram servers, or pass a file path as string to upload a new video note that exists on your local machine. Sending video notes by a URL is currently unsupported. quote (``bool``, *optional*): If ``True``, the message will be sent as a reply to this message. If *reply_to_message_id* is passed, this parameter will be ignored. Defaults to ``True`` in group chats and ``False`` in private chats. duration (``int``, *optional*): Duration of sent video in seconds. length (``int``, *optional*): Video width and height. thumb (``str``, *optional*): Thumbnail of the video sent. The thumbnail should be in JPEG format and less than 200 KB in size. A thumbnail's width and height should not exceed 320 pixels. Thumbnails can't be reused and can be only uploaded as a new file. disable_notification (``bool``, *optional*): Sends the message silently. Users will receive a notification with no sound. reply_to_message_id (``int``, *optional*): If the message is a reply, ID of the original message reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardRemove` | :obj:`~pyrogram.types.ForceReply`, *optional*): Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. progress (``Callable``, *optional*): Pass a callback function to view the file transmission progress. The function must take *(current, total)* as positional arguments (look at Other Parameters below for a detailed description) and will be called back each time a new file chunk has been successfully transmitted. progress_args (``tuple``, *optional*): Extra custom arguments for the progress callback function. You can pass anything you need to be available in the progress callback scope; for example, a Message object or a Client instance in order to edit the message with the updated progress status. Other Parameters: current (``int``): The amount of bytes transmitted so far. total (``int``): The total size of the file. *args (``tuple``, *optional*): Extra custom arguments as defined in the ``progress_args`` parameter. You can either keep ``*args`` or add every single extra argument in your function signature. Returns: On success, the sent :obj:`~pyrogram.types.Message` is returned. In case the upload is deliberately stopped with :meth:`~pyrogram.Client.stop_transmission`, None is returned instead. Raises: RPCError: In case of a Telegram RPC error.
@property def html(self): return Parser.unparse(self, self.entities, True)
(self, video_note: Union[str, BinaryIO], quote: bool = None, duration: int = 0, length: int = 1, thumb: str = None, disable_notification: bool = None, reply_to_message_id: int = None, reply_markup: Union[pyrogram.types.bots_and_keyboards.inline_keyboard_markup.InlineKeyboardMarkup, pyrogram.types.bots_and_keyboards.reply_keyboard_markup.ReplyKeyboardMarkup, pyrogram.types.bots_and_keyboards.reply_keyboard_remove.ReplyKeyboardRemove, pyrogram.types.bots_and_keyboards.force_reply.ForceReply] = None, progress: Callable = None, progress_args: tuple = ()) -> pyrogram.types.messages_and_media.message.Message
711,927
pyrogram.types.messages_and_media.message
reply_voice
Bound method *reply_voice* of :obj:`~pyrogram.types.Message`. Use as a shortcut for: .. code-block:: python await client.send_voice( chat_id=message.chat.id, voice=voice ) Example: .. code-block:: python await message.reply_voice(voice) Parameters: voice (``str``): Audio file to send. Pass a file_id as string to send an audio that exists on the Telegram servers, pass an HTTP URL as a string for Telegram to get an audio from the Internet, or pass a file path as string to upload a new audio that exists on your local machine. quote (``bool``, *optional*): If ``True``, the message will be sent as a reply to this message. If *reply_to_message_id* is passed, this parameter will be ignored. Defaults to ``True`` in group chats and ``False`` in private chats. caption (``str``, *optional*): Voice message caption, 0-1024 characters. parse_mode (:obj:`~pyrogram.enums.ParseMode`, *optional*): By default, texts are parsed using both Markdown and HTML styles. You can combine both syntaxes together. caption_entities (List of :obj:`~pyrogram.types.MessageEntity`): List of special entities that appear in the caption, which can be specified instead of *parse_mode*. duration (``int``, *optional*): Duration of the voice message in seconds. disable_notification (``bool``, *optional*): Sends the message silently. Users will receive a notification with no sound. reply_to_message_id (``int``, *optional*): If the message is a reply, ID of the original message reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardRemove` | :obj:`~pyrogram.types.ForceReply`, *optional*): Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. progress (``Callable``, *optional*): Pass a callback function to view the file transmission progress. The function must take *(current, total)* as positional arguments (look at Other Parameters below for a detailed description) and will be called back each time a new file chunk has been successfully transmitted. progress_args (``tuple``, *optional*): Extra custom arguments for the progress callback function. You can pass anything you need to be available in the progress callback scope; for example, a Message object or a Client instance in order to edit the message with the updated progress status. Other Parameters: current (``int``): The amount of bytes transmitted so far. total (``int``): The total size of the file. *args (``tuple``, *optional*): Extra custom arguments as defined in the ``progress_args`` parameter. You can either keep ``*args`` or add every single extra argument in your function signature. Returns: On success, the sent :obj:`~pyrogram.types.Message` is returned. In case the upload is deliberately stopped with :meth:`~pyrogram.Client.stop_transmission`, None is returned instead. Raises: RPCError: In case of a Telegram RPC error.
@property def html(self): return Parser.unparse(self, self.entities, True)
(self, voice: Union[str, BinaryIO], quote: bool = None, caption: str = '', parse_mode: Optional[pyrogram.enums.parse_mode.ParseMode] = None, caption_entities: List[pyrogram.types.messages_and_media.message_entity.MessageEntity] = None, duration: int = 0, disable_notification: bool = None, reply_to_message_id: int = None, reply_markup: Union[pyrogram.types.bots_and_keyboards.inline_keyboard_markup.InlineKeyboardMarkup, pyrogram.types.bots_and_keyboards.reply_keyboard_markup.ReplyKeyboardMarkup, pyrogram.types.bots_and_keyboards.reply_keyboard_remove.ReplyKeyboardRemove, pyrogram.types.bots_and_keyboards.force_reply.ForceReply] = None, progress: Callable = None, progress_args: tuple = ()) -> pyrogram.types.messages_and_media.message.Message
711,928
pyrogram.types.messages_and_media.message
retract_vote
Bound method *retract_vote* of :obj:`~pyrogram.types.Message`. Use as a shortcut for: .. code-block:: python client.retract_vote( chat_id=message.chat.id, message_id=message_id, ) Example: .. code-block:: python message.retract_vote() Returns: :obj:`~pyrogram.types.Poll`: On success, the poll with the retracted vote is returned. Raises: RPCError: In case of a Telegram RPC error.
@property def html(self): return Parser.unparse(self, self.entities, True)
(self) -> pyrogram.types.messages_and_media.poll.Poll
711,929
pyrogram.types.update
stop_propagation
null
def stop_propagation(self): raise pyrogram.StopPropagation
(self)
711,930
pyrogram.types.messages_and_media.message
unpin
Bound method *unpin* of :obj:`~pyrogram.types.Message`. Use as a shortcut for: .. code-block:: python await client.unpin_chat_message( chat_id=message.chat.id, message_id=message_id ) Example: .. code-block:: python await message.unpin() Returns: True on success. Raises: RPCError: In case of a Telegram RPC error.
@property def html(self): return Parser.unparse(self, self.entities, True)
(self) -> bool
711,931
pyrogram.types.messages_and_media.message
vote
Bound method *vote* of :obj:`~pyrogram.types.Message`. Use as a shortcut for: .. code-block:: python client.vote_poll( chat_id=message.chat.id, message_id=message.id, option=1 ) Example: .. code-block:: python message.vote(6) Parameters: option (``int``): Index of the poll option you want to vote for (0 to 9). Returns: :obj:`~pyrogram.types.Poll`: On success, the poll with the chosen option is returned. Raises: RPCError: In case of a Telegram RPC error.
@property def html(self): return Parser.unparse(self, self.entities, True)
(self, option: int) -> pyrogram.types.messages_and_media.poll.Poll
711,933
pyromod.listen.message_handler
MessageHandler
null
class MessageHandler(pyrogram.handlers.message_handler.MessageHandler): filters: Filter old__init__: Callable @should_patch() def __init__(self, callback: Callable, filters: Filter = None): self.original_callback = callback self.old__init__(self.resolve_future_or_callback, filters) @should_patch() async def check_if_has_matching_listener(self, client: Client, message: Message): from_user = message.from_user from_user_id = from_user.id if from_user else None from_user_username = from_user.username if from_user else None message_id = getattr(message, "id", getattr(message, "message_id", None)) data = Identifier( message_id=message_id, chat_id=[message.chat.id, message.chat.username], from_user_id=[from_user_id, from_user_username], ) listener = client.get_listener_matching_with_data(data, ListenerTypes.MESSAGE) listener_does_match = False if listener: filters = listener.filters if callable(filters): if iscoroutinefunction(filters.__call__): listener_does_match = await filters(client, message) else: listener_does_match = await client.loop.run_in_executor( None, filters, client, message ) else: listener_does_match = True return listener_does_match, listener @should_patch() async def check(self, client: Client, message: Message): listener_does_match = ( await self.check_if_has_matching_listener(client, message) )[0] if callable(self.filters): if iscoroutinefunction(self.filters.__call__): handler_does_match = await self.filters(client, message) else: handler_does_match = await client.loop.run_in_executor( None, self.filters, client, message ) else: handler_does_match = True # let handler get the chance to handle if listener # exists but its filters doesn't match return listener_does_match or handler_does_match @should_patch() async def resolve_future_or_callback(self, client: Client, message: Message, *args): listener_does_match, listener = await self.check_if_has_matching_listener( client, message ) if listener and listener_does_match: client.remove_listener(listener) if listener.future and not listener.future.done(): listener.future.set_result(message) raise pyrogram.StopPropagation elif listener.callback: if iscoroutinefunction(listener.callback): await listener.callback(client, message, *args) else: listener.callback(client, message, *args) raise pyrogram.StopPropagation else: raise ValueError("Listener must have either a future or a callback") else: await self.original_callback(client, message, *args)
(callback: Callable, filters: pyrogram.filters.Filter = None)
711,934
pyromod.listen.message_handler
__init__
null
@should_patch() async def check_if_has_matching_listener(self, client: Client, message: Message): from_user = message.from_user from_user_id = from_user.id if from_user else None from_user_username = from_user.username if from_user else None message_id = getattr(message, "id", getattr(message, "message_id", None)) data = Identifier( message_id=message_id, chat_id=[message.chat.id, message.chat.username], from_user_id=[from_user_id, from_user_username], ) listener = client.get_listener_matching_with_data(data, ListenerTypes.MESSAGE) listener_does_match = False if listener: filters = listener.filters if callable(filters): if iscoroutinefunction(filters.__call__): listener_does_match = await filters(client, message) else: listener_does_match = await client.loop.run_in_executor( None, filters, client, message ) else: listener_does_match = True return listener_does_match, listener
(self, callback: Callable, filters: pyrogram.filters.Filter = None)
711,940
pyromod.nav.pagination
Pagination
null
class Pagination: def __init__(self, objects, page_data=None, item_data=None, item_title=None): def default_page_callback(x): return str(x) def default_item_callback(i, pg): return f"[{pg}] {i}" self.objects = objects self.page_data = page_data or default_page_callback self.item_data = item_data or default_item_callback self.item_title = item_title or default_item_callback def create(self, page, lines=5, columns=1): quant_per_page = lines * columns page = 1 if page <= 0 else page offset = (page - 1) * quant_per_page stop = offset + quant_per_page cutted = self.objects[offset:stop] total = len(self.objects) pages_range = [ *range(1, math.ceil(total / quant_per_page) + 1) ] # each item is a page last_page = len(pages_range) nav = [] if page <= 3: for n in [1, 2, 3]: if n not in pages_range: continue text = f"· {n} ·" if n == page else n nav.append((text, self.page_data(n))) if last_page >= 4: nav.append(("4 ›" if last_page > 5 else 4, self.page_data(4))) if last_page > 4: nav.append( ( f"{last_page} »" if last_page > 5 else last_page, self.page_data(last_page), ) ) elif page >= last_page - 2: nav.extend( [ ("« 1" if last_page - 4 > 1 else 1, self.page_data(1)), ( f"‹ {last_page - 3}" if last_page - 4 > 1 else last_page - 3, self.page_data(last_page - 3), ), ] ) for n in range(last_page - 2, last_page + 1): text = f"· {n} ·" if n == page else n nav.append((text, self.page_data(n))) else: nav = [ ("« 1", self.page_data(1)), (f"‹ {page - 1}", self.page_data(page - 1)), (f"· {page} ·", "noop"), (f"{page + 1} ›", self.page_data(page + 1)), (f"{last_page} »", self.page_data(last_page)), ] buttons = [] for item in cutted: buttons.append((self.item_title(item, page), self.item_data(item, page))) kb_lines = array_chunk(buttons, columns) if last_page > 1: kb_lines.append(nav) return kb_lines
(objects, page_data=None, item_data=None, item_title=None)
711,941
pyromod.nav.pagination
__init__
null
def __init__(self, objects, page_data=None, item_data=None, item_title=None): def default_page_callback(x): return str(x) def default_item_callback(i, pg): return f"[{pg}] {i}" self.objects = objects self.page_data = page_data or default_page_callback self.item_data = item_data or default_item_callback self.item_title = item_title or default_item_callback
(self, objects, page_data=None, item_data=None, item_title=None)
711,942
pyromod.nav.pagination
create
null
def create(self, page, lines=5, columns=1): quant_per_page = lines * columns page = 1 if page <= 0 else page offset = (page - 1) * quant_per_page stop = offset + quant_per_page cutted = self.objects[offset:stop] total = len(self.objects) pages_range = [ *range(1, math.ceil(total / quant_per_page) + 1) ] # each item is a page last_page = len(pages_range) nav = [] if page <= 3: for n in [1, 2, 3]: if n not in pages_range: continue text = f"· {n} ·" if n == page else n nav.append((text, self.page_data(n))) if last_page >= 4: nav.append(("4 ›" if last_page > 5 else 4, self.page_data(4))) if last_page > 4: nav.append( ( f"{last_page} »" if last_page > 5 else last_page, self.page_data(last_page), ) ) elif page >= last_page - 2: nav.extend( [ ("« 1" if last_page - 4 > 1 else 1, self.page_data(1)), ( f"‹ {last_page - 3}" if last_page - 4 > 1 else last_page - 3, self.page_data(last_page - 3), ), ] ) for n in range(last_page - 2, last_page + 1): text = f"· {n} ·" if n == page else n nav.append((text, self.page_data(n))) else: nav = [ ("« 1", self.page_data(1)), (f"‹ {page - 1}", self.page_data(page - 1)), (f"· {page} ·", "noop"), (f"{page + 1} ›", self.page_data(page + 1)), (f"{last_page} »", self.page_data(last_page)), ] buttons = [] for item in cutted: buttons.append((self.item_title(item, page), self.item_data(item, page))) kb_lines = array_chunk(buttons, columns) if last_page > 1: kb_lines.append(nav) return kb_lines
(self, page, lines=5, columns=1)
711,943
pyromod.listen.user
User
null
class User(pyrogram.types.user_and_chats.user.User): _client: Client @should_patch() def listen(self, *args, **kwargs): return self._client.listen(*args, user_id=self.id, **kwargs) @should_patch() def ask(self, text, *args, **kwargs): return self._client.ask(self.id, text, *args, user_id=self.id, **kwargs) @should_patch() def stop_listening(self, *args, **kwargs): return self._client.stop_listening(*args, user_id=self.id, **kwargs)
(*, client: 'pyrogram.Client' = None, id: int, is_self: bool = None, is_contact: bool = None, is_mutual_contact: bool = None, is_deleted: bool = None, is_bot: bool = None, is_verified: bool = None, is_restricted: bool = None, is_scam: bool = None, is_fake: bool = None, is_support: bool = None, is_premium: bool = None, first_name: str = None, last_name: str = None, status: 'enums.UserStatus' = None, last_online_date: datetime.datetime = None, next_offline_date: datetime.datetime = None, username: str = None, language_code: str = None, emoji_status: Optional[ForwardRef('types.EmojiStatus')] = None, dc_id: int = None, phone_number: str = None, photo: 'types.ChatPhoto' = None, restrictions: List[ForwardRef('types.Restriction')] = None)
711,946
pyrogram.types.user_and_chats.user
__init__
null
def __init__( self, *, client: "pyrogram.Client" = None, id: int, is_self: bool = None, is_contact: bool = None, is_mutual_contact: bool = None, is_deleted: bool = None, is_bot: bool = None, is_verified: bool = None, is_restricted: bool = None, is_scam: bool = None, is_fake: bool = None, is_support: bool = None, is_premium: bool = None, first_name: str = None, last_name: str = None, status: "enums.UserStatus" = None, last_online_date: datetime = None, next_offline_date: datetime = None, username: str = None, language_code: str = None, emoji_status: Optional["types.EmojiStatus"] = None, dc_id: int = None, phone_number: str = None, photo: "types.ChatPhoto" = None, restrictions: List["types.Restriction"] = None ): super().__init__(client) self.id = id self.is_self = is_self self.is_contact = is_contact self.is_mutual_contact = is_mutual_contact self.is_deleted = is_deleted self.is_bot = is_bot self.is_verified = is_verified self.is_restricted = is_restricted self.is_scam = is_scam self.is_fake = is_fake self.is_support = is_support self.is_premium = is_premium self.first_name = first_name self.last_name = last_name self.status = status self.last_online_date = last_online_date self.next_offline_date = next_offline_date self.username = username self.language_code = language_code self.emoji_status = emoji_status self.dc_id = dc_id self.phone_number = phone_number self.photo = photo self.restrictions = restrictions
(self, *, client: Optional[pyrogram.client.Client] = None, id: int, is_self: Optional[bool] = None, is_contact: Optional[bool] = None, is_mutual_contact: Optional[bool] = None, is_deleted: Optional[bool] = None, is_bot: Optional[bool] = None, is_verified: Optional[bool] = None, is_restricted: Optional[bool] = None, is_scam: Optional[bool] = None, is_fake: Optional[bool] = None, is_support: Optional[bool] = None, is_premium: Optional[bool] = None, first_name: Optional[str] = None, last_name: Optional[str] = None, status: Optional[pyrogram.enums.user_status.UserStatus] = None, last_online_date: Optional[datetime.datetime] = None, next_offline_date: Optional[datetime.datetime] = None, username: Optional[str] = None, language_code: Optional[str] = None, emoji_status: Optional[pyrogram.types.user_and_chats.emoji_status.EmojiStatus] = None, dc_id: Optional[int] = None, phone_number: Optional[str] = None, photo: Optional[pyrogram.types.user_and_chats.chat_photo.ChatPhoto] = None, restrictions: Optional[List[pyrogram.types.user_and_chats.restriction.Restriction]] = None)
711,950
pyrogram.types.user_and_chats.user
_parse
null
@staticmethod def _parse(client, user: "raw.base.User") -> Optional["User"]: if user is None or isinstance(user, raw.types.UserEmpty): return None return User( id=user.id, is_self=user.is_self, is_contact=user.contact, is_mutual_contact=user.mutual_contact, is_deleted=user.deleted, is_bot=user.bot, is_verified=user.verified, is_restricted=user.restricted, is_scam=user.scam, is_fake=user.fake, is_support=user.support, is_premium=user.premium, first_name=user.first_name, last_name=user.last_name, **User._parse_status(user.status, user.bot), username=user.username, language_code=user.lang_code, emoji_status=types.EmojiStatus._parse(client, user.emoji_status), dc_id=getattr(user.photo, "dc_id", None), phone_number=user.phone, photo=types.ChatPhoto._parse(client, user.photo, user.id, user.access_hash), restrictions=types.List([types.Restriction._parse(r) for r in user.restriction_reason]) or None, client=client )
(client, user: pyrogram.raw.base.user.User) -> Optional[pyrogram.types.user_and_chats.user.User]
711,951
pyrogram.types.user_and_chats.user
_parse_status
null
@staticmethod def _parse_status(user_status: "raw.base.UserStatus", is_bot: bool = False): if isinstance(user_status, raw.types.UserStatusOnline): status, date = enums.UserStatus.ONLINE, user_status.expires elif isinstance(user_status, raw.types.UserStatusOffline): status, date = enums.UserStatus.OFFLINE, user_status.was_online elif isinstance(user_status, raw.types.UserStatusRecently): status, date = enums.UserStatus.RECENTLY, None elif isinstance(user_status, raw.types.UserStatusLastWeek): status, date = enums.UserStatus.LAST_WEEK, None elif isinstance(user_status, raw.types.UserStatusLastMonth): status, date = enums.UserStatus.LAST_MONTH, None else: status, date = enums.UserStatus.LONG_AGO, None last_online_date = None next_offline_date = None if is_bot: status = None if status == enums.UserStatus.ONLINE: next_offline_date = utils.timestamp_to_datetime(date) if status == enums.UserStatus.OFFLINE: last_online_date = utils.timestamp_to_datetime(date) return { "status": status, "last_online_date": last_online_date, "next_offline_date": next_offline_date }
(user_status: pyrogram.raw.base.user_status.UserStatus, is_bot: bool = False)
711,952
pyrogram.types.user_and_chats.user
_parse_user_status
null
@staticmethod def _parse_user_status(client, user_status: "raw.types.UpdateUserStatus"): return User( id=user_status.user_id, **User._parse_status(user_status.status), client=client )
(client, user_status: pyrogram.raw.types.update_user_status.UpdateUserStatus)
711,953
pyrogram.types.user_and_chats.user
archive
Bound method *archive* of :obj:`~pyrogram.types.User`. Use as a shortcut for: .. code-block:: python await client.archive_chats(123456789) Example: .. code-block:: python await user.archive() Returns: True on success. Raises: RPCError: In case of a Telegram RPC error.
@staticmethod def format(url: str, text: str, style: enums.ParseMode): if style == enums.ParseMode.MARKDOWN: fmt = Link.MARKDOWN else: fmt = Link.HTML return fmt.format(url=url, text=html.escape(text))
(self)
711,956
pyrogram.types.user_and_chats.user
block
Bound method *block* of :obj:`~pyrogram.types.User`. Use as a shortcut for: .. code-block:: python await client.block_user(123456789) Example: .. code-block:: python await user.block() Returns: True on success. Raises: RPCError: In case of a Telegram RPC error.
def block(self): """Bound method *block* of :obj:`~pyrogram.types.User`. Use as a shortcut for: .. code-block:: python await client.block_user(123456789) Example: .. code-block:: python await user.block() Returns: True on success. Raises: RPCError: In case of a Telegram RPC error. """ return self._client.block_user(self.id)
(self)
711,959
pyrogram.types.user_and_chats.user
get_common_chats
Bound method *get_common_chats* of :obj:`~pyrogram.types.User`. Use as a shortcut for: .. code-block:: python client.get_common_chats(123456789) Example: .. code-block:: python user.get_common_chats() Returns: True on success. Raises: RPCError: In case of a Telegram RPC error.
def get_common_chats(self): """Bound method *get_common_chats* of :obj:`~pyrogram.types.User`. Use as a shortcut for: .. code-block:: python client.get_common_chats(123456789) Example: .. code-block:: python user.get_common_chats() Returns: True on success. Raises: RPCError: In case of a Telegram RPC error. """ return self._client.get_common_chats(self.id)
(self)
711,963
pyrogram.types.user_and_chats.user
unarchive
Bound method *unarchive* of :obj:`~pyrogram.types.User`. Use as a shortcut for: .. code-block:: python await client.unarchive_chats(123456789) Example: .. code-block:: python await user.unarchive() Returns: True on success. Raises: RPCError: In case of a Telegram RPC error.
@staticmethod def format(url: str, text: str, style: enums.ParseMode): if style == enums.ParseMode.MARKDOWN: fmt = Link.MARKDOWN else: fmt = Link.HTML return fmt.format(url=url, text=html.escape(text))
(self)
711,964
pyrogram.types.user_and_chats.user
unblock
Bound method *unblock* of :obj:`~pyrogram.types.User`. Use as a shortcut for: .. code-block:: python client.unblock_user(123456789) Example: .. code-block:: python user.unblock() Returns: True on success. Raises: RPCError: In case of a Telegram RPC error.
def unblock(self): """Bound method *unblock* of :obj:`~pyrogram.types.User`. Use as a shortcut for: .. code-block:: python client.unblock_user(123456789) Example: .. code-block:: python user.unblock() Returns: True on success. Raises: RPCError: In case of a Telegram RPC error. """ return self._client.unblock_user(self.id)
(self)
711,965
pyromod.helpers.helpers
array_chunk
null
def array_chunk(input_array, size): return [input_array[i : i + size] for i in range(0, len(input_array), size)]
(input_array, size)
711,966
pyromod.helpers.helpers
bki
null
def bki(keyboard): lines = [] for row in keyboard.inline_keyboard: line = [] for button in row: button = ntb(button) # btn() format line.append(button) lines.append(line) return lines # return ikb() format
(keyboard)
711,967
pyromod.helpers.helpers
btn
null
def btn(text, value, type="callback_data"): return InlineKeyboardButton(text, **{type: value}) # return {'text': text, type: value}
(text, value, type='callback_data')
711,969
pyromod.helpers.helpers
force_reply
null
def force_reply(selective=True): return ForceReply(selective=selective)
(selective=True)
711,971
pyromod.helpers.helpers
ikb
null
def ikb(rows=None): if rows is None: rows = [] lines = [] for row in rows: line = [] for button in row: button = ( btn(button, button) if isinstance(button, str) else btn(*button) ) # InlineKeyboardButton line.append(button) lines.append(line) return InlineKeyboardMarkup(inline_keyboard=lines) # return {'inline_keyboard': lines}
(rows=None)
711,972
pyromod.helpers.helpers
kb
null
def kb(rows=None, **kwargs): if rows is None: rows = [] lines = [] for row in rows: line = [] for button in row: button_type = type(button) if button_type == str: button = KeyboardButton(button) elif button_type == dict: button = KeyboardButton(**button) line.append(button) lines.append(line) return ReplyKeyboardMarkup(keyboard=lines, **kwargs)
(rows=None, **kwargs)
711,973
pyrogram.types.bots_and_keyboards.keyboard_button
KeyboardButton
One button of the reply keyboard. For simple text buttons String can be used instead of this object to specify text of the button. Optional fields are mutually exclusive. Parameters: text (``str``): Text of the button. If none of the optional fields are used, it will be sent as a message when the button is pressed. request_contact (``bool``, *optional*): If True, the user's phone number will be sent as a contact when the button is pressed. Available in private chats only. request_location (``bool``, *optional*): If True, the user's current location will be sent when the button is pressed. Available in private chats only. web_app (:obj:`~pyrogram.types.WebAppInfo`, *optional*): If specified, the described `Web App <https://core.telegram.org/bots/webapps>`_ will be launched when the button is pressed. The Web App will be able to send a “web_app_data” service message. Available in private chats only.
class KeyboardButton(Object): """One button of the reply keyboard. For simple text buttons String can be used instead of this object to specify text of the button. Optional fields are mutually exclusive. Parameters: text (``str``): Text of the button. If none of the optional fields are used, it will be sent as a message when the button is pressed. request_contact (``bool``, *optional*): If True, the user's phone number will be sent as a contact when the button is pressed. Available in private chats only. request_location (``bool``, *optional*): If True, the user's current location will be sent when the button is pressed. Available in private chats only. web_app (:obj:`~pyrogram.types.WebAppInfo`, *optional*): If specified, the described `Web App <https://core.telegram.org/bots/webapps>`_ will be launched when the button is pressed. The Web App will be able to send a “web_app_data” service message. Available in private chats only. """ def __init__( self, text: str, request_contact: bool = None, request_location: bool = None, web_app: "types.WebAppInfo" = None ): super().__init__() self.text = str(text) self.request_contact = request_contact self.request_location = request_location self.web_app = web_app @staticmethod def read(b): if isinstance(b, raw.types.KeyboardButton): return b.text if isinstance(b, raw.types.KeyboardButtonRequestPhone): return KeyboardButton( text=b.text, request_contact=True ) if isinstance(b, raw.types.KeyboardButtonRequestGeoLocation): return KeyboardButton( text=b.text, request_location=True ) if isinstance(b, raw.types.KeyboardButtonSimpleWebView): return KeyboardButton( text=b.text, web_app=types.WebAppInfo( url=b.url ) ) def write(self): if self.request_contact: return raw.types.KeyboardButtonRequestPhone(text=self.text) elif self.request_location: return raw.types.KeyboardButtonRequestGeoLocation(text=self.text) elif self.web_app: return raw.types.KeyboardButtonSimpleWebView(text=self.text, url=self.web_app.url) else: return raw.types.KeyboardButton(text=self.text)
(text: str, request_contact: bool = None, request_location: bool = None, web_app: 'types.WebAppInfo' = None)
711,976
pyrogram.types.bots_and_keyboards.keyboard_button
__init__
null
def __init__( self, text: str, request_contact: bool = None, request_location: bool = None, web_app: "types.WebAppInfo" = None ): super().__init__() self.text = str(text) self.request_contact = request_contact self.request_location = request_location self.web_app = web_app
(self, text: str, request_contact: Optional[bool] = None, request_location: Optional[bool] = None, web_app: Optional[pyrogram.types.bots_and_keyboards.web_app_info.WebAppInfo] = None)
711,982
pyrogram.types.bots_and_keyboards.keyboard_button
read
null
@staticmethod def read(b): if isinstance(b, raw.types.KeyboardButton): return b.text if isinstance(b, raw.types.KeyboardButtonRequestPhone): return KeyboardButton( text=b.text, request_contact=True ) if isinstance(b, raw.types.KeyboardButtonRequestGeoLocation): return KeyboardButton( text=b.text, request_location=True ) if isinstance(b, raw.types.KeyboardButtonSimpleWebView): return KeyboardButton( text=b.text, web_app=types.WebAppInfo( url=b.url ) )
(b)
711,983
pyrogram.types.bots_and_keyboards.keyboard_button
write
null
def write(self): if self.request_contact: return raw.types.KeyboardButtonRequestPhone(text=self.text) elif self.request_location: return raw.types.KeyboardButtonRequestGeoLocation(text=self.text) elif self.web_app: return raw.types.KeyboardButtonSimpleWebView(text=self.text, url=self.web_app.url) else: return raw.types.KeyboardButton(text=self.text)
(self)
711,986
pyromod.helpers.helpers
ntb
null
def ntb(button): for btn_type in [ "callback_data", "url", "switch_inline_query", "switch_inline_query_current_chat", "callback_game", ]: value = getattr(button, btn_type) if value: break button = [button.text, value] if btn_type != "callback_data": button.append(btn_type) return button # return {'text': text, type: value}
(button)
711,987
pyromod.utils.patch
patch_into
null
def patch_into(target_class): def is_patchable(item): func = item[1] return getattr(func, "should_patch", False) def wrapper(container: Type[T]) -> T: for name, func in filter(is_patchable, container.__dict__.items()): old = getattr(target_class, name, None) if old is not None: # Not adding 'old' to new func setattr(target_class, "old" + name, old) # Worse Code tempConf = { i: getattr(func, i, False) for i in ["is_property", "is_static", "is_context"] } async_to_sync(container, name) func = getattr(container, name) for tKey, tValue in tempConf.items(): setattr(func, tKey, tValue) if func.is_property: func = property(func) elif func.is_static: func = staticmethod(func) elif func.is_context: if iscoroutinefunction(func.__call__): func = asynccontextmanager(func) else: func = contextmanager(func) setattr(target_class, name, func) return container return wrapper
(target_class)
711,988
pyromod.utils.patch
should_patch
A decorator that marks a function as patchable. Usage: @patchable(is_property=True) def my_property(): ... @patchable(is_static=True) def my_static_method(): ... @patchable(is_context=True) def my_context_manager(): ... @patchable(is_property=False, is_static=False, is_context=False) def my_function(): ... @patchable() def default_usage(): ... Parameters: - is_property (bool): whether the function is a property. Default is False. - is_static (bool): whether the function is a static method. Default is False. - is_context (bool): whether the function is a context manager. Default is False. Returns: - A callable object that marks the function as patchable.
def should_patch( is_property: bool = False, is_static: bool = False, is_context: bool = False ) -> Callable: """ A decorator that marks a function as patchable. Usage: @patchable(is_property=True) def my_property(): ... @patchable(is_static=True) def my_static_method(): ... @patchable(is_context=True) def my_context_manager(): ... @patchable(is_property=False, is_static=False, is_context=False) def my_function(): ... @patchable() def default_usage(): ... Parameters: - is_property (bool): whether the function is a property. Default is False. - is_static (bool): whether the function is a static method. Default is False. - is_context (bool): whether the function is a context manager. Default is False. Returns: - A callable object that marks the function as patchable. """ def wrapper(func: Callable) -> Callable: func.should_patch = True func.is_property = is_property func.is_static = is_static func.is_context = is_context return func return wrapper
(is_property: bool = False, is_static: bool = False, is_context: bool = False) -> Callable
711,991
acachecontrol.cache
AsyncCache
Asynchronous Cache implementation. Current implementation is a wrapper over OrderedDict object, implements LRU cache. Supports any OrderedDict-like object as cache_backend. Key: Tuple(http_method, url), value: aiohttp response obj
class AsyncCache: """Asynchronous Cache implementation. Current implementation is a wrapper over OrderedDict object, implements LRU cache. Supports any OrderedDict-like object as cache_backend. Key: Tuple(http_method, url), value: aiohttp response obj """ def __init__(self, config: Dict = None, cache_backend=None): self.cache = ( cache_backend if cache_backend is not None else OrderedDict() ) config = config or {} self._wait_until_completed = set() # type: Set self.default_max_age = config.get("max_age", DEFAULT_MAX_AGE) self.sleep_time = config.get("sleep_time", DEFAULT_SLEEP_TIME) self.cacheable_methods = config.get( "cacheable_methods", CACHEABLE_METHODS ) self.capacity = config.get("capacity", DEFAULT_CACHE_CAPACITY) def has_valid_entry(self, key: Tuple[str, str]) -> bool: """Check if entry exists and not expired, delete expired.""" if key in self.cache: if not self.is_cache_entry_expired(key): return True logger.debug(f"Cache entry is expired for {key} key") self.delete(key) return False def add(self, key: Tuple[str, str], value: Any, headers: Any) -> None: """Add value to the cache. headers - any dict-like obj """ cc_header = self.parse_cache_control_header(headers) if self._is_response_cacheable(key[0], cc_header): self.cache[key] = { "created_at": time.time(), "max-age": cc_header.get("max-age", self.default_max_age), "value": value, } self.cache.move_to_end(key) if len(self.cache) > self.capacity: self.cache.popitem(last=False) self.release_new_key(key) logger.debug(f"Added a new entry to cache for {key} key") def get(self, key: Tuple[str, str]) -> Any: """Get entry from cache.""" try: cache_entry = self.cache.get(key) if cache_entry: logger.debug(f"Get entry from cache for {key} key") self.cache.move_to_end(key) return cache_entry["value"] raise CacheException(f"No cache entry for {key} key") except Exception: raise CacheException( f"Error getting value from cache for {key} key" ) def delete(self, key: Tuple[str, str]) -> None: """Delete entry from cache.""" logger.debug(f"Delete entry from cache for {key} key") self.cache.pop(key, None) def clear_cache(self) -> None: """Delete everything from cache.""" self.cache.clear() def is_cache_entry_expired(self, key: Tuple[str, str]) -> bool: """Check if cache entry is expired.""" entry = self.cache[key] return entry["created_at"] + entry["max-age"] < time.time() async def register_new_key( self, key: Tuple[str, str], timeout=DEFAULT_WAIT_TIMEOUT ): """Register new key before actual request, so all subsequent requests will know and wait until this one returned a result. This should avoid dog-piling problem. More details here: https://en.wikipedia.org/wiki/Cache_stampede """ total_wait_time = 0.0 while True: if key not in self._wait_until_completed: break await asyncio.sleep(self.sleep_time) total_wait_time += self.sleep_time if total_wait_time >= timeout: raise TimeoutException(f"Timeout exceeded for {key}") if key not in self.cache: self._wait_until_completed.add(key) def release_new_key(self, key: Tuple[str, str]): """Release previously registered key, so all subsequent requests can use it.""" try: self._wait_until_completed.remove(key) except Exception: # TODO: consider adding debug log here pass def _is_response_cacheable(self, method, cc_header): """Check if response can be cached.""" if method not in self.cacheable_methods: return False # Although, no-cache means "The response may be stored by any cache, # but MUST always go through validation with the origin server first # before using it", we won't cache it for simplicity for now. if "no-cache" in cc_header or "no-store" in cc_header: return False return True @staticmethod def parse_cache_control_header(headers) -> Dict: """Parse cache-control header, get max-age value. Args: headers: any dict-like object Returns: dict: parsed cache-control header Example: >>> headers = {"Cache-Control": "max-age=604800", "Content-Type": "application/json"} >>> self.parse_cache_control_header(headers) {"max-age": 604800} """ cache_control_header = headers.get( "cache-control", headers.get("Cache-Control", headers.get("CACHE-CONTROL", "")), ) # Currently, parse the most important directives # TODO: consider parse all possible directives parsed_header = {} # type: Dict[str, Any] for directive in cache_control_header.split(","): cleaned_directive = directive.strip().lower() # get directives without values if cleaned_directive in ("no-cache", "no-store"): parsed_header[cleaned_directive] = True elif "=" in cleaned_directive: key, value = cleaned_directive.split("=", 1) if "max-age" == key: try: parsed_header["max-age"] = int(value) except ValueError: logger.debug('Failed to parse "max-age" directive.') # ignore all other directives except no-cache, no-store, max-age return parsed_header
(config: Dict = None, cache_backend=None)
711,992
acachecontrol.cache
__init__
null
def __init__(self, config: Dict = None, cache_backend=None): self.cache = ( cache_backend if cache_backend is not None else OrderedDict() ) config = config or {} self._wait_until_completed = set() # type: Set self.default_max_age = config.get("max_age", DEFAULT_MAX_AGE) self.sleep_time = config.get("sleep_time", DEFAULT_SLEEP_TIME) self.cacheable_methods = config.get( "cacheable_methods", CACHEABLE_METHODS ) self.capacity = config.get("capacity", DEFAULT_CACHE_CAPACITY)
(self, config: Optional[Dict] = None, cache_backend=None)
711,993
acachecontrol.cache
_is_response_cacheable
Check if response can be cached.
def _is_response_cacheable(self, method, cc_header): """Check if response can be cached.""" if method not in self.cacheable_methods: return False # Although, no-cache means "The response may be stored by any cache, # but MUST always go through validation with the origin server first # before using it", we won't cache it for simplicity for now. if "no-cache" in cc_header or "no-store" in cc_header: return False return True
(self, method, cc_header)
711,994
acachecontrol.cache
add
Add value to the cache. headers - any dict-like obj
def add(self, key: Tuple[str, str], value: Any, headers: Any) -> None: """Add value to the cache. headers - any dict-like obj """ cc_header = self.parse_cache_control_header(headers) if self._is_response_cacheable(key[0], cc_header): self.cache[key] = { "created_at": time.time(), "max-age": cc_header.get("max-age", self.default_max_age), "value": value, } self.cache.move_to_end(key) if len(self.cache) > self.capacity: self.cache.popitem(last=False) self.release_new_key(key) logger.debug(f"Added a new entry to cache for {key} key")
(self, key: Tuple[str, str], value: Any, headers: Any) -> NoneType
711,995
acachecontrol.cache
clear_cache
Delete everything from cache.
def clear_cache(self) -> None: """Delete everything from cache.""" self.cache.clear()
(self) -> NoneType
711,996
acachecontrol.cache
delete
Delete entry from cache.
def delete(self, key: Tuple[str, str]) -> None: """Delete entry from cache.""" logger.debug(f"Delete entry from cache for {key} key") self.cache.pop(key, None)
(self, key: Tuple[str, str]) -> NoneType
711,997
acachecontrol.cache
get
Get entry from cache.
def get(self, key: Tuple[str, str]) -> Any: """Get entry from cache.""" try: cache_entry = self.cache.get(key) if cache_entry: logger.debug(f"Get entry from cache for {key} key") self.cache.move_to_end(key) return cache_entry["value"] raise CacheException(f"No cache entry for {key} key") except Exception: raise CacheException( f"Error getting value from cache for {key} key" )
(self, key: Tuple[str, str]) -> Any
711,998
acachecontrol.cache
has_valid_entry
Check if entry exists and not expired, delete expired.
def has_valid_entry(self, key: Tuple[str, str]) -> bool: """Check if entry exists and not expired, delete expired.""" if key in self.cache: if not self.is_cache_entry_expired(key): return True logger.debug(f"Cache entry is expired for {key} key") self.delete(key) return False
(self, key: Tuple[str, str]) -> bool
711,999
acachecontrol.cache
is_cache_entry_expired
Check if cache entry is expired.
def is_cache_entry_expired(self, key: Tuple[str, str]) -> bool: """Check if cache entry is expired.""" entry = self.cache[key] return entry["created_at"] + entry["max-age"] < time.time()
(self, key: Tuple[str, str]) -> bool
712,000
acachecontrol.cache
parse_cache_control_header
Parse cache-control header, get max-age value. Args: headers: any dict-like object Returns: dict: parsed cache-control header Example: >>> headers = {"Cache-Control": "max-age=604800", "Content-Type": "application/json"} >>> self.parse_cache_control_header(headers) {"max-age": 604800}
@staticmethod def parse_cache_control_header(headers) -> Dict: """Parse cache-control header, get max-age value. Args: headers: any dict-like object Returns: dict: parsed cache-control header Example: >>> headers = {"Cache-Control": "max-age=604800", "Content-Type": "application/json"} >>> self.parse_cache_control_header(headers) {"max-age": 604800} """ cache_control_header = headers.get( "cache-control", headers.get("Cache-Control", headers.get("CACHE-CONTROL", "")), ) # Currently, parse the most important directives # TODO: consider parse all possible directives parsed_header = {} # type: Dict[str, Any] for directive in cache_control_header.split(","): cleaned_directive = directive.strip().lower() # get directives without values if cleaned_directive in ("no-cache", "no-store"): parsed_header[cleaned_directive] = True elif "=" in cleaned_directive: key, value = cleaned_directive.split("=", 1) if "max-age" == key: try: parsed_header["max-age"] = int(value) except ValueError: logger.debug('Failed to parse "max-age" directive.') # ignore all other directives except no-cache, no-store, max-age return parsed_header
(headers) -> Dict
712,001
acachecontrol.cache
register_new_key
Register new key before actual request, so all subsequent requests will know and wait until this one returned a result. This should avoid dog-piling problem. More details here: https://en.wikipedia.org/wiki/Cache_stampede
def is_cache_entry_expired(self, key: Tuple[str, str]) -> bool: """Check if cache entry is expired.""" entry = self.cache[key] return entry["created_at"] + entry["max-age"] < time.time()
(self, key: Tuple[str, str], timeout=300)
712,002
acachecontrol.cache
release_new_key
Release previously registered key, so all subsequent requests can use it.
def release_new_key(self, key: Tuple[str, str]): """Release previously registered key, so all subsequent requests can use it.""" try: self._wait_until_completed.remove(key) except Exception: # TODO: consider adding debug log here pass
(self, key: Tuple[str, str])
712,003
acachecontrol.acachecontrol
AsyncCacheControl
null
class AsyncCacheControl: def __init__( self, cache: AsyncCache = AsyncCache(), request_context_manager_cls=RequestContextManager, ): self._request_context_manager_cls = request_context_manager_cls self.cache = cache self._async_client_session = aiohttp.ClientSession() def request(self, method, url, **params): return self._request_context_manager_cls( self._async_client_session, self.cache, method, url, **params ) def head(self, url, allow_redirects=True, **params): return self.request( "HEAD", url, allow_redirects=allow_redirects, **params ) def get(self, url, allow_redirects=True, **params): return self.request( "GET", url, allow_redirects=allow_redirects, **params ) def post(self, url, data, **params): return self.request("POST", url, data=data, **params) def put(self, url, data, **params): return self.request("PUT", url, data=data, **params) def patch(self, url, data, **params): return self.request("PATCH", url, data=data, **params) def delete(self, url, **params): return self.request("DELETE", url, **params) def clear_cache(self): self.cache.clear_cache() async def __aenter__(self): return self async def __aexit__(self, exc_type, exc_val, exc_tb): await self._async_client_session.close()
(cache: acachecontrol.cache.AsyncCache = <acachecontrol.cache.AsyncCache object at 0x7feed72e0820>, request_context_manager_cls=<class 'acachecontrol.request_context_manager.RequestContextManager'>)
712,004
acachecontrol.acachecontrol
__aenter__
null
def clear_cache(self): self.cache.clear_cache()
(self)
712,006
acachecontrol.acachecontrol
__init__
null
def __init__( self, cache: AsyncCache = AsyncCache(), request_context_manager_cls=RequestContextManager, ): self._request_context_manager_cls = request_context_manager_cls self.cache = cache self._async_client_session = aiohttp.ClientSession()
(self, cache: acachecontrol.cache.AsyncCache = <acachecontrol.cache.AsyncCache object at 0x7feed72e0820>, request_context_manager_cls=<class 'acachecontrol.request_context_manager.RequestContextManager'>)
712,008
acachecontrol.acachecontrol
delete
null
def delete(self, url, **params): return self.request("DELETE", url, **params)
(self, url, **params)
712,009
acachecontrol.acachecontrol
get
null
def get(self, url, allow_redirects=True, **params): return self.request( "GET", url, allow_redirects=allow_redirects, **params )
(self, url, allow_redirects=True, **params)
712,010
acachecontrol.acachecontrol
head
null
def head(self, url, allow_redirects=True, **params): return self.request( "HEAD", url, allow_redirects=allow_redirects, **params )
(self, url, allow_redirects=True, **params)
712,011
acachecontrol.acachecontrol
patch
null
def patch(self, url, data, **params): return self.request("PATCH", url, data=data, **params)
(self, url, data, **params)
712,012
acachecontrol.acachecontrol
post
null
def post(self, url, data, **params): return self.request("POST", url, data=data, **params)
(self, url, data, **params)
712,013
acachecontrol.acachecontrol
put
null
def put(self, url, data, **params): return self.request("PUT", url, data=data, **params)
(self, url, data, **params)
712,014
acachecontrol.acachecontrol
request
null
def request(self, method, url, **params): return self._request_context_manager_cls( self._async_client_session, self.cache, method, url, **params )
(self, method, url, **params)
712,020
braintree.ach_mandate
AchMandate
null
class AchMandate(Resource): def __init__(self, gateway, attributes): Resource.__init__(self, gateway, attributes)
(gateway, attributes)
712,021
braintree.resource
__flattened_params_keys
null
@staticmethod def __flattened_params_keys(params, parent=None): if isinstance(params, text_type) or isinstance(params, raw_type): return [ "%s[%s]" % (parent, params) ] else: keys = [] for key, val in params.items(): full_key = "%s[%s]" % (parent, key) if parent else key if isinstance(val, dict): keys += Resource.__flattened_params_keys(val, full_key) elif isinstance(val, list): for item in val: keys += Resource.__flattened_params_keys(item, full_key) else: keys.append(full_key) return keys
(params, parent=None)
712,022
braintree.resource
__flattened_signature
null
@staticmethod def __flattened_signature(signature, parent=None): flat_sig = [] for item in signature: if isinstance(item, dict): for key, val in item.items(): full_key = '{0}[{1}]'.format(parent, key) if parent else key flat_sig += Resource.__flattened_signature(val, full_key) else: full_key = '{0}[{1}]'.format(parent, item) if parent else item flat_sig.append(full_key) return flat_sig
(signature, parent=None)
712,023
braintree.resource
__remove_wildcard_keys
null
@staticmethod def __remove_wildcard_keys(allowed_keys, invalid_keys): wildcard_keys = [ re.sub(r"(?<=[^\\])_", "\\_", re.escape(key)).replace(r"\[\_\_any\_key\_\_\]", r"\[[\w.-]+\]") for key in allowed_keys if re.search(r"\[__any_key__\]", key) ] new_keys = [] for key in invalid_keys: if len([match for match in wildcard_keys if re.match(r"\A" + match + r"\Z", key)]) == 0: new_keys.append(key) return new_keys
(allowed_keys, invalid_keys)
712,024
braintree.ach_mandate
__init__
null
def __init__(self, gateway, attributes): Resource.__init__(self, gateway, attributes)
(self, gateway, attributes)
712,025
braintree.attribute_getter
__repr__
null
def __repr__(self, detail_list=None): if detail_list is None: detail_list = self._setattrs details = ", ".join("%s: %r" % (attr, getattr(self, attr)) for attr in detail_list if hasattr(self, attr)) return "<%s {%s} at %d>" % (self.__class__.__name__, details, id(self))
(self, detail_list=None)
712,026
braintree.resource
verify_keys
null
@staticmethod def verify_keys(params, signature): allowed_keys = Resource.__flattened_signature(signature) params_keys = Resource.__flattened_params_keys(params) invalid_keys = [key for key in params_keys if key not in allowed_keys] invalid_keys = Resource.__remove_wildcard_keys(allowed_keys, invalid_keys) if len(invalid_keys) > 0: keys_string = ", ".join(invalid_keys) raise KeyError("Invalid keys: " + keys_string)
(params, signature)
712,027
braintree.add_on
AddOn
null
class AddOn(Modification): @staticmethod def all(): return Configuration.gateway().add_on.all()
(gateway, attributes)
712,031
braintree.modification
__init__
null
def __init__(self, gateway, attributes): Resource.__init__(self, gateway, attributes) self.amount = Decimal(self.amount)
(self, gateway, attributes)
712,033
braintree.add_on
all
null
@staticmethod def all(): return Configuration.gateway().add_on.all()
()
712,035
braintree.add_on_gateway
AddOnGateway
null
class AddOnGateway(object): def __init__(self, gateway): self.gateway = gateway self.config = gateway.config def all(self): response = self.config.http().get(self.config.base_merchant_path() + "/add_ons/") add_ons = {"add_on": response["add_ons"]} return [AddOn(self.gateway, item) for item in ResourceCollection._extract_as_array(add_ons, "add_on")]
(gateway)
712,036
braintree.add_on_gateway
__init__
null
def __init__(self, gateway): self.gateway = gateway self.config = gateway.config
(self, gateway)
712,037
braintree.add_on_gateway
all
null
def all(self): response = self.config.http().get(self.config.base_merchant_path() + "/add_ons/") add_ons = {"add_on": response["add_ons"]} return [AddOn(self.gateway, item) for item in ResourceCollection._extract_as_array(add_ons, "add_on")]
(self)
712,038
braintree.address
Address
A class representing Braintree Address objects. An example of creating an address with all available fields:: customer = braintree.Customer.create().customer result = braintree.Address.create({ "customer_id": customer.id, "first_name": "John", "last_name": "Doe", "company": "Braintree", "street_address": "111 First Street", "extended_address": "Apartment 1", "locality": "Chicago", "region": "IL", "postal_code": "60606", "country_name": "United States of America" }) print(result.customer.first_name) print(result.customer.last_name)
class Address(Resource): """ A class representing Braintree Address objects. An example of creating an address with all available fields:: customer = braintree.Customer.create().customer result = braintree.Address.create({ "customer_id": customer.id, "first_name": "John", "last_name": "Doe", "company": "Braintree", "street_address": "111 First Street", "extended_address": "Apartment 1", "locality": "Chicago", "region": "IL", "postal_code": "60606", "country_name": "United States of America" }) print(result.customer.first_name) print(result.customer.last_name) """ def __repr__(self): detail_list = [ "customer_id", "company", "country_code_alpha2", "country_code_alpha3", "country_code_numeric", "country_name", "extended_address", "first_name", "last_name", "locality", "postal_code", "region", "street_address", "shipping_method", ] return super(Address, self).__repr__(detail_list) # NEXT_MAJOR_VERSION this can be an enum! they were added as of python 3.4 and we support 3.5+ class ShippingMethod(object): """ Constants representing shipping methods for shipping addresses. Available types are: * braintree.Address.ShippingMethod.SameDay * braintree.Address.ShippingMethod.NextDay * braintree.Address.ShippingMethod.Priority * braintree.Address.ShippingMethod.Ground * braintree.Address.ShippingMethod.Electronic * braintree.Address.ShippingMethod.ShipToStore * braintree.Address.ShippingMethod.PickupInStore """ SameDay = "same_day" NextDay = "next_day" Priority = "priority" Ground = "ground" Electronic = "electronic" ShipToStore = "ship_to_store" PickupInStore = "pickup_in_store" @staticmethod def create(params=None): """ Create an Address. A customer_id is required:: customer = braintree.Customer.create().customer result = braintree.Address.create({ "customer_id": customer.id, "first_name": "John", ... }) """ if params is None: params = {} return Configuration.gateway().address.create(params) @staticmethod def delete(customer_id, address_id): """ Delete an address Given a customer_id and address_id:: result = braintree.Address.delete("my_customer_id", "my_address_id") """ return Configuration.gateway().address.delete(customer_id, address_id) @staticmethod def find(customer_id, address_id): """ Find an address, given a customer_id and address_id. This does not return a result object. This will raise a :class:`NotFoundError <braintree.exceptions.not_found_error.NotFoundError>` if the provided customer_id/address_id are not found. :: address = braintree.Address.find("my_customer_id", "my_address_id") """ return Configuration.gateway().address.find(customer_id, address_id) @staticmethod def update(customer_id, address_id, params=None): """ Update an existing Address. A customer_id and address_id are required:: result = braintree.Address.update("my_customer_id", "my_address_id", { "first_name": "John" }) """ if params is None: params = {} return Configuration.gateway().address.update(customer_id, address_id, params) @staticmethod def create_signature(): return ["company", "country_code_alpha2", "country_code_alpha3", "country_code_numeric", "country_name", "customer_id", "extended_address", "first_name", "last_name", "locality", "phone_number", "postal_code", "region", "street_address"] @staticmethod def update_signature(): return Address.create_signature()
(gateway, attributes)
712,042
braintree.resource
__init__
null
def __init__(self, gateway, attributes): AttributeGetter.__init__(self, attributes) self.gateway = gateway
(self, gateway, attributes)
712,043
braintree.address
__repr__
null
def __repr__(self): detail_list = [ "customer_id", "company", "country_code_alpha2", "country_code_alpha3", "country_code_numeric", "country_name", "extended_address", "first_name", "last_name", "locality", "postal_code", "region", "street_address", "shipping_method", ] return super(Address, self).__repr__(detail_list)
(self)
712,044
braintree.address
create
Create an Address. A customer_id is required:: customer = braintree.Customer.create().customer result = braintree.Address.create({ "customer_id": customer.id, "first_name": "John", ... })
@staticmethod def create(params=None): """ Create an Address. A customer_id is required:: customer = braintree.Customer.create().customer result = braintree.Address.create({ "customer_id": customer.id, "first_name": "John", ... }) """ if params is None: params = {} return Configuration.gateway().address.create(params)
(params=None)
712,045
braintree.address
create_signature
null
@staticmethod def create_signature(): return ["company", "country_code_alpha2", "country_code_alpha3", "country_code_numeric", "country_name", "customer_id", "extended_address", "first_name", "last_name", "locality", "phone_number", "postal_code", "region", "street_address"]
()
712,046
braintree.address
delete
Delete an address Given a customer_id and address_id:: result = braintree.Address.delete("my_customer_id", "my_address_id")
@staticmethod def delete(customer_id, address_id): """ Delete an address Given a customer_id and address_id:: result = braintree.Address.delete("my_customer_id", "my_address_id") """ return Configuration.gateway().address.delete(customer_id, address_id)
(customer_id, address_id)
712,047
braintree.address
find
Find an address, given a customer_id and address_id. This does not return a result object. This will raise a :class:`NotFoundError <braintree.exceptions.not_found_error.NotFoundError>` if the provided customer_id/address_id are not found. :: address = braintree.Address.find("my_customer_id", "my_address_id")
@staticmethod def find(customer_id, address_id): """ Find an address, given a customer_id and address_id. This does not return a result object. This will raise a :class:`NotFoundError <braintree.exceptions.not_found_error.NotFoundError>` if the provided customer_id/address_id are not found. :: address = braintree.Address.find("my_customer_id", "my_address_id") """ return Configuration.gateway().address.find(customer_id, address_id)
(customer_id, address_id)
712,048
braintree.address
update
Update an existing Address. A customer_id and address_id are required:: result = braintree.Address.update("my_customer_id", "my_address_id", { "first_name": "John" })
@staticmethod def update(customer_id, address_id, params=None): """ Update an existing Address. A customer_id and address_id are required:: result = braintree.Address.update("my_customer_id", "my_address_id", { "first_name": "John" }) """ if params is None: params = {} return Configuration.gateway().address.update(customer_id, address_id, params)
(customer_id, address_id, params=None)
712,049
braintree.address
update_signature
null
@staticmethod def update_signature(): return Address.create_signature()
()
712,051
braintree.address_gateway
AddressGateway
null
class AddressGateway(object): def __init__(self, gateway): self.gateway = gateway self.config = gateway.config def __validate_chars_in_args(self, customer_id, address_id): if not re.search(r"\A[0-9A-Za-z_-]+\Z", customer_id): raise KeyError("customer_id contains invalid characters") if not re.search(r"\A[0-9A-Za-z]+\Z", address_id): raise KeyError("address_id contains invalid characters") def create(self, params=None): if params is None: params = {} Resource.verify_keys(params, Address.create_signature()) if "customer_id" not in params: raise KeyError("customer_id must be provided") if not re.search(r"\A[0-9A-Za-z_-]+\Z", params["customer_id"]): raise KeyError("customer_id contains invalid characters") response = self.config.http().post(self.config.base_merchant_path() + "/customers/" + params.pop("customer_id") + "/addresses", {"address": params}) if "address" in response: return SuccessfulResult({"address": Address(self.gateway, response["address"])}) elif "api_error_response" in response: return ErrorResult(self.gateway, response["api_error_response"]) def delete(self, customer_id, address_id): self.__validate_chars_in_args(customer_id, address_id) self.config.http().delete(self.config.base_merchant_path() + "/customers/" + customer_id + "/addresses/" + address_id) return SuccessfulResult() def find(self, customer_id, address_id): try: # NEXT_MAJOR_VERSION return KeyError instead of NotFoundError, it's a more helpful error message to the developer that way if customer_id is None or customer_id.strip() == "" or address_id is None or address_id.strip() == "": raise NotFoundError() self.__validate_chars_in_args(customer_id, address_id) response = self.config.http().get(self.config.base_merchant_path() + "/customers/" + customer_id + "/addresses/" + address_id) return Address(self.gateway, response["address"]) except NotFoundError: raise NotFoundError("address for customer " + repr(customer_id) + " with id " + repr(address_id) + " not found") def update(self, customer_id, address_id, params=None): if params is None: params = {} Resource.verify_keys(params, Address.update_signature()) self.__validate_chars_in_args(customer_id, address_id) response = self.config.http().put( self.config.base_merchant_path() + "/customers/" + customer_id + "/addresses/" + address_id, {"address": params} ) if "address" in response: return SuccessfulResult({"address": Address(self.gateway, response["address"])}) elif "api_error_response" in response: return ErrorResult(self.gateway, response["api_error_response"])
(gateway)
712,052
braintree.address_gateway
__validate_chars_in_args
null
def __validate_chars_in_args(self, customer_id, address_id): if not re.search(r"\A[0-9A-Za-z_-]+\Z", customer_id): raise KeyError("customer_id contains invalid characters") if not re.search(r"\A[0-9A-Za-z]+\Z", address_id): raise KeyError("address_id contains invalid characters")
(self, customer_id, address_id)
712,054
braintree.address_gateway
create
null
def create(self, params=None): if params is None: params = {} Resource.verify_keys(params, Address.create_signature()) if "customer_id" not in params: raise KeyError("customer_id must be provided") if not re.search(r"\A[0-9A-Za-z_-]+\Z", params["customer_id"]): raise KeyError("customer_id contains invalid characters") response = self.config.http().post(self.config.base_merchant_path() + "/customers/" + params.pop("customer_id") + "/addresses", {"address": params}) if "address" in response: return SuccessfulResult({"address": Address(self.gateway, response["address"])}) elif "api_error_response" in response: return ErrorResult(self.gateway, response["api_error_response"])
(self, params=None)
712,055
braintree.address_gateway
delete
null
def delete(self, customer_id, address_id): self.__validate_chars_in_args(customer_id, address_id) self.config.http().delete(self.config.base_merchant_path() + "/customers/" + customer_id + "/addresses/" + address_id) return SuccessfulResult()
(self, customer_id, address_id)
712,056
braintree.address_gateway
find
null
def find(self, customer_id, address_id): try: # NEXT_MAJOR_VERSION return KeyError instead of NotFoundError, it's a more helpful error message to the developer that way if customer_id is None or customer_id.strip() == "" or address_id is None or address_id.strip() == "": raise NotFoundError() self.__validate_chars_in_args(customer_id, address_id) response = self.config.http().get(self.config.base_merchant_path() + "/customers/" + customer_id + "/addresses/" + address_id) return Address(self.gateway, response["address"]) except NotFoundError: raise NotFoundError("address for customer " + repr(customer_id) + " with id " + repr(address_id) + " not found")
(self, customer_id, address_id)