Exemplo n.º 1
0
        def decorator(self, *args, **kwargs):
            """
            decorator
            """
            url, data = func(self, *args, **kwargs)

            if not data.get('chat_id'):
                raise TelegramError('Invalid chat_id')

            if kwargs.get('reply_to_message_id'):
                reply_to_message_id = kwargs.get('reply_to_message_id')
                data['reply_to_message_id'] = reply_to_message_id

            if kwargs.get('reply_markup'):
                reply_markup = kwargs.get('reply_markup')
                if isinstance(reply_markup, ReplyMarkup):
                    data['reply_markup'] = reply_markup.to_json()
                else:
                    data['reply_markup'] = reply_markup

            result = request.post(url, data)

            if result is True:
                return result

            return Message.de_json(result)
Exemplo n.º 2
0
    def getFile(self,
                file_id):
        """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.

        Args:
          file_id:
            File identifier to get info about.

        Returns:
          Returns a telegram.File object
        """

        url = '%s/getFile' % self.base_url

        data = {'file_id': file_id}

        result = request.post(url, data)

        if result.get('file_path'):
            result['file_path'] = '%s/%s' % (self.base_file_url,
                                             result['file_path'])

        return File.de_json(result)
Exemplo n.º 3
0
    def getFile(self, file_id, **kwargs):
        """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.

        Args:
          file_id:
            File identifier to get info about.

        Keyword Args:
            timeout (Optional[float]): If this value is specified, use it as
                the definitive timeout (in seconds) for urlopen() operations.

        Returns:
            :class:`telegram.File`: On success, a :class:`telegram.File`
            object is returned.

        Raises:
            :class:`telegram.TelegramError`

        """

        url = '{0}/getFile'.format(self.base_url)

        data = {'file_id': file_id}

        result = request.post(url, data, timeout=kwargs.get('timeout'))

        if result.get('file_path'):
            result['file_path'] = '%s/%s' % (self.base_file_url, result['file_path'])

        return File.de_json(result)
Exemplo n.º 4
0
    def setWebhook(self,
                   webhook_url=None,
                   certificate=None):
        """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.

        Args:
          url:
            HTTPS url to send updates to.
            Use an empty string to remove webhook integration

        Returns:
          True if successful else TelegramError was raised
        """
        url = '%s/setWebhook' % self.base_url

        data = {}
        if webhook_url:
            data['url'] = webhook_url
        if certificate:
            data['certificate'] = certificate

        result = request.post(url, data)

        return result
Exemplo n.º 5
0
    def setWebhook(self, webhook_url=None, certificate=None):
        """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.

        Args:
          url:
            HTTPS url to send updates to.
            Use an empty string to remove webhook integration

        Returns:
          True if successful else TelegramError was raised
        """
        url = '%s/setWebhook' % self.base_url

        data = {}
        if webhook_url:
            data['url'] = webhook_url
        if certificate:
            data['certificate'] = certificate

        result = request.post(url, data)

        return result
Exemplo n.º 6
0
    def getUserProfilePhotos(self, user_id, offset=None, limit=100):
        """Use this method to get a list of profile pictures for a user.

        Args:
          user_id:
            Unique identifier of the target user.
          offset:
            Sequential number of the first photo to be returned. By default,
            all photos are returned. [Optional]
          limit:
            Limits the number of photos to be retrieved. Values between 1-100
            are accepted. Defaults to 100. [Optional]

        Returns:
          Returns a telegram.UserProfilePhotos object.
        """

        url = '%s/getUserProfilePhotos' % self.base_url

        data = {'user_id': user_id}

        if offset:
            data['offset'] = offset
        if limit:
            data['limit'] = limit

        result = request.post(url, data)

        return UserProfilePhotos.de_json(result)
Exemplo n.º 7
0
    def getFile(self, file_id, **kwargs):
        """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.

        Args:
          file_id:
            File identifier to get info about.

        Keyword Args:
            timeout (Optional[float]): If this value is specified, use it as
                the definitive timeout (in seconds) for urlopen() operations.

        Returns:
            :class:`telegram.File`: On success, a :class:`telegram.File`
            object is returned.

        Raises:
            :class:`telegram.TelegramError`

        """

        url = '{0}/getFile'.format(self.base_url)

        data = {'file_id': file_id}

        result = request.post(url, data, timeout=kwargs.get('timeout'))

        if result.get('file_path'):
            result['file_path'] = '%s/%s' % (self.base_file_url,
                                             result['file_path'])

        return File.de_json(result)
Exemplo n.º 8
0
    def unbanChatMember(self, chat_id, user_id, **kwargs):
        """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:
            Unique identifier for the target group or username of the target
            supergroup (in the format @supergroupusername).
          user_id:
            Unique identifier of the target user.

        Keyword Args:
            timeout (Optional[float]): If this value is specified, use it as
                the definitive timeout (in seconds) for urlopen() operations.

        Returns:
            bool: On success, `True` is returned.

        Raises:
            :class:`telegram.TelegramError`

        """

        url = '{0}/unbanChatMember'.format(self.base_url)

        data = {'chat_id': chat_id, 'user_id': user_id}

        result = request.post(url, data, timeout=kwargs.get('timeout'))

        return result
Exemplo n.º 9
0
    def kickChatMember(self, chat_id, user_id, **kwargs):
        """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:
            Unique identifier for the target group or username of the target
            supergroup (in the format @supergroupusername).
          user_id:
            Unique identifier of the target user.

        Keyword Args:
            timeout (Optional[float]): If this value is specified, use it as
                the definitive timeout (in seconds) for urlopen() operations.

        Returns:
            bool: On success, `True` is returned.

        Raises:
            :class:`telegram.TelegramError`

        """

        url = '{0}/kickChatMember'.format(self.base_url)

        data = {'chat_id': chat_id, 'user_id': user_id}

        result = request.post(url, data, timeout=kwargs.get('timeout'))

        return result
Exemplo n.º 10
0
    def _post_message(url, data, kwargs, timeout=None, network_delay=2.):
        """Posts a message to the telegram servers.

        Returns:
            telegram.Message

        """
        if not data.get('chat_id'):
            raise TelegramError('Invalid chat_id')

        if kwargs.get('reply_to_message_id'):
            reply_to_message_id = kwargs.get('reply_to_message_id')
            data['reply_to_message_id'] = reply_to_message_id

        if kwargs.get('reply_markup'):
            reply_markup = kwargs.get('reply_markup')
            if isinstance(reply_markup, ReplyMarkup):
                data['reply_markup'] = reply_markup.to_json()
            else:
                data['reply_markup'] = reply_markup

        result = request.post(url,
                              data,
                              timeout=timeout,
                              network_delay=network_delay)

        if result is True:
            return result

        return Message.de_json(result)
Exemplo n.º 11
0
    def _post_message(url, data, kwargs, timeout=None, network_delay=2.):
        """Posts a message to the telegram servers.

        Returns:
            telegram.Message

        """
        if not data.get('chat_id'):
            raise TelegramError('Invalid chat_id')

        if kwargs.get('reply_to_message_id'):
            reply_to_message_id = kwargs.get('reply_to_message_id')
            data['reply_to_message_id'] = reply_to_message_id

        if kwargs.get('reply_markup'):
            reply_markup = kwargs.get('reply_markup')
            if isinstance(reply_markup, ReplyMarkup):
                data['reply_markup'] = reply_markup.to_json()
            else:
                data['reply_markup'] = reply_markup

        result = request.post(url, data, timeout=timeout,
                              network_delay=network_delay)

        if result is True:
            return result

        return Message.de_json(result)
Exemplo n.º 12
0
        def decorator(self, *args, **kwargs):
            url, data = func(self, *args, **kwargs)

            if kwargs.get('reply_to_message_id'):
                data['reply_to_message_id'] = \
                    kwargs.get('reply_to_message_id')

            if kwargs.get('disable_notification'):
                data['disable_notification'] = \
                    kwargs.get('disable_notification')

            if kwargs.get('reply_markup'):
                reply_markup = kwargs.get('reply_markup')
                if isinstance(reply_markup, ReplyMarkup):
                    data['reply_markup'] = reply_markup.to_json()
                else:
                    data['reply_markup'] = reply_markup

            result = request.post(url, data,
                                  timeout=kwargs.get('timeout'))

            if result is True:
                return result

            return Message.de_json(result)
Exemplo n.º 13
0
        def decorator(self, *args, **kwargs):
            """
            decorator
            """
            url, data = func(self, *args, **kwargs)

            if not data.get('chat_id'):
                raise TelegramError('Invalid chat_id')

            if kwargs.get('reply_to_message_id'):
                reply_to_message_id = kwargs.get('reply_to_message_id')
                data['reply_to_message_id'] = reply_to_message_id

            if kwargs.get('reply_markup'):
                reply_markup = kwargs.get('reply_markup')
                if isinstance(reply_markup, ReplyMarkup):
                    data['reply_markup'] = reply_markup.to_json()
                else:
                    data['reply_markup'] = reply_markup

            result = request.post(url, data)

            if result is True:
                return result

            return Message.de_json(result)
Exemplo n.º 14
0
    def getUserProfilePhotos(self,
                             user_id,
                             offset=None,
                             limit=100):
        """Use this method to get a list of profile pictures for a user.

        Args:
          user_id:
            Unique identifier of the target user.
          offset:
            Sequential number of the first photo to be returned. By default,
            all photos are returned. [Optional]
          limit:
            Limits the number of photos to be retrieved. Values between 1-100
            are accepted. Defaults to 100. [Optional]

        Returns:
          Returns a telegram.UserProfilePhotos object.
        """

        url = '%s/getUserProfilePhotos' % self.base_url

        data = {'user_id': user_id}

        if offset:
            data['offset'] = offset
        if limit:
            data['limit'] = limit

        result = request.post(url, data)

        return UserProfilePhotos.de_json(result)
Exemplo n.º 15
0
    def getFile(self,
                file_id):
        """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.

        Args:
          file_id:
            File identifier to get info about.

        Returns:
          Returns a telegram.File object
        """

        url = '%s/getFile' % self.base_url

        data = {'file_id': file_id}

        result = request.post(url, data)

        if result.get('file_path'):
            result['file_path'] = '%s/%s' % (self.base_file_url,
                                             result['file_path'])

        return File.de_json(result)
Exemplo n.º 16
0
    def kickChatMember(self, chat_id, user_id, **kwargs):
        """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:
            Unique identifier for the target group or username of the target
            supergroup (in the format @supergroupusername).
          user_id:
            Unique identifier of the target user.

        Keyword Args:
            timeout (Optional[float]): If this value is specified, use it as
                the definitive timeout (in seconds) for urlopen() operations.

        Returns:
            bool: On success, `True` is returned.

        Raises:
            :class:`telegram.TelegramError`

        """

        url = '{0}/kickChatMember'.format(self.base_url)

        data = {'chat_id': chat_id, 'user_id': user_id}

        result = request.post(url, data, timeout=kwargs.get('timeout'))

        return result
Exemplo n.º 17
0
    def unbanChatMember(self, chat_id, user_id, **kwargs):
        """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:
            Unique identifier for the target group or username of the target
            supergroup (in the format @supergroupusername).
          user_id:
            Unique identifier of the target user.

        Keyword Args:
            timeout (Optional[float]): If this value is specified, use it as
                the definitive timeout (in seconds) for urlopen() operations.

        Returns:
            bool: On success, `True` is returned.

        Raises:
            :class:`telegram.TelegramError`

        """

        url = '{0}/unbanChatMember'.format(self.base_url)

        data = {'chat_id': chat_id, 'user_id': user_id}

        result = request.post(url, data, timeout=kwargs.get('timeout'))

        return result
Exemplo n.º 18
0
    def getUpdates(self,
                   offset=None,
                   limit=100,
                   timeout=0,
                   network_delay=.2):
        """Use this method to receive incoming updates using long polling.

        Args:
          offset:
            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 returned. An update is considered confirmed as soon as
            getUpdates is called with an offset higher than its update_id.
          limit:
            Limits the number of updates to be retrieved. Values between 1-100
            are accepted. Defaults to 100.
          timeout:
            Timeout in seconds for long polling. Defaults to 0, i.e. usual
            short polling.
          network_delay:
            Additional timeout in seconds to allow the response from Telegram
            to take some time when using long polling. Defaults to 2, which
            should be enough for most connections. Increase it if it takes very
            long for data to be transmitted from and to the Telegram servers.

        Returns:
            list[:class:`telegram.Update`]: A list of :class:`telegram.Update`
            objects are returned.

        Raises:
            :class:`telegram.TelegramError`

        """

        url = '{0}/getUpdates'.format(self.base_url)

        data = {'timeout': timeout}

        if offset:
            data['offset'] = offset
        if limit:
            data['limit'] = limit

        urlopen_timeout = timeout + network_delay

        result = request.post(url, data, timeout=urlopen_timeout)

        if result:
            self.logger.debug(
                'Getting updates: %s', [u['update_id'] for u in result])
        else:
            self.logger.debug('No new updates found.')

        return [Update.de_json(x) for x in result]
Exemplo n.º 19
0
    def getUpdates(self, offset=None, limit=100, timeout=0, network_delay=.2):
        """Use this method to receive incoming updates using long polling.

        Args:
          offset:
            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 returned. An update is considered confirmed as soon as
            getUpdates is called with an offset higher than its update_id.
          limit:
            Limits the number of updates to be retrieved. Values between 1-100
            are accepted. Defaults to 100.
          timeout:
            Timeout in seconds for long polling. Defaults to 0, i.e. usual
            short polling.
          network_delay:
            Additional timeout in seconds to allow the response from Telegram
            to take some time when using long polling. Defaults to 2, which
            should be enough for most connections. Increase it if it takes very
            long for data to be transmitted from and to the Telegram servers.

        Returns:
            list[:class:`telegram.Update`]: A list of :class:`telegram.Update`
            objects are returned.

        Raises:
            :class:`telegram.TelegramError`

        """

        url = '{0}/getUpdates'.format(self.base_url)

        data = {'timeout': timeout}

        if offset:
            data['offset'] = offset
        if limit:
            data['limit'] = limit

        urlopen_timeout = timeout + network_delay

        result = request.post(url, data, timeout=urlopen_timeout)

        if result:
            self.logger.debug('Getting updates: %s',
                              [u['update_id'] for u in result])
        else:
            self.logger.debug('No new updates found.')

        return [Update.de_json(x) for x in result]
Exemplo n.º 20
0
    def answerInlineQuery(self,
                          inline_query_id,
                          results,
                          cache_time=None,
                          is_personal=None,
                          next_offset=None):
        """Use this method to reply to an inline query.

        Args:
            inline_query_id (str):
                Unique identifier for answered query
            results (list[InlineQueryResult]):
                A list of results for the inline query

        Keyword Args:
            cache_time (Optional[int]): The maximum amount of time the result
                of the inline query may be cached on the server
            is_personal (Optional[bool]): Pass True, if results may be cached
                on the server side only for the user that sent the query. By
                default, results may be returned to any user who sends the same
                query
            next_offset (Optional[str]): Pass the offset that a client should
                send in the next query with the same text to receive more
                results. Pass an empty string if there are no more results or
                if you don't support pagination. Offset length can't exceed 64
                bytes.

        Returns:
            A boolean if answering was successful
        """

        validate_string(inline_query_id, 'inline_query_id')
        validate_string(inline_query_id, 'next_offset')

        url = '%s/answerInlineQuery' % self.base_url

        results = [res.to_dict() for res in results]

        data = {'inline_query_id': inline_query_id,
                'results': results}

        if cache_time is not None:
            data['cache_time'] = int(cache_time)
        if is_personal is not None:
            data['is_personal'] = bool(is_personal)
        if next_offset is not None:
            data['next_offset'] = next_offset

        result = request.post(url, data)

        return result
Exemplo n.º 21
0
    def answerInlineQuery(self,
                          inline_query_id,
                          results,
                          cache_time=None,
                          is_personal=None,
                          next_offset=None):
        """Use this method to reply to an inline query.

        Args:
            inline_query_id (str):
                Unique identifier for answered query
            results (list[InlineQueryResult]):
                A list of results for the inline query

        Keyword Args:
            cache_time (Optional[int]): The maximum amount of time the result
                of the inline query may be cached on the server
            is_personal (Optional[bool]): Pass True, if results may be cached
                on the server side only for the user that sent the query. By
                default, results may be returned to any user who sends the same
                query
            next_offset (Optional[str]): Pass the offset that a client should
                send in the next query with the same text to receive more
                results. Pass an empty string if there are no more results or
                if you don't support pagination. Offset length can't exceed 64
                bytes.

        Returns:
            A boolean if answering was successful
        """

        validate_string(inline_query_id, 'inline_query_id')
        validate_string(inline_query_id, 'next_offset')

        url = '%s/answerInlineQuery' % self.base_url

        results = [res.to_dict() for res in results]

        data = {'inline_query_id': inline_query_id,
                'results': results}

        if cache_time is not None:
            data['cache_time'] = int(cache_time)
        if is_personal is not None:
            data['is_personal'] = bool(is_personal)
        if next_offset is not None:
            data['next_offset'] = next_offset

        result = request.post(url, data)

        return result
Exemplo n.º 22
0
    def answerCallbackQuery(self,
                            callback_query_id,
                            text=None,
                            show_alert=False,
                            **kwargs):
        """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.

        Args:
            callback_query_id (str): Unique identifier for the query to be
                answered.
            text (Optional[str]): Text of the notification. If not
                specified, nothing will be shown to the user.
            show_alert (Optional[bool]): If `True`, an alert will be shown
                by the client instead of a notification at the top of the chat
                screen. Defaults to `False`.

        Keyword Args:
            timeout (Optional[float]): If this value is specified, use it as
                the definitive timeout (in seconds) for urlopen() operations.
            network_delay (Optional[float]): If using the timeout (which is
                a `timeout` for the Telegram servers operation),
                then `network_delay` as an extra delay (in seconds) to
                compensate for network latency. Defaults to 2.

        Returns:
            bool: On success, `True` is returned.

        Raises:
            :class:`telegram.TelegramError`

        """

        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

        result = request.post(url, data,
                              timeout=kwargs.get('timeout'))

        return result
Exemplo n.º 23
0
    def answerCallbackQuery(self,
                            callback_query_id,
                            text=None,
                            show_alert=False,
                            **kwargs):
        """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.

        Args:
            callback_query_id (str): Unique identifier for the query to be
                answered.
            text (Optional[str]): Text of the notification. If not
                specified, nothing will be shown to the user.
            show_alert (Optional[bool]): If `True`, an alert will be shown
                by the client instead of a notification at the top of the chat
                screen. Defaults to `False`.

        Keyword Args:
            timeout (Optional[float]): If this value is specified, use it as
                the definitive timeout (in seconds) for urlopen() operations.
            network_delay (Optional[float]): If using the timeout (which is
                a `timeout` for the Telegram servers operation),
                then `network_delay` as an extra delay (in seconds) to
                compensate for network latency. Defaults to 2.

        Returns:
            bool: On success, `True` is returned.

        Raises:
            :class:`telegram.TelegramError`

        """

        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

        result = request.post(url, data, timeout=kwargs.get('timeout'))

        return result
Exemplo n.º 24
0
    def getUserProfilePhotos(self,
                             user_id,
                             offset=None,
                             limit=100,
                             **kwargs):
        """Use this method to get a list of profile pictures for a user.

        Args:
          user_id:
            Unique identifier of the target user.
          offset:
            Sequential number of the first photo to be returned. By default,
            all photos are returned. [Optional]
          limit:
            Limits the number of photos to be retrieved. Values between 1-100
            are accepted. Defaults to 100. [Optional]

        Keyword Args:
            timeout (Optional[float]): If this value is specified, use it as
                the definitive timeout (in seconds) for urlopen() operations.

        Returns:
            list[:class:`telegram.UserProfilePhotos`]: A list of
            :class:`telegram.UserProfilePhotos` objects are returned.

        Raises:
            :class:`telegram.TelegramError`

        """

        url = '{0}/getUserProfilePhotos'.format(self.base_url)

        data = {'user_id': user_id}

        if offset:
            data['offset'] = offset
        if limit:
            data['limit'] = limit

        result = request.post(url, data,
                              timeout=kwargs.get('timeout'))

        return UserProfilePhotos.de_json(result)
Exemplo n.º 25
0
    def getUpdates(self,
                   offset=None,
                   limit=100,
                   timeout=0):
        """Use this method to receive incoming updates using long polling.

        Args:
          offset:
            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 returned. An update is considered confirmed as soon as
            getUpdates is called with an offset higher than its update_id.
          limit:
            Limits the number of updates to be retrieved. Values between 1-100
            are accepted. Defaults to 100.
          timeout:
            Timeout in seconds for long polling. Defaults to 0, i.e. usual
            short polling.

        Returns:
          A list of telegram.Update objects are returned.
        """

        url = '%s/getUpdates' % self.base_url

        data = {}
        if offset:
            data['offset'] = offset
        if limit:
            data['limit'] = limit
        if timeout:
            data['timeout'] = timeout

        result = request.post(url, data)

        if result:
            self.logger.info(
                'Getting updates: %s', [u['update_id'] for u in result])
        else:
            self.logger.info('No new updates found.')

        return [Update.de_json(x) for x in result]
Exemplo n.º 26
0
    def getUpdates(self, offset=None, limit=100, timeout=0):
        """Use this method to receive incoming updates using long polling.

        Args:
          offset:
            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 returned. An update is considered confirmed as soon as
            getUpdates is called with an offset higher than its update_id.
          limit:
            Limits the number of updates to be retrieved. Values between 1-100
            are accepted. Defaults to 100.
          timeout:
            Timeout in seconds for long polling. Defaults to 0, i.e. usual
            short polling.

        Returns:
          A list of telegram.Update objects are returned.
        """

        url = '%s/getUpdates' % self.base_url

        data = {}
        if offset:
            data['offset'] = offset
        if limit:
            data['limit'] = limit
        if timeout:
            data['timeout'] = timeout

        result = request.post(url, data)

        if result:
            self.logger.info('Getting updates: %s',
                             [u['update_id'] for u in result])
        else:
            self.logger.info('No new updates found.')

        return [Update.de_json(x) for x in result]
Exemplo n.º 27
0
    def setWebhook(self,
                   webhook_url=None,
                   certificate=None,
                   **kwargs):
        """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.

        Args:
          webhook_url:
            HTTPS url to send updates to.
            Use an empty string to remove webhook integration

        Keyword Args:
            timeout (Optional[float]): If this value is specified, use it as
                the definitive timeout (in seconds) for urlopen() operations.

        Returns:
            bool: On success, `True` is returned.

        Raises:
            :class:`telegram.TelegramError`

        """

        url = '{0}/setWebhook'.format(self.base_url)

        data = {}

        if webhook_url is not None:
            data['url'] = webhook_url
        if certificate:
            data['certificate'] = certificate

        result = request.post(url, data,
                              timeout=kwargs.get('timeout'))

        return result
Exemplo n.º 28
0
        def decorator(self, *args, **kwargs):
            url, data = func(self, *args, **kwargs)

            if kwargs.get('reply_to_message_id'):
                data['reply_to_message_id'] = kwargs.get('reply_to_message_id')

            if kwargs.get('disable_notification'):
                data['disable_notification'] = kwargs.get('disable_notification')

            if kwargs.get('reply_markup'):
                reply_markup = kwargs.get('reply_markup')
                if isinstance(reply_markup, ReplyMarkup):
                    data['reply_markup'] = reply_markup.to_json()
                else:
                    data['reply_markup'] = reply_markup

            result = request.post(url, data, timeout=kwargs.get('timeout'))

            if result is True:
                return result

            return Message.de_json(result)
Exemplo n.º 29
0
    def getUserProfilePhotos(self, user_id, offset=None, limit=100, **kwargs):
        """Use this method to get a list of profile pictures for a user.

        Args:
          user_id:
            Unique identifier of the target user.
          offset:
            Sequential number of the first photo to be returned. By default,
            all photos are returned. [Optional]
          limit:
            Limits the number of photos to be retrieved. Values between 1-100
            are accepted. Defaults to 100. [Optional]

        Keyword Args:
            timeout (Optional[float]): If this value is specified, use it as
                the definitive timeout (in seconds) for urlopen() operations.

        Returns:
            list[:class:`telegram.UserProfilePhotos`]: A list of
            :class:`telegram.UserProfilePhotos` objects are returned.

        Raises:
            :class:`telegram.TelegramError`

        """

        url = '{0}/getUserProfilePhotos'.format(self.base_url)

        data = {'user_id': user_id}

        if offset:
            data['offset'] = offset
        if limit:
            data['limit'] = limit

        result = request.post(url, data, timeout=kwargs.get('timeout'))

        return UserProfilePhotos.de_json(result)
Exemplo n.º 30
0
    def setWebhook(self, webhook_url=None, certificate=None, **kwargs):
        """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.

        Args:
          webhook_url:
            HTTPS url to send updates to.
            Use an empty string to remove webhook integration

        Keyword Args:
            timeout (Optional[float]): If this value is specified, use it as
                the definitive timeout (in seconds) for urlopen() operations.

        Returns:
            bool: On success, `True` is returned.

        Raises:
            :class:`telegram.TelegramError`

        """

        url = '{0}/setWebhook'.format(self.base_url)

        data = {}

        if webhook_url is not None:
            data['url'] = webhook_url
        if certificate:
            data['certificate'] = certificate

        result = request.post(url, data, timeout=kwargs.get('timeout'))

        return result
Exemplo n.º 31
0
    def editMessageText(self,
                        text,
                        chat_id=None,
                        message_id=None,
                        inline_message_id=None,
                        parse_mode=None,
                        disable_web_page_preview=None,
                        reply_markup=None,
                        **kwargs):
        """Use this method to edit text messages sent by the bot or via the bot
        (for inline bots).

        Args:
          text:
            New text of the message.
          chat_id:
            Required if inline_message_id is not specified. Unique identifier
            for the target chat or username of the target channel (in the
            format @channelusername).
          message_id:
            Required if inline_message_id is not specified. Unique identifier
            of the sent message.
          inline_message_id:
            Required if chat_id and message_id are not specified. Identifier of
            the inline message.
          parse_mode:
            Send Markdown or HTML, if you want Telegram apps to show bold,
            italic, fixed-width text or inline URLs in your bot's message.
          disable_web_page_preview:
            Disables link previews for links in this message.
          reply_markup:
            A JSON-serialized object for an inline keyboard.

        Keyword Args:
            timeout (Optional[float]): If this value is specified, use it as
                the definitive timeout (in seconds) for urlopen() operations.

        Returns:
            :class:`telegram.Message`: On success, if edited message is sent by
            the bot, the edited message is returned, otherwise `True` is
            returned.

        Raises:
            :class:`telegram.TelegramError`

        """

        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'] = parse_mode
        if disable_web_page_preview:
            data['disable_web_page_preview'] = disable_web_page_preview
        if reply_markup:
            if isinstance(reply_markup, ReplyMarkup):
                data['reply_markup'] = reply_markup.to_json()
            else:
                data['reply_markup'] = reply_markup

        result = request.post(url, data, timeout=kwargs.get('timeout'))

        return Message.de_json(result)
Exemplo n.º 32
0
    def answerInlineQuery(self,
                          inline_query_id,
                          results,
                          cache_time=300,
                          is_personal=None,
                          next_offset=None,
                          switch_pm_text=None,
                          switch_pm_parameter=None,
                          **kwargs):
        """Use this method to send answers to an inline query. No more than
        50 results per query are allowed.

        Args:
            inline_query_id (str): Unique identifier for the answered query.
            results (list[:class:`telegram.InlineQueryResult`]): A list of
                results for the inline query.
            cache_time (Optional[int]): The maximum amount of time the
                result of the inline query may be cached on the server.
            is_personal (Optional[bool]): Pass `True`, if results may be
                cached on the server side only for the user that sent the
                query. By default, results may be returned to any user who
                sends the same query.
            next_offset (Optional[str]): Pass the offset that a client
                should send in the next query with the same text to receive
                more results. Pass an empty string if there are no more
                results or if you don't support pagination. Offset length
                can't exceed 64 bytes.
            switch_pm_text (Optional[str]): If passed, clients will display
                a button with specified text that switches the user to a
                private chat with the bot and sends the bot a start message
                with the parameter switch_pm_parameter.
            switch_pm_parameter (Optional[str]): Parameter for the start
                message sent to the bot when user presses the switch button.

        Keyword Args:
            timeout (Optional[float]): If this value is specified, use it as
                the definitive timeout (in seconds) for urlopen() operations.

        Returns:
            bool: On success, `True` is returned.

        Raises:
            :class:`telegram.TelegramError`

        """

        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
        if next_offset is not None:
            data['next_offset'] = next_offset
        if switch_pm_text:
            data['switch_pm_text'] = switch_pm_text
        if switch_pm_parameter:
            data['switch_pm_parameter'] = switch_pm_parameter

        result = request.post(url, data, timeout=kwargs.get('timeout'))

        return result
Exemplo n.º 33
0
    def answerInlineQuery(self,
                          inline_query_id,
                          results,
                          cache_time=300,
                          is_personal=None,
                          next_offset=None,
                          switch_pm_text=None,
                          switch_pm_parameter=None,
                          **kwargs):
        """Use this method to send answers to an inline query. No more than
        50 results per query are allowed.

        Args:
            inline_query_id (str): Unique identifier for the answered query.
            results (list[:class:`telegram.InlineQueryResult`]): A list of
                results for the inline query.
            cache_time (Optional[int]): The maximum amount of time the
                result of the inline query may be cached on the server.
            is_personal (Optional[bool]): Pass `True`, if results may be
                cached on the server side only for the user that sent the
                query. By default, results may be returned to any user who
                sends the same query.
            next_offset (Optional[str]): Pass the offset that a client
                should send in the next query with the same text to receive
                more results. Pass an empty string if there are no more
                results or if you don't support pagination. Offset length
                can't exceed 64 bytes.
            switch_pm_text (Optional[str]): If passed, clients will display
                a button with specified text that switches the user to a
                private chat with the bot and sends the bot a start message
                with the parameter switch_pm_parameter.
            switch_pm_parameter (Optional[str]): Parameter for the start
                message sent to the bot when user presses the switch button.

        Keyword Args:
            timeout (Optional[float]): If this value is specified, use it as
                the definitive timeout (in seconds) for urlopen() operations.

        Returns:
            bool: On success, `True` is returned.

        Raises:
            :class:`telegram.TelegramError`

        """

        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
        if next_offset is not None:
            data['next_offset'] = next_offset
        if switch_pm_text:
            data['switch_pm_text'] = switch_pm_text
        if switch_pm_parameter:
            data['switch_pm_parameter'] = switch_pm_parameter

        result = request.post(url, data,
                              timeout=kwargs.get('timeout'))

        return result
Exemplo n.º 34
0
    def editMessageText(self,
                        text,
                        chat_id=None,
                        message_id=None,
                        inline_message_id=None,
                        parse_mode=None,
                        disable_web_page_preview=None,
                        reply_markup=None,
                        **kwargs):
        """Use this method to edit text messages sent by the bot or via the bot
        (for inline bots).

        Args:
          text:
            New text of the message.
          chat_id:
            Required if inline_message_id is not specified. Unique identifier
            for the target chat or username of the target channel (in the
            format @channelusername).
          message_id:
            Required if inline_message_id is not specified. Unique identifier
            of the sent message.
          inline_message_id:
            Required if chat_id and message_id are not specified. Identifier of
            the inline message.
          parse_mode:
            Send Markdown or HTML, if you want Telegram apps to show bold,
            italic, fixed-width text or inline URLs in your bot's message.
          disable_web_page_preview:
            Disables link previews for links in this message.
          reply_markup:
            A JSON-serialized object for an inline keyboard.

        Keyword Args:
            timeout (Optional[float]): If this value is specified, use it as
                the definitive timeout (in seconds) for urlopen() operations.

        Returns:
            :class:`telegram.Message`: On success, if edited message is sent by
            the bot, the edited message is returned, otherwise `True` is
            returned.

        Raises:
            :class:`telegram.TelegramError`

        """

        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'] = parse_mode
        if disable_web_page_preview:
            data['disable_web_page_preview'] = disable_web_page_preview
        if reply_markup:
            if isinstance(reply_markup, ReplyMarkup):
                data['reply_markup'] = reply_markup.to_json()
            else:
                data['reply_markup'] = reply_markup

        result = request.post(url, data,
                              timeout=kwargs.get('timeout'))

        return Message.de_json(result)