INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Attach an existing transform job to a new Transformer instance Args: transform_job_name (str): Name for the transform job to be attached. sagemaker_session (sagemaker.session.Session): Session object which manages interactions with Amazon SageMaker APIs and any other AWS...
def attach(cls, transform_job_name, sagemaker_session=None): """Attach an existing transform job to a new Transformer instance Args: transform_job_name (str): Name for the transform job to be attached. sagemaker_session (sagemaker.session.Session): Session object which manages i...
Convert the transform job description to init params that can be handled by the class constructor Args: job_details (dict): the returned job details from a describe_transform_job API call. Returns: dict: The transformed init_params
def _prepare_init_params_from_job_description(cls, job_details): """Convert the transform job description to init params that can be handled by the class constructor Args: job_details (dict): the returned job details from a describe_transform_job API call. Returns: dict...
Returns the piece size (vocabulary size). Args: model_file: The sentencepiece model file path. model_proto: The sentencepiece model serialized proto. Either `model_file` or `model_proto` must be set. name: The name argument that is passed to the op function. Returns: A scalar repre...
def piece_size(model_file=None, model_proto=None, name=None): """Returns the piece size (vocabulary size). Args: model_file: The sentencepiece model file path. model_proto: The sentencepiece model serialized proto. Either `model_file` or `model_proto` must be set. name: The name argume...
Converts piece into vocabulary id. Args: input: An arbitrary tensor of string. model_file: The sentencepiece model file path. model_proto: The sentencepiece model serialized proto. Either `model_file` or `model_proto` must be set. name: The name argument that is passed to the op func...
def piece_to_id(input, model_file=None, model_proto=None, name=None): """Converts piece into vocabulary id. Args: input: An arbitrary tensor of string. model_file: The sentencepiece model file path. model_proto: The sentencepiece model serialized proto. Either `model_file` or `model_pr...
Converts vocabulary id into piece. Args: input: An arbitrary tensor of int32. model_file: The sentencepiece model file path. model_proto: The sentencepiece model serialized proto. Either `model_file` or `model_proto` must be set. name: The name argument that is passed to the op funct...
def id_to_piece(input, model_file=None, model_proto=None, name=None): """Converts vocabulary id into piece. Args: input: An arbitrary tensor of int32. model_file: The sentencepiece model file path. model_proto: The sentencepiece model serialized proto. Either `model_file` or `model_pro...
Returns true if input id is unknown piece. Args: input: An arbitrary tensor of int32. model_file: The sentencepiece model file path. model_proto: The sentencepiece model serialized proto. Either `model_file` or `model_proto` must be set. name: The name argument that is passed to the ...
def is_unknown(input, model_file=None, model_proto=None, name=None): """Returns true if input id is unknown piece. Args: input: An arbitrary tensor of int32. model_file: The sentencepiece model file path. model_proto: The sentencepiece model serialized proto. Either `model_file` or `mo...
Returns true if input id is control piece. Args: input: An arbitrary tensor of int32. model_file: The sentencepiece model file path. model_proto: The sentencepiece model serialized proto. Either `model_file` or `model_proto` must be set. name: The name argument that is passed to the ...
def is_control(input, model_file=None, model_proto=None, name=None): """Returns true if input id is control piece. Args: input: An arbitrary tensor of int32. model_file: The sentencepiece model file path. model_proto: The sentencepiece model serialized proto. Either `model_file` or `mo...
Returns true if input id is unused piece. Args: input: An arbitrary tensor of int32. model_file: The sentencepiece model file path. model_proto: The sentencepiece model serialized proto. Either `model_file` or `model_proto` must be set. name: The name argument that is passed to the o...
def is_unused(input, model_file=None, model_proto=None, name=None): """Returns true if input id is unused piece. Args: input: An arbitrary tensor of int32. model_file: The sentencepiece model file path. model_proto: The sentencepiece model serialized proto. Either `model_file` or `mode...
Encodes sentences into pieces in dense tensor format. Args: input_sentences: A 1D string tensor of arbitrary size holding the raw text of input sentences. nbest_size: A scalar or 1D tensor for sampling. nbest_size = {0,1}: No sampling is performed. nbest_s...
def encode_dense(input_sentences, nbest_size=0, alpha=1.0, model_file=None, model_proto=None, reverse=False, add_bos=False, add_eos=False, out_type=tf.int32, name=None): """Encodes sentences into pieces in dense tensor format. Args: input_sentences: A 1D strin...
Encodes sentences into pieces in sparse tensor format. Args: input_sentences: A 1D string tensor of arbitrary size holding the raw text of input sentences. nbest_size: A scalar or 1D tensor for sampling. nbest_size = {0,1}: No sampling is performed. nbest_...
def encode_sparse(input_sentences, nbest_size=0, alpha=1.0, model_file=None, model_proto=None, reverse=False, add_bos=False, add_eos=False, out_type=tf.int32, name=None): """Encodes sentences into pieces in sparse tensor format. Args: input_sentences: A 1D ...
Decode pieces into postprocessed text. Args: pieces: A 2D int32 or string tensor [batch_size x max_length] of encoded sequences. sequence_length: A 1D int32 tensor [batch_size] representing the length of pieces. model_file: The sentencepiece model file path. model_proto...
def decode(pieces, sequence_length, model_file=None, model_proto=None, reverse=False, name=None): """Decode pieces into postprocessed text. Args: pieces: A 2D int32 or string tensor [batch_size x max_length] of encoded sequences. sequence_length: A 1D int32 tensor [batch_size] repres...
Splits one string into multiple strings, with a maximum amount of `chars_per_string` characters per string. This is very useful for splitting one giant message into multiples. :param text: The text to split :param chars_per_string: The number of characters per line the text is split into. :return: The ...
def split_string(text, chars_per_string): """ Splits one string into multiple strings, with a maximum amount of `chars_per_string` characters per string. This is very useful for splitting one giant message into multiples. :param text: The text to split :param chars_per_string: The number of charact...
Returns the argument after the command. Examples: extract_arguments("/get name"): 'name' extract_arguments("/get"): '' extract_arguments("/get@botName name"): 'name' :param text: String to extract the arguments from a command :return: the arguments if `text` is a command (according to ...
def extract_arguments(text): """ Returns the argument after the command. Examples: extract_arguments("/get name"): 'name' extract_arguments("/get"): '' extract_arguments("/get@botName name"): 'name' :param text: String to extract the arguments from a command :return: the argume...
When new messages arrive TeleBot will call this function.
def listener(messages): """ When new messages arrive TeleBot will call this function. """ for m in messages: if m.content_type == 'text': # print the sent message to the console print(str(m.chat.first_name) + " [" + str(m.chat.id) + "]: " + m.text)
Checks whether json_type is a dict or a string. If it is already a dict, it is returned as-is. If it is not, it is converted to a dict by means of json.loads(json_type) :param json_type: :return:
def check_json(json_type): """ Checks whether json_type is a dict or a string. If it is already a dict, it is returned as-is. If it is not, it is converted to a dict by means of json.loads(json_type) :param json_type: :return: """ try: str_types = (str...
Author: @sviat9440 Message: "*Test* parse _formatting_, [url](https://example.com), [text_mention](tg://user?id=123456) and mention @username" Example: message.html_text >> "<b>Test</b> parse <i>formatting</i>, <a href=\"https://example.com\">url</a>, <a href=\"tg://user?id=1234...
def __html_text(self, text, entities): """ Author: @sviat9440 Message: "*Test* parse _formatting_, [url](https://example.com), [text_mention](tg://user?id=123456) and mention @username" Example: message.html_text >> "<b>Test</b> parse <i>formatting</i>, <a href=\...
This function adds strings to the keyboard, while not exceeding row_width. E.g. ReplyKeyboardMarkup#add("A", "B", "C") yields the json result {keyboard: [["A"], ["B"], ["C"]]} when row_width is set to 1. When row_width is set to 2, the following is the result of this function: {keyboard: [["A", ...
def add(self, *args): """ This function adds strings to the keyboard, while not exceeding row_width. E.g. ReplyKeyboardMarkup#add("A", "B", "C") yields the json result {keyboard: [["A"], ["B"], ["C"]]} when row_width is set to 1. When row_width is set to 2, the following is the r...
Converts this object to its json representation following the Telegram API guidelines described here: https://core.telegram.org/bots/api#replykeyboardmarkup :return:
def to_json(self): """ Converts this object to its json representation following the Telegram API guidelines described here: https://core.telegram.org/bots/api#replykeyboardmarkup :return: """ json_dict = {'keyboard': self.keyboard} if self.one_time_keyboard: ...
This function adds strings to the keyboard, while not exceeding row_width. E.g. ReplyKeyboardMarkup#add("A", "B", "C") yields the json result {keyboard: [["A"], ["B"], ["C"]]} when row_width is set to 1. When row_width is set to 2, the following is the result of this function: {keyboard: [["A", ...
def add(self, *args): """ This function adds strings to the keyboard, while not exceeding row_width. E.g. ReplyKeyboardMarkup#add("A", "B", "C") yields the json result {keyboard: [["A"], ["B"], ["C"]]} when row_width is set to 1. When row_width is set to 2, the following is the r...
Adds a list of KeyboardButton to the keyboard. This function does not consider row_width. ReplyKeyboardMarkup#row("A")#row("B", "C")#to_json() outputs '{keyboard: [["A"], ["B", "C"]]}' See https://core.telegram.org/bots/api#inlinekeyboardmarkup :param args: strings :return: self, to allo...
def row(self, *args): """ Adds a list of KeyboardButton to the keyboard. This function does not consider row_width. ReplyKeyboardMarkup#row("A")#row("B", "C")#to_json() outputs '{keyboard: [["A"], ["B", "C"]]}' See https://core.telegram.org/bots/api#inlinekeyboardmarkup :param ar...
Makes a request to the Telegram API. :param token: The bot's API token. (Created with @BotFather) :param method_name: Name of the API method to be called. (E.g. 'getUpdates') :param method: HTTP method to be used. Defaults to 'get'. :param params: Optional parameters. Should be a dictionary with key-val...
def _make_request(token, method_name, method='get', params=None, files=None, base_url=API_URL): """ Makes a request to the Telegram API. :param token: The bot's API token. (Created with @BotFather) :param method_name: Name of the API method to be called. (E.g. 'getUpdates') :param method: HTTP metho...
Checks whether `result` is a valid API response. A result is considered invalid if: - The server returned an HTTP response code other than 200 - The content of the result is invalid JSON. - The method call was unsuccessful (The JSON 'ok' field equals False) :raises ApiException: if one ...
def _check_result(method_name, result): """ Checks whether `result` is a valid API response. A result is considered invalid if: - The server returned an HTTP response code other than 200 - The content of the result is invalid JSON. - The method call was unsuccessful (The JSON 'ok' fi...
Use this method to send text messages. On success, the sent Message is returned. :param token: :param chat_id: :param text: :param disable_web_page_preview: :param reply_to_message_id: :param reply_markup: :param parse_mode: :param disable_notification: :return:
def send_message(token, chat_id, text, disable_web_page_preview=None, reply_to_message_id=None, reply_markup=None, parse_mode=None, disable_notification=None): """ Use this method to send text messages. On success, the sent Message is returned. :param token: :param chat_id: :param t...
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. :param token: Bot's token (you don't need to fill this) ...
def set_game_score(token, user_id, score, force=None, disable_edit_message=None, 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 ...
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...
def get_game_high_scores(token, 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 ...
Use this method to send invoices. On success, the sent Message is returned. :param token: Bot's token (you don't need to fill this) :param chat_id: Unique identifier for the target private chat :param title: Product name :param description: Product description :param invoice_payload: Bot-defined inv...
def send_invoice(token, chat_id, title, description, invoice_payload, provider_token, currency, prices, start_parameter, photo_url=None, photo_size=None, photo_width=None, photo_height=None, need_name=None, need_phone_number=None, need_email=None, need_shipping_address=None, is_flexibl...
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. :param token: Bot's token (you don't need to fill this) :param shi...
def answer_shipping_query(token, 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 q...
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...
def answer_pre_checkout_query(token, 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. O...
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 mus...
def answer_callback_query(token, 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, Tru...
Enable saving next step handlers (by default saving disable) :param delay: Delay between changes in handlers and saving :param filename: Filename of save file
def enable_save_next_step_handlers(self, delay=120, filename="./.handler-saves/step.save"): """ Enable saving next step handlers (by default saving disable) :param delay: Delay between changes in handlers and saving :param filename: Filename of save file """ self.next_st...
Enable saving reply handlers (by default saving disable) :param delay: Delay between changes in handlers and saving :param filename: Filename of save file
def enable_save_reply_handlers(self, delay=120, filename="./.handler-saves/reply.save"): """ Enable saving reply handlers (by default saving disable) :param delay: Delay between changes in handlers and saving :param filename: Filename of save file """ self.reply_saver = ...
Load next step handlers from save file :param filename: Filename of the file where handlers was saved :param del_file_after_loading: Is passed True, after loading save file will be deleted
def load_next_step_handlers(self, filename="./.handler-saves/step.save", del_file_after_loading=True): """ Load next step handlers from save file :param filename: Filename of the file where handlers was saved :param del_file_after_loading: Is passed True, after loading save file will be...
Use this method to receive incoming updates using long polling (wiki). An Array of Update objects is returned. :param allowed_updates: Array of string. List the types of updates you want your bot to receive. :param offset: Integer. Identifier of the first update to be returned. :param limit: Int...
def get_updates(self, offset=None, limit=None, timeout=20, allowed_updates=None): """ Use this method to receive incoming updates using long polling (wiki). An Array of Update objects is returned. :param allowed_updates: Array of string. List the types of updates you want your bot to receive. ...
Get and discard all pending updates before first poll of the bot :return: total updates skipped
def __skip_updates(self): """ Get and discard all pending updates before first poll of the bot :return: total updates skipped """ total = 0 updates = self.get_updates(offset=self.last_update_id, timeout=1) while updates: total += len(updates) ...
Retrieves any updates from the Telegram API. Registered listeners and applicable message handlers will be notified when a new message arrives. :raises ApiException when a call has failed.
def __retrieve_updates(self, timeout=20): """ Retrieves any updates from the Telegram API. Registered listeners and applicable message handlers will be notified when a new message arrives. :raises ApiException when a call has failed. """ if self.skip_pending: ...
This function creates a new Thread that calls an internal __retrieve_updates function. This allows the bot to retrieve Updates automagically and notify listeners and message handlers accordingly. Warning: Do not call this function more than once! Always get updates. :param interval: ...
def polling(self, none_stop=False, interval=0, timeout=20): """ This function creates a new Thread that calls an internal __retrieve_updates function. This allows the bot to retrieve Updates automagically and notify listeners and message handlers accordingly. Warning: Do not call this f...
Retrieves the user profile photos of the person with 'user_id' See https://core.telegram.org/bots/api#getuserprofilephotos :param user_id: :param offset: :param limit: :return: API reply.
def get_user_profile_photos(self, user_id, offset=None, limit=None): """ Retrieves the user profile photos of the person with 'user_id' See https://core.telegram.org/bots/api#getuserprofilephotos :param user_id: :param offset: :param limit: :return: API reply. ...
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. :param chat_id: :return:
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. :param chat_id: :return: """ ...
Use this method for your bot to leave a group, supergroup or channel. Returns True on success. :param chat_id: :return:
def leave_chat(self, chat_id): """ Use this method for your bot to leave a group, supergroup or channel. Returns True on success. :param chat_id: :return: """ result = apihelper.leave_chat(self.token, chat_id) return result
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. :param chat_id: :return:
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. :param chat_id: :return: """ re...
Use this method to get the number of members in a chat. Returns Int on success. :param chat_id: :return:
def get_chat_members_count(self, chat_id): """ Use this method to get the number of members in a chat. Returns Int on success. :param chat_id: :return: """ result = apihelper.get_chat_members_count(self.token, chat_id) return result
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 Tr...
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 ...
Use this method to delete a group sticker set from 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 su...
def delete_chat_sticker_set(self, chat_id): """ Use this method to delete a group sticker set from 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 requ...
Use this method to get information about a member of a chat. Returns a ChatMember object on success. :param chat_id: :param user_id: :return:
def get_chat_member(self, chat_id, user_id): """ Use this method to get information about a member of a chat. Returns a ChatMember object on success. :param chat_id: :param user_id: :return: """ result = apihelper.get_chat_member(self.token, chat_id, user_id) ...
Use this method to send text messages. Warning: Do not send more than about 5000 characters each message, otherwise you'll risk an HTTP 414 error. If you must send more than 5000 characters, use the split_string function in apihelper.py. :param chat_id: :param text: :param disa...
def send_message(self, chat_id, text, disable_web_page_preview=None, reply_to_message_id=None, reply_markup=None, parse_mode=None, disable_notification=None): """ Use this method to send text messages. Warning: Do not send more than about 5000 characters each message, other...
Use this method to forward messages of any kind. :param disable_notification: :param chat_id: which chat to forward :param from_chat_id: which chat message from :param message_id: message id :return: API reply.
def forward_message(self, chat_id, from_chat_id, message_id, disable_notification=None): """ Use this method to forward messages of any kind. :param disable_notification: :param chat_id: which chat to forward :param from_chat_id: which chat message from :param message_id:...
Use this method to delete message. Returns True on success. :param chat_id: in which chat to delete :param message_id: which message to delete :return: API reply.
def delete_message(self, chat_id, message_id): """ Use this method to delete message. Returns True on success. :param chat_id: in which chat to delete :param message_id: which message to delete :return: API reply. """ return apihelper.delete_message(self.token, ch...
Use this method to send photos. :param disable_notification: :param chat_id: :param photo: :param caption: :param parse_mode :param reply_to_message_id: :param reply_markup: :return: API reply.
def send_photo(self, chat_id, photo, caption=None, reply_to_message_id=None, reply_markup=None, parse_mode=None, disable_notification=None): """ Use this method to send photos. :param disable_notification: :param chat_id: :param photo: :param caption: ...
Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .mp3 format. :param chat_id:Unique identifier for the message recipient :param audio:Audio file to send. :param duration:Duration of the audio in seconds :para...
def send_audio(self, chat_id, audio, caption=None, duration=None, performer=None, title=None, reply_to_message_id=None, reply_markup=None, parse_mode=None, disable_notification=None, timeout=None): """ Use this method to send audio files, if you want Telegram client...
Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. :param chat_id:Unique identifier for the message recipient. :param voice: :param duration:Duration of sent audio in seconds :param reply_to_message_id: :param reply_...
def send_voice(self, chat_id, voice, caption=None, duration=None, reply_to_message_id=None, reply_markup=None, parse_mode=None, disable_notification=None, timeout=None): """ Use this method to send audio files, if you want Telegram clients to display the file as a playable voice messa...
Use this method to send general files. :param chat_id: :param data: :param reply_to_message_id: :param reply_markup: :param parse_mode: :param disable_notification: :return: API reply.
def send_document(self, chat_id, data, reply_to_message_id=None, caption=None, reply_markup=None, parse_mode=None, disable_notification=None, timeout=None): """ Use this method to send general files. :param chat_id: :param data: :param reply_to_message_id: ...
Use this method to send .webp stickers. :param chat_id: :param data: :param reply_to_message_id: :param reply_markup: :return: API reply.
def send_sticker(self, chat_id, data, reply_to_message_id=None, reply_markup=None, disable_notification=None, timeout=None): """ Use this method to send .webp stickers. :param chat_id: :param data: :param reply_to_message_id: :param reply_markup: ...
Use this method to send video files, Telegram clients support mp4 videos. :param chat_id: Integer : Unique identifier for the message recipient — User or GroupChat id :param data: InputFile or String : Video to send. You can either pass a file_id as String to resend a video that is already on the Telegr...
def send_video(self, chat_id, data, duration=None, caption=None, reply_to_message_id=None, reply_markup=None, parse_mode=None, supports_streaming=None, disable_notification=None, timeout=None): """ Use this method to send video files, Telegram clients support mp4 videos. :para...
Use this method to send video files, Telegram clients support mp4 videos. :param chat_id: Integer : Unique identifier for the message recipient — User or GroupChat id :param data: InputFile or String : Video note to send. You can either pass a file_id as String to resend a video that is already on the T...
def send_video_note(self, chat_id, data, duration=None, length=None, reply_to_message_id=None, reply_markup=None, disable_notification=None, timeout=None): """ Use this method to send video files, Telegram clients support mp4 videos. :param chat_id: Integer : Unique ident...
send a group of photos or videos as an album. On success, an array of the sent Messages is returned. :param chat_id: :param media: :param disable_notification: :param reply_to_message_id: :return:
def send_media_group(self, chat_id, media, disable_notification=None, reply_to_message_id=None): """ send a group of photos or videos as an album. On success, an array of the sent Messages is returned. :param chat_id: :param media: :param disable_notification: :param repl...
Use this method to send point on the map. :param chat_id: :param latitude: :param longitude: :param live_period :param reply_to_message_id: :param reply_markup: :return: API reply.
def send_location(self, chat_id, latitude, longitude, live_period=None, reply_to_message_id=None, reply_markup=None, disable_notification=None): """ Use this method to send point on the map. :param chat_id: :param latitude: :param longitude: :param l...
Use this method to edit live location :param latitude: :param longitude: :param chat_id: :param message_id: :param inline_message_id: :param reply_markup: :return:
def edit_message_live_location(self, latitude, longitude, chat_id=None, message_id=None, inline_message_id=None, reply_markup=None): """ Use this method to edit live location :param latitude: :param longitude: :param chat_id: :param mess...
Use this method to stop updating a live location message sent by the bot or via the bot (for inline bots) before live_period expires :param chat_id: :param message_id: :param inline_message_id: :param reply_markup: :return:
def stop_message_live_location(self, chat_id=None, message_id=None, inline_message_id=None, reply_markup=None): """ Use this method to stop updating a live location message sent by the bot or via the bot (for inline bots) before live_period expires :param chat_id: :param message_...
Use this method to send information about a venue. :param chat_id: Integer or String : Unique identifier for the target chat or username of the target channel :param latitude: Float : Latitude of the venue :param longitude: Float : Longitude of the venue :param title: String : Name of th...
def send_venue(self, chat_id, latitude, longitude, title, address, foursquare_id=None, disable_notification=None, reply_to_message_id=None, reply_markup=None): """ Use this method to send information about a venue. :param chat_id: Integer or String : Unique identifier for the ...
Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). :param chat_id: :param action: One of the following strings: 'typing', ...
def send_chat_action(self, chat_id, action): """ Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). :param chat_id:...
Use this method to kick a user from a group or a supergroup. :param chat_id: Int or string : Unique identifier for the target group or username of the target supergroup :param user_id: Int : Unique identifier of the target user :param until_date: Date when the user will be unbanned, unix time. I...
def kick_chat_member(self, chat_id, user_id, until_date=None): """ Use this method to kick a user from a group or a supergroup. :param chat_id: Int or string : Unique identifier for the target group or username of the target supergroup :param user_id: Int : Unique identifier of the targe...
Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate admin rights. Pass True for all boolean parameters to lift restrictions from a user. Returns True on success. :param chat_id: Int or Strin...
def restrict_chat_member(self, chat_id, user_id, until_date=None, can_send_messages=None, can_send_media_messages=None, can_send_other_messages=None, can_add_web_page_previews=None): """ Use this method to restrict a user in a supergroup. ...
Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Pass False for all boolean parameters to demote a user. Returns True on success. :param chat_id: Unique identifier f...
def promote_chat_member(self, chat_id, user_id, can_change_info=None, can_post_messages=None, can_edit_messages=None, can_delete_messages=None, can_invite_users=None, can_restrict_members=None, can_pin_messages=None, can_promote_members=None): """ ...
Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. Note: In regular groups (non-supergroups), this method will only ...
def set_chat_photo(self, chat_id, photo): """ Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. Not...
Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. Note: In regular groups (non-supergroups), this method will only work if th...
def set_chat_title(self, chat_id, title): """ Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. Note: In regu...
Use this method to change the description of a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. :param chat_id: Int or Str: Unique identifier for the target chat or username of the target c...
def set_chat_description(self, chat_id, description): """ Use this method to change the description of a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. :param chat_id: Int...
Use this method to pin a message in a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. :param chat_id: Int or Str: Unique identifier for the target chat or username of the target channel (in...
def pin_chat_message(self, chat_id, message_id, disable_notification=False): """ Use this method to pin a message in a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. :param chat_id: In...
Convenience function for `send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs)`
def reply_to(self, message, text, **kwargs): """ Convenience function for `send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs)` """ return self.send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs)
Use this method to send answers to an inline query. On success, True is returned. No more than 50 results per query are allowed. :param inline_query_id: Unique identifier for the answered query :param results: Array of results for the inline query :param cache_time: The maximum amount of...
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 p...
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. :param callback_query_id: :param text: :param show_alert: :return:
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. ...
Use this method to get a sticker set. On success, a StickerSet object is returned. :param name: :return:
def get_sticker_set(self, name): """ Use this method to get a sticker set. On success, a StickerSet object is returned. :param name: :return: """ result = apihelper.get_sticker_set(self.token, name) return types.StickerSet.de_json(result)
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. :param user_id: :param png_sticker: :return:
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. :param user_id: :param png_sticker: ...
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. :param user_id: :param name: :param title: :param png_sticker: :param emojis: :param contains_masks: :param mask_posit...
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. ...
Use this method to add a new sticker to a set created by the bot. Returns True on success. :param user_id: :param name: :param png_sticker: :param emojis: :param mask_position: :return:
def add_sticker_to_set(self, user_id, name, png_sticker, emojis, mask_position=None): """ Use this method to add a new sticker to a set created by the bot. Returns True on success. :param user_id: :param name: :param png_sticker: :param emojis: :param mask_positio...
Use this method to move a sticker in a set created by the bot to a specific position . Returns True on success. :param sticker: :param position: :return:
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. :param sticker: :param position: :return: """ return apihelper.set_sticker_position_in_set...
Registers a callback function to be notified when a reply to `message` arrives. Warning: In case `callback` as lambda function, saving reply handlers will not work. :param message: The message for which we are awaiting a reply. :param callback: The callback function to be called when a ...
def register_for_reply(self, message, callback, *args, **kwargs): """ Registers a callback function to be notified when a reply to `message` arrives. Warning: In case `callback` as lambda function, saving reply handlers will not work. :param message: The message for which we are aw...
Registers a callback function to be notified when a reply to `message` arrives. Warning: In case `callback` as lambda function, saving reply handlers will not work. :param message_id: The id of the message for which we are awaiting a reply. :param callback: The callback function to be call...
def register_for_reply_by_message_id(self, message_id, callback, *args, **kwargs): """ Registers a callback function to be notified when a reply to `message` arrives. Warning: In case `callback` as lambda function, saving reply handlers will not work. :param message_id: The id of the ...
Registers a callback function to be notified when new message arrives after `message`. Warning: In case `callback` as lambda function, saving next step handlers will not work. :param message: The message for which we want to handle new message in the same chat. :param callback: The call...
def register_next_step_handler(self, message, callback, *args, **kwargs): """ Registers a callback function to be notified when new message arrives after `message`. Warning: In case `callback` as lambda function, saving next step handlers will not work. :param message: The message ...
Registers a callback function to be notified when new message arrives after `message`. Warning: In case `callback` as lambda function, saving next step handlers will not work. :param chat_id: The chat for which we want to handle new message. :param callback: The callback function which ...
def register_next_step_handler_by_chat_id(self, chat_id, callback, *args, **kwargs): """ Registers a callback function to be notified when new message arrives after `message`. Warning: In case `callback` as lambda function, saving next step handlers will not work. :param chat_id: T...
Clears all callback functions registered by register_next_step_handler(). :param message: The message for which we want to handle new message after that in same chat.
def clear_step_handler(self, message): """ Clears all callback functions registered by register_next_step_handler(). :param message: The message for which we want to handle new message after that in same chat. """ chat_id = message.chat.id self.clear_step_handler_by_...
Clears all callback functions registered by register_next_step_handler(). :param chat_id: The chat for which we want to clear next step handlers
def clear_step_handler_by_chat_id(self, chat_id): """ Clears all callback functions registered by register_next_step_handler(). :param chat_id: The chat for which we want to clear next step handlers """ self.next_step_handlers[chat_id] = [] if self.next_step_saver is no...
Clears all callback functions registered by register_for_reply() and register_for_reply_by_message_id(). :param message_id: The message id for which we want to clear reply handlers
def clear_reply_handlers_by_message_id(self, message_id): """ Clears all callback functions registered by register_for_reply() and register_for_reply_by_message_id(). :param message_id: The message id for which we want to clear reply handlers """ self.reply_handlers[message_id] ...
Message handler decorator. This decorator can be used to decorate functions that must handle certain types of messages. All message handlers are tested in the order they were added. Example: bot = TeleBot('TOKEN') # Handles all messages which text matches regexp. @bot....
def message_handler(self, commands=None, regexp=None, func=None, content_types=['text'], **kwargs): """ Message handler decorator. This decorator can be used to decorate functions that must handle certain types of messages. All message handlers are tested in the order they were added. ...
Generates code samples. Args: max_length: int. max literal length. max_nest: int. max nesting level. ops: CodeOp. set of allowable operations. Returns: 1. (str) output value. 2. (str) Code operation.
def generate_code(max_length, max_nest, ops): """Generates code samples. Args: max_length: int. max literal length. max_nest: int. max nesting level. ops: CodeOp. set of allowable operations. Returns: 1. (str) output value. 2. (str) Code operation. """ stack = [] def fetch_one(): ...
Defines tokens. Args: max_value: the maximum numeric range for the token. Returns: list of string tokens in vocabulary.
def get_tokens(max_value): """Defines tokens. Args: max_value: the maximum numeric range for the token. Returns: list of string tokens in vocabulary. """ vocab = [str(i) for i in range(max_value)] vocab = set(vocab) vocab.update(CodeOp.LITERALS) vocab.update(CodeOp.KEYWORDS) vocab |= set(""....
Samples up to maximum difficulty.
def fetch(self): """Samples up to maximum difficulty.""" length = np.random.randint(1, self._max_length + 1) nesting = np.random.randint(1, self._max_length + 1) return length, nesting
Factory method for LearnToExecute Dataset module. Args: batch_size: (int). The number of elements in a mini-batch. max_length: (int). Maximum character length. max_nesting: (int). Maximum level of statement nesting. token_by_char: (bool). Tokenize by character or words? mode: (string). Either 'tr...
def LearnToExecute( # pylint: disable=invalid-name batch_size, max_length=1, max_nesting=1, token_by_char=True, mode=Mode.TRAIN_COMBINE, loss_threshold=0.1, min_tries=DEFAULT_MIN_CURRICULUM_EVAL_TRIES, task_type=TaskType.ALG_CTRL): """Factory method for LearnToExecute Dataset module. Args: batch_...
Increments level difficulty (length and nesting) by 1 until maximum.
def update(self, loss, force=False): """Increments level difficulty (length and nesting) by 1 until maximum.""" do_update = super(CombineCurriculum, self).update(loss, force) if not do_update: return False if self._curr_length < self._max_length: self._curr_length += 1 elif self._curr_n...
Samples up to current difficulty.
def fetch(self): """Samples up to current difficulty.""" length = np.random.randint(1, self._curr_length + 1) nesting = np.random.randint(1, self._curr_nesting + 1) return length, nesting
Generates batched data in flat numpy arrays. Raises: ValueError: When too many generate calls are required.
def generate_flat_data(self): """Generates batched data in flat numpy arrays. Raises: ValueError: When too many generate calls are required. """ # Construct the string statements. all_statements = [] all_targets = [] self.sequence_sizes_in = [] self.sequence_sizes_out = [] for...
Produces the list of integer indices corresponding to a token list. Args: char_input: The character string to be tokenized. max_len: Truncation length. by_char: If true each character is a token - otherwise alpha-numeric groupings are tokens. Returns: A padded list of st...
def tokenize(self, char_input, max_len, by_char=False): """Produces the list of integer indices corresponding to a token list. Args: char_input: The character string to be tokenized. max_len: Truncation length. by_char: If true each character is a token - otherwise alpha-numeric ...
Returns an operations list based on the specified task index. Args: task_type: indicates the task type used. Returns: List of the eligible ops.
def get_task_ops(task_type=TaskType.ALG_CTRL): """Returns an operations list based on the specified task index. Args: task_type: indicates the task type used. Returns: List of the eligible ops. """ try: return LearnToExecuteState.TASK_TYPE_OPS[task_type] except KeyError: ...
Generator function for batchifying data for learning to execute. Yields: tuple: 1. one-hot input tensor, representing programmatic input 2. one-hot target tensor, the vealuation result. 3. one-hot decoder target, start symbol added for sequence decoding. 4. batch size tensor c...
def make_batch(self): """Generator function for batchifying data for learning to execute. Yields: tuple: 1. one-hot input tensor, representing programmatic input 2. one-hot target tensor, the vealuation result. 3. one-hot decoder target, start symbol added for sequence decoding. ...
Returns a human-readable version of a one-hot encoding of words. Args: data: (numpy.ndarray S x B x OH). One-hot encoding of words. S is sequence length, B is batch size, OH is one hot dimensionality. label_batch_entries: (bool). Whether to add numerical label before each batch elem...
def to_human_readable(self, data, label_batch_entries=True, indices=None, sep="\n"): """Returns a human-readable version of a one-hot encoding of words. Args: data: (numpy.ndarray S x B x OH). One-hot encoding of words. S is sequence length, B is batch size, OH is one ho...
Infers the data format for the fused batch norm. It uses the axis option to infer this information. Specifically, the axis value (0, 1, 2) corresponds to data format NHWC and the axis value (0, 2, 3) to data format NCHW. Args: input_batch: A Tensor of arbitrary dimension. Returns: A s...
def _infer_fused_data_format(self, input_batch): """Infers the data format for the fused batch norm. It uses the axis option to infer this information. Specifically, the axis value (0, 1, 2) corresponds to data format NHWC and the axis value (0, 2, 3) to data format NCHW. Args: input_batch: ...
Creates a fused batch normalization op.
def _fused_batch_norm_op(self, input_batch, mean, variance, use_batch_stats): """Creates a fused batch normalization op.""" # Store the original shape of the mean and variance. mean_shape = mean.get_shape() variance_shape = variance.get_shape() # The fused batch norm expects the mean, variance, gamm...
Creates a batch normalization op. It uses the tf.nn.batch_normalization op by default and the tf.nn.fused_batch_norm op to support fused batch normalization. Args: input_batch: A input Tensor of arbitrary dimension. mean: A mean tensor, of the same dtype as `input_batch`. variance: A var...
def _batch_norm_op(self, input_batch, mean, variance, use_batch_stats, stat_dtype): """Creates a batch normalization op. It uses the tf.nn.batch_normalization op by default and the tf.nn.fused_batch_norm op to support fused batch normalization. Args: input_batch: A input Ten...
Sets up optional scale and offset factors.
def _build_scale_offset(self, dtype): """Sets up optional scale and offset factors.""" # tf.nn.fused_batch_norm accepts float16 batch data, but not scale/offset. if self._fused and dtype == tf.float16: dtype = tf.float32 # The fused batch norm operation needs the beta, gamma variables, # so ...
Connects the BatchNorm module into the graph. Args: input_batch: A Tensor of arbitrary dimension. By default, the final dimension is not reduced over when computing the minibatch statistics. is_training: A boolean to indicate if the module should be connected in training mode, meaning t...
def _build(self, input_batch, is_training, test_local_stats=True): """Connects the BatchNorm module into the graph. Args: input_batch: A Tensor of arbitrary dimension. By default, the final dimension is not reduced over when computing the minibatch statistics. is_training: A boolean to indi...
Produces the list of integer indices corresponding to a token list.
def tokenize(self, token_list): """Produces the list of integer indices corresponding to a token list.""" return [ self._vocab_dict.get(token, self._vocab_dict[self.UNK]) for token in token_list ]