def test_de_json_all(self, bot, user): loc = Location(-42.003, 34.004) json_dict = {'result_id': self.result_id, 'from': user.to_dict(), 'query': self.query, 'location': loc.to_dict(), 'inline_message_id': 'a random id'} result = ChosenInlineResult.de_json(json_dict, bot) assert result.result_id == self.result_id assert result.from_user == user assert result.query == self.query assert result.location == loc assert result.inline_message_id == 'a random id'
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 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 test_de_json(self, bot): json_dict = {'latitude': TestLocation.latitude, 'longitude': TestLocation.longitude} location = Location.de_json(json_dict, bot) assert location.latitude == self.latitude assert location.longitude == self.longitude
def de_json(cls, data: Optional[JSONDict], bot: 'Bot') -> Optional['Venue']: data = cls.parse_data(data) if not data: return None data['location'] = Location.de_json(data.get('location'), bot) return cls(**data)
def test_de_json(self, bot): json_dict = { 'latitude': TestLocation.latitude, 'longitude': TestLocation.longitude } location = Location.de_json(json_dict, bot) assert location.latitude == self.latitude assert location.longitude == self.longitude
def sendloc(bot:Bot, update:Update): l = Location(24.245331, 50.400863,) bot.send_location( chat_id= update.message.chat_id, latitude=l.latitude, longitude=l.longitude, )
def location(): return Location( latitude=TestLocation.latitude, longitude=TestLocation.longitude, horizontal_accuracy=TestLocation.horizontal_accuracy, live_period=TestLocation.live_period, heading=TestLocation.live_period, proximity_alert_radius=TestLocation.proximity_alert_radius, )
def test_with_location(self): u = self.iqc.get_chosen_inline_result("testid", location=True) self.assertIsInstance(u.chosen_inline_result.location, Location) loc = Location(23.0, 90.0) u = self.iqc.get_chosen_inline_result("testid", location=loc) self.assertEqual(u.chosen_inline_result.location.longitude, 23.0) with self.assertRaisesRegexp(AttributeError, "telegram\.Location"): self.iqc.get_chosen_inline_result("test_id", location="loc")
def de_json(cls, data, bot): data = super(Venue, cls).de_json(data, bot) if not data: return None data['location'] = Location.de_json(data.get('location'), bot) return cls(**data)
def de_json(data): data = super(Venue, Venue).de_json(data) if not data: return None data['location'] = Location.de_json(data.get('location')) return Venue(**data)
def de_json(data, bot): data = super(Venue, Venue).de_json(data, bot) if not data: return None data["location"] = Location.de_json(data.get("location"), bot) return Venue(**data)
def de_json(data): if not data: return None data = super(Venue, Venue).de_json(data) data['location'] = Location.de_json(data.get('location')) return Venue(**data)
def inline_query(bot): return Update(0, inline_query=InlineQuery('id', User(2, 'test user', False), 'test query', offset='22', location=Location( latitude=-23.691288, longitude=-46.788279)))
def test_equality(self): a = Venue(Location(0, 0), self.title, self.address) b = Venue(Location(0, 0), self.title, self.address) c = Venue(Location(0, 0), self.title, '') d = Venue(Location(0, 1), self.title, self.address) d2 = Venue(Location(0, 0), '', self.address) 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 != d2 assert hash(a) != hash(d2)
def de_json(cls, data, bot): data = super(InlineQuery, cls).de_json(data, bot) if not data: return None data['from_user'] = User.de_json(data.get('from'), bot) data['location'] = Location.de_json(data.get('location'), bot) return cls(bot=bot, **data)
def test_venue(self): ven = Venue(Location(1.0, 1.0), "some place", "somewhere") u = self.mg.get_message(venue=ven) self.assertEqual(u.message.venue.title, ven.title) u = self.mg.get_message(venue=True) self.assertIsInstance(u.message.venue, Venue) with self.assertRaisesRegexp(BadMessageException, r"telegram\.Venue"): self.mg.get_message(venue="Venue")
def test_max_next_reply(context): context.user_data = utils.get_user_data(Location(-0.09531, 51.521681)) context.user_data['next'] = config.n_next + 1 reply = callbacks.NextSight().create_reply(context) button = reply.markup.keyboard[0][0] assert reply.__class__.__name__ == 'MaxNextEventsReply' assert len(reply.markup.keyboard) == 1 assert len(reply.markup.keyboard[0]) == 1 assert button.request_location is True
def _ros_location_callback(self, msg): """ Call when a new ROS NavSatFix message should be sent to the telegram session. :config msg: NavSatFix that the robot wants to share """ self._telegram_updater.bot.send_location(self._telegram_chat_id, location=Location( msg.longitude, msg.latitude))
def de_json(cls, data: Optional[JSONDict], bot: 'Bot') -> Optional['InlineQuery']: data = cls.parse_data(data) if not data: return None data['from_user'] = User.de_json(data.get('from'), bot) data['location'] = Location.de_json(data.get('location'), bot) return cls(bot=bot, **data)
def test_location(self): u = self.iqg.get_inline_query(location=True) self.assertIsInstance(u.inline_query.location, Location) loc = Location(23.0, 90.0) u = self.iqg.get_inline_query(location=loc) self.assertEqual(u.inline_query.location.longitude, 23.0) with self.assertRaisesRegexp(AttributeError, "telegram\.Location"): self.iqg.get_inline_query(location="location")
def accident_message(accident): data = accident['date'].strftime("%d/%m/%Y") hour = accident['date'].strftime("%H:%M:%S") msg = f"Incidente rilevato il {data} alle {hour} per l'auto con targa *{accident['car_id']}*\.\nPosizione dell'incidente:" bot = Bot(token=telegram_key) bot.send_message(chat_id=accident['chat_id'], text=msg, parse_mode=ParseMode.MARKDOWN_V2) bot.sendLocation(chat_id=accident['chat_id'], location=Location(latitude=accident['lat'], longitude=accident['lng']))
def test_location(self): loc = Location(50.012, -32.11) u = self.mg.get_message(location=loc) self.assertEqual(loc.longitude, u.message.location.longitude) u = self.mg.get_message(location=True) self.assertIsInstance(u.message.location, Location) with self.assertRaisesRegexp(BadMessageException, r"telegram\.Location"): self.mg.get_message(location="location")
def regular_choice(bot, update, user_data): if user_data.get('verified', False): step = user_data.get('step', 0) if step < len(story): storyline = story[step] if storyline[:5] == u'loc::': lat_lon = storyline[5:].split(', ') lat = float(lat_lon[0]) lon = float(lat_lon[1]) update.message.reply_location(location=Location(lon, lat), reply_markup=markup) elif storyline[:5] == u'img::': parts = storyline[5:].split('::') photo = parts[0] caption = parts[1] update.message.reply_photo(photo=photo, caption=caption, reply_markup=markup) elif storyline[:5] == u'tlk::': parts = storyline[5:].split('::') options = parts[1].split('||') buttons = [str(i + 1) for i in range(len(options))] opt_txt = u'\n'.join( [b + ') ' + options[int(b) - 1] for b in buttons]) user_data['talks_available'] = buttons talks_keyboard = [buttons, [u'Закончить разговор']] talks_markup = ReplyKeyboardMarkup(talks_keyboard, one_time_keyboard=True, resize_keyboard=True) update.message.reply_text(parts[0] + '\n\n' + opt_txt, reply_markup=talks_markup) return TALKS else: update.message.reply_text(storyline, reply_markup=markup) user_data['step'] = user_data.get('step', 0) + 1 else: storyline = u'Далее текст игры пока не написан. Ждите обновлений!' user_data['finished'] = True update.message.reply_text(storyline, reply_markup=final_markup) return CHOOSING else: start(bot, update)
def test_check_answer_free_text_location_coords(self, answer, result, member): q = Question(member, Question.ADDRESS, multiple_choice=False) update = Update(1, message=Message(1, None, None, None, location=Location(*reversed(answer)))) assert q.check_answer(update) is result assert q.correct_answer == member.address
def de_json(cls, data, bot): if not data: return None data = super(ChosenInlineResult, cls).de_json(data, bot) # Required data['from_user'] = User.de_json(data.pop('from'), bot) # Optionals data['location'] = Location.de_json(data.get('location'), bot) return cls(**data)
def inline_query(bot): return Update( 0, inline_query=InlineQuery( "id", User(2, "test user", False), "test query", offset="22", location=Location(latitude=-23.691288, longitude=-46.788279), ), )
def de_json(cls, data: Optional[JSONDict], bot: 'Bot') -> Optional['Venue']: """See :meth:`telegram.TelegramObject.de_json`.""" data = cls._parse_data(data) if not data: return None data['location'] = Location.de_json(data.get('location'), bot) return cls(**data)
class TestChatLocation: location = Location(123, 456) address = 'The Shire' def test_slot_behaviour(self, chat_location, recwarn, mro_slots): inst = chat_location for attr in inst.__slots__: assert getattr(inst, attr, 'err') != 'err', f"got extra slot '{attr}'" assert not inst.__dict__, f"got missing slot(s): {inst.__dict__}" assert len(mro_slots(inst)) == len(set( mro_slots(inst))), "duplicate slot" inst.custom, inst.address = 'should give warning', self.address assert len(recwarn) == 1 and 'custom' in str( recwarn[0].message), recwarn.list def test_de_json(self, bot): json_dict = { 'location': self.location.to_dict(), 'address': self.address, } chat_location = ChatLocation.de_json(json_dict, bot) assert chat_location.location == self.location assert chat_location.address == self.address def test_to_dict(self, chat_location): chat_location_dict = chat_location.to_dict() assert isinstance(chat_location_dict, dict) assert chat_location_dict[ 'location'] == chat_location.location.to_dict() assert chat_location_dict['address'] == chat_location.address def test_equality(self, chat_location): a = chat_location b = ChatLocation(self.location, self.address) c = ChatLocation(self.location, 'Mordor') d = ChatLocation(Location(456, 132), self.address) e = User(456, '', False) 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)
def de_json(cls, data: Optional[JSONDict], bot: 'Bot') -> Optional['ChosenInlineResult']: data = cls.parse_data(data) if not data: return None # Required data['from_user'] = User.de_json(data.pop('from'), bot) # Optionals data['location'] = Location.de_json(data.get('location'), bot) return cls(**data)
def show_location(update, context): print('show loc') print(context.user_data['state']) if context.user_data['state'] == states.CAR_ACTION_CHOSEN: print('ok') current_car = context.user_data['current_car'] location_data = context.user_data['cars'][current_car]['location'] location = Location(longitude=location_data[0], latitude=location_data[1]) update.message.reply_location(location=location) context.user_data['state'] = states.STARTED
def de_json(cls, data: Optional[JSONDict], bot: 'Bot') -> Optional['InlineQuery']: """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['location'] = Location.de_json(data.get('location'), bot) return cls(bot=bot, **data)
def get_chosen_inline_result(self, result_id=None, query=None, user=None, location=None, inline_message_id=None): """ Returns a telegram.Update object containing a inline_query. Parameters: result_id (str): The result_id belonging to this chosen result inline_message_id (Optional[str]): Of omitted will be generated location (Optional[telegram.Location or True]): simulates a location query (Optional[str]): The query used to send this query user (Optional[telegram.User): If omitted will be randomly generated Returns: telegram.Update: an update containing a :py:class:`telegram.ChosenInlineResult` """ if not result_id: raise AttributeError( "result_id must be present for chosen_inline_result") if user: if not isinstance(user, User): raise BadUserException else: user = self.ug.get_user() if not query: query = "" if location: if isinstance(location, Location): pass elif isinstance(location, bool): import random location = Location(random.uniform(-180, 180), random.uniform(-90, 90)) else: raise AttributeError( "Location must be either telegram.Location or True") if not inline_message_id: inline_message_id = self._gen_id() return ChosenInlineResult(result_id=result_id, from_user=user, query=query, location=location, inline_message_id=inline_message_id)
def get_inline_query(self, user=None, query=None, offset=None, location=None): """ Returns a telegram.Update object containing a inline_query. Parameters: location (Optional[telegram.Location or True]): simulates a location offset (Optional[str]): query (Optional[str]): user (Optional[telegram.User): If omitted will be randomly generated Returns: telegram.Update: an update containing a :py:class:`telegram.InlineQuery` """ if user: if not isinstance(user, User): raise BadUserException else: user = self.ug.get_user() if query: if not isinstance(query, str): raise AttributeError("query must be string") if offset: if not isinstance(offset, str): raise AttributeError("offset must be string") if location: if isinstance(location, Location): pass elif isinstance(location, bool): import random location = Location(random.uniform(-180, 180), random.uniform(-90, 90)) else: raise AttributeError( "Location must be either telegram.Location or True") return InlineQuery(self._gen_id(), from_user=user, query=query, offset=offset, location=location, bot=self.bot)
def de_json(data, bot): """ Args: data (dict): bot (telegram.Bot): Returns: telegram.Message: """ if not data: return None data = super(Message, Message).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 Message(bot=bot, **data)
def test_equality(self): a = LabeledPrice('label', 100) b = LabeledPrice('label', 100) c = LabeledPrice('Label', 101) d = Location(123, 456) assert a == b assert hash(a) == hash(b) assert a != c assert hash(a) != hash(c) assert a != d assert hash(a) != hash(d)
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 de_json(data): """ Args: data (dict): Returns: telegram.InlineQuery: """ data = super(InlineQuery, InlineQuery).de_json(data) if not data: return None data['from_user'] = User.de_json(data.get('from')) data['location'] = Location.de_json(data.get('location')) return InlineQuery(**data)
def de_json(data): """ Args: data (dict): Returns: telegram.ChosenInlineResult: """ if not data: return None # Required data['from_user'] = User.de_json(data.pop('from')) # Optionals data['location'] = Location.de_json(data.get('location')) return ChosenInlineResult(**data)
def de_json(data, bot): """ Args: data (dict): bot (telegram.Bot): Returns: telegram.ChosenInlineResult: """ if not data: return None data = super(ChosenInlineResult, ChosenInlineResult).de_json(data, bot) # Required data['from_user'] = User.de_json(data.pop('from'), bot) # Optionals data['location'] = Location.de_json(data.get('location'), bot) return ChosenInlineResult(**data)
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))