Example #1
0
    def de_json(cls, data: Optional[JSONDict],
                bot: 'Bot') -> Optional['Update']:
        data = cls.parse_data(data)

        if not data:
            return None

        data['message'] = Message.de_json(data.get('message'), bot)
        data['edited_message'] = Message.de_json(data.get('edited_message'),
                                                 bot)
        data['inline_query'] = InlineQuery.de_json(data.get('inline_query'),
                                                   bot)
        data['chosen_inline_result'] = ChosenInlineResult.de_json(
            data.get('chosen_inline_result'), bot)
        data['callback_query'] = CallbackQuery.de_json(
            data.get('callback_query'), bot)
        data['shipping_query'] = ShippingQuery.de_json(
            data.get('shipping_query'), bot)
        data['pre_checkout_query'] = PreCheckoutQuery.de_json(
            data.get('pre_checkout_query'), bot)
        data['channel_post'] = Message.de_json(data.get('channel_post'), bot)
        data['edited_channel_post'] = Message.de_json(
            data.get('edited_channel_post'), bot)
        data['poll'] = Poll.de_json(data.get('poll'), bot)
        data['poll_answer'] = PollAnswer.de_json(data.get('poll_answer'), bot)

        return cls(**data)
Example #2
0
    def de_json(cls, data: Optional[JSONDict],
                bot: 'Bot') -> Optional['Update']:
        """See :meth:`telegram.TelegramObject.de_json`."""
        data = cls._parse_data(data)

        if not data:
            return None

        data['message'] = Message.de_json(data.get('message'), bot)
        data['edited_message'] = Message.de_json(data.get('edited_message'),
                                                 bot)
        data['inline_query'] = InlineQuery.de_json(data.get('inline_query'),
                                                   bot)
        data['chosen_inline_result'] = ChosenInlineResult.de_json(
            data.get('chosen_inline_result'), bot)
        data['callback_query'] = CallbackQuery.de_json(
            data.get('callback_query'), bot)
        data['shipping_query'] = ShippingQuery.de_json(
            data.get('shipping_query'), bot)
        data['pre_checkout_query'] = PreCheckoutQuery.de_json(
            data.get('pre_checkout_query'), bot)
        data['channel_post'] = Message.de_json(data.get('channel_post'), bot)
        data['edited_channel_post'] = Message.de_json(
            data.get('edited_channel_post'), bot)
        data['poll'] = Poll.de_json(data.get('poll'), bot)
        data['poll_answer'] = PollAnswer.de_json(data.get('poll_answer'), bot)
        data['my_chat_member'] = ChatMemberUpdated.de_json(
            data.get('my_chat_member'), bot)
        data['chat_member'] = ChatMemberUpdated.de_json(
            data.get('chat_member'), bot)
        data['chat_join_request'] = ChatJoinRequest.de_json(
            data.get('chat_join_request'), bot)

        return cls(**data)
Example #3
0
    def de_json(data, bot):
        """
        Args:
            data (dict):
            bot (telegram.Bot):

        Returns:
            telegram.Update:
        """
        if not data:
            return None

        data = super(Update, Update).de_json(data, bot)

        data['message'] = Message.de_json(data.get('message'), bot)
        data['edited_message'] = Message.de_json(data.get('edited_message'),
                                                 bot)
        data['inline_query'] = InlineQuery.de_json(data.get('inline_query'),
                                                   bot)
        data['chosen_inline_result'] = ChosenInlineResult.de_json(
            data.get('chosen_inline_result'), bot)
        data['callback_query'] = CallbackQuery.de_json(
            data.get('callback_query'), bot)
        data['channel_post'] = Message.de_json(data.get('channel_post'), bot)
        data['edited_channel_post'] = Message.de_json(
            data.get('edited_channel_post'), bot)

        return Update(**data)
Example #4
0
    def de_json(cls, data, bot):
        if not data:
            return None

        data = super(Update, cls).de_json(data, bot)

        data['message'] = Message.de_json(data.get('message'), bot)
        data['edited_message'] = Message.de_json(data.get('edited_message'),
                                                 bot)
        data['inline_query'] = InlineQuery.de_json(data.get('inline_query'),
                                                   bot)
        data['chosen_inline_result'] = ChosenInlineResult.de_json(
            data.get('chosen_inline_result'), bot)
        data['callback_query'] = CallbackQuery.de_json(
            data.get('callback_query'), bot)
        data['shipping_query'] = ShippingQuery.de_json(
            data.get('shipping_query'), bot)
        data['pre_checkout_query'] = PreCheckoutQuery.de_json(
            data.get('pre_checkout_query'), bot)
        data['channel_post'] = Message.de_json(data.get('channel_post'), bot)
        data['edited_channel_post'] = Message.de_json(
            data.get('edited_channel_post'), bot)
        data['poll'] = Poll.de_json(data.get('poll'), bot)

        return cls(**data)
Example #5
0
    def de_json(cls, data, bot):
        if not data:
            return None

        data = super(Update, cls).de_json(data, bot)

        message = data.get('message')
        if message:
            message['default_quote'] = data.get('default_quote')
        data['message'] = Message.de_json(message, bot)
        edited_message = data.get('edited_message')
        if edited_message:
            edited_message['default_quote'] = data.get('default_quote')
        data['edited_message'] = Message.de_json(edited_message, bot)
        data['inline_query'] = InlineQuery.de_json(data.get('inline_query'), bot)
        data['chosen_inline_result'] = ChosenInlineResult.de_json(
            data.get('chosen_inline_result'), bot)
        callback_query = data.get('callback_query')
        if callback_query:
            callback_query['default_quote'] = data.get('default_quote')
        data['callback_query'] = CallbackQuery.de_json(callback_query, bot)
        data['shipping_query'] = ShippingQuery.de_json(data.get('shipping_query'), bot)
        data['pre_checkout_query'] = PreCheckoutQuery.de_json(data.get('pre_checkout_query'), bot)
        channel_post = data.get('channel_post')
        if channel_post:
            channel_post['default_quote'] = data.get('default_quote')
        data['channel_post'] = Message.de_json(channel_post, bot)
        edited_channel_post = data.get('edited_channel_post')
        if edited_channel_post:
            edited_channel_post['default_quote'] = data.get('default_quote')
        data['edited_channel_post'] = Message.de_json(edited_channel_post, bot)
        data['poll'] = Poll.de_json(data.get('poll'), bot)

        return cls(**data)
    def de_json(data, bot):
        """
        Args:
            data (dict):
            bot (telegram.Bot):

        Returns:
            telegram.Update:
        """
        if not data:
            return None

        data = super(Update, Update).de_json(data, bot)

        data['message'] = Message.de_json(data.get('message'), bot)
        data['edited_message'] = Message.de_json(data.get('edited_message'), bot)
        data['inline_query'] = InlineQuery.de_json(data.get('inline_query'), bot)
        data['chosen_inline_result'] = ChosenInlineResult.de_json(
            data.get('chosen_inline_result'), bot)
        data['callback_query'] = CallbackQuery.de_json(data.get('callback_query'), bot)
        data['shipping_query'] = ShippingQuery.de_json(data.get('shipping_query'), bot)
        data['pre_checkout_query'] = PreCheckoutQuery.de_json(data.get('pre_checkout_query'), bot)
        data['channel_post'] = Message.de_json(data.get('channel_post'), bot)
        data['edited_channel_post'] = Message.de_json(data.get('edited_channel_post'), bot)

        return Update(**data)
Example #7
0
        def decorator(self, *args, **kwargs):
            """
            decorator
            """
            url, data = func(self, *args, **kwargs)

            if not kwargs.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

            json_data = Bot._requestUrl(url, 'POST', data=data)
            data = Bot._parseAndCheckTelegram(json_data)

            if data is True:
                return data

            return Message.de_json(data)
Example #8
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)
Example #9
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)
Example #10
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)
Example #11
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)
Example #12
0
    def forwardMessage(self, chat_id, from_chat_id, message_id):
        """Use this method to forward messages of any kind.

        Args:
          chat_id:
            Unique identifier for the message recipient — User or GroupChat id.
          from_chat_id:
            Unique identifier for the chat where the original message was sent
            — User or GroupChat id.
          message_id:
            Unique message identifier.

        Returns:
          A telegram.Message instance representing the message forwarded.
        """

        url = "%s/forwardMessage" % (self.base_url)

        if not self.__auth:
            raise TelegramError({"message": "API must be authenticated."})

        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

        json_data = self._requestUrl(url, "POST", data=data)
        data = self._parseAndCheckTelegram(json_data.decode())

        return Message.de_json(data)
Example #13
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)
Example #14
0
    def get_all_replies(self, chat_id: int):
        try:
            chat_doc = self.db.collection("chats").document(str(chat_id))
            replies = chat_doc.collection("messages").get()
        except NotFoundError:
            replies = []

        return [Message.de_json(item.to_dict(), None) for item in replies]
    def de_json(data):
        if not data:
            return None

        data['from_user'] = User.de_json(data.get('from'))
        data['message'] = Message.de_json(data.get('message'))

        return CallbackQuery(**data)
Example #16
0
    def de_json(data):
        if not data:
            return None

        data['from_user'] = User.de_json(data.get('from'))
        data['message'] = Message.de_json(data.get('message'))

        return CallbackQuery(**data)
Example #17
0
    def de_json(data):
        if 'message' in data:
            from telegram import Message
            message = Message.de_json(data['message'])
        else:
            message = None

        return Update(update_id=data.get('update_id', None), message=message)
Example #18
0
    def de_json(data):
        """
        Args:
            data (dict):

        Returns:
            telegram.Update:
        """
        if not data:
            return None

        data['message'] = Message.de_json(data.get('message'))
        data['edited_message'] = Message.de_json(data.get('edited_message'))
        data['inline_query'] = InlineQuery.de_json(data.get('inline_query'))
        data['chosen_inline_result'] = ChosenInlineResult.de_json(data.get('chosen_inline_result'))
        data['callback_query'] = CallbackQuery.de_json(data.get('callback_query'))

        return Update(**data)
Example #19
0
    def de_json(cls, data, bot):
        if not data:
            return None

        data['photo'] = ChatPhoto.de_json(data.get('photo'), bot)
        from telegram import Message
        data['pinned_message'] = Message.de_json(data.get('pinned_message'), bot)

        return cls(bot=bot, **data)
Example #20
0
    def de_json(cls, data, bot):
        if not data:
            return None

        data['photo'] = ChatPhoto.de_json(data.get('photo'), bot)
        from telegram import Message
        data['pinned_message'] = Message.de_json(data.get('pinned_message'), bot)

        return cls(bot=bot, **data)
Example #21
0
    def de_json(cls, data, bot):
        if not data:
            return None

        data = super(Update, cls).de_json(data, bot)

        data['message'] = Message.de_json(data.get('message'), bot)
        data['edited_message'] = Message.de_json(data.get('edited_message'), bot)
        data['inline_query'] = InlineQuery.de_json(data.get('inline_query'), bot)
        data['chosen_inline_result'] = ChosenInlineResult.de_json(
            data.get('chosen_inline_result'), bot)
        data['callback_query'] = CallbackQuery.de_json(data.get('callback_query'), bot)
        data['shipping_query'] = ShippingQuery.de_json(data.get('shipping_query'), bot)
        data['pre_checkout_query'] = PreCheckoutQuery.de_json(data.get('pre_checkout_query'), bot)
        data['channel_post'] = Message.de_json(data.get('channel_post'), bot)
        data['edited_channel_post'] = Message.de_json(data.get('edited_channel_post'), bot)

        return cls(**data)
Example #22
0
    def de_json(data):
        if 'message' in data:
            from telegram import Message
            message = Message.de_json(data['message'])
        else:
            message = None

        return Update(update_id=data.get('update_id', None),
                      message=message)
Example #23
0
    def de_json(cls, data, bot):
        if not data:
            return None

        data = super(CallbackQuery, cls).de_json(data, bot)

        data['from_user'] = User.de_json(data.get('from'), bot)
        data['message'] = Message.de_json(data.get('message'), bot)

        return cls(bot=bot, **data)
Example #24
0
    def de_json(cls, data: Optional[JSONDict], bot: 'Bot') -> Optional['CallbackQuery']:
        data = cls.parse_data(data)

        if not data:
            return None

        data['from_user'] = User.de_json(data.get('from'), bot)
        data['message'] = Message.de_json(data.get('message'), bot)

        return cls(bot=bot, **data)
Example #25
0
    def de_json(cls, data, bot):
        if not data:
            return None

        data = super(CallbackQuery, cls).de_json(data, bot)

        data['from_user'] = User.de_json(data.get('from'), bot)
        data['message'] = Message.de_json(data.get('message'), bot)

        return cls(bot=bot, **data)
Example #26
0
 def _create_tg_message(bot=None, user=None, chat=None, **kwargs):
     bot = bot or create_bot()
     user = decode_tg_object(user, create_tg_user().to_dict())
     chat = decode_tg_object(chat, create_tg_chat().to_dict())
     data = {
         'message_id': get_id(),
         'date': 1564646464,
         'from': user,
         'chat': chat,
         **kwargs,
     }
     return TGMessage.de_json(data, bot)
Example #27
0
    def de_json(cls, data: JSONDict, bot: 'Bot') -> Optional['Chat']:
        data = cls.parse_data(data)

        if not data:
            return None

        data['photo'] = ChatPhoto.de_json(data.get('photo'), bot)
        from telegram import Message
        data['pinned_message'] = Message.de_json(data.get('pinned_message'), bot)
        data['permissions'] = ChatPermissions.de_json(data.get('permissions'), bot)

        return cls(bot=bot, **data)
    def de_json(cls, data: Optional[JSONDict],
                bot: 'Bot') -> Optional['CallbackQuery']:
        """See :meth:`telegram.TelegramObject.de_json`."""
        data = cls._parse_data(data)

        if not data:
            return None

        data['from_user'] = User.de_json(data.get('from'), bot)
        data['message'] = Message.de_json(data.get('message'), bot)

        return cls(bot=bot, **data)
Example #29
0
    def get_all_replies(self, chat_id: int) -> list[Message]:
        try:
            file_handle = open(self.file_path)
        except FileNotFoundError:
            file_handle = open(self.file_path, "a+")

        with file_handle as file:
            replies = [
                Message.de_json(json.loads(line), None) for line in file
            ]

        return replies or []
Example #30
0
def main():
    firebase_admin.initialize_app(
        firebase_admin.credentials.Certificate(cert_file_path)
    )

    db: Client = firebase_admin.firestore.client()
    for line in SAVED_REPLIES_FILE_PATH.read_text().splitlines():
        message = Message.de_json(json.loads(line), None)
        process_message(db, message)

    scores = json.load(SCORES_FILE_PATH.open("r"))
    for first_name, score in scores.items():
        process_scores(db, first_name, score)
Example #31
0
 def process(self, data: str):
     try:
         data = json.loads(data)
         send_messages(
             tg_chat_id=data['tg_chat_id'],
             original_message=(data['original_message']
                               and TgMessage.de_json(
                                   data['original_message'], None)),
             replies=[Reply(**x) for x in data['replies']],
             workflow=Workflow(data['workflow']),
         )
     except Exception:
         logger.exception('Message was not sent. Data:\n%s', data)
Example #32
0
    def de_json(cls, data, bot):
        if not data:
            return None

        data['photo'] = ChatPhoto.de_json(data.get('photo'), bot)
        from telegram import Message
        pinned_message = data.get('pinned_message')
        if pinned_message:
            pinned_message['default_quote'] = data.get('default_quote')
        data['pinned_message'] = Message.de_json(pinned_message, bot)
        data['permissions'] = ChatPermissions.de_json(data.get('permissions'), bot)

        return cls(bot=bot, **data)
Example #33
0
    def de_json(cls, data, bot):
        if not data:
            return None

        data = super().de_json(data, bot)

        data['from_user'] = User.de_json(data.get('from'), bot)
        message = data.get('message')
        if message:
            message['default_quote'] = data.get('default_quote')
        data['message'] = Message.de_json(message, bot)

        return cls(bot=bot, **data)
Example #34
0
    def sendPhoto(self,
                  chat_id,
                  photo,
                  caption=None,
                  reply_to_message_id=None,
                  reply_markup=None):
        """Use this method to send photos.

        Args:
          chat_id:
            Unique identifier for the message recipient — User or GroupChat id.
          photo:
            Photo to send. You can either pass a file_id as String to resend a
            photo that is already on the Telegram servers, or upload a new
            photo using multipart/form-data.
          caption:
            Photo caption (may also be used when resending photos by file_id).
            [Optional]
          reply_to_message_id:
            If the message is a reply, ID of the original message. [Optional]
          reply_markup:
            Additional interface options. A JSON-serialized object for a custom
            reply keyboard, instructions to hide keyboard or to force a reply
            from the user. [Optional]

        Returns:
          A telegram.Message instance representing the message posted.
        """

        url = '%s/sendPhoto' % (self.base_url)

        if not self.__auth:
            raise TelegramError({'message': "API must be authenticated."})

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

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

        json_data = self._requestUrl(url, 'POST', data=data)
        data = self._parseAndCheckTelegram(json_data.content)

        return Message.de_json(data)
Example #35
0
    def de_json(data):
        """
        Args:
            data (str):

        Returns:
            telegram.Update:
        """
        if not data:
            return None

        data['message'] = Message.de_json(data['message'])

        return Update(**data)
Example #36
0
    def de_json(data):
        """
        Args:
            data (str):

        Returns:
            telegram.Update:
        """
        if not data:
            return None

        data["message"] = Message.de_json(data["message"])

        return Update(**data)
Example #37
0
    def sendMessage(self,
                    chat_id,
                    text,
                    disable_web_page_preview=None,
                    reply_to_message_id=None,
                    reply_markup=None):
        """Use this method to send text messages.

        Args:
          chat_id:
            Unique identifier for the message recipient — telegram.User or
            telegram.GroupChat id.
          text:
            Text of the message to be sent.
          disable_web_page_preview:
            Disables link previews for links in this message. [Optional]
          reply_to_message_id:
            If the message is a reply, ID of the original message. [Optional]
          reply_markup:
            Additional interface options. A JSON-serialized object for a custom
            reply keyboard, instructions to hide keyboard or to force a reply
            from the user. [Optional]

        Returns:
          A telegram.Message instance representing the message posted.
        """

        url = '%s/sendMessage' % (self.base_url)

        if not self.__auth:
            raise TelegramError({'message': "API must be authenticated."})

        data = {'chat_id': chat_id,
                'text': text}
        if disable_web_page_preview:
            data['disable_web_page_preview'] = disable_web_page_preview
        if reply_to_message_id:
            data['reply_to_message_id'] = reply_to_message_id
        if reply_markup:
            if isinstance(reply_markup, ReplyMarkup):
                data['reply_markup'] = reply_markup.to_json()
            else:
                data['reply_markup'] = reply_markup

        json_data = self._requestUrl(url, 'POST', data=data)
        data = self._parseAndCheckTelegram(json_data.content)

        return Message.de_json(data)
Example #38
0
    def sendAudio(self,
                  chat_id,
                  audio,
                  reply_to_message_id=None,
                  reply_markup=None):
        """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 telegram.Document).

        Args:
          chat_id:
            Unique identifier for the message recipient — User or GroupChat id.
          audio:
            Audio file to send. You can either pass a file_id as String to
            resend an audio that is already on the Telegram servers, or upload
            a new audio file using multipart/form-data.
          reply_to_message_id:
            If the message is a reply, ID of the original message. [Optional]
          reply_markup:
            Additional interface options. A JSON-serialized object for a
            custom reply keyboard, instructions to hide keyboard or to force a
            reply from the user. [Optional]

        Returns:
          A telegram.Message instance representing the message posted.
        """

        url = '%s/sendAudio' % (self.base_url)

        if not self.__auth:
            raise TelegramError({'message': "API must be authenticated."})

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

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

        json_data = self._requestUrl(url, 'POST', data=data)
        data = self._parseAndCheckTelegram(json_data.content)

        return Message.de_json(data)
Example #39
0
    def sendLocation(self,
                     chat_id,
                     latitude,
                     longitude,
                     reply_to_message_id=None,
                     reply_markup=None):
        """Use this method to send point on the map.

        Args:
          chat_id:
            Unique identifier for the message recipient — User or GroupChat id.
          latitude:
            Latitude of location.
          longitude:
            Longitude of location.
          reply_to_message_id:
            If the message is a reply, ID of the original message. [Optional]
          reply_markup:
            Additional interface options. A JSON-serialized object for a
            custom reply keyboard, instructions to hide keyboard or to force a
            reply from the user. [Optional]

        Returns:
          A telegram.Message instance representing the message posted.
        """

        url = '%s/sendLocation' % (self.base_url)

        if not self.__auth:
            raise TelegramError({'message': "API must be authenticated."})

        data = {'chat_id': chat_id,
                'latitude': latitude,
                'longitude': longitude}

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

        json_data = self._requestUrl(url, 'POST', data=data)
        data = self._parseAndCheckTelegram(json_data.content)

        return Message.de_json(data)
Example #40
0
    def de_json(data, bot):
        """
        Args:
            data (dict):
            bot (telegram.Bot):

        Returns:
            telegram.CallbackQuery:
        """

        if not data:
            return None

        data['from_user'] = User.de_json(data.get('from'), bot)
        data['message'] = Message.de_json(data.get('message'), bot)

        return CallbackQuery(bot=bot, **data)
    def de_json(data, bot):
        """
        Args:
            data (dict):
            bot (telegram.Bot):

        Returns:
            telegram.CallbackQuery:
        """

        if not data:
            return None

        data['from_user'] = User.de_json(data.get('from'), bot)
        data['message'] = Message.de_json(data.get('message'), bot)

        return CallbackQuery(bot=bot, **data)
Example #42
0
    def original_message(self, query: CallbackQuery) -> Message or None:
        chat_id = query.message.chat_id
        msg_id = query.message.message_id

        msg = self.messages.find_one({
            'chat_id': chat_id,
            'msg_id': msg_id,
        })
        if msg is None:
            self.logger.debug('Unregistered messages rated.')
            return None

        if msg.get('original', None) is None:
            self.logger.debug("Original message wasn't saved")
            return None

        return Message.de_json(msg['original'], None)
Example #43
0
    def sendVideo(self, chat_id, video, reply_to_message_id=None, reply_markup=None):
        """Use this method to send video files, Telegram clients support mp4
        videos (other formats may be sent as telegram.Document).

        Args:
          chat_id:
            Unique identifier for the message recipient — User or GroupChat id.
          video:
            Video to send. You can either pass a file_id as String to resend a
            video that is already on the Telegram servers, or upload a new
            video file using multipart/form-data.
          reply_to_message_id:
            If the message is a reply, ID of the original message. [Optional]
          reply_markup:
            Additional interface options. A JSON-serialized object for a
            custom reply keyboard, instructions to hide keyboard or to force a
            reply from the user. [Optional]

        Returns:
          A telegram.Message instance representing the message posted.
        """

        url = "%s/sendVideo" % (self.base_url)

        if not self.__auth:
            raise TelegramError({"message": "API must be authenticated."})

        data = {"chat_id": chat_id, "video": video}

        if reply_to_message_id:
            data["reply_to_message_id"] = reply_to_message_id
        if reply_markup:
            if isinstance(reply_markup, ReplyMarkup):
                data["reply_markup"] = reply_markup.to_json()
            else:
                data["reply_markup"] = reply_markup

        json_data = self._requestUrl(url, "POST", data=data)
        data = self._parseAndCheckTelegram(json_data.decode())

        return Message.de_json(data)
Example #44
0
        def wrap(self, *args, **kwargs):
            url, data = func(self, *args, **kwargs)

            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

            json_data = self._requestUrl(url, 'POST', data=data)
            data = self._parseAndCheckTelegram(json_data)

            if data is True:
                return data

            return Message.de_json(data)
Example #45
0
        def decorator(self, *args, **kwargs):
            url, data = func(self, *args, **kwargs)

            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

            json_data = self._requestUrl(url, "POST", data=data)
            data = self._parseAndCheckTelegram(json_data)

            if data is True:
                return data

            return Message.de_json(data)
Example #46
0
        def decorator(self, *args, **kwargs):
            url, data = func(self, *args, **kwargs)

            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

            json_data = self._requestUrl(url, 'POST', data=data)
            data = self._parseAndCheckTelegram(json_data)

            if data is True:
                return data

            return Message.de_json(data)
Example #47
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)
    def test_all_possibilities_de_json_and_to_dict(self, bot, message_params):
        new = Message.de_json(message_params.to_dict(), bot)

        assert new.to_dict() == message_params.to_dict()
Example #49
0
def parse_post_to_send(post_id):
    session = db.Session()
    post_instance = session.query(Post).get(post_id)
    session.close()
    if post_instance.data is None:
        return None, None, None
    message = Message.de_json(data=json.loads(post_instance.data), bot=None)
    reply_markup = None
    if post_instance.reply_markup_data is not None:
        reply_markup = de_json_inline_keyboard_markup(json.loads(post_instance.reply_markup_data))

    kwargs = {}
    method = None
    if message.audio is not None:
        method = "audio"
        kwargs["audio"] = message.audio.file_id
        kwargs["duration"] = message.audio.duration
        kwargs["performer"] = message.audio.performer
        kwargs["title"] = message.audio.title
        if message.audio.thumb is not None:
            kwargs["thumb"] = message.audio.thumb.file_id
    elif message.document is not None:
        method = "document"
        kwargs["document"] = message.document.file_id
        if message.document.thumb is not None:
            kwargs["thumb"] = message.document.thumb.file_id
    elif message.video is not None:
        method = "video"
        kwargs["video"] = message.video.file_id
        kwargs["duration"] = message.video.duration
        kwargs["width"] = message.video.width
        kwargs["height"] = message.video.height
        if message.video.thumb is not None:
            kwargs["thumb"] = message.video.thumb.file_id
    elif message.animation is not None:
        method = "animation"
        kwargs["animation"] = message.animation.file_id
        kwargs["duration"] = message.animation.duration
        kwargs["width"] = message.animation.width
        kwargs["height"] = message.animation.height
        if message.animation.thumb is not None:
            kwargs["thumb"] = message.animation.thumb.file_id
    elif message.voice is not None:
        method = "voice"
        kwargs["voice"] = message.voice.file_id
        kwargs["duration"] = message.voice.duration
    elif message.video_note is not None:
        method = "video_note"
        kwargs["video_note"] = message.video_note.file_id
        kwargs["duration"] = message.video_note.duration
        kwargs["length"] = message.video_note.length
        if message.video_note.thumb is not None:
            kwargs["thumb"] = message.video_note.thumb.file_id
    elif message.location is not None:
        method = "location"
        kwargs["latitude"] = message.location.latitude
        kwargs["longitude"] = message.location.longitude
    elif message.venue is not None:
        method = "venue"
        kwargs["latitude"] = message.venue.location.latitude
        kwargs["longitude"] = message.venue.location.longitude
        kwargs["title"] = message.venue.title
        kwargs["address"] = message.venue.address
        kwargs["foursquare_id"] = message.venue.foursquare_id
        kwargs["foursquare_type"] = message.venue.foursquare_type
    elif message.contact is not None:
        method = "contact"
        kwargs["phone_number"] = message.contact.phone_number
        kwargs["first_name"] = message.contact.first_name
        kwargs["last_name"] = message.contact.last_name
        kwargs["vcard"] = message.contact.vcard
    elif len(message.photo) > 0:
        method = "photo"
        kwargs["photo"] = sorted(message.photo, key=lambda x: x.width * x.height, reverse=True)[0].file_id
    elif message.sticker is not None:
        method = "sticker"
        kwargs["sticker"] = message.sticker.file_id
    elif message.text is not None:
        method = "message"
        kwargs["text"] = message.text
    else:
        raise NotImplementedError("Unsupported post type")

    if message.caption is not None:
        kwargs["caption"] = message.caption

    return "send_" + method, kwargs, reply_markup
Example #50
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)
Example #51
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)
    def test_all_posibilities_de_json_and_to_dict(self, bot, message_params):
        new = Message.de_json(message_params.to_dict(), bot)

        assert new.to_dict() == message_params.to_dict()