Example #1
0
    def de_json(data):
        """
        Args:
            data (dict):

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

        data['from_user'] = User.de_json(data.get('from'))
        data['date'] = datetime.fromtimestamp(data['date'])
        data['chat'] = Chat.de_json(data.get('chat'))
        data['entities'] = MessageEntity.de_list(data.get('entities'))
        data['forward_from'] = User.de_json(data.get('forward_from'))
        data['forward_from_chat'] = Chat.de_json(data.get('forward_from_chat'))
        data['forward_date'] = Message._fromtimestamp(data.get('forward_date'))
        data['reply_to_message'] = Message.de_json(
            data.get('reply_to_message'))
        data['audio'] = Audio.de_json(data.get('audio'))
        data['document'] = Document.de_json(data.get('document'))
        data['photo'] = PhotoSize.de_list(data.get('photo'))
        data['sticker'] = Sticker.de_json(data.get('sticker'))
        data['video'] = Video.de_json(data.get('video'))
        data['voice'] = Voice.de_json(data.get('voice'))
        data['contact'] = Contact.de_json(data.get('contact'))
        data['location'] = Location.de_json(data.get('location'))
        data['venue'] = Venue.de_json(data.get('venue'))
        data['new_chat_member'] = User.de_json(data.get('new_chat_member'))
        data['left_chat_member'] = User.de_json(data.get('left_chat_member'))
        data['new_chat_photo'] = PhotoSize.de_list(data.get('new_chat_photo'))
        data['pinned_message'] = Message.de_json(data.get('pinned_message'))

        return Message(**data)
Example #2
0
def get_several_details_messages(update, context):
    result_list = context.user_data['response']['result_list']
    update.callback_query.edit_message_text(
        'Ми знайшли медиків поряд з місцем вашого відправлення!')

    context.chat_data['info'] = {'count_of_active_messages': 0}

    for key, value in result_list.items():
        context.chat_data['info']['count_of_active_messages'] += 1

        location = Location(latitude=value['finish_point']['latitude'],
                            longitude=value['finish_point']['longitude'])

        contact = Contact(phone_number=value['user_phone_number'],
                          first_name=value['user_first_name'],
                          last_name=value['user_last_name'])

        context.bot.send_message(
            update.effective_message.chat_id,
            text=f'Час відправлення: {value["time_of_departure"]}.\n'
            f'Дата відправлення: {value["date_of_departure"]}.\n'
            f'Місце призначення:')
        context.bot.send_location(chat_id=update.effective_message.chat_id,
                                  location=location)
        context.bot.send_contact(update.effective_message.chat_id,
                                 contact=contact)
    return ConversationHandler.END
Example #3
0
    def de_json(data):
        """
        Args:
            data (dict):

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

        data['from_user'] = User.de_json(data.get('from'))
        data['date'] = datetime.fromtimestamp(data['date'])
        data['chat'] = Chat.de_json(data.get('chat'))
        data['entities'] = MessageEntity.de_list(data.get('entities'))
        data['forward_from'] = User.de_json(data.get('forward_from'))
        data['forward_date'] = Message._fromtimestamp(data.get('forward_date'))
        data['reply_to_message'] = \
            Message.de_json(data.get('reply_to_message'))
        data['audio'] = Audio.de_json(data.get('audio'))
        data['document'] = Document.de_json(data.get('document'))
        data['photo'] = PhotoSize.de_list(data.get('photo'))
        data['sticker'] = Sticker.de_json(data.get('sticker'))
        data['video'] = Video.de_json(data.get('video'))
        data['voice'] = Voice.de_json(data.get('voice'))
        data['contact'] = Contact.de_json(data.get('contact'))
        data['location'] = Location.de_json(data.get('location'))
        data['venue'] = Venue.de_json(data.get('venue'))
        data['new_chat_member'] = User.de_json(data.get('new_chat_member'))
        data['left_chat_member'] = User.de_json(data.get('left_chat_member'))
        data['new_chat_photo'] = PhotoSize.de_list(data.get('new_chat_photo'))
        data['pinned_message'] = Message.de_json(data.get('pinned_message'))

        return Message(**data)
def contact():
    return Contact(
        TestContact.phone_number,
        TestContact.first_name,
        TestContact.last_name,
        TestContact.user_id,
    )
Example #5
0
    def de_json(cls, data, bot):
        if not data:
            return None

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

        data['from_user'] = User.de_json(data.get('from'), bot)
        data['date'] = from_timestamp(data['date'])
        data['chat'] = Chat.de_json(data.get('chat'), bot)
        data['entities'] = MessageEntity.de_list(data.get('entities'), bot)
        data['forward_from'] = User.de_json(data.get('forward_from'), bot)
        data['forward_from_chat'] = Chat.de_json(data.get('forward_from_chat'), bot)
        data['forward_date'] = from_timestamp(data.get('forward_date'))
        data['reply_to_message'] = Message.de_json(data.get('reply_to_message'), bot)
        data['edit_date'] = from_timestamp(data.get('edit_date'))
        data['audio'] = Audio.de_json(data.get('audio'), bot)
        data['document'] = Document.de_json(data.get('document'), bot)
        data['game'] = Game.de_json(data.get('game'), bot)
        data['photo'] = PhotoSize.de_list(data.get('photo'), bot)
        data['sticker'] = Sticker.de_json(data.get('sticker'), bot)
        data['video'] = Video.de_json(data.get('video'), bot)
        data['voice'] = Voice.de_json(data.get('voice'), bot)
        data['video_note'] = VideoNote.de_json(data.get('video_note'), bot)
        data['contact'] = Contact.de_json(data.get('contact'), bot)
        data['location'] = Location.de_json(data.get('location'), bot)
        data['venue'] = Venue.de_json(data.get('venue'), bot)
        data['new_chat_member'] = User.de_json(data.get('new_chat_member'), bot)
        data['new_chat_members'] = User.de_list(data.get('new_chat_members'), bot)
        data['left_chat_member'] = User.de_json(data.get('left_chat_member'), bot)
        data['new_chat_photo'] = PhotoSize.de_list(data.get('new_chat_photo'), bot)
        data['pinned_message'] = Message.de_json(data.get('pinned_message'), bot)
        data['invoice'] = Invoice.de_json(data.get('invoice'), bot)
        data['successful_payment'] = SuccessfulPayment.de_json(data.get('successful_payment'), bot)

        return cls(bot=bot, **data)
    def test_de_json_required(self, bot):
        json_dict = {
            'phone_number': self.phone_number,
            'first_name': self.first_name
        }
        contact = Contact.de_json(json_dict, bot)

        assert contact.phone_number == self.phone_number
        assert contact.first_name == self.first_name
    def test_de_json_all(self, bot):
        json_dict = {'phone_number': self.phone_number, 'first_name': self.first_name,
                     'last_name': self.last_name, 'user_id': self.user_id}
        contact = Contact.de_json(json_dict, bot)

        assert contact.phone_number == self.phone_number
        assert contact.first_name == self.first_name
        assert contact.last_name == self.last_name
        assert contact.user_id == self.user_id
    def test_equality(self):
        a = Contact(self.phone_number, self.first_name)
        b = Contact(self.phone_number, self.first_name)
        c = Contact(self.phone_number, '')
        d = Contact('', self.first_name)
        e = Voice('', 'unique_id', 0)

        assert a == b
        assert hash(a) == hash(b)
        assert a is not b

        assert a == c
        assert hash(a) == hash(c)

        assert a != d
        assert hash(a) != hash(d)

        assert a != e
        assert hash(a) != hash(e)
Example #9
0
    def test_contact(self):
        con = Contact("0612345", "testman")
        u = self.mg.get_message(contact=con)
        self.assertEqual(con.phone_number, u.message.contact.phone_number)

        u = self.mg.get_message(contact=True)
        self.assertIsInstance(u.message.contact, Contact)

        with self.assertRaisesRegexp(BadMessageException,
                                     r"telegram\.Contact"):
            self.mg.get_message(contact="contact")
    def test_de_json_all(self, bot):
        json_dict = {
            "phone_number": self.phone_number,
            "first_name": self.first_name,
            "last_name": self.last_name,
            "user_id": self.user_id,
        }
        contact = Contact.de_json(json_dict, bot)

        assert contact.phone_number == self.phone_number
        assert contact.first_name == self.first_name
        assert contact.last_name == self.last_name
        assert contact.user_id == self.user_id
    def test_de_json_all(self, bot):
        json_dict = {
            'phone_number': self.phone_number,
            'first_name': self.first_name,
            'last_name': self.last_name,
            'user_id': self.user_id,
        }
        contact = Contact.de_json(json_dict, bot)

        assert contact.phone_number == self.phone_number
        assert contact.first_name == self.first_name
        assert contact.last_name == self.last_name
        assert contact.user_id == self.user_id
Example #12
0
    def de_json(data):
        """
        Args:
            data (str):

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

        data['from_user'] = User.de_json(data.get('from'))
        data['date'] = datetime.fromtimestamp(data['date'])
        if 'first_name' in data.get('chat', ''):
            data['chat'] = User.de_json(data.get('chat'))
        elif 'title' in data.get('chat', ''):
            data['chat'] = GroupChat.de_json(data.get('chat'))
        data['forward_from'] = \
            User.de_json(data.get('forward_from'))
        data['forward_date'] = \
            Message._fromtimestamp(data.get('forward_date'))
        data['reply_to_message'] = \
            Message.de_json(data.get('reply_to_message'))
        data['audio'] = \
            Audio.de_json(data.get('audio'))
        data['document'] = \
            Document.de_json(data.get('document'))
        data['photo'] = \
            PhotoSize.de_list(data.get('photo'))
        data['sticker'] = \
            Sticker.de_json(data.get('sticker'))
        data['video'] = \
            Video.de_json(data.get('video'))
        data['voice'] = \
            Voice.de_json(data.get('voice'))
        data['contact'] = \
            Contact.de_json(data.get('contact'))
        data['location'] = \
            Location.de_json(data.get('location'))
        data['new_chat_participant'] = \
            User.de_json(data.get('new_chat_participant'))
        data['left_chat_participant'] = \
            User.de_json(data.get('left_chat_participant'))
        data['new_chat_photo'] = \
            PhotoSize.de_list(data.get('new_chat_photo'))

        return Message(**data)
Example #13
0
    def de_json(data):
        """
        Args:
            data (str):

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

        data['from_user'] = User.de_json(data.get('from'))
        data['date'] = datetime.fromtimestamp(data['date'])
        if 'first_name' in data.get('chat', ''):
            data['chat'] = User.de_json(data.get('chat'))
        elif 'title' in data.get('chat', ''):
            data['chat'] = GroupChat.de_json(data.get('chat'))
        data['forward_from'] = \
            User.de_json(data.get('forward_from'))
        data['forward_date'] = \
            Message._fromtimestamp(data.get('forward_date'))
        data['reply_to_message'] = \
            Message.de_json(data.get('reply_to_message'))
        data['audio'] = \
            Audio.de_json(data.get('audio'))
        data['document'] = \
            Document.de_json(data.get('document'))
        data['photo'] = \
            PhotoSize.de_list(data.get('photo'))
        data['sticker'] = \
            Sticker.de_json(data.get('sticker'))
        data['video'] = \
            Video.de_json(data.get('video'))
        data['voice'] = \
            Voice.de_json(data.get('voice'))
        data['contact'] = \
            Contact.de_json(data.get('contact'))
        data['location'] = \
            Location.de_json(data.get('location'))
        data['new_chat_participant'] = \
            User.de_json(data.get('new_chat_participant'))
        data['left_chat_participant'] = \
            User.de_json(data.get('left_chat_participant'))
        data['new_chat_photo'] = \
            PhotoSize.de_list(data.get('new_chat_photo'))

        return Message(**data)
def get_several_details_messages(update, context):
    result_list = context.user_data['response']
    update.callback_query.edit_message_text(
        'Ми знайшли медиків поряд з місцем вашого відправлення!')

    for route in result_list:
        location = Location(latitude=route['finish_point']['latitude'],
                            longitude=route['finish_point']['longitude'])
        contact = Contact(phone_number=route['user']['phone_number'],
                          first_name=route['user']['first_name'],
                          last_name=route['user']['last_name'])

        if route.get('date_and_time'):

            date = route['date_and_time'][:10]
            time = route['date_and_time'][11:16]

            text = f'Час та дата відправлення: {date}, {time}.\n' \
                   f'Місце призначення:'
        else:
            text = 'Регулярна поїздка.\n' \
                   'Місце призначення:'

        context.bot.send_message(update.effective_message.chat_id, text=text)
        context.bot.send_location(chat_id=update.effective_message.chat_id,
                                  location=location)
        context.bot.send_contact(update.effective_message.chat_id,
                                 contact=contact)

    context.bot.send_message(
        update.effective_message.chat_id,
        "Перегляньте місця призначення. Якщо вам по дорозі, "
        "будь ласка, зв'яжіться з медиком, аби домовитися про "
        "поїздку!")

    context.user_data.clear()

    return ConversationHandler.END
Example #15
0
def start(update: Update, context: CallbackContext) -> None:
    global state
    user = getUser(update.message.chat_id, state.users)
    if user is None:
        if str(update.message.from_user.id) in admins:
            user = User(Contact("", update.message.from_user.first_name, user_id=update.message.from_user.id), 7)
            state.users.append(user)
            saveState()
        else:
            kb = [[KeyboardButton('/start')]]
            kb_markup = ReplyKeyboardMarkup(kb)
            message = "No access rights. Contact an admin."
            context.bot.send_message(chat_id=update.message.chat_id, text=message, reply_markup=kb_markup)
            return
    if user.permissions == 0:
        kb = [[KeyboardButton('/start')]]
        kb_markup = ReplyKeyboardMarkup(kb)
        message = "No access rights. Contact an admin."
        context.bot.send_message(chat_id=update.message.chat_id, text=message, reply_markup=kb_markup)
        return
            
    message = buildMessage("Welcome")
    result = context.bot.send_message(chat_id=update.message.chat_id, text=message, reply_markup=makeKeyboard(user))
    user.message_id = result['message_id']
 def _handle_attachments(
         self,
         audio,
         contact,
         document,
         location,
         photo,
         sticker,
         user,
         venue,
         video,
         voice,
         caption,
 ):
     attachments = [
         x
         for x in [
             photo,
             venue,
             location,
             contact,
             voice,
             video,
             sticker,
             document,
             audio,
         ]
         if x
     ]
     if caption and not attachments:
         raise BadMessageException("Can't have a caption without attachment")
     if len(attachments) > 1:
         raise BadMessageException("can't add more than one attachment")
     if photo:
         if isinstance(photo, list):
             if all([isinstance(x, PhotoSize) for x in photo]):
                 pass
             else:
                 raise BadMessageException(
                     "photo must either be True or list(telegram.PhotoSize)"
                 )
         elif isinstance(photo, bool):
             photo = self._get_photosize()
         else:
             raise BadMessageException(
                 "photo must either be True or list(telegram.PhotoSize)"
             )
     if location:
         if isinstance(location, Location):
             pass
         elif isinstance(location, dict):
             location = Location(**location)
         elif isinstance(location, bool):
             location = self._get_location()
         else:
             raise BadMessageException(
                 "location must either be True or telegram.Location"
             )
     if venue:
         if isinstance(venue, Venue):
             pass
         elif isinstance(venue, bool):
             venue = self._get_venue()
         elif isinstance(venue, dict):
             venue["location"] = Location(**venue)
             venue = Venue(**venue)
         else:
             raise BadMessageException("venue must either be True or telegram.Venue")
     if contact:
         if isinstance(contact, Contact):
             pass
         elif isinstance(contact, dict):
             contact = Contact(**contact)
         elif isinstance(contact, bool):
             contact = self._get_contact(user)
         else:
             raise BadMessageException(
                 "contact must either be True or telegram.Contact"
             )
     if voice:
         if isinstance(voice, Voice):
             pass
         elif isinstance(voice, bool):
             voice = self._get_voice()
         elif isinstance(voice, dict):
             voice = Voice(**voice)
         else:
             raise BadMessageException("voice must either be True or telegram.Voice")
     if video:
         if isinstance(video, Video):
             pass
         elif isinstance(video, bool):
             video = self._get_video()
         elif isinstance(video, dict):
             video = self._get_video(data=video)
         else:
             raise BadMessageException("video must either be True or telegram.Video")
     if sticker:
         if isinstance(sticker, Sticker):
             pass
         elif isinstance(sticker, bool):
             sticker = self._get_sticker()
         elif isinstance(sticker, dict):
             sticker = self._get_sticker(sticker)
         else:
             raise BadMessageException(
                 "sticker must either be True or telegram.Sticker"
             )
     if document:
         if isinstance(document, Document):
             pass
         elif isinstance(document, dict):
             document = Document(**document)
         elif isinstance(document, bool):
             document = self._get_document()
         else:
             raise BadMessageException(
                 "document must either be True or telegram.Document"
             )
     if audio:
         if isinstance(audio, Audio):
             pass
         elif isinstance(audio, bool):
             audio = self._get_audio()
         elif isinstance(audio, dict):
             audio = Audio(**audio)
         else:
             raise BadMessageException("audio must either be True or telegram.Audio")
     return audio, contact, document, location, photo, sticker, venue, video, voice
Example #17
0
def get_db_response(update, context):

    # отправляем запрос на наличие совпадений -- GET
    if context.user_data['ride_type'] == 'ONE_TIME':
        response = get_similar_routes_request(
            telegram_id=context.user_data['telegram_id'],
            time_of_departure=context.user_data['time_of_departure'],
            date_of_departure=context.user_data['date_of_departure'],
            start_latitude=context.user_data['start_latitude'],
            start_longitude=context.user_data['start_longitude'],
            finish_latitude=context.user_data["finish_latitude"],
            finish_longitude=context.user_data["finish_longitude"])
    else:
        response = get_similar_routes_request(
            telegram_id=context.user_data['telegram_id'],
            start_latitude=context.user_data['start_latitude'],
            start_longitude=context.user_data['start_longitude'],
            finish_latitude=context.user_data["finish_latitude"],
            finish_longitude=context.user_data["finish_longitude"])

    context.user_data['response'] = response

    if len(context.user_data['response']):

        user_type = context.user_data['response'][0]['user']['type']

        if user_type == 'doctor':
            keyboard = [[
                InlineKeyboardButton("Деталі", callback_data=str(GET_DETAILS))
            ]]
            reply_markup = InlineKeyboardMarkup(keyboard)
            update.message.reply_text(
                'Ми знайшли медиків поряд з місцем вашого відправлення!',
                reply_markup=reply_markup)

            for route in response:
                medic_telegram_id = route['user']['telegram_id']
                context.bot.send_message(
                    chat_id=medic_telegram_id,
                    text="Поряд з місцем вашого відправлення знайшлися водії!\n"
                    "Ми відправили їм ваши контакти, та інформацію про ваш маршрут.\n"
                    "Можливо скоро з вами зв'яжуться!")

            # после отправки запроса перезаписываем содержимое user_data, чтобы передать их в get_details
            context.user_data.clear()
            context.user_data['response'] = response

            return GET_RESULT_LIST
        else:
            # отправка сообщения медику
            update.message.reply_text(
                "Поряд з місцем вашого відправлення знайшлися водії!\n"
                "Ми відправили їм ваши контакти, та інформацію про ваш маршрут.\n"
                "Можливо скоро з вами зв'яжуться!")

            # рассылка уведомлений водителям
            for route in response:
                driver_telegram_id = route['user']['telegram_id']
                medic_user_instance = get_user(update.effective_user.id)
                data = medic_user_instance.content.decode('utf-8')
                user_instance = json.loads(data)

                location = Location(
                    latitude=context.user_data['finish_latitude'],
                    longitude=context.user_data['finish_longitude'])

                user_contact = Contact(
                    phone_number=user_instance['phone_number'],
                    first_name=user_instance['first_name'],
                    last_name=user_instance['last_name'],
                    user_id=user_instance['telegram_id'])

                if context.user_data.get('time_of_departure'):
                    date = context.user_data['date_of_departure']
                    time = context.user_data['time_of_departure']
                    text = f'Ми знайшли нове співпадіння за маршрутом!\n' \
                           f'Час та дата відправлення: {date}, {time}.\n' \
                           f'Місце призначення:'
                else:
                    text = 'Ми знайшли нове співпадіння за маршрутом!\n' \
                           'Регулярна поїздка.\n' \
                           'Місце призначення:'

                context.bot.send_message(chat_id=driver_telegram_id, text=text)
                context.bot.send_location(chat_id=driver_telegram_id,
                                          location=location)
                context.bot.send_contact(chat_id=driver_telegram_id,
                                         contact=user_contact)

                context.bot.send_message(
                    chat_id=driver_telegram_id,
                    text="Перегляньте місця призначення. Якщо вам по дорозі, "
                    "будь ласка, зв'яжіться з медиком, аби домовитися про "
                    "поїздку!")

                context.user_data.clear()
            return ConversationHandler.END
    else:
        update.message.reply_text(
            'Наразі у систумі немає Ваших попутників. Ми повідомимо, коли такі знайдуться.'
        )
        context.user_data.clear()
        return ConversationHandler.END
Example #18
0
    def de_json(data):
        if 'from' in data:  # from is a reserved word, use from_user instead.
            from telegram import User
            from_user = User.de_json(data['from'])
        else:
            from_user = None

        if 'chat' in data:
            if 'first_name' in data['chat']:
                from telegram import User
                chat = User.de_json(data['chat'])
            if 'title' in data['chat']:
                from telegram import GroupChat
                chat = GroupChat.de_json(data['chat'])
        else:
            chat = None

        if 'forward_from' in data:
            from telegram import User
            forward_from = User.de_json(data['forward_from'])
        else:
            forward_from = None

        if 'reply_to_message' in data:
            reply_to_message = Message.de_json(data['reply_to_message'])
        else:
            reply_to_message = None

        if 'text' in data:
            text = data['text']
        else:
            text = None

        if 'audio' in data:
            from telegram import Audio
            audio = Audio.de_json(data['audio'])
        else:
            audio = None

        if 'document' in data:
            from telegram import Document
            document = Document.de_json(data['document'])
        else:
            document = None

        if 'photo' in data:
            from telegram import PhotoSize
            photo = [PhotoSize.de_json(x) for x in data['photo']]
        else:
            photo = None

        if 'sticker' in data:
            from telegram import Sticker
            sticker = Sticker.de_json(data['sticker'])
        else:
            sticker = None

        if 'video' in data:
            from telegram import Video
            video = Video.de_json(data['video'])
        else:
            video = None

        if 'contact' in data:
            from telegram import Contact
            contact = Contact.de_json(data['contact'])
        else:
            contact = None

        if 'location' in data:
            from telegram import Location
            location = Location.de_json(data['location'])
        else:
            location = None

        if 'new_chat_participant' in data:
            from telegram import User
            new_chat_participant = User.de_json(data['new_chat_participant'])
        else:
            new_chat_participant = None

        if 'left_chat_participant' in data:
            from telegram import User
            left_chat_participant = User.de_json(data['left_chat_participant'])
        else:
            left_chat_participant = None

        return Message(message_id=data.get('message_id', None),
                       from_user=from_user,
                       date=data.get('date', None),
                       chat=chat,
                       forward_from=forward_from,
                       forward_date=data.get('forward_date', None),
                       reply_to_message=reply_to_message,
                       text=text,
                       audio=audio,
                       document=document,
                       photo=photo,
                       sticker=sticker,
                       video=video,
                       contact=contact,
                       location=location,
                       new_chat_participant=new_chat_participant,
                       left_chat_participant=left_chat_participant,
                       new_chat_title=data.get('new_chat_title', None),
                       new_chat_photo=data.get('new_chat_photo', None),
                       delete_chat_photo=data.get('delete_chat_photo', None),
                       group_chat_created=data.get('group_chat_created', None))
 def _get_contact(self, user):
     return Contact("06123456789", user.first_name)
 },
 {
     'video': Video('video_id', 'unique_id', 12, 12, 12),
     'caption': 'video_file'
 },
 {
     'voice': Voice('voice_id', 'unique_id', 5)
 },
 {
     'video_note': VideoNote('video_note_id', 'unique_id', 20, 12)
 },
 {
     'new_chat_members': [User(55, 'new_user', False)]
 },
 {
     'contact': Contact('phone_numner', 'contact_name')
 },
 {
     'location': Location(-23.691288, 46.788279)
 },
 {
     'venue':
     Venue(Location(-23.691288, 46.788279), 'some place', 'right here')
 },
 {
     'left_chat_member': User(33, 'kicked', False)
 },
 {
     'new_chat_title': 'new title'
 },
 {
Example #21
0
    def de_json(data):
        if 'from' in data:  # from is a reserved word, use from_user instead.
            from telegram import User
            from_user = User.de_json(data['from'])
        else:
            from_user = None

        if 'date' in data:
            date = datetime.fromtimestamp(data['date'])
        else:
            date = None

        if 'chat' in data:
            if 'first_name' in data['chat']:
                from telegram import User
                chat = User.de_json(data['chat'])
            if 'title' in data['chat']:
                from telegram import GroupChat
                chat = GroupChat.de_json(data['chat'])
        else:
            chat = None

        if 'forward_from' in data:
            from telegram import User
            forward_from = User.de_json(data['forward_from'])
        else:
            forward_from = None

        if 'forward_date' in data:
            forward_date = datetime.fromtimestamp(data['forward_date'])
        else:
            forward_date = None

        if 'reply_to_message' in data:
            reply_to_message = Message.de_json(data['reply_to_message'])
        else:
            reply_to_message = None

        if 'audio' in data:
            from telegram import Audio
            audio = Audio.de_json(data['audio'])
        else:
            audio = None

        if 'document' in data:
            from telegram import Document
            document = Document.de_json(data['document'])
        else:
            document = None

        if 'photo' in data:
            from telegram import PhotoSize
            photo = [PhotoSize.de_json(x) for x in data['photo']]
        else:
            photo = None

        if 'sticker' in data:
            from telegram import Sticker
            sticker = Sticker.de_json(data['sticker'])
        else:
            sticker = None

        if 'video' in data:
            from telegram import Video
            video = Video.de_json(data['video'])
        else:
            video = None

        if 'voice' in data:
            from telegram import Voice
            voice = Voice.de_json(data['voice'])
        else:
            voice = None

        if 'contact' in data:
            from telegram import Contact
            contact = Contact.de_json(data['contact'])
        else:
            contact = None

        if 'location' in data:
            from telegram import Location
            location = Location.de_json(data['location'])
        else:
            location = None

        if 'new_chat_participant' in data:
            from telegram import User
            new_chat_participant = User.de_json(data['new_chat_participant'])
        else:
            new_chat_participant = None

        if 'left_chat_participant' in data:
            from telegram import User
            left_chat_participant = User.de_json(data['left_chat_participant'])
        else:
            left_chat_participant = None

        if 'new_chat_photo' in data:
            from telegram import PhotoSize
            new_chat_photo = \
                [PhotoSize.de_json(x) for x in data['new_chat_photo']]
        else:
            new_chat_photo = None

        return Message(message_id=data.get('message_id', None),
                       from_user=from_user,
                       date=date,
                       chat=chat,
                       forward_from=forward_from,
                       forward_date=forward_date,
                       reply_to_message=reply_to_message,
                       text=data.get('text', ''),
                       audio=audio,
                       document=document,
                       photo=photo,
                       sticker=sticker,
                       video=video,
                       voice=voice,
                       caption=data.get('caption', ''),
                       contact=contact,
                       location=location,
                       new_chat_participant=new_chat_participant,
                       left_chat_participant=left_chat_participant,
                       new_chat_title=data.get('new_chat_title', None),
                       new_chat_photo=new_chat_photo,
                       delete_chat_photo=data.get('delete_chat_photo', None),
                       group_chat_created=data.get('group_chat_created', None))
    def test_de_json_required(self, bot):
        json_dict = {'phone_number': self.phone_number, 'first_name': self.first_name}
        contact = Contact.de_json(json_dict, bot)

        assert contact.phone_number == self.phone_number
        assert contact.first_name == self.first_name