code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id") result = self.do("getChat", chat_id=chat_id) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) from pytgbot.api_types.receivable.peer import Chat try: return Chat.from_array(result) except TgApiParseException: logger.debug("Failed parsing as api_type Chat", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
def get_chat(self, chat_id)
Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). Returns a Chat object on success. https://core.telegram.org/bots/api#getchat Parameters: :param chat_id: Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername) :type chat_id: int | str|unicode Returns: :return: Returns a Chat object on success :rtype: pytgbot.api_types.receivable.peer.Chat
3.487219
3.526212
0.988942
assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id") result = self.do("getChatAdministrators", chat_id=chat_id) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) from pytgbot.api_types.receivable.peer import ChatMember try: return ChatMember.from_array_list(result, list_level=1) except TgApiParseException: logger.debug("Failed parsing as api_type ChatMember", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
def get_chat_administrators(self, chat_id)
Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned. https://core.telegram.org/bots/api#getchatadministrators Parameters: :param chat_id: Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername) :type chat_id: int | str|unicode Returns: :return: On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots :rtype: list of pytgbot.api_types.receivable.peer.ChatMember
3.527688
3.453423
1.021505
assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id") assert_type_or_raise(sticker_set_name, unicode_type, parameter_name="sticker_set_name") result = self.do("setChatStickerSet", chat_id=chat_id, sticker_set_name=sticker_set_name) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) try: return from_array_list(bool, result, list_level=0, is_builtin=True) except TgApiParseException: logger.debug("Failed parsing as primitive bool", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
def set_chat_sticker_set(self, chat_id, sticker_set_name)
Use this method to set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success. https://core.telegram.org/bots/api#setchatstickerset Parameters: :param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername) :type chat_id: int | str|unicode :param sticker_set_name: Name of the sticker set to be set as the group sticker set :type sticker_set_name: str|unicode Returns: :return: Returns True on success :rtype: bool
3.40586
2.96215
1.149793
assert_type_or_raise(callback_query_id, unicode_type, parameter_name="callback_query_id") assert_type_or_raise(text, None, unicode_type, parameter_name="text") assert_type_or_raise(show_alert, None, bool, parameter_name="show_alert") assert_type_or_raise(url, None, unicode_type, parameter_name="url") assert_type_or_raise(cache_time, None, int, parameter_name="cache_time") result = self.do("answerCallbackQuery", callback_query_id=callback_query_id, text=text, show_alert=show_alert, url=url, cache_time=cache_time) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) try: return from_array_list(bool, result, list_level=0, is_builtin=True) except TgApiParseException: logger.debug("Failed parsing as primitive bool", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
def answer_callback_query(self, callback_query_id, text=None, show_alert=None, url=None, cache_time=None)
Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned. Alternatively, the user can be redirected to the specified Game URL. For this option to work, you must first create a game for your bot via @Botfather and accept the terms. Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter. https://core.telegram.org/bots/api#answercallbackquery Parameters: :param callback_query_id: Unique identifier for the query to be answered :type callback_query_id: str|unicode Optional keyword parameters: :param text: Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters :type text: str|unicode :param show_alert: If true, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to false. :type show_alert: bool :param url: URL that will be opened by the user's client. If you have created a Game and accepted the conditions via @Botfather, specify the URL that opens your game – note that this will only work if the query comes from a callback_game button.Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter. :type url: str|unicode :param cache_time: The maximum amount of time in seconds that the result of the callback query may be cached client-side. Telegram apps will support caching starting in version 3.14. Defaults to 0. :type cache_time: int Returns: :return: On success, True is returned :rtype: bool
2.524524
2.437585
1.035666
from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup assert_type_or_raise(text, unicode_type, parameter_name="text") assert_type_or_raise(chat_id, None, (int, unicode_type), parameter_name="chat_id") assert_type_or_raise(message_id, None, int, parameter_name="message_id") assert_type_or_raise(inline_message_id, None, unicode_type, parameter_name="inline_message_id") assert_type_or_raise(parse_mode, None, unicode_type, parameter_name="parse_mode") assert_type_or_raise(disable_web_page_preview, None, bool, parameter_name="disable_web_page_preview") assert_type_or_raise(reply_markup, None, InlineKeyboardMarkup, parameter_name="reply_markup") result = self.do("editMessageText", text=text, chat_id=chat_id, message_id=message_id, inline_message_id=inline_message_id, parse_mode=parse_mode, disable_web_page_preview=disable_web_page_preview, reply_markup=reply_markup) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) from pytgbot.api_types.receivable.updates import Message try: return Message.from_array(result) except TgApiParseException: logger.debug("Failed parsing as api_type Message", exc_info=True) # end try try: return from_array_list(bool, result, list_level=0, is_builtin=True) except TgApiParseException: logger.debug("Failed parsing as primitive bool", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
def edit_message_text(self, text, chat_id=None, message_id=None, inline_message_id=None, parse_mode=None, disable_web_page_preview=None, reply_markup=None)
Use this method to edit text and game messages sent by the bot or via the bot (for inline bots). On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. https://core.telegram.org/bots/api#editmessagetext Parameters: :param text: New text of the message :type text: str|unicode Optional keyword parameters: :param chat_id: Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername) :type chat_id: int | str|unicode :param message_id: Required if inline_message_id is not specified. Identifier of the sent message :type message_id: int :param inline_message_id: Required if chat_id and message_id are not specified. Identifier of the inline message :type inline_message_id: str|unicode :param parse_mode: Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. :type parse_mode: str|unicode :param disable_web_page_preview: Disables link previews for links in this message :type disable_web_page_preview: bool :param reply_markup: A JSON-serialized object for an inline keyboard. :type reply_markup: pytgbot.api_types.sendable.reply_markup.InlineKeyboardMarkup Returns: :return: On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned :rtype: pytgbot.api_types.receivable.updates.Message | bool
1.834741
1.753921
1.04608
assert_type_or_raise(name, unicode_type, parameter_name="name") result = self.do("getStickerSet", name=name) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) from pytgbot.api_types.receivable.stickers import StickerSet try: return StickerSet.from_array(result) except TgApiParseException: logger.debug("Failed parsing as api_type StickerSet", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
def get_sticker_set(self, name)
Use this method to get a sticker set. On success, a StickerSet object is returned. https://core.telegram.org/bots/api#getstickerset Parameters: :param name: Name of the sticker set :type name: str|unicode Returns: :return: On success, a StickerSet object is returned :rtype: pytgbot.api_types.receivable.stickers.StickerSet
3.461299
3.53527
0.979076
from pytgbot.api_types.sendable.files import InputFile assert_type_or_raise(user_id, int, parameter_name="user_id") assert_type_or_raise(png_sticker, InputFile, parameter_name="png_sticker") result = self.do("uploadStickerFile", user_id=user_id, png_sticker=png_sticker) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) from pytgbot.api_types.receivable.media import File try: return File.from_array(result) except TgApiParseException: logger.debug("Failed parsing as api_type File", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
def upload_sticker_file(self, user_id, png_sticker)
Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times). Returns the uploaded File on success. https://core.telegram.org/bots/api#uploadstickerfile Parameters: :param user_id: User identifier of sticker file owner :type user_id: int :param png_sticker: Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. More info on Sending Files » :type png_sticker: pytgbot.api_types.sendable.files.InputFile Returns: :return: Returns the uploaded File on success :rtype: pytgbot.api_types.receivable.media.File
2.860324
2.787112
1.026268
from pytgbot.api_types.receivable.stickers import MaskPosition from pytgbot.api_types.sendable.files import InputFile assert_type_or_raise(user_id, int, parameter_name="user_id") assert_type_or_raise(name, unicode_type, parameter_name="name") assert_type_or_raise(title, unicode_type, parameter_name="title") assert_type_or_raise(png_sticker, (InputFile, unicode_type), parameter_name="png_sticker") assert_type_or_raise(emojis, unicode_type, parameter_name="emojis") assert_type_or_raise(contains_masks, None, bool, parameter_name="contains_masks") assert_type_or_raise(mask_position, None, MaskPosition, parameter_name="mask_position") result = self.do("createNewStickerSet", user_id=user_id, name=name, title=title, png_sticker=png_sticker, emojis=emojis, contains_masks=contains_masks, mask_position=mask_position) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) try: return from_array_list(bool, result, list_level=0, is_builtin=True) except TgApiParseException: logger.debug("Failed parsing as primitive bool", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
def create_new_sticker_set(self, user_id, name, title, png_sticker, emojis, contains_masks=None, mask_position=None)
Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set. Returns True on success. https://core.telegram.org/bots/api#createnewstickerset Parameters: :param user_id: User identifier of created sticker set owner :type user_id: int :param name: Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only english letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in “_by_<bot username>”. <bot_username> is case insensitive. 1-64 characters. :type name: str|unicode :param title: Sticker set title, 1-64 characters :type title: str|unicode :param png_sticker: Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More info on Sending Files » :type png_sticker: pytgbot.api_types.sendable.files.InputFile | str|unicode :param emojis: One or more emoji corresponding to the sticker :type emojis: str|unicode Optional keyword parameters: :param contains_masks: Pass True, if a set of mask stickers should be created :type contains_masks: bool :param mask_position: A JSON-serialized object for position where the mask should be placed on faces :type mask_position: pytgbot.api_types.receivable.stickers.MaskPosition Returns: :return: Returns True on success :rtype: bool
2.146161
1.949575
1.100835
assert_type_or_raise(sticker, unicode_type, parameter_name="sticker") assert_type_or_raise(position, int, parameter_name="position") result = self.do("setStickerPositionInSet", sticker=sticker, position=position) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) try: return from_array_list(bool, result, list_level=0, is_builtin=True) except TgApiParseException: logger.debug("Failed parsing as primitive bool", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
def set_sticker_position_in_set(self, sticker, position)
Use this method to move a sticker in a set created by the bot to a specific position . Returns True on success. https://core.telegram.org/bots/api#setstickerpositioninset Parameters: :param sticker: File identifier of the sticker :type sticker: str|unicode :param position: New sticker position in the set, zero-based :type position: int Returns: :return: Returns True on success :rtype: bool
4.321121
3.667954
1.178074
from pytgbot.api_types.sendable.inline import InlineQueryResult assert_type_or_raise(inline_query_id, unicode_type, parameter_name="inline_query_id") assert_type_or_raise(results, list, parameter_name="results") assert_type_or_raise(cache_time, None, int, parameter_name="cache_time") assert_type_or_raise(is_personal, None, bool, parameter_name="is_personal") assert_type_or_raise(next_offset, None, unicode_type, parameter_name="next_offset") assert_type_or_raise(switch_pm_text, None, unicode_type, parameter_name="switch_pm_text") assert_type_or_raise(switch_pm_parameter, None, unicode_type, parameter_name="switch_pm_parameter") result = self.do("answerInlineQuery", inline_query_id=inline_query_id, results=results, cache_time=cache_time, is_personal=is_personal, next_offset=next_offset, switch_pm_text=switch_pm_text, switch_pm_parameter=switch_pm_parameter) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) try: return from_array_list(bool, result, list_level=0, is_builtin=True) except TgApiParseException: logger.debug("Failed parsing as primitive bool", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
def answer_inline_query(self, inline_query_id, results, cache_time=None, is_personal=None, next_offset=None, switch_pm_text=None, switch_pm_parameter=None)
Use this method to send answers to an inline query. On success, True is returned.No more than 50 results per query are allowed. https://core.telegram.org/bots/api#answerinlinequery Parameters: :param inline_query_id: Unique identifier for the answered query :type inline_query_id: str|unicode :param results: A JSON-serialized array of results for the inline query :type results: list of pytgbot.api_types.sendable.inline.InlineQueryResult Optional keyword parameters: :param cache_time: The maximum amount of time in seconds that the result of the inline query may be cached on the server. Defaults to 300. :type cache_time: int :param is_personal: Pass True, if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query :type is_personal: bool :param next_offset: Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you don‘t support pagination. Offset length can’t exceed 64 bytes. :type next_offset: str|unicode :param switch_pm_text: If passed, clients will display a button with specified text that switches the user to a private chat with the bot and sends the bot a start message with the parameter switch_pm_parameter :type switch_pm_text: str|unicode :param switch_pm_parameter: Deep-linking parameter for the /start message sent to the bot when user presses the switch button. 1-64 characters, only A-Z, a-z, 0-9, _ and - are allowed.Example: An inline bot that sends YouTube videos can ask the user to connect the bot to their YouTube account to adapt search results accordingly. To do this, it displays a ‘Connect your YouTube account’ button above the results, or even before showing any. The user presses the button, switches to a private chat with the bot and, in doing so, passes a start parameter that instructs the bot to return an oauth link. Once done, the bot can offer a switch_inline button so that the user can easily return to the chat where they wanted to use the bot's inline capabilities. :type switch_pm_parameter: str|unicode Returns: :return: On success, True is returned :rtype: bool
2.04787
1.867891
1.096354
from pytgbot.api_types.sendable.payments import ShippingOption assert_type_or_raise(shipping_query_id, unicode_type, parameter_name="shipping_query_id") assert_type_or_raise(ok, bool, parameter_name="ok") assert_type_or_raise(shipping_options, None, list, parameter_name="shipping_options") assert_type_or_raise(error_message, None, unicode_type, parameter_name="error_message") result = self.do("answerShippingQuery", shipping_query_id=shipping_query_id, ok=ok, shipping_options=shipping_options, error_message=error_message) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) try: return from_array_list(bool, result, list_level=0, is_builtin=True) except TgApiParseException: logger.debug("Failed parsing as primitive bool", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
def answer_shipping_query(self, shipping_query_id, ok, shipping_options=None, error_message=None)
If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned. https://core.telegram.org/bots/api#answershippingquery Parameters: :param shipping_query_id: Unique identifier for the query to be answered :type shipping_query_id: str|unicode :param ok: Specify True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible) :type ok: bool Optional keyword parameters: :param shipping_options: Required if ok is True. A JSON-serialized array of available shipping options. :type shipping_options: list of pytgbot.api_types.sendable.payments.ShippingOption :param error_message: Required if ok is False. Error message in human readable form that explains why it is impossible to complete the order (e.g. "Sorry, delivery to your desired address is unavailable'). Telegram will display this message to the user. :type error_message: str|unicode Returns: :return: On success, True is returned :rtype: bool
2.732312
2.416995
1.130458
assert_type_or_raise(pre_checkout_query_id, unicode_type, parameter_name="pre_checkout_query_id") assert_type_or_raise(ok, bool, parameter_name="ok") assert_type_or_raise(error_message, None, unicode_type, parameter_name="error_message") result = self.do("answerPreCheckoutQuery", pre_checkout_query_id=pre_checkout_query_id, ok=ok, error_message=error_message) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) try: return from_array_list(bool, result, list_level=0, is_builtin=True) except TgApiParseException: logger.debug("Failed parsing as primitive bool", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
def answer_pre_checkout_query(self, pre_checkout_query_id, ok, error_message=None)
Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned. Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent. https://core.telegram.org/bots/api#answerprecheckoutquery Parameters: :param pre_checkout_query_id: Unique identifier for the query to be answered :type pre_checkout_query_id: str|unicode :param ok: Specify True if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use False if there are any problems. :type ok: bool Optional keyword parameters: :param error_message: Required if ok is False. Error message in human readable form that explains the reason for failure to proceed with the checkout (e.g. "Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling out your payment details. Please choose a different color or garment!"). Telegram will display this message to the user. :type error_message: str|unicode Returns: :return: On success, True is returned :rtype: bool
3.162977
2.725476
1.160523
from pytgbot.api_types.sendable.passport import PassportElementError assert_type_or_raise(user_id, int, parameter_name="user_id") assert_type_or_raise(errors, list, parameter_name="errors") result = self.do("setPassportDataErrors", user_id=user_id, errors=errors) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) try: return from_array_list(bool, result, list_level=0, is_builtin=True) except TgApiParseException: logger.debug("Failed parsing as primitive bool", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
def set_passport_data_errors(self, user_id, errors)
Informs a user that some of the Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). Returns True on success. Use this if the data submitted by the user doesn't satisfy the standards your service requires for any reason. For example, if a birthday date seems invalid, a submitted document is blurry, a scan shows evidence of tampering, etc. Supply some details in the error message to make sure the user knows how to correct the issues. https://core.telegram.org/bots/api#setpassportdataerrors Parameters: :param user_id: User identifier :type user_id: int :param errors: A JSON-serialized array describing the errors :type errors: list of pytgbot.api_types.sendable.passport.PassportElementError Returns: :return: Returns True on success :rtype: bool
4.092308
3.336196
1.226639
from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup assert_type_or_raise(chat_id, int, parameter_name="chat_id") assert_type_or_raise(game_short_name, unicode_type, parameter_name="game_short_name") assert_type_or_raise(disable_notification, None, bool, parameter_name="disable_notification") assert_type_or_raise(reply_to_message_id, None, int, parameter_name="reply_to_message_id") assert_type_or_raise(reply_markup, None, InlineKeyboardMarkup, parameter_name="reply_markup") result = self.do("sendGame", chat_id=chat_id, game_short_name=game_short_name, disable_notification=disable_notification, reply_to_message_id=reply_to_message_id, reply_markup=reply_markup) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) from pytgbot.api_types.receivable.updates import Message try: return Message.from_array(result) except TgApiParseException: logger.debug("Failed parsing as api_type Message", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
def send_game(self, chat_id, game_short_name, disable_notification=None, reply_to_message_id=None, reply_markup=None)
Use this method to send a game. On success, the sent Message is returned. https://core.telegram.org/bots/api#sendgame Parameters: :param chat_id: Unique identifier for the target chat :type chat_id: int :param game_short_name: Short name of the game, serves as the unique identifier for the game. Set up your games via Botfather. :type game_short_name: str|unicode Optional keyword parameters: :param disable_notification: Sends the message silently. Users will receive a notification with no sound. :type disable_notification: bool :param reply_to_message_id: If the message is a reply, ID of the original message :type reply_to_message_id: int :param reply_markup: A JSON-serialized object for an inline keyboard. If empty, one ‘Play game_title’ button will be shown. If not empty, the first button must launch the game. :type reply_markup: pytgbot.api_types.sendable.reply_markup.InlineKeyboardMarkup Returns: :return: On success, the sent Message is returned :rtype: pytgbot.api_types.receivable.updates.Message
1.935295
1.900635
1.018236
assert_type_or_raise(user_id, int, parameter_name="user_id") assert_type_or_raise(chat_id, None, int, parameter_name="chat_id") assert_type_or_raise(message_id, None, int, parameter_name="message_id") assert_type_or_raise(inline_message_id, None, unicode_type, parameter_name="inline_message_id") result = self.do("getGameHighScores", user_id=user_id, chat_id=chat_id, message_id=message_id, inline_message_id=inline_message_id) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) from pytgbot.api_types.receivable.game import GameHighScore try: return GameHighScore.from_array_list(result, list_level=1) except TgApiParseException: logger.debug("Failed parsing as api_type GameHighScore", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
def get_game_high_scores(self, user_id, chat_id=None, message_id=None, inline_message_id=None)
Use this method to get data for high score tables. Will return the score of the specified user and several of his neighbors in a game. On success, returns an Array of GameHighScore objects. This method will currently return scores for the target user, plus two of his closest neighbors on each side. Will also return the top three users if the user and his neighbors are not among them. Please note that this behavior is subject to change. https://core.telegram.org/bots/api#getgamehighscores Parameters: :param user_id: Target user id :type user_id: int Optional keyword parameters: :param chat_id: Required if inline_message_id is not specified. Unique identifier for the target chat :type chat_id: int :param message_id: Required if inline_message_id is not specified. Identifier of the sent message :type message_id: int :param inline_message_id: Required if chat_id and message_id are not specified. Identifier of the inline message :type inline_message_id: str|unicode Returns: :return: On success, returns an Array of GameHighScore objects :rtype: list of pytgbot.api_types.receivable.game.GameHighScore
2.401125
2.298058
1.04485
import requests url, params = self._prepare_request(command, query) r = requests.post(url, params=params, files=files, stream=use_long_polling, verify=True, # No self signed certificates. Telegram should be trustworthy anyway... timeout=request_timeout) return self._postprocess_request(r)
def do(self, command, files=None, use_long_polling=False, request_timeout=None, **query)
Send a request to the api. If the bot is set to return the json objects, it will look like this: ```json { "ok": bool, "result": {...}, # optionally present: "description": "human-readable description of the result", "error_code": int } ``` :param command: The Url command parameter :type command: str :param request_timeout: When the request should time out. Default: `None` :type request_timeout: int :param files: if it needs to send files. :param use_long_polling: if it should use long polling. Default: `False` (see http://docs.python-requests.org/en/latest/api/#requests.Response.iter_content) :type use_long_polling: bool :param query: all the other `**kwargs` will get json encoded. :return: The json response from the server, or, if `self.return_python_objects` is `True`, a parsed return type. :rtype: DictObject.DictObject | pytgbot.api_types.receivable.Receivable
5.787019
6.417216
0.901796
from DictObject import DictObject import requests assert isinstance(r, requests.Response) try: logger.debug(r.json()) res = DictObject.objectify(r.json()) except Exception: logger.exception("Parsing answer failed.\nRequest: {r!s}\nContent: {r.content}".format(r=r)) raise # end if res["response"] = r # TODO: does this failes on json lists? Does TG does that? # TG should always return an dict, with at least a status or something. if self.return_python_objects: if res.ok != True: raise TgApiServerException( error_code=res.error_code if "error_code" in res else None, response=res.response if "response" in res else None, description=res.description if "description" in res else None, request=r.request ) # end if not ok if "result" not in res: raise TgApiParseException('Key "result" is missing.') # end if no result return res.result # end if return_python_objects return res # end def _postprocess_request def _do_fileupload(self, file_param_name, value, _command=None, **kwargs): from pytgbot.api_types.sendable.files import InputFile from luckydonaldUtils.encoding import unicode_type from luckydonaldUtils.encoding import to_native as n if isinstance(value, str): kwargs[file_param_name] = str(value) elif isinstance(value, unicode_type): kwargs[file_param_name] = n(value) elif isinstance(value, InputFile): kwargs["files"] = value.get_request_files(file_param_name) else: raise TgApiTypeError("Parameter {key} is not type (str, {text_type}, {input_file_type}), but type {type}".format( key=file_param_name, type=type(value), input_file_type=InputFile, text_type=unicode_type)) # end if if not _command: # command as camelCase # "voice_note" -> "sendVoiceNote" # https://stackoverflow.com/a/10984923/3423324 command = re.sub(r'(?!^)_([a-zA-Z])', lambda m: m.group(1).upper(), "send_" + file_param_name) else: command = _command # end def return self.do(command, **kwargs)
def _postprocess_request(self, r)
This converts the response to either the response or a parsed :class:`pytgbot.api_types.receivable.Receivable`. :param r: the request response :type r: requests.Response :return: The json response from the server, or, if `self.return_python_objects` is `True`, a parsed return type. :rtype: DictObject.DictObject | pytgbot.api_types.receivable.Receivable
3.961436
3.733773
1.060974
from .api_types.receivable.media import File assert isinstance(file, File) return file.get_download_url(self.api_key)
def get_download_url(self, file)
Creates a url to download the file. Note: Contains the secret API key, so you should not share this url! :param file: The File you want to get the url to download. :type file: pytgbot.api_types.receivable.media.File :return: url :rtype: str
10.329956
4.422898
2.335563
myself = self.get_me() if self.return_python_objects: self._id = myself.id self._username = myself.username else: self._id = myself["result"]["id"] self._username = myself["result"]["username"]
def _load_info(self)
This functions stores the id and the username of the bot. Called by `.username` and `.id` properties. :return:
4.894471
3.544194
1.380983
if full_data: data = self.to_array() data['media'], file = self.get_inputfile_data(self.media, var_name, suffix='_media') return data, file # end if return self.get_inputfile_data(self.media, var_name, suffix='_media')
def get_request_data(self, var_name, full_data=False)
:param var_name: :param full_data: If you want `.to_array()` with this data, ready to be sent. :return: A tuple of `to_array()` dict and the files (:py:func:`InputFile.get_request_files()`). Files can be None, if no file was given, but an url or existing `file_id`. If `media` is :py:class:`InputFile` however, the first tuple element, media, will have ['media'] set to `attach://{var_name}_media` automatically.
5.011336
3.303895
1.516796
if not full_data: raise ArithmeticError('we have a thumbnail, please use `full_data=True`.') # end if file = {} data, file_to_add = super(InputMediaWithThumb, self).get_request_data(var_name, full_data=True) if file_to_add: file.update(file_to_add) # end if data['thumb'], file_to_add = self.get_inputfile_data(self.thumb, var_name, suffix='_thumb') if data['thumb'] is None: del data['thumb'] # having `'thumb': null` in the json produces errors. # end if if file_to_add: file.update(file_to_add) # end if return data, (file or None)
def get_request_data(self, var_name, full_data=False)
:param var_name: :param full_data: If you want `.to_array()` with this data, ready to be sent. :return: A tuple of `to_array()` dict and the files (:py:func:`InputFile.get_request_files()`). Files can be None, if no file was given, but an url or existing `file_id`. If `self.media` is an `InputFile` however, the first tuple element (either the string, or the dict's `['media']` if `full_data=True`), will be set to `attach://{var_name}_media` automatically. If `self.thumb` is an `InputFile` however, the first tuple element's `['thumb']`, will be set to `attach://{var_name}_thumb` automatically.
4.605335
3.950482
1.165765
from .files import InputFile array = super(InputMediaVideo, self).to_array() # 'type' given by superclass # 'media' given by superclass if self.thumb is not None: if isinstance(self.thumb, InputFile): array['thumb'] = None # type InputFile elif isinstance(self.thumb, str): array['thumb'] = u(self.thumb) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if # 'caption' given by superclass # 'parse_mode' given by superclass if self.width is not None: array['width'] = int(self.width) # type int if self.height is not None: array['height'] = int(self.height) # type int if self.duration is not None: array['duration'] = int(self.duration) # type int if self.supports_streaming is not None: array['supports_streaming'] = bool(self.supports_streaming) # type bool return array
def to_array(self)
Serializes this InputMediaVideo to a dictionary. :return: dictionary representation of this object. :rtype: dict
2.346583
2.119044
1.107378
array = super(InputMediaAnimation, self).to_array() # 'type' given by superclass # 'media' given by superclass if self.thumb is not None: if isinstance(self.thumb, InputFile): array['thumb'] = None # type InputFile elif isinstance(self.thumb, str): array['thumb'] = u(self.thumb) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if # 'caption' given by superclass # 'parse_mode' given by superclass if self.width is not None: array['width'] = int(self.width) # type int if self.height is not None: array['height'] = int(self.height) # type int if self.duration is not None: array['duration'] = int(self.duration) # type int return array
def to_array(self)
Serializes this InputMediaAnimation to a dictionary. :return: dictionary representation of this object. :rtype: dict
2.497829
2.270752
1.100001
array = super(InputMediaAudio, self).to_array() # 'type' given by superclass # 'media' given by superclass if self.thumb is not None: if isinstance(self.thumb, InputFile): array['thumb'] = None # type InputFile elif isinstance(self.thumb, str): array['thumb'] = u(self.thumb) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if # 'caption' given by superclass # 'parse_mode' given by superclass if self.duration is not None: array['duration'] = int(self.duration) # type int if self.performer is not None: array['performer'] = u(self.performer) # py2: type unicode, py3: type str if self.title is not None: array['title'] = u(self.title) # py2: type unicode, py3: type str return array
def to_array(self)
Serializes this InputMediaAudio to a dictionary. :return: dictionary representation of this object. :rtype: dict
2.30965
2.147435
1.075539
array = super(InputMediaDocument, self).to_array() # 'type' given by superclass # 'media' given by superclass if self.thumb is not None: if isinstance(self.thumb, InputFile): array['thumb'] = None # type InputFile elif isinstance(self.thumb, str): array['thumb'] = u(self.thumb) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if # 'caption' given by superclass # 'parse_mode' given by superclass return array
def to_array(self)
Serializes this InputMediaDocument to a dictionary. :return: dictionary representation of this object. :rtype: dict
3.564964
3.087507
1.154642
if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.sendable.files import InputFile data = {} # 'type' is given by class type data['media'] = u(array.get('media')) if array.get('thumb') is None: data['thumb'] = None elif isinstance(array.get('thumb'), InputFile): data['thumb'] = None # will be filled later by get_request_data() elif isinstance(array.get('thumb'), str): data['thumb'] = u(array.get('thumb')) else: raise TypeError('Unknown type, must be one of InputFile, str or None.') # end if data['caption'] = u(array.get('caption')) if array.get('caption') is not None else None data['parse_mode'] = u(array.get('parse_mode')) if array.get('parse_mode') is not None else None instance = InputMediaDocument(**data) instance._raw = array return instance
def from_array(array)
Deserialize a new InputMediaDocument from a given dictionary. :return: new InputMediaDocument instance. :rtype: InputMediaDocument
2.802762
2.447481
1.145162
merged = array('i', [0] * len(map2)) for i, shift in enumerate(map2): merged[i] = shift + map1[i + shift] return merged
def _mergemap(map1, map2)
Positions in map2 have an integer indicating the relative shift to the equivalent position in map1. E.g., the i'th position in map2 corresponds to the i + map2[i] position in map1.
4.667645
3.576084
1.305239
if not exists(path): raise REPPError('REPP config file not found: {}'.format(path)) confdir = dirname(path) # TODO: can TDL parsing be repurposed for this variant? conf = io.open(path, encoding='utf-8').read() conf = re.sub(r';.*', '', conf).replace('\n',' ') m = re.search( r'repp-modules\s*:=\s*((?:[-\w]+\s+)*[-\w]+)\s*\.', conf) t = re.search( r'repp-tokenizer\s*:=\s*([-\w]+)\s*\.', conf) a = re.search( r'repp-calls\s*:=\s*((?:[-\w]+\s+)*[-\w]+)\s*\.', conf) f = re.search( r'format\s*:=\s*(\w+)\s*\.', conf) d = re.search( r'repp-directory\s*:=\s*(.*)\.\s*$', conf) if m is None: raise REPPError('repp-modules option must be set') if t is None: raise REPPError('repp-tokenizer option must be set') mods = m.group(1).split() tok = t.group(1).strip() active = a.group(1).split() if a is not None else None fmt = f.group(1).strip() if f is not None else None if directory is None: if d is not None: directory = d.group(1).strip(' "') elif exists(joinpath(confdir, tok + '.rpp')): directory = confdir elif exists(joinpath(confdir, 'rpp', tok + '.rpp')): directory = joinpath(confdir, 'rpp') elif exists(joinpath(confdir, '../rpp', tok + '.rpp')): directory = joinpath(confdir, '../rpp') else: raise REPPError('Could not find a suitable REPP directory.') # ignore repp-modules and format? return REPP.from_file( joinpath(directory, tok + '.rpp'), directory=directory, active=active )
def from_config(cls, path, directory=None)
Instantiate a REPP from a PET-style `.set` configuration file. The *path* parameter points to the configuration file. Submodules are loaded from *directory*. If *directory* is not given, it is the directory part of *path*. Args: path (str): the path to the REPP configuration file directory (str, optional): the directory in which to search for submodules
2.851802
2.830025
1.007695
name = basename(path) if name.endswith('.rpp'): name = name[:-4] lines = _repp_lines(path) directory = dirname(path) if directory is None else directory r = cls(name=name, modules=modules, active=active) _parse_repp(lines, r, directory) return r
def from_file(cls, path, directory=None, modules=None, active=None)
Instantiate a REPP from a `.rpp` file. The *path* parameter points to the top-level module. Submodules are loaded from *directory*. If *directory* is not given, it is the directory part of *path*. A REPP module may utilize external submodules, which may be defined in two ways. The first method is to map a module name to an instantiated REPP instance in *modules*. The second method assumes that an external group call `>abc` corresponds to a file `abc.rpp` in *directory* and loads that file. The second method only happens if the name (e.g., `abc`) does not appear in *modules*. Only one module may define a tokenization pattern. Args: path (str): the path to the base REPP file to load directory (str, optional): the directory in which to search for submodules modules (dict, optional): a mapping from identifiers to REPP modules active (iterable, optional): an iterable of default module activations
4.273137
4.041458
1.057326
r = cls(name=name, modules=modules, active=active) _parse_repp(s.splitlines(), r, None) return r
def from_string(cls, s, name=None, modules=None, active=None)
Instantiate a REPP from a string. Args: name (str, optional): the name of the REPP module modules (dict, optional): a mapping from identifiers to REPP modules active (iterable, optional): an iterable of default module activations
6.18864
7.079707
0.874138
if mod in self.active: self.active.remove(mod)
def deactivate(self, mod)
Set external module *mod* to inactive.
4.257676
3.647807
1.167188
if active is None: active = self.active return self.group.apply(s, active=active)
def apply(self, s, active=None)
Apply the REPP's rewrite rules to the input string *s*. Args: s (str): the input string to process active (optional): a collection of external module names that may be applied if called Returns: a :class:`REPPResult` object containing the processed string and characterization maps
3.742559
6.19467
0.604158
if active is None: active = self.active return self.group.trace(s, active=active, verbose=verbose)
def trace(self, s, active=None, verbose=False)
Rewrite string *s* like `apply()`, but yield each rewrite step. Args: s (str): the input string to process active (optional): a collection of external module names that may be applied if called verbose (bool, optional): if `False`, only output rules or groups that matched the input Yields: a :class:`REPPStep` object for each intermediate rewrite step, and finally a :class:`REPPResult` object after the last rewrite
3.066832
6.397186
0.479403
if pattern is None: if self.tokenize_pattern is None: pattern = r'[ \t]+' else: pattern = self.tokenize_pattern if active is None: active = self.active return self.group.tokenize(s, pattern=pattern, active=active)
def tokenize(self, s, pattern=None, active=None)
Rewrite and tokenize the input string *s*. Args: s (str): the input string to process pattern (str, optional): the regular expression pattern on which to split tokens; defaults to `[ \t]+` active (optional): a collection of external module names that may be applied if called Returns: a :class:`~delphin.tokens.YyTokenLattice` containing the tokens and their characterization information
2.492968
2.665511
0.935268
if self.receiver is None: self.receiver = receiver # end if if self.reply_id is DEFAULT_MESSAGE_ID: self.reply_id = reply_id
def _apply_update_receiver(self, receiver, reply_id)
Updates `self.receiver` and/or `self.reply_id` if they still contain the default value. :param receiver: The receiver `chat_id` to use. Either `self.receiver`, if set, e.g. when instancing `TextMessage(receiver=10001231231, ...)`, or the `chat.id` of the update context, being the id of groups or the user's `from_peer.id` in private messages. :type receiver: None | str|unicode | int :param reply_id: Reply to that `message_id` in the chat we send to. Either `self.reply_id`, if set, e.g. when instancing `TextMessage(reply_id=123123, ...)`, or the `message_id` of the update which triggered the bot's functions. :type reply_id: DEFAULT_MESSAGE_ID | int
4.022811
3.27214
1.229413
return sender.send_message( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id text=self.text, chat_id=self.receiver, reply_to_message_id=self.reply_id, parse_mode=self.parse_mode, disable_web_page_preview=self.disable_web_page_preview, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
def send(self, sender: PytgbotApiBot)
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
2.521927
2.708553
0.931098
array = super(TextMessage, self).to_array() array['text'] = u(self.text) # py2: type unicode, py3: type str if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.disable_web_page_preview is not None: array['disable_web_page_preview'] = bool(self.disable_web_page_preview) # type bool if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
def to_array(self)
Serializes this TextMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict
1.658867
1.638063
1.0127
return sender.send_photo( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id photo=self.photo, chat_id=self.receiver, reply_to_message_id=self.reply_id, caption=self.caption, parse_mode=self.parse_mode, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
def send(self, sender: PytgbotApiBot)
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
2.965837
3.059237
0.96947
return sender.send_audio( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id audio=self.audio, chat_id=self.receiver, reply_to_message_id=self.reply_id, caption=self.caption, parse_mode=self.parse_mode, duration=self.duration, performer=self.performer, title=self.title, thumb=self.thumb, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
def send(self, sender: PytgbotApiBot)
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
2.566917
2.704495
0.94913
array = super(AudioMessage, self).to_array() if isinstance(self.audio, InputFile): array['audio'] = self.audio.to_array() # type InputFile elif isinstance(self.audio, str): array['audio'] = u(self.audio) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.caption is not None: array['caption'] = u(self.caption) # py2: type unicode, py3: type str if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.duration is not None: array['duration'] = int(self.duration) # type int if self.performer is not None: array['performer'] = u(self.performer) # py2: type unicode, py3: type str if self.title is not None: array['title'] = u(self.title) # py2: type unicode, py3: type str if self.thumb is not None: if isinstance(self.thumb, InputFile): array['thumb'] = self.thumb.to_array() # type InputFile elif isinstance(self.thumb, str): array['thumb'] = u(self.thumb) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
def to_array(self)
Serializes this AudioMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict
1.504337
1.480116
1.016365
return sender.send_document( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id document=self.document, chat_id=self.receiver, reply_to_message_id=self.reply_id, thumb=self.thumb, caption=self.caption, parse_mode=self.parse_mode, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
def send(self, sender: PytgbotApiBot)
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
2.910611
3.075571
0.946365
return sender.send_video( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id video=self.video, chat_id=self.receiver, reply_to_message_id=self.reply_id, duration=self.duration, width=self.width, height=self.height, thumb=self.thumb, caption=self.caption, parse_mode=self.parse_mode, supports_streaming=self.supports_streaming, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
def send(self, sender: PytgbotApiBot)
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
2.522563
2.684248
0.939765
return sender.send_animation( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id animation=self.animation, chat_id=self.receiver, reply_to_message_id=self.reply_id, duration=self.duration, width=self.width, height=self.height, thumb=self.thumb, caption=self.caption, parse_mode=self.parse_mode, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
def send(self, sender: PytgbotApiBot)
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
2.580864
2.727812
0.94613
array = super(AnimationMessage, self).to_array() if isinstance(self.animation, InputFile): array['animation'] = self.animation.to_array() # type InputFile elif isinstance(self.animation, str): array['animation'] = u(self.animation) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.duration is not None: array['duration'] = int(self.duration) # type int if self.width is not None: array['width'] = int(self.width) # type int if self.height is not None: array['height'] = int(self.height) # type int if self.thumb is not None: if isinstance(self.thumb, InputFile): array['thumb'] = self.thumb.to_array() # type InputFile elif isinstance(self.thumb, str): array['thumb'] = u(self.thumb) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.caption is not None: array['caption'] = u(self.caption) # py2: type unicode, py3: type str if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
def to_array(self)
Serializes this AnimationMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict
1.52213
1.498485
1.01578
return sender.send_voice( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id voice=self.voice, chat_id=self.receiver, reply_to_message_id=self.reply_id, caption=self.caption, parse_mode=self.parse_mode, duration=self.duration, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
def send(self, sender: PytgbotApiBot)
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
3.043864
3.279164
0.928244
array = super(VoiceMessage, self).to_array() if isinstance(self.voice, InputFile): array['voice'] = self.voice.to_array() # type InputFile elif isinstance(self.voice, str): array['voice'] = u(self.voice) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.caption is not None: array['caption'] = u(self.caption) # py2: type unicode, py3: type str if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.duration is not None: array['duration'] = int(self.duration) # type int if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
def to_array(self)
Serializes this VoiceMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict
1.630363
1.610216
1.012512
return sender.send_video_note( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id video_note=self.video_note, chat_id=self.receiver, reply_to_message_id=self.reply_id, duration=self.duration, length=self.length, thumb=self.thumb, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
def send(self, sender: PytgbotApiBot)
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
3.115086
3.323957
0.937162
array = super(VideoNoteMessage, self).to_array() if isinstance(self.video_note, InputFile): array['video_note'] = self.video_note.to_array() # type InputFile elif isinstance(self.video_note, str): array['video_note'] = u(self.video_note) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.duration is not None: array['duration'] = int(self.duration) # type int if self.length is not None: array['length'] = int(self.length) # type int if self.thumb is not None: if isinstance(self.thumb, InputFile): array['thumb'] = self.thumb.to_array() # type InputFile elif isinstance(self.thumb, str): array['thumb'] = u(self.thumb) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
def to_array(self)
Serializes this VideoNoteMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict
1.568257
1.518914
1.032486
return sender.send_media_group( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id media=self.media, chat_id=self.receiver, reply_to_message_id=self.reply_id, disable_notification=self.disable_notification )
def send(self, sender: PytgbotApiBot)
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
3.496421
3.867356
0.904086
array = super(MediaGroupMessage, self).to_array() if isinstance(self.media, InputMediaPhoto): array['media'] = self._as_array(self.media) # type list of InputMediaPhoto | list of InputMediaVideo elif isinstance(self.media, InputMediaVideo): array['media'] = self._as_array(self.media) # type list of InputMediaPhoto | list of InputMediaVideo else: raise TypeError('Unknown type, must be one of InputMediaPhoto, InputMediaVideo.') # end if if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool return array
def to_array(self)
Serializes this MediaGroupMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict
2.388833
2.303066
1.03724
if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.sendable.input_media import InputMediaPhoto from pytgbot.api_types.sendable.input_media import InputMediaVideo data = {} if isinstance(array.get('media'), InputMediaPhoto): data['media'] = InputMediaPhoto.from_array_list(array.get('media'), list_level=1) elif isinstance(array.get('media'), InputMediaVideo): data['media'] = InputMediaVideo.from_array_list(array.get('media'), list_level=1) else: raise TypeError('Unknown type, must be one of InputMediaPhoto, InputMediaVideo.') # end if if array.get('chat_id') is None: data['receiver'] = None elif isinstance(array.get('chat_id'), None): data['receiver'] = None(array.get('chat_id')) elif isinstance(array.get('chat_id'), str): data['receiver'] = u(array.get('chat_id')) elif isinstance(array.get('chat_id'), int): data['receiver'] = int(array.get('chat_id')) else: raise TypeError('Unknown type, must be one of None, str, int or None.') # end if if array.get('reply_to_message_id') is None: data['reply_id'] = None elif isinstance(array.get('reply_to_message_id'), DEFAULT_MESSAGE_ID): data['reply_id'] = DEFAULT_MESSAGE_ID(array.get('reply_to_message_id')) elif isinstance(array.get('reply_to_message_id'), int): data['reply_id'] = int(array.get('reply_to_message_id')) else: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int or None.') # end if data['disable_notification'] = bool(array.get('disable_notification')) if array.get('disable_notification') is not None else None return MediaGroupMessage(**data)
def from_array(array)
Deserialize a new MediaGroupMessage from a given dictionary. :return: new MediaGroupMessage instance. :rtype: MediaGroupMessage
1.856321
1.758023
1.055914
return sender.send_location( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id latitude=self.latitude, longitude=self.longitude, chat_id=self.receiver, reply_to_message_id=self.reply_id, live_period=self.live_period, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
def send(self, sender: PytgbotApiBot)
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
3.181278
3.340485
0.95234
array = super(LocationMessage, self).to_array() array['latitude'] = float(self.latitude) # type float array['longitude'] = float(self.longitude) # type float if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.live_period is not None: array['live_period'] = int(self.live_period) # type int if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
def to_array(self)
Serializes this LocationMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict
1.783563
1.744182
1.022578
return sender.send_venue( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id latitude=self.latitude, longitude=self.longitude, title=self.title, address=self.address, chat_id=self.receiver, reply_to_message_id=self.reply_id, foursquare_id=self.foursquare_id, foursquare_type=self.foursquare_type, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
def send(self, sender: PytgbotApiBot)
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
2.702659
2.792638
0.96778
array = super(VenueMessage, self).to_array() array['latitude'] = float(self.latitude) # type float array['longitude'] = float(self.longitude) # type float array['title'] = u(self.title) # py2: type unicode, py3: type str array['address'] = u(self.address) # py2: type unicode, py3: type str if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.foursquare_id is not None: array['foursquare_id'] = u(self.foursquare_id) # py2: type unicode, py3: type str if self.foursquare_type is not None: array['foursquare_type'] = u(self.foursquare_type) # py2: type unicode, py3: type str if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
def to_array(self)
Serializes this VenueMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict
1.660543
1.628906
1.019423
return sender.send_contact( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id phone_number=self.phone_number, first_name=self.first_name, chat_id=self.receiver, reply_to_message_id=self.reply_id, last_name=self.last_name, vcard=self.vcard, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
def send(self, sender: PytgbotApiBot)
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
3.133752
3.214903
0.974758
array = super(ContactMessage, self).to_array() array['phone_number'] = u(self.phone_number) # py2: type unicode, py3: type str array['first_name'] = u(self.first_name) # py2: type unicode, py3: type str if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.last_name is not None: array['last_name'] = u(self.last_name) # py2: type unicode, py3: type str if self.vcard is not None: array['vcard'] = u(self.vcard) # py2: type unicode, py3: type str if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
def to_array(self)
Serializes this ContactMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict
1.720972
1.696553
1.014393
return sender.send_chat_action( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id action=self.action, chat_id=self.receiver )
def send(self, sender: PytgbotApiBot)
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
6.555262
7.151574
0.916618
array = super(ChatActionMessage, self).to_array() array['action'] = u(self.action) # py2: type unicode, py3: type str if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if return array
def to_array(self)
Serializes this ChatActionMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict
3.736141
3.42485
1.090892
if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['action'] = u(array.get('action')) if array.get('chat_id') is None: data['receiver'] = None elif isinstance(array.get('chat_id'), None): data['receiver'] = None(array.get('chat_id')) elif isinstance(array.get('chat_id'), str): data['receiver'] = u(array.get('chat_id')) elif isinstance(array.get('chat_id'), int): data['receiver'] = int(array.get('chat_id')) else: raise TypeError('Unknown type, must be one of None, str, int or None.') # end if return ChatActionMessage(**data)
def from_array(array)
Deserialize a new ChatActionMessage from a given dictionary. :return: new ChatActionMessage instance. :rtype: ChatActionMessage
2.903899
2.546785
1.140221
return sender.send_sticker( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id sticker=self.sticker, chat_id=self.receiver, reply_to_message_id=self.reply_id, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
def send(self, sender: PytgbotApiBot)
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
3.479856
3.730852
0.932724
array = super(StickerMessage, self).to_array() if isinstance(self.sticker, InputFile): array['sticker'] = self.sticker.to_array() # type InputFile elif isinstance(self.sticker, str): array['sticker'] = u(self.sticker) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
def to_array(self)
Serializes this StickerMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict
1.713621
1.659807
1.032422
if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.sendable.files import InputFile from pytgbot.api_types.sendable.reply_markup import ForceReply from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup from pytgbot.api_types.sendable.reply_markup import ReplyKeyboardMarkup from pytgbot.api_types.sendable.reply_markup import ReplyKeyboardRemove data = {} if isinstance(array.get('sticker'), InputFile): data['sticker'] = InputFile.from_array(array.get('sticker')) elif isinstance(array.get('sticker'), str): data['sticker'] = u(array.get('sticker')) else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if array.get('chat_id') is None: data['receiver'] = None elif isinstance(array.get('chat_id'), None): data['receiver'] = None(array.get('chat_id')) elif isinstance(array.get('chat_id'), str): data['receiver'] = u(array.get('chat_id')) elif isinstance(array.get('chat_id'), int): data['receiver'] = int(array.get('chat_id')) else: raise TypeError('Unknown type, must be one of None, str, int or None.') # end if if array.get('reply_to_message_id') is None: data['reply_id'] = None elif isinstance(array.get('reply_to_message_id'), DEFAULT_MESSAGE_ID): data['reply_id'] = DEFAULT_MESSAGE_ID(array.get('reply_to_message_id')) elif isinstance(array.get('reply_to_message_id'), int): data['reply_id'] = int(array.get('reply_to_message_id')) else: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int or None.') # end if data['disable_notification'] = bool(array.get('disable_notification')) if array.get('disable_notification') is not None else None if array.get('reply_markup') is None: data['reply_markup'] = None elif isinstance(array.get('reply_markup'), InlineKeyboardMarkup): data['reply_markup'] = InlineKeyboardMarkup.from_array(array.get('reply_markup')) elif isinstance(array.get('reply_markup'), ReplyKeyboardMarkup): data['reply_markup'] = ReplyKeyboardMarkup.from_array(array.get('reply_markup')) elif isinstance(array.get('reply_markup'), ReplyKeyboardRemove): data['reply_markup'] = ReplyKeyboardRemove.from_array(array.get('reply_markup')) elif isinstance(array.get('reply_markup'), ForceReply): data['reply_markup'] = ForceReply.from_array(array.get('reply_markup')) else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply or None.') # end if return StickerMessage(**data)
def from_array(array)
Deserialize a new StickerMessage from a given dictionary. :return: new StickerMessage instance. :rtype: StickerMessage
1.546904
1.512368
1.022836
return sender.send_invoice( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id title=self.title, description=self.description, payload=self.payload, provider_token=self.provider_token, start_parameter=self.start_parameter, currency=self.currency, prices=self.prices, chat_id=self.receiver, reply_to_message_id=self.reply_id, provider_data=self.provider_data, photo_url=self.photo_url, photo_size=self.photo_size, photo_width=self.photo_width, photo_height=self.photo_height, need_name=self.need_name, need_phone_number=self.need_phone_number, need_email=self.need_email, need_shipping_address=self.need_shipping_address, send_phone_number_to_provider=self.send_phone_number_to_provider, send_email_to_provider=self.send_email_to_provider, is_flexible=self.is_flexible, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
def send(self, sender: PytgbotApiBot)
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
1.660075
1.700356
0.97631
array = super(InvoiceMessage, self).to_array() array['title'] = u(self.title) # py2: type unicode, py3: type str array['description'] = u(self.description) # py2: type unicode, py3: type str array['payload'] = u(self.payload) # py2: type unicode, py3: type str array['provider_token'] = u(self.provider_token) # py2: type unicode, py3: type str array['start_parameter'] = u(self.start_parameter) # py2: type unicode, py3: type str array['currency'] = u(self.currency) # py2: type unicode, py3: type str array['prices'] = self._as_array(self.prices) # type list of LabeledPrice if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.provider_data is not None: array['provider_data'] = u(self.provider_data) # py2: type unicode, py3: type str if self.photo_url is not None: array['photo_url'] = u(self.photo_url) # py2: type unicode, py3: type str if self.photo_size is not None: array['photo_size'] = int(self.photo_size) # type int if self.photo_width is not None: array['photo_width'] = int(self.photo_width) # type int if self.photo_height is not None: array['photo_height'] = int(self.photo_height) # type int if self.need_name is not None: array['need_name'] = bool(self.need_name) # type bool if self.need_phone_number is not None: array['need_phone_number'] = bool(self.need_phone_number) # type bool if self.need_email is not None: array['need_email'] = bool(self.need_email) # type bool if self.need_shipping_address is not None: array['need_shipping_address'] = bool(self.need_shipping_address) # type bool if self.send_phone_number_to_provider is not None: array['send_phone_number_to_provider'] = bool(self.send_phone_number_to_provider) # type bool if self.send_email_to_provider is not None: array['send_email_to_provider'] = bool(self.send_email_to_provider) # type bool if self.is_flexible is not None: array['is_flexible'] = bool(self.is_flexible) # type bool if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup return array
def to_array(self)
Serializes this InvoiceMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict
1.511785
1.495146
1.011128
if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.sendable.payments import LabeledPrice from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup data = {} data['title'] = u(array.get('title')) data['description'] = u(array.get('description')) data['payload'] = u(array.get('payload')) data['provider_token'] = u(array.get('provider_token')) data['start_parameter'] = u(array.get('start_parameter')) data['currency'] = u(array.get('currency')) data['prices'] = LabeledPrice.from_array_list(array.get('prices'), list_level=1) if array.get('chat_id') is None: data['receiver'] = None elif isinstance(array.get('chat_id'), None): data['receiver'] = None(array.get('chat_id')) elif isinstance(array.get('chat_id'), str): data['receiver'] = u(array.get('chat_id')) elif isinstance(array.get('chat_id'), int): data['receiver'] = int(array.get('chat_id')) else: raise TypeError('Unknown type, must be one of None, str, int or None.') # end if if array.get('reply_to_message_id') is None: data['reply_id'] = None elif isinstance(array.get('reply_to_message_id'), DEFAULT_MESSAGE_ID): data['reply_id'] = DEFAULT_MESSAGE_ID(array.get('reply_to_message_id')) elif isinstance(array.get('reply_to_message_id'), int): data['reply_id'] = int(array.get('reply_to_message_id')) else: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int or None.') # end if data['provider_data'] = u(array.get('provider_data')) if array.get('provider_data') is not None else None data['photo_url'] = u(array.get('photo_url')) if array.get('photo_url') is not None else None data['photo_size'] = int(array.get('photo_size')) if array.get('photo_size') is not None else None data['photo_width'] = int(array.get('photo_width')) if array.get('photo_width') is not None else None data['photo_height'] = int(array.get('photo_height')) if array.get('photo_height') is not None else None data['need_name'] = bool(array.get('need_name')) if array.get('need_name') is not None else None data['need_phone_number'] = bool(array.get('need_phone_number')) if array.get('need_phone_number') is not None else None data['need_email'] = bool(array.get('need_email')) if array.get('need_email') is not None else None data['need_shipping_address'] = bool(array.get('need_shipping_address')) if array.get('need_shipping_address') is not None else None data['send_phone_number_to_provider'] = bool(array.get('send_phone_number_to_provider')) if array.get('send_phone_number_to_provider') is not None else None data['send_email_to_provider'] = bool(array.get('send_email_to_provider')) if array.get('send_email_to_provider') is not None else None data['is_flexible'] = bool(array.get('is_flexible')) if array.get('is_flexible') is not None else None data['disable_notification'] = bool(array.get('disable_notification')) if array.get('disable_notification') is not None else None data['reply_markup'] = InlineKeyboardMarkup.from_array(array.get('reply_markup')) if array.get('reply_markup') is not None else None return InvoiceMessage(**data)
def from_array(array)
Deserialize a new InvoiceMessage from a given dictionary. :return: new InvoiceMessage instance. :rtype: InvoiceMessage
1.440165
1.398246
1.02998
return sender.send_game( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id game_short_name=self.game_short_name, chat_id=self.receiver, reply_to_message_id=self.reply_id, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
def send(self, sender: PytgbotApiBot)
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
3.477679
3.664513
0.949015
array = super(GameMessage, self).to_array() array['game_short_name'] = u(self.game_short_name) # py2: type unicode, py3: type str if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup return array
def to_array(self)
Serializes this GameMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict
2.268575
2.251011
1.007803
if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup data = {} data['game_short_name'] = u(array.get('game_short_name')) if array.get('chat_id') is None: data['receiver'] = None elif isinstance(array.get('chat_id'), None): data['receiver'] = None(array.get('chat_id')) elif isinstance(array.get('chat_id'), str): data['receiver'] = u(array.get('chat_id')) elif isinstance(array.get('chat_id'), int): data['receiver'] = int(array.get('chat_id')) else: raise TypeError('Unknown type, must be one of None, str, int or None.') # end if if array.get('reply_to_message_id') is None: data['reply_id'] = None elif isinstance(array.get('reply_to_message_id'), DEFAULT_MESSAGE_ID): data['reply_id'] = DEFAULT_MESSAGE_ID(array.get('reply_to_message_id')) elif isinstance(array.get('reply_to_message_id'), int): data['reply_id'] = int(array.get('reply_to_message_id')) else: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int or None.') # end if data['disable_notification'] = bool(array.get('disable_notification')) if array.get('disable_notification') is not None else None data['reply_markup'] = InlineKeyboardMarkup.from_array(array.get('reply_markup')) if array.get('reply_markup') is not None else None return GameMessage(**data)
def from_array(array)
Deserialize a new GameMessage from a given dictionary. :return: new GameMessage instance. :rtype: GameMessage
2.017756
1.898057
1.063064
def datamatch(nid): ep = xmrs.ep(nid) return ((iv is None or ep.iv == iv) and (pred is None or ep.pred == pred) and (label is None or ep.label == label)) return list(filter(datamatch, xmrs.nodeids()))
def select_nodeids(xmrs, iv=None, label=None, pred=None)
Return the list of matching nodeids in *xmrs*. Nodeids in *xmrs* match if their corresponding :class:`~delphin.mrs.components.ElementaryPredication` object matches its `intrinsic_variable` to *iv*, `label` to *label*, and `pred` to *pred*. The *iv*, *label*, and *pred* filters are ignored if they are `None`. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to query iv (str, optional): intrinsic variable to match label (str, optional): label to match pred (str, :class:`~delphin.mrs.components.Pred`, optional): predicate to match Returns: list: matching nodeids
3.447068
3.649809
0.944452
nodematch = lambda n: ((nodeid is None or n.nodeid == nodeid) and (pred is None or n.pred == pred)) return list(filter(nodematch, nodes(xmrs)))
def select_nodes(xmrs, nodeid=None, pred=None)
Return the list of matching nodes in *xmrs*. DMRS :class:`nodes <delphin.mrs.components.node>` for *xmrs* match if their `nodeid` matches *nodeid* and `pred` matches *pred*. The *nodeid* and *pred* filters are ignored if they are `None`. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to query nodeid (optional): DMRS nodeid to match pred (str, :class:`~delphin.mrs.components.Pred`, optional): predicate to match Returns: list: matching nodes
3.296883
4.022703
0.819569
epmatch = lambda n: ((nodeid is None or n.nodeid == nodeid) and (iv is None or n.iv == iv) and (label is None or n.label == label) and (pred is None or n.pred == pred)) return list(filter(epmatch, xmrs.eps()))
def select_eps(xmrs, nodeid=None, iv=None, label=None, pred=None)
Return the list of matching elementary predications in *xmrs*. :class:`~delphin.mrs.components.ElementaryPredication` objects for *xmrs* match if their `nodeid` matches *nodeid*, `intrinsic_variable` matches *iv*, `label` matches *label*, and `pred` to *pred*. The *nodeid*, *iv*, *label*, and *pred* filters are ignored if they are `None`. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to query nodeid (optional): nodeid to match iv (str, optional): intrinsic variable to match label (str, optional): label to match pred (str, :class:`~delphin.mrs.components.Pred`, optional): predicate to match Returns: list: matching elementary predications
2.271007
2.567575
0.884495
argmatch = lambda a: ((nodeid is None or a[0] == nodeid) and (rargname is None or a[1].upper() == rargname.upper()) and (value is None or a[2] == value)) all_args = ( (nid, role, val) for nid in xmrs.nodeids() for role, val in sorted( xmrs.args(nid).items(), key=lambda i: rargname_sortkey(i[0]) ) ) return list(filter(argmatch, all_args))
def select_args(xmrs, nodeid=None, rargname=None, value=None)
Return the list of matching (nodeid, role, value) triples in *xmrs*. Predication arguments in *xmrs* match if the `nodeid` of the :class:`~delphin.mrs.components.ElementaryPredication` they are arguments of match *nodeid*, their role matches *rargname*, and their value matches *value*. The *nodeid*, *rargname*, and *value* filters are ignored if they are `None`. Note: The *value* filter matches the variable, handle, or constant that is the overt value for the argument. If you want to find arguments that target a particular nodeid, look into :meth:`Xmrs.incoming_args() <delphin.mrs.xmrs.Xmrs.incoming_args>`. If you want to match a target value to its resolved object, see :func:`find_argument_target`. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to query nodeid (optional): nodeid to match rargname (str, optional): role name to match value (str, optional): argument value to match Returns: list: matching arguments as (nodeid, role, value) triples
2.810562
2.746696
1.023252
linkmatch = lambda l: ( (start is None or l.start == start) and (end is None or l.end == end) and (rargname is None or l.rargname == rargname) and (post is None or l.post == post)) return list(filter(linkmatch, links(xmrs)))
def select_links(xmrs, start=None, end=None, rargname=None, post=None)
Return the list of matching links for *xmrs*. :class:`~delphin.mrs.components.Link` objects for *xmrs* match if their `start` matches *start*, `end` matches *end*, `rargname` matches *rargname*, and `post` matches *post*. The *start*, *end*, *rargname*, and *post* filters are ignored if they are `None`. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to query start (optional): link start nodeid to match end (optional): link end nodeid to match rargname (str, optional): role name to match post (str, optional): Link post-slash label to match Returns: list: matching links
2.098516
2.3396
0.896955
hcmatch = lambda hc: ( (hi is None or hc.hi == hi) and (relation is None or hc.relation == relation) and (lo is None or hc.lo == lo)) return list(filter(hcmatch, xmrs.hcons()))
def select_hcons(xmrs, hi=None, relation=None, lo=None)
Return the list of matching HCONS for *xmrs*. :class:`~delphin.mrs.components.HandleConstraint` objects for *xmrs* match if their `hi` matches *hi*, `relation` matches *relation*, and `lo` matches *lo*. The *hi*, *relation*, and *lo* filters are ignored if they are `None`. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to query hi (str, optional): hi handle (hole) to match relation (str, optional): handle constraint relation to match lo (str, optional): lo handle (label) to match Returns: list: matching HCONS
2.895469
2.980479
0.971478
icmatch = lambda ic: ( (left is None or ic.left == left) and (relation is None or ic.relation == relation) and (right is None or ic.right == right)) return list(filter(icmatch, xmrs.icons()))
def select_icons(xmrs, left=None, relation=None, right=None)
Return the list of matching ICONS for *xmrs*. :class:`~delphin.mrs.components.IndividualConstraint` objects for *xmrs* match if their `left` matches *left*, `relation` matches *relation*, and `right` matches *right*. The *left*, *relation*, and *right* filters are ignored if they are `None`. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to query left (str, optional): left variable to match relation (str, optional): individual constraint relation to match right (str, optional): right variable to match Returns: list: matching ICONS
2.828863
2.869109
0.985972
tgt = xmrs.args(nodeid)[rargname] if tgt in xmrs.variables(): try: return xmrs.nodeid(tgt) except KeyError: pass try: tgt = xmrs.hcon(tgt).lo return next(iter(xmrs.labelset_heads(tgt)), None) except KeyError: pass try: return next(iter(xmrs.labelset_heads(tgt))) except (KeyError, StopIteration): pass return tgt
def find_argument_target(xmrs, nodeid, rargname)
Return the target of an argument (rather than just the variable). Note: If the argument value is an intrinsic variable whose target is an EP that has a quantifier, the non-quantifier EP's nodeid will be returned. With this nodeid, one can then use :meth:`Xmrs.nodeid() <delphin.mrs.xmrs.Xmrs.nodeid>` to get its quantifier's nodeid. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to use nodeid: nodeid of the argument. rargname: role name of the argument. Returns: The object that is the target of the argument. Possible values include: ================== ===== ============================= Argument value e.g. Target ------------------ ----- ----------------------------- intrinsic variable x4 nodeid; of the EP with the IV hole variable h0 nodeid; HCONS's labelset head label h1 nodeid; label's labelset head unbound variable i3 the variable itself constant "IBM" the constant itself ================== ===== =============================
4.042448
3.448931
1.172087
preds = list(preds) count = len(preds) # find all lists of nodeids such that the lists have no repeated nids; # keep them as a list (fixme: why not just get sets?) nidsets = set( tuple(sorted(ns)) for ns in filter( lambda ns: len(set(ns)) == count, product(*[select_nodeids(xmrs, pred=p) for p in preds]) ) ) for nidset in nidsets: sg = xmrs.subgraph(nidset) if connected is None or sg.is_connected() == connected: yield sg
def find_subgraphs_by_preds(xmrs, preds, connected=None)
Yield subgraphs matching a list of predicates. Predicates may match multiple EPs/nodes in the *xmrs*, meaning that more than one subgraph is possible. Also, predicates in *preds* match in number, so if a predicate appears twice in *preds*, there will be two matching EPs/nodes in each subgraph. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to use preds: iterable of predicates to include in subgraphs connected (bool, optional): if `True`, all yielded subgraphs must be connected, as determined by :meth:`Xmrs.is_connected() <delphin.mrs.xmrs.Xmrs.is_connected>`. Yields: A :class:`~delphin.mrs.xmrs.Xmrs` object for each subgraphs found.
5.332167
5.883059
0.90636
ivs = set( ep.intrinsic_variable for ep in xmrs.eps() if not ep.is_quantifier() and ep.intrinsic_variable is not None ) return sorted(ivs, key=var_id)
def intrinsic_variables(xmrs)
Return the list of all intrinsic variables in *xmrs*
5.435201
5.056525
1.074889
bvs = set( ep.intrinsic_variable for ep in xmrs.eps() if ep.is_quantifier() and ep.intrinsic_variable is not None ) return sorted(bvs, key=var_id)
def bound_variables(xmrs)
Return the list of all bound variables in *xmrs*
6.19392
5.845613
1.059584
nodeids = set(nodeids) if label is None: label = xmrs.ep(next(iter(nodeids))).label return nodeids.issubset(xmrs._vars[label]['refs']['LBL'])
def in_labelset(xmrs, nodeids, label=None)
Test if all nodeids share a label. Args: nodeids: iterable of nodeids label (str, optional): the label that all nodeids must share Returns: bool: `True` if all nodeids share a label, otherwise `False`
7.574464
9.635788
0.786076
# file to be uploaded string = 'attach://{name}'.format(name=var_name) return string, self.get_request_files(var_name)
def get_input_media_referenced_files(self, var_name)
Generates a tuple with the value for the json/url argument and a dictionary for the multipart file upload. Will return something which might be similar to `('attach://{var_name}', {var_name: ('foo.png', open('foo.png', 'rb'), 'image/png')})` or in the case of the :class:`InputFileUseFileID` class, just `('AwADBAADbXXXXXXXXXXXGBdhD2l6_XX', None)` :param var_name: name used to reference the file. :type var_name: str :return: tuple of (file_id, dict) :rtype: tuple
9.647192
10.85702
0.888567
if create_instance: clazz, args, kwargs = cls.factory( file_id=file_id, path=path, url=url, blob=blob, mime=mime, create_instance=False, ) return clazz(*args, **kwargs) if file_id: if prefer_str: assert_type_or_raise(file_id, str, parameter_name='file_id') return str, (file_id,), dict() # end if return InputFileUseFileID, (file_id,), dict() if blob: name = "file" suffix = ".blob" if path: name = os_path.basename(os_path.normpath(path)) # http://stackoverflow.com/a/3925147/3423324#last-part name, suffix = os_path.splitext(name) # http://stackoverflow.com/a/541394/3423324#extension elif url: # http://stackoverflow.com/a/18727481/3423324#how-to-extract-a-filename-from-a-url url = urlparse(url) name = os_path.basename(url.path) name, suffix = os_path.splitext(name) # end if if mime: import mimetypes suffix = mimetypes.guess_extension(mime) suffix = '.jpg' if suffix == '.jpe' else suffix # .jpe -> .jpg # end if if not suffix or not suffix.strip().lstrip("."): logger.debug("suffix was empty. Using '.blob'") suffix = ".blob" # end if name = "{filename}{suffix}".format(filename=name, suffix=suffix) return InputFileFromBlob, (blob,), dict(name=name, mime=mime) if path: return InputFileFromDisk, (path,), dict(mime=mime) if url: if prefer_local_download: return InputFileFromURL, (url,), dict(mime=mime) # end if # else -> so we wanna let telegram handle it if prefer_str: assert_type_or_raise(url, str, parameter_name='url') return str, (url,), dict() # end if return InputFileUseUrl, (url,), dict() # end if raise ValueError('Could not find a matching subclass. You might need to do it manually instead.')
def factory( cls, file_id=None, path=None, url=None, blob=None, mime=None, prefer_local_download=True, prefer_str=False, create_instance=True )
Creates a new InputFile subclass instance fitting the given parameters. :param prefer_local_download: If `True`, we download the file and send it to telegram. This is the default. If `False`, we send Telegram just the URL, and they'll try to download it. :type prefer_local_download: bool :param prefer_str: Return just the `str` instead of a `InputFileUseFileID` or `InputFileUseUrl` object. :type prefer_str: bool :param create_instance: If we should return a instance ready to use (default), or the building parts being a tuple of `(class, args_tuple, kwargs_dict)`. Setting this to `False` is probably only ever required for internal usage by the :class:`InputFile` constructor which uses this very factory. :type create_instance: bool :returns: if `create_instance=True` it returns a instance of some InputFile subclass or a string, if `create_instance=False` it returns a tuple of the needed class, args and kwargs needed to create a instance. :rtype: InputFile|InputFileFromBlob|InputFileFromDisk|InputFileFromURL|str|tuple
3.078896
2.713259
1.134759
array = super(PassportData, self).to_array() array['data'] = self._as_array(self.data) # type list of EncryptedPassportElement array['credentials'] = self.credentials.to_array() # type EncryptedCredentials return array
def to_array(self)
Serializes this PassportData to a dictionary. :return: dictionary representation of this object. :rtype: dict
5.165143
4.370925
1.181705
if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['data'] = EncryptedPassportElement.from_array_list(array.get('data'), list_level=1) data['credentials'] = EncryptedCredentials.from_array(array.get('credentials')) data['_raw'] = array return PassportData(**data)
def from_array(array)
Deserialize a new PassportData from a given dictionary. :return: new PassportData instance. :rtype: PassportData
3.971239
3.227184
1.230559
array = super(PassportFile, self).to_array() array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str array['file_size'] = int(self.file_size) # type int array['file_date'] = int(self.file_date) # type int return array
def to_array(self)
Serializes this PassportFile to a dictionary. :return: dictionary representation of this object. :rtype: dict
2.585634
2.358651
1.096234
array = super(EncryptedPassportElement, self).to_array() array['type'] = u(self.type) # py2: type unicode, py3: type str array['hash'] = u(self.hash) # py2: type unicode, py3: type str if self.data is not None: array['data'] = u(self.data) # py2: type unicode, py3: type str if self.phone_number is not None: array['phone_number'] = u(self.phone_number) # py2: type unicode, py3: type str if self.email is not None: array['email'] = u(self.email) # py2: type unicode, py3: type str if self.files is not None: array['files'] = self._as_array(self.files) # type list of PassportFile if self.front_side is not None: array['front_side'] = self.front_side.to_array() # type PassportFile if self.reverse_side is not None: array['reverse_side'] = self.reverse_side.to_array() # type PassportFile if self.selfie is not None: array['selfie'] = self.selfie.to_array() # type PassportFile if self.translation is not None: array['translation'] = self._as_array(self.translation) # type list of PassportFile return array
def to_array(self)
Serializes this EncryptedPassportElement to a dictionary. :return: dictionary representation of this object. :rtype: dict
1.522291
1.515677
1.004364
if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['type'] = u(array.get('type')) data['hash'] = u(array.get('hash')) data['data'] = u(array.get('data')) if array.get('data') is not None else None data['phone_number'] = u(array.get('phone_number')) if array.get('phone_number') is not None else None data['email'] = u(array.get('email')) if array.get('email') is not None else None data['files'] = PassportFile.from_array_list(array.get('files'), list_level=1) if array.get('files') is not None else None data['front_side'] = PassportFile.from_array(array.get('front_side')) if array.get('front_side') is not None else None data['reverse_side'] = PassportFile.from_array(array.get('reverse_side')) if array.get('reverse_side') is not None else None data['selfie'] = PassportFile.from_array(array.get('selfie')) if array.get('selfie') is not None else None data['translation'] = PassportFile.from_array_list(array.get('translation'), list_level=1) if array.get('translation') is not None else None data['_raw'] = array return EncryptedPassportElement(**data)
def from_array(array)
Deserialize a new EncryptedPassportElement from a given dictionary. :return: new EncryptedPassportElement instance. :rtype: EncryptedPassportElement
1.736038
1.547495
1.121838
array = super(EncryptedCredentials, self).to_array() array['data'] = u(self.data) # py2: type unicode, py3: type str array['hash'] = u(self.hash) # py2: type unicode, py3: type str array['secret'] = u(self.secret) # py2: type unicode, py3: type str return array
def to_array(self)
Serializes this EncryptedCredentials to a dictionary. :return: dictionary representation of this object. :rtype: dict
2.746619
2.262532
1.213958
if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['data'] = u(array.get('data')) data['hash'] = u(array.get('hash')) data['secret'] = u(array.get('secret')) data['_raw'] = array return EncryptedCredentials(**data)
def from_array(array)
Deserialize a new EncryptedCredentials from a given dictionary. :return: new EncryptedCredentials instance. :rtype: EncryptedCredentials
3.703406
2.988552
1.239197
result = self.do("getMe") if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) from pytgbot.api_types.receivable.peer import User try: return User.from_array(result) except TgApiParseException: logger.debug("Failed parsing as api_type User", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
def get_me(self)
A simple method for testing your bot's auth token. Requires no parameters. Returns basic information about the bot in form of a :class:`pytgbot.api_types.receivable.peer.User` object. https://core.telegram.org/bots/api#getme Returns: :return: Returns basic information about the bot in form of a User object :rtype: pytgbot.api_types.receivable.peer.User
4.904485
4.064276
1.20673
assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id") assert_type_or_raise(from_chat_id, (int, unicode_type), parameter_name="from_chat_id") assert_type_or_raise(message_id, int, parameter_name="message_id") assert_type_or_raise(disable_notification, None, bool, parameter_name="disable_notification") result = self.do( "forwardMessage", chat_id=chat_id, from_chat_id=from_chat_id, message_id=message_id, disable_notification=disable_notification ) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) from pytgbot.api_types.receivable.updates import Message try: return Message.from_array(result) except TgApiParseException: logger.debug("Failed parsing as api_type Message", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
def forward_message(self, chat_id, from_chat_id, message_id, disable_notification=False)
Use this method to forward messages of any kind. On success, the sent Message is returned. https://core.telegram.org/bots/api#forwardmessage Parameters: :param chat_id: Unique identifier for the target chat (chat id of user chat or group chat) or username of the target channel (in the format @channelusername) :type chat_id: int | str|unicode :param from_chat_id: Unique identifier for the chat where the original message was sent (id for chats or the channel's username in the format @channelusername) :type from_chat_id: int | str|unicode :param message_id: Message identifier in the chat specified in from_chat_id :type message_id: int Optional keyword parameters: :param disable_notification: Sends the message silently. Users will receive a notification with no sound. :type disable_notification: bool Returns: :return: On success, the sent Message is returned :rtype: pytgbot.api_types.receivable.updates.Message
2.279421
2.172832
1.049055
assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id") from .api_types.sendable.input_media import InputMediaPhoto, InputMediaVideo files = {} new_media = [] assert_type_or_raise(media, list, parameter_name="media") for i, medium in enumerate(media): assert_type_or_raise(medium, InputMediaPhoto, InputMediaVideo, parameter_name="media[{i}]".format(i=i)) assert isinstance(medium, (InputMediaPhoto, InputMediaVideo)) new_medium, file = medium.get_request_data('pytgbot{i}'.format(i=i), full_data=True) logger.debug('InputMedia {} found.'.format(new_medium)) new_media.append(new_medium) if file: files.update(file) # end if # end for new_media = json.dumps(new_media) assert_type_or_raise(disable_notification, None, bool, parameter_name="disable_notification") assert_type_or_raise(reply_to_message_id, None, int, parameter_name="reply_to_message_id") result = self.do( "sendMediaGroup", chat_id=chat_id, media=new_media, files=files, disable_notification=disable_notification, reply_to_message_id=reply_to_message_id, ) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) # no valid parsing so far if not isinstance(result, list): raise TgApiParseException("Could not parse result als list.") # See debug log for details! # end if from .api_types.receivable.updates import Message return [Message.from_array(msg) for msg in result] # parse them all as Message. raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
def send_media_group(self, chat_id, media, disable_notification=None, reply_to_message_id=None)
Use this method to send a group of photos or videos as an album. On success, an array of the sent Messages is returned. https://core.telegram.org/bots/api#sendmediagroup Parameters: :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) :type chat_id: int | str|unicode :param media: A array describing photos and videos to be sent, must include 2–10 items :type media: list of (pytgbot.api_types.sendable.input_media.InputMediaPhoto|pytgbot.api_types.sendable.input_media.InputMediaVideo) Optional keyword parameters: :param disable_notification: Sends the messages silently. Users will receive a notification with no sound. :type disable_notification: bool :param reply_to_message_id: If the messages are a reply, ID of the original message :type reply_to_message_id: int Returns: :return: On success, an array of the sent Messages is returned :rtype: Messages
3.043208
2.967787
1.025413
assert_type_or_raise(user_id, int, parameter_name="user_id") assert_type_or_raise(score, int, parameter_name="score") assert_type_or_raise(force, None, bool, parameter_name="force") assert_type_or_raise(disable_edit_message, None, bool, parameter_name="disable_edit_message") assert_type_or_raise(chat_id, None, int, parameter_name="chat_id") assert_type_or_raise(message_id, None, int, parameter_name="message_id") assert_type_or_raise(inline_message_id, None, unicode_type, parameter_name="inline_message_id") result = self.do("setGameScore", user_id=user_id, score=score, force=force, disable_edit_message=disable_edit_message, chat_id=chat_id, message_id=message_id, inline_message_id=inline_message_id) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) from pytgbot.api_types.receivable.updates import Message try: return Message.from_array(result) except TgApiParseException: logger.debug("Failed parsing as api_type Message", exc_info=True) # end try try: return from_array_list(bool, result, list_level=0, is_builtin=True) except TgApiParseException: logger.debug("Failed parsing as primitive bool", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
def set_game_score(self, user_id, score, force=False, disable_edit_message=False, chat_id=None, message_id=None, inline_message_id=None)
Use this method to set the score of the specified user in a game. On success, if the message was sent by the bot, returns the edited Message, otherwise returns True. Returns an error, if the new score is not greater than the user's current score in the chat and force is False. https://core.telegram.org/bots/api#setgamescore Parameters: :param user_id: User identifier :type user_id: int :param score: New score, must be non-negative :type score: int Optional keyword parameters: :param force: Pass True, if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters :type force: bool :param disable_edit_message: Pass True, if the game message should not be automatically edited to include the current scoreboard :type disable_edit_message: bool :param chat_id: Required if inline_message_id is not specified. Unique identifier for the target chat (or username of the target channel in the format @channelusername) :type chat_id: int :param message_id: Required if inline_message_id is not specified. Identifier of the sent message :type message_id: int :param inline_message_id: Required if chat_id and message_id are not specified. Identifier of the inline message :type inline_message_id: str|unicode Returns: :return: On success, if the message was sent by the bot, returns the edited Message, otherwise returns True :rtype: pytgbot.api_types.receivable.updates.Message | bool
1.940017
1.801504
1.076888
from DictObject import DictObject import requests assert isinstance(r, requests.Response) try: logger.debug(r.json()) res = DictObject.objectify(r.json()) except Exception as e: raise TgApiResponseException('Parsing answer as json failed.', r, e) # end if res["response"] = r # TODO: does this failes on json lists? Does TG does that? # TG should always return an dict, with at least a status or something. if self.return_python_objects: if res.ok is not True: raise TgApiServerException( error_code=res.error_code if "error_code" in res else None, response=res.response if "response" in res else None, description=res.description if "description" in res else None, request=r.request ) # end if not ok if "result" not in res: raise TgApiParseException('Key "result" is missing.') # end if no result return res.result # end if return_python_objects return res
def _postprocess_request(self, r)
This converts the response to either the response or a parsed :class:`pytgbot.api_types.receivable.Receivable`. :param r: the request response :type r: requests.Response :return: The json response from the server, or, if `self.return_python_objects` is `True`, a parsed return type. :rtype: DictObject.DictObject | pytgbot.api_types.receivable.Receivable
5.353155
4.775428
1.120979
from .api_types.sendable.files import InputFile from luckydonaldUtils.encoding import unicode_type from luckydonaldUtils.encoding import to_native as n if value is None and _file_is_optional: # Is None but set optional, so do nothing. pass elif isinstance(value, str): kwargs[file_param_name] = str(value) elif isinstance(value, unicode_type): kwargs[file_param_name] = n(value) elif isinstance(value, InputFile): files = value.get_request_files(file_param_name) if "files" in kwargs and kwargs["files"]: # already are some files there, merge them. assert isinstance(kwargs["files"], dict), \ 'The files should be of type dict, but are of type {}.'.format(type(kwargs["files"])) for key in files.keys(): assert key not in kwargs["files"], '{key} would be overwritten!' kwargs["files"][key] = files[key] # end for else: # no files so far kwargs["files"] = files # end if else: raise TgApiTypeError("Parameter {key} is not type (str, {text_type}, {input_file_type}), but type {type}".format( key=file_param_name, type=type(value), input_file_type=InputFile, text_type=unicode_type)) # end if if not _command: # command as camelCase # "voice_note" -> "sendVoiceNote" # https://stackoverflow.com/a/10984923/3423324 command = re.sub(r'(?!^)_([a-zA-Z])', lambda m: m.group(1).upper(), "send_" + file_param_name) else: command = _command # end def return self.do(command, **kwargs)
def _do_fileupload(self, file_param_name, value, _command=None, _file_is_optional=False, **kwargs)
:param file_param_name: For what field the file should be uploaded. :type file_param_name: str :param value: File to send. You can either pass a file_id as String to resend a file file that is already on the Telegram servers, or upload a new file, specifying the file path as :class:`pytgbot.api_types.sendable.files.InputFile`. If `_file_is_optional` is set to `True`, it can also be set to `None`. :type value: pytgbot.api_types.sendable.files.InputFile | str | None :param _command: Overwrite the command to be send. Default is to convert `file_param_name` to camel case (`"voice_note"` -> `"sendVoiceNote"`) :type _command: str|None :param _file_is_optional: If the file (`value`) is allowed to be None. :type _file_is_optional: bool :param kwargs: will get json encoded. :return: The json response from the server, or, if `self.return_python_objects` is `True`, a parsed return type. :rtype: DictObject.DictObject | pytgbot.api_types.receivable.Receivable :raises TgApiTypeError, TgApiParseException, TgApiServerException: Everything from :meth:`Bot.do`, and :class:`TgApiTypeError`
3.533526
3.097246
1.14086
array = super(LabeledPrice, self).to_array() array['label'] = u(self.label) # py2: type unicode, py3: type str array['amount'] = int(self.amount) # type int return array
def to_array(self)
Serializes this LabeledPrice to a dictionary. :return: dictionary representation of this object. :rtype: dict
5.902792
3.787541
1.558476
if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['label'] = u(array.get('label')) data['amount'] = int(array.get('amount')) instance = LabeledPrice(**data) instance._raw = array return instance
def from_array(array)
Deserialize a new LabeledPrice from a given dictionary. :return: new LabeledPrice instance. :rtype: LabeledPrice
4.03774
3.101956
1.301675
array = super(ShippingOption, self).to_array() array['id'] = u(self.id) # py2: type unicode, py3: type str array['title'] = u(self.title) # py2: type unicode, py3: type str array['prices'] = self._as_array(self.prices) # type list of LabeledPrice return array
def to_array(self)
Serializes this ShippingOption to a dictionary. :return: dictionary representation of this object. :rtype: dict
3.530576
3.183109
1.109159
if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.sendable.payments import LabeledPrice data = {} data['id'] = u(array.get('id')) data['title'] = u(array.get('title')) data['prices'] = LabeledPrice.from_array_list(array.get('prices'), list_level=1) instance = ShippingOption(**data) instance._raw = array return instance
def from_array(array)
Deserialize a new ShippingOption from a given dictionary. :return: new ShippingOption instance. :rtype: ShippingOption
3.418355
3.051906
1.120072