def get_ride_type_or_start_point(update, context): if update.callback_query: query = update.callback_query ride_type = query.data # adding vars to user_data if ride_type is ONE_TIME: context.user_data['ride_type'] = 'ONE_TIME' else: context.user_data['ride_type'] = 'REGULAR' text = f'Тип вашої поїздки: {context.user_data["ride_type"]}' context.bot.send_message(chat_id=update.effective_message.chat_id, text=text) else: if update.message.text: latitude, longitude = update.message.text.split(', ') user_location = Location(longitude=longitude, latitude=latitude) # тут пытаемся принять объект геолокации else: location = update.message.location latitude, longitude = location.latitude, location.longitude user_location = Location(longitude=longitude, latitude=latitude) # adding vars to user_data context.user_data['start_latitude'] = latitude context.user_data['start_longitude'] = longitude text = f'Координати місця вашого відправлення: {context.user_data["start_latitude"]}, ' \ f'{context.user_data["start_longitude"]}' context.bot.send_message(chat_id=update.effective_message.chat_id, text=text) context.bot.send_location(chat_id=update.effective_message.chat_id, location=user_location) context.bot.send_message(chat_id=update.effective_message.chat_id, text='А тепер вкажіть, куди ви прямуєте:') return GET_FINISH_POINT
def test_equality(self): a = Location(self.longitude, self.latitude) b = Location(self.longitude, self.latitude) d = Location(0, self.latitude) assert a == b assert hash(a) == hash(b) assert a is not b assert a != d assert hash(a) != hash(d)
def test_sight_history(): _, history = utils.get_sights(Location(-0.09531, 51.521681)) _history = history[0][0][1][:25] assert len(history[0][0][1]) > 1000 for word in config.parser['remove_words_hist']: assert word not in _history.lower()
def test_check_update_free_text(self, member): valid_update = Update(1, message=Message(1, None, None, None, text='text')) invalid_update = Update(1, poll_answer=PollAnswer(123, None, [1])) for attr in [ a for a in Question.SUPPORTED_ATTRIBUTES if a != Question.PHOTO ]: q = Question(member, attr, multiple_choice=False) assert q.check_update(valid_update) assert not q.check_update(invalid_update) q = Question(member, Question.ADDRESS, multiple_choice=False) valid_update = Update(1, message=Message(1, None, None, None, location=Location(longitude=1, latitude=1))) invalid_update = Update(1, poll_answer=PollAnswer(123, None, [1])) assert q.check_update(valid_update) assert not q.check_update(invalid_update)
def test_sight_reply(context): context.user_data = utils.get_user_data(Location(37.620948, 55.688832)) reply = callbacks.Location().create_reply(context) assert reply.__class__.__name__ == 'SightReply' assert len(reply.markup.keyboard[0]) >= 2 assert len(reply.markup.keyboard[1]) == 1
def gps(update, context, *args, **kwargs): args = context.args update.effective_message if len(args) == 0: update.effective_message.reply_text( "That was a funny joke, but no really, put in a location" ) try: geolocator = Nominatim(user_agent="SkittBot") location = " ".join(args) geoloc = geolocator.geocode(location) chat_id = update.effective_chat.id lon = geoloc.longitude lat = geoloc.latitude the_loc = Location(lon, lat) gm = "https://www.google.com/maps/search/{},{}".format(lat, lon) dispatcher.bot.send_location(chat_id, location=the_loc) update.message.reply_text( "Open with: [Google Maps]({})".format(gm), parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, ) except AttributeError: update.message.reply_text("I can't find that")
def _ros_location_callback(self, msg: NavSatFix): """ Called when a new ROS NavSatFix message is coming in that should be sent to the Telegram conversation :param 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 test_equality(self): a = InputVenueMessageContent(123, 456, 'title', 'address') b = InputVenueMessageContent(123, 456, 'title', '') c = InputVenueMessageContent(123, 456, 'title', 'address', foursquare_id=123) d = InputVenueMessageContent(456, 123, 'title', 'address', foursquare_id=123) e = 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) assert a != e assert hash(a) != hash(e)
def test_show_map_reply(context): context.user_data = utils.get_user_data(Location(-0.09531, 51.521681)) reply = callbacks.ShowMap().create_reply(context) assert reply.location is not None assert isinstance(reply.location.latitude, float) is True assert isinstance(reply.location.longitude, float) is True
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
class TestInlineQuery: id_ = 1234 from_user = User(1, 'First name', False) query = 'query text' offset = 'offset' location = Location(8.8, 53.1) def test_de_json(self, bot): json_dict = { 'id': self.id_, 'from': self.from_user.to_dict(), 'query': self.query, 'offset': self.offset, 'location': self.location.to_dict() } inline_query_json = InlineQuery.de_json(json_dict, bot) assert inline_query_json.id == self.id_ assert inline_query_json.from_user == self.from_user assert inline_query_json.location == self.location assert inline_query_json.query == self.query assert inline_query_json.offset == self.offset def test_to_dict(self, inline_query): inline_query_dict = inline_query.to_dict() assert isinstance(inline_query_dict, dict) assert inline_query_dict['id'] == inline_query.id assert inline_query_dict['from'] == inline_query.from_user.to_dict() assert inline_query_dict['location'] == inline_query.location.to_dict() assert inline_query_dict['query'] == inline_query.query assert inline_query_dict['offset'] == inline_query.offset def test_answer(self, monkeypatch, inline_query): def test(*args, **kwargs): return args[0] == inline_query.id monkeypatch.setattr(inline_query.bot, 'answer_inline_query', test) assert inline_query.answer() def test_equality(self): a = InlineQuery(self.id_, User(1, '', False), '', '') b = InlineQuery(self.id_, User(1, '', False), '', '') c = InlineQuery(self.id_, User(0, '', False), '', '') d = InlineQuery(0, User(1, '', False), '', '') e = Update(self.id_) 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 test_history_location_reply(context): context.user_data = utils.get_user_data(Location(-0.09531, 51.521681)) reply = callbacks.Location().create_reply(context) assert reply.__class__.__name__ == 'SightReply' assert len(reply.history) > 0 assert len(reply.markup.keyboard[0]) == 3 assert len(reply.markup.keyboard[1]) == 1
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 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_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 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 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 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 _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 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 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_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 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 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 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
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 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 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)