desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Creates an HTML-formatted string from the markup entities found in the message. Use this if you want to retrieve the message text with the entities formatted as HTML. This also formats :attr:`telegram.MessageEntity.URL` as a hyperlink. Returns: :obj:`str`: Message text with entities formatted as HTML.'
@property def text_html_urled(self):
return self._text_html(urled=True)
'Creates an Markdown-formatted string from the markup entities found in the message. Use this if you want to retrieve the message text with the entities formatted as Markdown in the same way the original message was formatted. Returns: :obj:`str`: Message text with entities formatted as Markdown.'
@property def text_markdown(self):
return self._text_markdown(urled=False)
'Creates an Markdown-formatted string from the markup entities found in the message. Use this if you want to retrieve the message text with the entities formatted as Markdown. This also formats :attr:`telegram.MessageEntity.URL` as a hyperlink. Returns: :obj:`str`: Message text with entities formatted as Markdown.'
@property def text_markdown_urled(self):
return self._text_markdown(urled=True)
'Deprecated'
@property def new_chat_member(self):
warn_deprecate_obj('new_chat_member', 'new_chat_members') return self._new_chat_member
'Shortcut for:: bot.send_chat_action(update.message.chat.id, *args, **kwargs) Returns: :obj:`bool`: If the action was sent successfully.'
def send_action(self, *args, **kwargs):
return self.bot.send_chat_action(self.id, *args, **kwargs)
'Shortcut for:: bot.leave_chat(update.message.chat.id, *args, **kwargs) Returns: :obj:`bool` If the action was sent successfully.'
def leave(self, *args, **kwargs):
return self.bot.leave_chat(self.id, *args, **kwargs)
'Shortcut for:: bot.get_chat_administrators(update.message.chat.id, *args, **kwargs) Returns: List[:class:`telegram.ChatMember`]: A list of administrators in a chat. An Array of :class:`telegram.ChatMember` objects that contains information about all chat administrators except other bots. If the chat is a group or a su...
def get_administrators(self, *args, **kwargs):
return self.bot.get_chat_administrators(self.id, *args, **kwargs)
'Shortcut for:: bot.get_chat_members_count(update.message.chat.id, *args, **kwargs) Returns: :obj:`int`'
def get_members_count(self, *args, **kwargs):
return self.bot.get_chat_members_count(self.id, *args, **kwargs)
'Shortcut for:: bot.get_chat_member(update.message.chat.id, *args, **kwargs) Returns: :class:`telegram.ChatMember`'
def get_member(self, *args, **kwargs):
return self.bot.get_chat_member(self.id, *args, **kwargs)
'Shortcut for:: bot.kick_chat_member(update.message.chat.id, *args, **kwargs) Returns: :obj:`bool`: If the action was sent succesfully. Note: This method will only work if the `All Members Are Admins` setting is off in the target group. Otherwise members may only be removed by the group\'s creator or by the member that...
def kick_member(self, *args, **kwargs):
return self.bot.kick_chat_member(self.id, *args, **kwargs)
'Shortcut for:: bot.unban_chat_member(update.message.chat.id, *args, **kwargs) Returns: :obj:`bool`: If the action was sent successfully.'
def unban_member(self, *args, **kwargs):
return self.bot.unban_chat_member(self.id, *args, **kwargs)
'a very basic validation on token'
@staticmethod def _validate_token(token):
if any((x.isspace() for x in token)): raise InvalidToken() (left, sep, _right) = token.partition(':') if ((not sep) or (not left.isdigit()) or (len(left) < 3)): raise InvalidToken() return token
':obj:`int`: Unique identifier for this bot.'
@property @info def id(self):
return self.bot.id
':obj:`str`: Bot\'s first name.'
@property @info def first_name(self):
return self.bot.first_name
':obj:`str`: Optional. Bot\'s last name.'
@property @info def last_name(self):
return self.bot.last_name
':obj:`str`: Bot\'s username.'
@property @info def username(self):
return self.bot.username
':obj:`str`: Bot\'s @username.'
@property def name(self):
return '@{0}'.format(self.username)
'A simple method for testing your bot\'s auth token. Requires no parameters. Args: timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as the read timeout from the server (instead of the one specified during creation of the connection pool). Returns: :class:`telegram.User`: A :class:`teleg...
@log def get_me(self, timeout=None, **kwargs):
url = '{0}/getMe'.format(self.base_url) result = self._request.get(url, timeout=timeout) self.bot = User.de_json(result, self) return self.bot
'Use this method to send text messages. Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target channel (in the format @channelusername). text (:obj:`str`): Text of the message to be sent. Max 4096 characters. Also found as :attr:`telegram.constants.MAX_MESSAGE_LENGTH`. ...
@log @message def send_message(self, chat_id, text, parse_mode=None, disable_web_page_preview=None, disable_notification=False, reply_to_message_id=None, reply_markup=None, timeout=None, **kwargs):
url = '{0}/sendMessage'.format(self.base_url) data = {'chat_id': chat_id, 'text': text} if parse_mode: data['parse_mode'] = parse_mode if disable_web_page_preview: data['disable_web_page_preview'] = disable_web_page_preview return (url, data)
'Use this method to delete a message. A message can only be deleted if it was sent less than 48 hours ago. Any such recently sent outgoing message may be deleted. Additionally, if the bot is an administrator in a group chat, it can delete any message. If the bot is an administrator in a supergroup, it can delete messag...
@log def delete_message(self, chat_id, message_id, timeout=None, **kwargs):
url = '{0}/deleteMessage'.format(self.base_url) data = {'chat_id': chat_id, 'message_id': message_id} result = self._request.post(url, data, timeout=timeout) return result
'Use this method to forward messages of any kind. Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target channel (in the format @channelusername). from_chat_id (:obj:`int` | :obj:`str`): Unique identifier for the chat where the original message was sent (or channel user...
@log @message def forward_message(self, chat_id, from_chat_id, message_id, disable_notification=False, timeout=None, **kwargs):
url = '{0}/forwardMessage'.format(self.base_url) data = {} if chat_id: data['chat_id'] = chat_id if from_chat_id: data['from_chat_id'] = from_chat_id if message_id: data['message_id'] = message_id return (url, data)
'Use this method to send photos. Note: The video argument can be either a file_id, an URL or a file from disk ``open(filename, \'rb\')`` Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target channel (in the format @channelusername). photo (:obj:`str` | `filelike object...
@log @message def send_photo(self, chat_id, photo, caption=None, disable_notification=False, reply_to_message_id=None, reply_markup=None, timeout=20.0, **kwargs):
url = '{0}/sendPhoto'.format(self.base_url) if isinstance(photo, PhotoSize): photo = photo.file_id data = {'chat_id': chat_id, 'photo': photo} if caption: data['caption'] = caption return (url, data)
'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. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future. For sending voice messages, use th...
@log @message def send_audio(self, chat_id, audio, duration=None, performer=None, title=None, caption=None, disable_notification=False, reply_to_message_id=None, reply_markup=None, timeout=20.0, **kwargs):
url = '{0}/sendAudio'.format(self.base_url) if isinstance(audio, Audio): audio = audio.file_id data = {'chat_id': chat_id, 'audio': audio} if duration: data['duration'] = duration if performer: data['performer'] = performer if title: data['title'] = title if c...
'Use this method to send general files. Note: The document argument can be either a file_id, an URL or a file from disk ``open(filename, \'rb\')`` Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target channel (in the format @channelusername). document (:obj:`str` | `fi...
@log @message def send_document(self, chat_id, document, filename=None, caption=None, disable_notification=False, reply_to_message_id=None, reply_markup=None, timeout=20.0, **kwargs):
url = '{0}/sendDocument'.format(self.base_url) if isinstance(document, Document): document = document.file_id data = {'chat_id': chat_id, 'document': document} if filename: data['filename'] = filename if caption: data['caption'] = caption return (url, data)
'Use this method to send .webp stickers. Note: The sticker argument can be either a file_id, an URL or a file from disk ``open(filename, \'rb\')`` Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target channel (in the format @channelusername). sticker (:obj:`str` | `fil...
@log @message def send_sticker(self, chat_id, sticker, disable_notification=False, reply_to_message_id=None, reply_markup=None, timeout=None, **kwargs):
url = '{0}/sendSticker'.format(self.base_url) if isinstance(sticker, Sticker): sticker = sticker.file_id data = {'chat_id': chat_id, 'sticker': sticker} return (url, data)
'Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document). Note: The video argument can be either a file_id, an URL or a file from disk ``open(filename, \'rb\')`` Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the tar...
@log @message def send_video(self, chat_id, video, duration=None, caption=None, disable_notification=False, reply_to_message_id=None, reply_markup=None, timeout=20.0, width=None, height=None, **kwargs):
url = '{0}/sendVideo'.format(self.base_url) if isinstance(video, Video): video = video.file_id data = {'chat_id': chat_id, 'video': video} if duration: data['duration'] = duration if caption: data['caption'] = caption if width: data['width'] = width if height:...
'Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .ogg file encoded with OPUS (other formats may be sent as Audio or Document). Note: The voice argument can be either a file_id, an URL or a file from disk ``open...
@log @message def send_voice(self, chat_id, voice, duration=None, caption=None, disable_notification=False, reply_to_message_id=None, reply_markup=None, timeout=20.0, **kwargs):
url = '{0}/sendVoice'.format(self.base_url) if isinstance(voice, Voice): voice = voice.file_id data = {'chat_id': chat_id, 'voice': voice} if duration: data['duration'] = duration if caption: data['caption'] = caption return (url, data)
'Use this method to send video messages. Note: The video_note argument can be either a file_id or a file from disk ``open(filename, \'rb\')`` Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target channel (in the format @channelusername). video_note (:obj:`str` | `filel...
@log @message def send_video_note(self, chat_id, video_note, duration=None, length=None, disable_notification=False, reply_to_message_id=None, reply_markup=None, timeout=20.0, **kwargs):
url = '{0}/sendVideoNote'.format(self.base_url) if isinstance(video_note, VideoNote): video_note = video_note.file_id data = {'chat_id': chat_id, 'video_note': video_note} if (duration is not None): data['duration'] = duration if (length is not None): data['length'] = length ...
'Use this method to send point on the map. Note: You can either supply a :obj:`latitude` and :obj:`longitude` or a :obj:`location`. Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target channel (in the format @channelusername). latitude (:obj:`float`, optional): Latitu...
@log @message def send_location(self, chat_id, latitude=None, longitude=None, disable_notification=False, reply_to_message_id=None, reply_markup=None, timeout=None, location=None, **kwargs):
url = '{0}/sendLocation'.format(self.base_url) if (not (all([latitude, longitude]) or location)): raise ValueError('Either location or latitude and longitude must be passed asargument') if isinstance(location, Location): latitude = location.latitude longitu...
'Use this method to send information about a venue. Note: you can either supply :obj:`venue`, or :obj:`latitude`, :obj:`longitude`, :obj:`title` and :obj:`address` and optionally :obj:`foursquare_id`. Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target channel (in th...
@log @message def send_venue(self, chat_id, latitude=None, longitude=None, title=None, address=None, foursquare_id=None, disable_notification=False, reply_to_message_id=None, reply_markup=None, timeout=None, venue=None, **kwargs):
url = '{0}/sendVenue'.format(self.base_url) if (not (venue or all([latitude, longitude, address, title]))): raise ValueError('Either venue or latitude, longitude, address and title must bepassed as arguments.') if isinstance(venue, Venue): latitude = venue.lo...
'Use this method to send phone contacts. Note: You can either supply :obj:`contact` or :obj:`phone_number` and :obj:`first_name` with optionally :obj:`last_name`. Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target channel (in the format @channelusername). phone_numb...
@log @message def send_contact(self, chat_id, phone_number=None, first_name=None, last_name=None, disable_notification=False, reply_to_message_id=None, reply_markup=None, timeout=None, contact=None, **kwargs):
url = '{0}/sendContact'.format(self.base_url) if ((not contact) and (not all([phone_number, first_name]))): raise ValueError('Either contact or phone_number and first_name must be passed asarguments.') if isinstance(contact, Contact): phone_number = contact.phone_n...
'Use this method to send a game. Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target channel (in the format @channelusername). game_short_name (:obj:`str`): Short name of the game, serves as the unique identifier for the game. Set up your games via Botfather. disable...
@log @message def send_game(self, chat_id, game_short_name, disable_notification=False, reply_to_message_id=None, reply_markup=None, timeout=None, **kwargs):
url = '{0}/sendGame'.format(self.base_url) data = {'chat_id': chat_id, 'game_short_name': game_short_name} return (url, data)
'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). Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the targ...
@log def send_chat_action(self, chat_id, action, timeout=None, **kwargs):
url = '{0}/sendChatAction'.format(self.base_url) data = {'chat_id': chat_id, 'action': action} data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return result
'Use this method to send answers to an inline query. No more than 50 results per query are allowed. Args: inline_query_id (:obj:`str`): Unique identifier for the answered query. results (List[:class:`telegram.InlineQueryResult`)]: A list of results for the inline query. cache_time (:obj:`int`, optional): The maximum am...
@log def answer_inline_query(self, inline_query_id, results, cache_time=300, is_personal=None, next_offset=None, switch_pm_text=None, switch_pm_parameter=None, timeout=None, **kwargs):
url = '{0}/answerInlineQuery'.format(self.base_url) results = [res.to_dict() for res in results] data = {'inline_query_id': inline_query_id, 'results': results} if (cache_time or (cache_time == 0)): data['cache_time'] = cache_time if is_personal: data['is_personal'] = is_personal ...
'Use this method to get a list of profile pictures for a user. Args: user_id (:obj:`int`): Unique identifier of the target user. offset (:obj:`int`, optional): Sequential number of the first photo to be returned. By default, all photos are returned. limit (:obj:`int`, optional): Limits the number of photos to be retrie...
@log def get_user_profile_photos(self, user_id, offset=None, limit=100, timeout=None, **kwargs):
url = '{0}/getUserProfilePhotos'.format(self.base_url) data = {'user_id': user_id} if (offset is not None): data['offset'] = offset if limit: data['limit'] = limit data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return UserProfilePhotos.de_json(res...
'Use this method to get basic info about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. The file can then be downloaded with :attr:`telegram.File.download`. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be re...
@log def get_file(self, file_id, timeout=None, **kwargs):
url = '{0}/getFile'.format(self.base_url) data = {'file_id': file_id} data.update(kwargs) result = self._request.post(url, data, timeout=timeout) if result.get('file_path'): result['file_path'] = ('%s/%s' % (self.base_file_url, result['file_path'])) return File.de_json(result, self)
'Use this method to kick a user from a group or a supergroup. In the case of supergroups, the user will not be able to return to the group on their own using invite links, etc., unless unbanned first. The bot must be an administrator in the group for this to work. Args: chat_id (:obj:`int` | :obj:`str`): Unique identif...
@log def kick_chat_member(self, chat_id, user_id, timeout=None, until_date=None, **kwargs):
url = '{0}/kickChatMember'.format(self.base_url) data = {'chat_id': chat_id, 'user_id': user_id} data.update(kwargs) if (until_date is not None): if isinstance(until_date, datetime): until_date = to_timestamp(until_date) data['until_date'] = until_date result = self._requ...
'Use this method to unban a previously kicked user in a supergroup. The user will not return to the group automatically, but will be able to join via link, etc. The bot must be an administrator in the group for this to work. Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of t...
@log def unban_chat_member(self, chat_id, user_id, timeout=None, **kwargs):
url = '{0}/unbanChatMember'.format(self.base_url) data = {'chat_id': chat_id, 'user_id': user_id} data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return result
'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. Alternatively, the user can be redirected to the specified Game URL. For this option to work, you must first create a game for your bo...
@log def answer_callback_query(self, callback_query_id, text=None, show_alert=False, url=None, cache_time=None, timeout=None, **kwargs):
url_ = '{0}/answerCallbackQuery'.format(self.base_url) data = {'callback_query_id': callback_query_id} if text: data['text'] = text if show_alert: data['show_alert'] = show_alert if url: data['url'] = url if (cache_time is not None): data['cache_time'] = cache_tim...
'Use this method to edit text and game messages sent by the bot or via the bot (for inline bots). Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target channel (in the format @channelusername). message_id (:obj:`int`, optional): Required if inline_message_id is not spe...
@log @message 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, timeout=None, **kwargs):
url = '{0}/editMessageText'.format(self.base_url) data = {'text': text} if chat_id: data['chat_id'] = chat_id if message_id: data['message_id'] = message_id if inline_message_id: data['inline_message_id'] = inline_message_id if parse_mode: data['parse_mode'] = par...
'Use this method to edit captions of messages sent by the bot or via the bot (for inline bots). Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target`channel (in the format @channelusername). message_id (:obj:`int`, optional): Required if inline_message_id is not speci...
@log @message def edit_message_caption(self, chat_id=None, message_id=None, inline_message_id=None, caption=None, reply_markup=None, timeout=None, **kwargs):
if ((inline_message_id is None) and ((chat_id is None) or (message_id is None))): raise ValueError('edit_message_caption: Both chat_id and message_id are required when inline_message_id is not specified') url = '{0}/editMessageCaption'.format(self.base_url) data = {}...
'Use this method to edit only the reply markup of messages sent by the bot or via the bot (for inline bots). Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target`channel (in the format @channelusername). message_id (:obj:`int`, optional): Required if inline_message_id...
@log @message def edit_message_reply_markup(self, chat_id=None, message_id=None, inline_message_id=None, reply_markup=None, timeout=None, **kwargs):
if ((inline_message_id is None) and ((chat_id is None) or (message_id is None))): raise ValueError('edit_message_reply_markup: Both chat_id and message_id are required when inline_message_id is not specified') url = '{0}/editMessageReplyMarkup'.format(self.base_url) ...
'Use this method to receive incoming updates using long polling. Args: offset (:obj:`int`, optional): Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returne...
@log def get_updates(self, offset=None, limit=100, timeout=0, network_delay=None, read_latency=2.0, allowed_updates=None, **kwargs):
url = '{0}/getUpdates'.format(self.base_url) if (network_delay is not None): warnings.warn('network_delay is deprecated, use read_latency instead') read_latency = network_delay data = {'timeout': timeout} if offset: data['offset'] = offset if limit: dat...
'Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url, containing a JSON-serialized Update. In case of an unsuccessful request, we will give up after a reasonable amount of attempts. If you...
@log def set_webhook(self, url=None, certificate=None, timeout=None, max_connections=40, allowed_updates=None, **kwargs):
url_ = '{0}/setWebhook'.format(self.base_url) if ('webhook_url' in kwargs): warnings.warn("The 'webhook_url' parameter has been renamed to 'url' in accordance with the API") if (url is not None): raise ValueError("The parameters 'url' and ...
'Use this method to remove webhook integration if you decide to switch back to getUpdates. Requires no parameters. Args: timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as the read timeout from the server (instead of the one specified during creation of the connection pool). **kwargs (...
@log def delete_webhook(self, timeout=None, **kwargs):
url = '{0}/deleteWebhook'.format(self.base_url) data = kwargs result = self._request.post(url, data, timeout=timeout) return result
'Use this method for your bot to leave a group, supergroup or channel. Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target`channel (in the format @channelusername). timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as the read timeout ...
@log def leave_chat(self, chat_id, timeout=None, **kwargs):
url = '{0}/leaveChat'.format(self.base_url) data = {'chat_id': chat_id} data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return result
'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.). Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target`channel (in the format @channelusername). ti...
@log def get_chat(self, chat_id, timeout=None, **kwargs):
url = '{0}/getChat'.format(self.base_url) data = {'chat_id': chat_id} data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return Chat.de_json(result, self)
'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. Args: chat_id (:obj:`i...
@log def get_chat_administrators(self, chat_id, timeout=None, **kwargs):
url = '{0}/getChatAdministrators'.format(self.base_url) data = {'chat_id': chat_id} data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return [ChatMember.de_json(x, self) for x in result]
'Use this method to get the number of members in a chat Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target`channel (in the format @channelusername). timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as the read timeout from the server...
@log def get_chat_members_count(self, chat_id, timeout=None, **kwargs):
url = '{0}/getChatMembersCount'.format(self.base_url) data = {'chat_id': chat_id} data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return result
'Use this method to get information about a member of a chat. Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target`channel (in the format @channelusername). user_id (:obj:`int`): Unique identifier of the target user. timeout (:obj:`int` | :obj:`float`, optional): If t...
@log def get_chat_member(self, chat_id, user_id, timeout=None, **kwargs):
url = '{0}/getChatMember'.format(self.base_url) data = {'chat_id': chat_id, 'user_id': user_id} data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return ChatMember.de_json(result, self)
'Use this method to get current webhook status. Requires no parameters. If the bot is using getUpdates, will return an object with the url field empty. Args: timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as the read timeout from the server (instead of the one specified during creatio...
def get_webhook_info(self, timeout=None, **kwargs):
url = '{0}/getWebhookInfo'.format(self.base_url) data = kwargs result = self._request.post(url, data, timeout=timeout) return WebhookInfo.de_json(result, self)
'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. Args: user_id (:obj:`int`): User identif...
@log @message def set_game_score(self, user_id, score, chat_id=None, message_id=None, inline_message_id=None, force=None, disable_edit_message=None, timeout=None, **kwargs):
url = '{0}/setGameScore'.format(self.base_url) data = {'user_id': user_id, 'score': score} if chat_id: data['chat_id'] = chat_id if message_id: data['message_id'] = message_id if inline_message_id: data['inline_message_id'] = inline_message_id if (force is not 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 Args: user_id (:obj:`int`): User identifier. chat_id (:obj:`int` | :obj:`str`, optional): Required if inline_message_id is not specified. Unique identifier for the target chat. message_...
@log def get_game_high_scores(self, user_id, chat_id=None, message_id=None, inline_message_id=None, timeout=None, **kwargs):
url = '{0}/getGameHighScores'.format(self.base_url) data = {'user_id': user_id} if chat_id: data['chat_id'] = chat_id if message_id: data['message_id'] = message_id if inline_message_id: data['inline_message_id'] = inline_message_id data.update(kwargs) result = self._...
'Use this method to send invoices. Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target private chat. title (:obj:`str`): Product name. description (:obj:`str`): Product description. payload (:obj:`str`): Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your...
@log @message def send_invoice(self, chat_id, title, description, payload, provider_token, start_parameter, currency, prices, 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_flexible=None, disable_notification=...
url = '{0}/sendInvoice'.format(self.base_url) data = {'chat_id': chat_id, 'title': title, 'description': description, 'payload': payload, 'provider_token': provider_token, 'start_parameter': start_parameter, 'currency': currency, 'prices': [p.to_dict() for p in prices]} if (photo_url is not None): d...
'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. Args: shipping_query_id (:obj:`str`): Unique identifier for the query to be answered. ok (:obj:`bool`):...
@log def answer_shipping_query(self, shipping_query_id, ok, shipping_options=None, error_message=None, timeout=None, **kwargs):
ok = bool(ok) if (ok and ((shipping_options is None) or (error_message is not None))): raise TelegramError('answerShippingQuery: If ok is True, shipping_options should not be empty and there should not be error_message') if ((not ok) and ((shipping_option...
'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. Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent....
@log def answer_pre_checkout_query(self, pre_checkout_query_id, ok, error_message=None, timeout=None, **kwargs):
ok = bool(ok) if (not (ok ^ (error_message is not None))): raise TelegramError('answerPreCheckoutQuery: If ok is True, there should not be error_message; if ok is False, error_message should not be empty') url_ = '{0}/answerPreCheckoutQuery'.form...
'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. Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or us...
@log 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, timeout=None, **kwargs):
url = '{0}/restrictChatMember'.format(self.base_url) data = {'chat_id': chat_id, 'user_id': user_id} if (until_date is not None): if isinstance(until_date, datetime): until_date = to_timestamp(until_date) data['until_date'] = until_date if (can_send_messages is not None): ...
'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 Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or us...
@log 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, timeout=None, **kwargs):
url = '{0}/promoteChatMember'.format(self.base_url) data = {'chat_id': chat_id, 'user_id': user_id} if (can_change_info is not None): data['can_change_info'] = can_change_info if (can_post_messages is not None): data['can_post_messages'] = can_post_messages if (can_edit_messages is n...
'Use this method to export an invite link to 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. Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target`channel (in the format @channeluserna...
@log def export_chat_invite_link(self, chat_id, timeout=None, **kwargs):
url = '{0}/exportChatInviteLink'.format(self.base_url) data = {'chat_id': chat_id} data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return result
'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. Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target`channel...
@log def set_chat_photo(self, chat_id, photo, timeout=None, **kwargs):
url = '{0}/setChatPhoto'.format(self.base_url) data = {'chat_id': chat_id, 'photo': photo} data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return result
'Use this method to delete a chat photo. 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. Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target`channel (in the format @...
@log def delete_chat_photo(self, chat_id, timeout=None, **kwargs):
url = '{0}/deleteChatPhoto'.format(self.base_url) data = {'chat_id': chat_id} data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return result
'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. Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target`channel (in the f...
@log def set_chat_title(self, chat_id, title, timeout=None, **kwargs):
url = '{0}/setChatTitle'.format(self.base_url) data = {'chat_id': chat_id, 'title': title} data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return result
'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. Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target`channel (in the format @channelusern...
@log def set_chat_description(self, chat_id, description, timeout=None, **kwargs):
url = '{0}/setChatDescription'.format(self.base_url) data = {'chat_id': chat_id, 'description': description} data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return result
'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. Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target`channel (in the format @channelusername). message_id (:obj...
@log def pin_chat_message(self, chat_id, message_id, disable_notification=None, timeout=None, **kwargs):
url = '{0}/pinChatMessage'.format(self.base_url) data = {'chat_id': chat_id, 'message_id': message_id} if (disable_notification is not None): data['disable_notification'] = disable_notification data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return result
'Use this method to unpin 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. Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target`channel (in the format @channelusername). timeout (:obj:...
@log def unpin_chat_message(self, chat_id, timeout=None, **kwargs):
url = '{0}/unpinChatMessage'.format(self.base_url) data = {'chat_id': chat_id} data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return result
'Use this method to get a sticker set. Args: name (:obj:`str`): Short name of the sticker set that is used in t.me/addstickers/ URLs (e.g., animals) timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as the read timeout from the server (instead of the one specified during creation of the ...
@log def get_sticker_set(self, name, timeout=None, **kwargs):
url = '{0}/getStickerSet'.format(self.base_url) data = {'name': name} data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return StickerSet.de_json(result, self)
'Use this method to upload a .png file with a sticker for later use in :attr:`create_new_sticker_set` and :attr:`add_sticker_to_set` methods (can be used multiple times). Note: The png_sticker argument can be either a file_id, an URL or a file from disk ``open(filename, \'rb\')`` Args: user_id (:obj:`int`): User identi...
@log def upload_sticker_file(self, user_id, png_sticker, timeout=None, **kwargs):
url = '{0}/uploadStickerFile'.format(self.base_url) data = {'user_id': user_id, 'png_sticker': png_sticker} data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return File.de_json(result, self)
'Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set. Note: The png_sticker argument can be either a file_id, an URL or a file from disk ``open(filename, \'rb\')`` Args: user_id (:obj:`int`): User identifier of created sticker set owner. name (:obj:`str`): Sho...
@log def create_new_sticker_set(self, user_id, name, title, png_sticker, emojis, contains_masks=None, mask_position=None, timeout=None, **kwargs):
url = '{0}/createNewStickerSet'.format(self.base_url) data = {'user_id': user_id, 'name': name, 'title': title, 'png_sticker': png_sticker, 'emojis': emojis} if (contains_masks is not None): data['contains_masks'] = contains_masks if (mask_position is not None): data['mask_position'] = m...
'Use this method to add a new sticker to a set created by the bot. Note: The png_sticker argument can be either a file_id, an URL or a file from disk ``open(filename, \'rb\')`` Args: user_id (:obj:`int`): User identifier of created sticker set owner. name (:obj:`str`): Sticker set name. png_sticker (:obj:`str` | `filel...
@log def add_sticker_to_set(self, user_id, name, png_sticker, emojis, mask_position=None, timeout=None, **kwargs):
url = '{0}/addStickerToSet'.format(self.base_url) data = {'user_id': user_id, 'name': name, 'png_sticker': png_sticker, 'emojis': emojis} if (mask_position is not None): data['mask_position'] = mask_position data.update(kwargs) result = self._request.post(url, data, timeout=timeout) retu...
'Use this method to move a sticker in a set created by the bot to a specific position. Args: sticker (:obj:`str`): File identifier of the sticker. position (:obj:`int`): New sticker position in the set, zero-based. timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as the read timeout fro...
@log def set_sticker_position_in_set(self, sticker, position, timeout=None, **kwargs):
url = '{0}/setStickerPositionInSet'.format(self.base_url) data = {'sticker': sticker, 'position': position} data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return result
'Use this method to delete a sticker from a set created by the bot. Args: sticker (:obj:`str`): File identifier of the sticker. timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as the read timeout from the server (instead of the one specified during creation of the connection pool). **k...
@log def delete_sticker_from_set(self, sticker, timeout=None, **kwargs):
url = '{0}/deleteStickerFromSet'.format(self.base_url) data = {'sticker': sticker} data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return result
'Try and parse the JSON returned from Telegram. Returns: dict: A JSON parsed as Python dict with results - on error this dict will be empty.'
@staticmethod def _parse(json_data):
decoded_s = json_data.decode('utf-8') try: data = json.loads(decoded_s) except ValueError: raise TelegramError('Invalid server response') if (not data.get('ok')): description = data.get('description') parameters = data.get('parameters') if parameters: ...
'Wraps urllib3 request for handling known exceptions. Args: args: unnamed arguments, passed to urllib3 request. kwargs: keyword arguments, passed tp urllib3 request. Returns: str: A non-parsed JSON text. Raises: TelegramError'
def _request_wrapper(self, *args, **kwargs):
if ('headers' not in kwargs): kwargs['headers'] = {} kwargs['headers']['connection'] = 'keep-alive' try: resp = self._con_pool.request(*args, **kwargs) except urllib3.exceptions.TimeoutError: raise TimedOut() except urllib3.exceptions.HTTPError as error: raise Network...
'Request an URL. Args: url (:obj:`str`): The web location we want to retrieve. timeout (:obj:`int` | :obj:`float`): If this value is specified, use it as the read timeout from the server (instead of the one specified during creation of the connection pool). Returns: A JSON object.'
def get(self, url, timeout=None):
urlopen_kwargs = {} if (timeout is not None): urlopen_kwargs['timeout'] = Timeout(read=timeout, connect=self._connect_timeout) result = self._request_wrapper('GET', url, **urlopen_kwargs) return self._parse(result)
'Request an URL. Args: url (:obj:`str`): The web location we want to retrieve. data (dict[str, str|int]): A dict of key/value pairs. Note: On py2.7 value is unicode. timeout (:obj:`int` | :obj:`float`): If this value is specified, use it as the read timeout from the server (instead of the one specified during creation ...
def post(self, url, data, timeout=None):
urlopen_kwargs = {} if (timeout is not None): urlopen_kwargs['timeout'] = Timeout(read=timeout, connect=self._connect_timeout) if InputFile.is_inputfile(data): data = InputFile(data) result = self._request_wrapper('POST', url, body=data.to_form(), headers=data.headers, **urlopen_kwar...
'Retrieve the contents of a file by its URL. Args: url (:obj:`str`): The web location we want to retrieve. timeout (:obj:`int` | :obj:`float`): If this value is specified, use it as the read timeout from the server (instead of the one specified during creation of the connection pool).'
def retrieve(self, url, timeout=None):
urlopen_kwargs = {} if (timeout is not None): urlopen_kwargs['timeout'] = Timeout(read=timeout, connect=self._connect_timeout) return self._request_wrapper('GET', url, **urlopen_kwargs)
'Download a file by its URL. Args: url (str): The web location we want to retrieve. timeout (:obj:`int` | :obj:`float`): If this value is specified, use it as the read timeout from the server (instead of the one specified during creation of the connection pool). filename: The filename within the path to download the fi...
def download(self, url, filename, timeout=None):
buf = self.retrieve(url, timeout=timeout) with open(filename, 'wb') as fobj: fobj.write(buf)
'Log an arbitrary message. This is used by all other logging functions. It overrides ``BaseHTTPRequestHandler.log_message``, which logs to ``sys.stderr``. The first argument, FORMAT, is a format string for the message to be logged. If the format string contains any % escapes requiring parameters, they should be specif...
def log_message(self, format, *args):
self.logger.debug(('%s - - %s' % (self.address_string(), (format % args))))
'Each subclass of Preprocessor should override the `run` method, which takes the document as a list of strings split by newlines and returns the (possibly modified) list of lines.'
def run(self, lines):
pass
'Create a HtmlStash.'
def __init__(self):
self.html_counter = 0 self.rawHtmlBlocks = []
'Saves an HTML segment for later reinsertion. Returns a placeholder string that needs to be inserted into the document. Keyword arguments: * html: an html segment * safe: label an html segment as safe for safemode Returns : a placeholder string'
def store(self, html, safe=False):
self.rawHtmlBlocks.append((html, safe)) placeholder = (HTML_PLACEHOLDER % self.html_counter) self.html_counter += 1 return placeholder
'Create an instant of an inline pattern. Keyword arguments: * pattern: A regular expression that matches a pattern'
def __init__(self, pattern, markdown_instance=None):
self.pattern = pattern self.compiled_re = re.compile(('^(.*?)%s(.*?)$' % pattern), re.DOTALL) self.safe_mode = False if markdown_instance: self.markdown = markdown_instance
'Return a compiled regular expression.'
def getCompiledRegExp(self):
return self.compiled_re
'Return a ElementTree element from the given match. Subclasses should override this method. Keyword arguments: * m: A re match object containing a match of the pattern.'
def handleMatch(self, m):
pass
'Return class name, to define pattern type'
def type(self):
return self.__class__.__name__
'Sanitize a url against xss attacks in "safe_mode". Rather than specifically blacklisting `javascript:alert("XSS")` and all its aliases (see <http://ha.ckers.org/xss.html>), we whitelist known safe url formats. Most urls contain a network location, however some are known not to (i.e.: mailto links). Script urls do not ...
def sanitize_url(self, url):
locless_schemes = ['', 'mailto', 'news'] (scheme, netloc, path, params, query, fragment) = url = urlparse(url) safe_url = False if ((netloc != '') or (scheme in locless_schemes)): safe_url = True for part in url[2:]: if (':' in part): safe_url = False if (self.markdow...
'Subclasses of Treeprocessor should implement a `run` method, which takes a root ElementTree. This method can return another ElementTree object, and the existing root ElementTree will be replaced, or it can modify the current tree and return None.'
def run(self, root):
pass
'Generate a placeholder'
def __makePlaceholder(self, type):
id = ('%04d' % len(self.stashed_nodes)) hash = (markdown.INLINE_PLACEHOLDER % id) return (hash, id)
'Extract id from data string, start from index Keyword arguments: * data: string * index: index, from which we start search Returns: placeholder id and string index, after the found placeholder.'
def __findPlaceholder(self, data, index):
m = self.__placeholder_re.search(data, index) if m: return (m.group(1), m.end()) else: return (None, (index + 1))
'Add node to stash'
def __stashNode(self, node, type):
(placeholder, id) = self.__makePlaceholder(type) self.stashed_nodes[id] = node return placeholder
'Process string with inline patterns and replace it with placeholders Keyword arguments: * data: A line of Markdown text * patternIndex: The index of the inlinePattern to start with Returns: String with placeholders.'
def __handleInline(self, data, patternIndex=0):
if (not isinstance(data, markdown.AtomicString)): startIndex = 0 while (patternIndex < len(self.markdown.inlinePatterns)): (data, matched, startIndex) = self.__applyPattern(self.markdown.inlinePatterns.value_for_index(patternIndex), data, patternIndex, startIndex) if (not mat...
'Process placeholders in Element.text or Element.tail of Elements popped from self.stashed_nodes. Keywords arguments: * node: parent node * subnode: processing node * isText: bool variable, True - it\'s text, False - it\'s tail Returns: None'
def __processElementText(self, node, subnode, isText=True):
if isText: text = subnode.text subnode.text = None else: text = subnode.tail subnode.tail = None childResult = self.__processPlaceholders(text, subnode) if ((not isText) and (node is not subnode)): pos = node.getchildren().index(subnode) node.remove(subnod...
'Process string with placeholders and generate ElementTree tree. Keyword arguments: * data: string with placeholders instead of ElementTree elements. * parent: Element, which contains processing inline data Returns: list with ElementTree elements with applied inline patterns.'
def __processPlaceholders(self, data, parent):
def linkText(text): if text: if result: if result[(-1)].tail: result[(-1)].tail += text else: result[(-1)].tail = text elif parent.text: parent.text += text else: paren...
'Check if the line fits the pattern, create the necessary elements, add it to stashed_nodes. Keyword arguments: * data: the text to be processed * pattern: the pattern to be checked * patternIndex: index of current pattern * startIndex: string index, from which we starting search Returns: String with placeholders inste...
def __applyPattern(self, pattern, data, patternIndex, startIndex=0):
match = pattern.getCompiledRegExp().match(data[startIndex:]) leftData = data[:startIndex] if (not match): return (data, False, 0) node = pattern.handleMatch(match) if (node is None): return (data, True, (len(leftData) + match.span(len(match.groups()))[0])) if (not isString(node))...
'Apply inline patterns to a parsed Markdown tree. Iterate over ElementTree, find elements with inline tag, apply inline patterns and append newly created Elements to tree. If you don\'t want process your data with inline paterns, instead of normal string, use subclass AtomicString: node.text = markdown.AtomicString("d...
def run(self, tree):
self.stashed_nodes = {} stack = [tree] while stack: currElement = stack.pop() insertQueue = [] for child in currElement.getchildren(): if (child.text and (not isinstance(child.text, markdown.AtomicString))): text = child.text child.text = N...
'Recursively add linebreaks to ElementTree children.'
def _prettifyETree(self, elem):
i = '\n' if (markdown.isBlockLevel(elem.tag) and (elem.tag not in ['code', 'pre'])): if (((not elem.text) or (not elem.text.strip())) and len(elem) and markdown.isBlockLevel(elem[0].tag)): elem.text = i for e in elem: if markdown.isBlockLevel(e.tag): self....
'Add linebreaks to ElementTree root object.'
def run(self, root):
self._prettifyETree(root) brs = root.getiterator('br') for br in brs: if ((not br.tail) or (not br.tail.strip())): br.tail = '\n' else: br.tail = ('\n%s' % br.tail)
'Creates a new Markdown instance. Keyword arguments: * extensions: A list of extensions. If they are of type string, the module mdx_name.py will be loaded. If they are a subclass of markdown.Extension, they will be used as-is. * extension-configs: Configuration setting for extensions. * safe_mode: Disallow raw html. On...
def __init__(self, extensions=[], extension_configs={}, safe_mode=False, output_format=DEFAULT_OUTPUT_FORMAT):
self.safeMode = safe_mode self.registeredExtensions = [] self.docType = '' self.stripTopLevelTags = True self.preprocessors = odict.OrderedDict() self.preprocessors['html_block'] = preprocessors.HtmlBlockPreprocessor(self) self.preprocessors['reference'] = preprocessors.ReferencePreprocessor...
'Register extensions with this instance of Markdown. Keyword aurguments: * extensions: A list of extensions, which can either be strings or objects. See the docstring on Markdown. * configs: A dictionary mapping module names to config options.'
def registerExtensions(self, extensions, configs):
for ext in extensions: if isinstance(ext, basestring): ext = load_extension(ext, configs.get(ext, [])) if isinstance(ext, Extension): try: ext.extendMarkdown(self, globals()) except NotImplementedError as e: message(ERROR, e) ...
'This gets called by the extension'
def registerExtension(self, extension):
self.registeredExtensions.append(extension)