def handle_dialog(res, req): user_id = req['session']['user_id'] if req['session']['new']: res['response'][ 'text'] = 'Привет! Я могу сказать в какой стране город или сказать расстояние между городами!' return cities = get_cities(req) if len(cities) == 0: res['response']['text'] = 'Ты не написал название не одного города!' elif len(cities) == 1: res['response']['text'] = 'Этот город в стране - ' + get_country( cities[0]) elif len(cities) == 2: distance = get_distance(get_coordinates(cities[0]), get_coordinates(cities[1])) res['response']['text'] = 'расстояние между этими городами: ' + str( round(distance)) + ' км.' else: res['response']['text'] = 'Слишком много городов!'
def handle_dialog(res, req): user_id = req['session']['user_id'] if req['session']['new']: res['response'][ 'text'] = 'Привет! РЇ РјРѕРіСѓ сказать РІ какой стране РіРѕСЂРѕРґ или сказать расстояние между городами!' return cities = get_cities(req) if len(cities) == 0: res['response'][ 'text'] = 'РўС‹ РЅРµ написал название РЅРµ РѕРґРЅРѕРіРѕ РіРѕСЂРѕРґР°!' elif len(cities) == 1: res['response'][ 'text'] = 'Ртот РіРѕСЂРѕРґ РІ стране - ' + get_country( cities[0]) elif len(cities) == 2: distance = get_distance(get_coordinates(cities[0]), get_coordinates(cities[1])) res['response'][ 'text'] = 'Расстояние между этими городами: ' + str( round(distance)) + ' РєРј.' else: res['response']['text'] = 'Слишком РјРЅРѕРіРѕ РіРѕСЂРѕРґРѕРІ!'
def handle_dialog(res, req): user_id = req['session']['user_id'] if req['session']['new']: res['response']['text'] = 'Привет! Назови своё имя!' sessionStorage[user_id] = { 'first_name': None, } return if sessionStorage[user_id]['first_name'] is None: first_name = get_first_name(req) if first_name is None: res['response']['text'] = 'Не расслышала имя. Повтори, пожалуйста!' else: sessionStorage[user_id]['first_name'] = first_name sessionStorage[user_id]['guessed_cities'] = [] res['response'][ 'text'] = f'Приятно познакомиться, {first_name.title()}. Я Алиса. Я могу показать город или сказать расстояние между городами!' else: cities = get_cities(req) if not cities: res['response']['text'] = sessionStorage[user_id][ 'first_name'] + ', ты не написал название не одного города!' elif len(cities) == 1: res['response']['text'] = 'Этот город в стране - ' + \ get_country(cities[0]) elif len(cities) == 2: distance = get_distance(get_coordinates(cities[0]), get_coordinates(cities[1])) res['response']['text'] = 'Расстояние между этими городами: ' + \ str(round(distance)) + ' км.' else: res['response']['text'] = sessionStorage[user_id][ 'first_name'] + ', cлишком много городов!'
def handle_dialog(res, req): user_id = req['session']['user_id'] if req['session']['new']: res['response']['text'] = \ 'Привет! Я могу показать город или сказать расстояние между городами! ' \ 'Но сначала скажи своё имя!' sessionStorage[user_id] = {'first_name': None} return if sessionStorage[user_id]['first_name'] is None: first_name = get_first_name(req) if first_name is None: res['response']['text'] = 'Не расслышала имя. Повтори, пожалуйста!' return else: sessionStorage[user_id]['first_name'] = first_name res['response'][ 'text'] = f'Хорошо, {first_name.title()}. Напиши название города или 2-ух!' return cities = get_cities(req) if not cities: res['response']['text'] = f'{sessionStorage[user_id]["first_name"].title()}, ' \ f'ты не написал название не одного города!' elif len(cities) == 1: res['response']['text'] = f'{sessionStorage[user_id]["first_name"].title()}, этот город в стране - ' + \ get_country(cities[0]) elif len(cities) == 2: distance = get_distance(get_coordinates(cities[0]), get_coordinates(cities[1])) res['response']['text'] = f'{sessionStorage[user_id]["first_name"].title()}, расстояние между этими городами: ' + \ str(round(distance)) + ' км.' else: res['response'][ 'text'] = f'{sessionStorage[user_id]["first_name"].title()}, слишком много городов!'
def handle_dialog(res, req): user_id = req['session']['user_id'] res['response']['buttons'] = [{ 'title': 'Помощь', 'hide': False, }] if req['request']['original_utterance'].lower() == "помощь": res['response']['text'] = "Я - бот, в зависимости от того, сколько названий городов вы мне скажете, " \ "показывающий город или говорящий расстояние между ними." return if req['session']['new']: res['response']['text'] = 'Привет! Назови своё имя!' sessionStorage[user_id] = { 'first_name': None, } return user_name = sessionStorage[user_id]['first_name'] if user_name is None: first_name = get_first_name(req) if first_name is None: res['response']['text'] = 'Не расслышала имя. Повтори, пожалуйста!' else: sessionStorage[user_id]['first_name'] = first_name res['response']['text'] = f'Приятно познакомиться, {first_name.title()}. Я Алиса. Я могу показать город ' \ f'или сказать расстояние между городами!' else: cities = get_cities(req) if not cities: res['response'][ 'text'] = f'{user_name.title()}, ты не написал название не одного города!' elif len(cities) == 1: res['response']['text'] = f'{user_name.title()}, этот город в стране - ' + \ get_country(cities[0]) elif len(cities) == 2: distance = get_distance(get_coordinates(cities[0]), get_coordinates(cities[1])) res['response']['text'] = f'{user_name.title()}, расстояние между этими городами: ' + \ str(round(distance)) + ' км.' else: res['response'][ 'text'] = f'Слишком много городов, {user_name.title()}!'
def handle_dialog(res, req): user_id = req['session']['user_id'] if req['session']['new']: res['response']['text'] = \ 'Привет! Я могу показать город или сказать расстояние между городами!' return # Получаем города из нашего cities = get_cities(req) if not cities: res['response']['text'] = 'Вы не написали название ни одного города!' elif len(cities) == 1: res['response']['text'] = 'Этот город в стране - ' + \ get_country(cities[0]) elif len(cities) == 2: distance = get_distance(get_coordinates(cities[0]), get_coordinates(cities[1])) res['response']['text'] = 'Расстояние между этими городами: ' + \ str(round(distance)) + ' км.' else: res['response']['text'] = 'Слишком много городов!'
def play_game(res, req): user_id = req['session']['user_id'] attempt = sessionStorage[user_id]['attempt'] if attempt == 1: city = random.choice(list(cities)) while city in sessionStorage[user_id]['guessed_cities']: city = random.choice(list(cities)) sessionStorage[user_id]['city'] = city res['response']['card'] = {} res['response']['card']['type'] = 'BigImage' res['response']['card']['title'] = 'Что это за город?' res['response']['card']['image_id'] = cities[city][attempt - 1] res['response']['text'] = 'Тогда сыграем!' elif not sessionStorage[user_id]['city_answered']: city = sessionStorage[user_id]['city'] if get_city(req) == city: res['response']['text'] = 'Правильно! А в какой стране этот город?' sessionStorage[user_id]['attempt'] = 2 sessionStorage[user_id]['guessed_cities'].append(city) sessionStorage[user_id]['city_answered'] = True return else: if attempt == 3: res['response'][ 'text'] = f'Вы пытались. Это {city.title()}. Сыграем ещё?' sessionStorage[user_id]['game_started'] = False sessionStorage[user_id]['attempt'] = 1 sessionStorage[user_id]['guessed_cities'].append(city) return else: res['response']['card'] = {} res['response']['card']['type'] = 'BigImage' res['response']['card'][ 'title'] = 'Неправильно. Вот тебе дополнительное фото' res['response']['card']['image_id'] = cities[city][attempt - 1] res['response']['text'] = 'А вот и не угадал!' else: if get_country(sessionStorage[user_id]['guessed_cities'] [-1]) in req['request']['command']: res['response']['text'] = 'Правильно! Сыграем ещё?' sessionStorage[user_id]['game_started'] = False res['response']['buttons'] = [{ 'title': 'Да', 'hide': True }, { 'title': 'Нет', 'hide': True }, { 'title': 'Покажи город на карте', 'url': f"https://yandex.ru/maps/?mode=search&text={sessionStorage[user_id]['guessed_cities'][-1]}", 'hide': True }] return else: if attempt == 3: sessionStorage[user_id]['attempt'] = 1 sessionStorage[user_id]['game_started'] = False res['response']['text'] = 'Вы пытались. Это ' \ f"{get_country(sessionStorage[user_id]['guessed_cities'][-1])}. Сыграем ещё?" return else: res['response']['text'] = 'Попробуйте ещё!' sessionStorage[user_id]['attempt'] += 1
def handle_dialog(res, req): user_id = req['session']['user_id'] # если пользователь новый if req['session']['new']: res['response']['text'] = 'Привет! Назови свое имя!' sessionStorage[user_id] = { 'first_name': None } return # если пользователь не новый if sessionStorage[user_id]['first_name'] is None: first_name = get_first_name(req) # если не нашли if first_name is None: res['response']['text'] = \ 'Не расслышала имя. Повтори, пожалуйста!' # если нашли else: sessionStorage[user_id]['first_name'] = first_name res['response'][ 'text'] = 'Приятно познакомиться, ' + first_name.title() + '. Я - Алиса. Я могу показать город или сказать расстояние между городами!' res['response']['buttons'] = [ { 'title': city.title(), 'hide': True } for city in cities_ ] # если пользователь уже что-то написал else: # ищем города в сообщении от пользователя cities = get_cities(req) if not cities: res['response']['text'] = 'Ты не написал название ни одного города!' elif len(cities) == 1: if cities[0] in cities_: if 'подробнее' in req['request']['original_utterance'].lower() or 'хочу больше информации' in req['request']['original_utterance'].lower(): res['response']['text'] = 'https://ru.wikipedia.org/wiki/' + cities[0] else: res['response']['card'] = {} res['response']['card']['type'] = 'BigImage' res['response']['card']['title'] = 'Этот город я знаю. Он в стране ' + get_country(cities[0]) + '.' res['response']['card']['image_id'] = random.choice(cities_[cities[0]]) res['response']['text'] = 'Этот город я знаю.' else: res['response']['text'] = 'Этот город я знаю. Он в стране ' + get_country(cities[0]) + '.' elif len(cities) == 2: distance = get_distance(get_coordinates( cities[0]), get_coordinates(cities[1])) res['response']['text'] = 'Расстояние между этими городами: ' + str(round(distance)) + ' км.' else: res['response']['text'] = 'Слишком много городов!' res['response']['buttons'] = [ { 'title': city.title(), 'hide': True } for city in cities_ ]
def handle_dialog(res, req): user_id = req['session']['user_id'] nothing_message = [ "В вашем сообщении не было указано ничего того, что я умею. Может попробуйте еще раз? Если нужна помощь, то напишите 'помощь' или 'документация'", "Извините, вы что спросили? Может попробуйте еще раз? Если нужна помощь, то напишите 'помощь' или 'документация'", "Возможно вам нужна помощь? Напишите 'помощь' или 'документация'", "Хмм... забавно", "Может уже приступим к картам?" ] # Ключевые слова help_words = ['помощь', 'документация'] map_type_words = ['спутник', 'карта', 'гибрид'] search_org_words = ['найди организацию', 'где находится организация'] traffic_words = ['трафик', 'пробки'] original_utterance = req['request']['original_utterance'].lower() # Если пользователь новый, то предоставляем ему информацию о навыке и просим представиться if req['session']['new']: res['response']['text'] = "Здравствуйте, данный навык позволяет получить некоторые геоданные, " \ "используя API Яндекс.Карт, а также фотографии городов. " \ "Напишите 'помощь' или 'документация', " \ "чтобы получить полную информацию о работе навыка. " \ "Но для начала, прошу вас представиться." sessionStorage[user_id] = {'first_name': None, 'image_id': []} return if sessionStorage[user_id]['first_name'] is None: # Получаем первую именнованую сущность first_name = get_first_name(req) # Если не обнаружено - просим повторить if first_name is None: res['response']['text'] = \ 'Не расслышала имя. Повтори, пожалуйста!' # Иначе записываем имя в словарь и обращаемся к пользователю по имени else: sessionStorage[user_id]['first_name'] = first_name res['response'][ 'text'] = 'Приятно познакомиться, ' + first_name.title( ) + '. Я - Алиса. Чем займемся?' return if original_utterance in help_words: res['response']['text'] = "Здравствуйте, " + sessionStorage[user_id][ 'first_name'].title() + " , вас приветствует навык 'pass'. " \ "Данный навык работает с API Яндекс.Карт. " \ "\n\nПо умолчаниию тип карты, возвращаемой навыком, 'карта', но если в вашем сообщении " \ "содержатся слова: 'карта', 'гибрид', 'спутник' - " \ "то навык это учтет и вернет карту соответствующего типа" \ "\n\nВведите 'найди организацию' или 'где находится организация', " \ "а затем название организации, разделив слова помощью ' - ' или ': '. " \ "\nПример: 'Найди организацию - Аптека'" \ "\n\nЕсли в вашем сообщении содержится город и слова: 'пробка(и)', 'трафик', " \ "то навык вернет карту, показыващую трафик в данном городе." \ "\n\nЕсли в вашем сообщении содержится один город, " \ "то навык вернет карту с городом и расскажет о стране, в которой находится город." \ "\n\nЕсли в сообщении содержится два города, " \ "то навык вернет карту с городами и дистанцию между ними" \ "\n\nЕсли же в сообщении содержится несколько топонимов и слово 'покажи', то навык просто вернет карту, " \ "на которой отмечены данные топонимы." return # Узнаем тип карты map_type = 'карта' for word in req['request']['nlu']['tokens']: if word in map_type_words: map_type = word # Получаем список всех городов во фразе cities = get_cities(req) if cities: # Если город один, то называем страну, в которой он находится if len(cities) == 1 and not ('покажи' in req['request']['nlu']['tokens']): for word in req['request']['nlu']['tokens']: if word in traffic_words: try: image = get_traffic(cities[0], map_type) image_id = post_image(image) sessionStorage[user_id]['image_id'].append(image_id) # Ответ в виде карты города с трафиком res['response']['text'] = 'Трафик в городе' + str( cities[0]).title() res['response']['card'] = {} res['response']['card']['type'] = 'BigImage' res['response']['card']['image_id'] = image_id res['response']['card'][ 'title'] = 'Трафик в городе ' + str( cities[0]).title() except Exception as e: res['response'][ 'text'] = ':/ Что-то пошло не так. Ошибка: ' + str( e) finally: return try: # Получаем карту города и загружаем её на Яндекс.Диалоги image, country = get_country(cities[0], map_type) image_id = post_image(image) sessionStorage[user_id]['image_id'].append(image_id) res['response']['text'] = 'Этот город в стране - ' + country res['response']['card'] = {} res['response']['card']['type'] = 'BigImage' res['response']['card'][ 'title'] = 'Этот город в стране - ' + country res['response']['card']['image_id'] = image_id except Exception as e: res['response'][ 'text'] = ':/ Что-то пошло не так. Ошибка: ' + str(e) finally: return # Если же во фразе два города, то вычисляем расстояние между городами и отмечаем их на карте elif len(cities) == 2 and not ('покажи' in req['request']['nlu']['tokens']): try: # Получаем карту с городами и расстояние между ними, # загружаем фрагмент карты на Яндекс.Диалоги и получаем id изображения image, distance = get_distance_on_map(cities[0], cities[1], map_type) image_id = post_image(image) sessionStorage[user_id]['image_id'].append(image_id) # Ответ в виде изображения карты с двумя городами res['response'][ 'text'] = 'Расстояние между этими городами: ' + str( distance) + ' км.' res['response']['card'] = {} res['response']['card']['type'] = 'BigImage' res['response']['card'][ 'title'] = 'Расстояние между этими городами: ' + str( distance) + ' км.' res['response']['card']['image_id'] = image_id except Exception as e: res['response'][ 'text'] = ':/ Что-то пошло не так. Ошибка: ' + str(e) finally: return # Проверяем вхождение ключевого поискового слова в фразу splitting = False if ' - ' in original_utterance: splitter = ' - ' splitting = True elif ': ' in original_utterance: splitter = ': ' splitting = True if splitting: split_phrase = original_utterance.split(splitter) if split_phrase[0] in search_org_words: try: image, org_info = search_organization(split_phrase[-1], map_type) image_id = post_image(image) sessionStorage[user_id]['image_id'].append(image_id) # Формируем список категорий, чтобы отобразить их в виде списка categories = [' Категории'] for category in org_info['categories']: categories.append(category) # Текст ответа text = 'Название организации: {}\nАдрес: {}\nURL: {}\n' \ 'Часы работы организации: {}\nКатегория: {}'.format(org_info['org_name'], org_info['org_address'], org_info['url'], org_info['categories'], org_info['hours']) # Ответ в виде изображения карты с отмеченной организацией res['response']['text'] = text res['response']['card'] = {} res['response']['card']['type'] = 'BigImage' res['response']['card']['image_id'] = image_id res['response']['card']['title'] = org_info['org_name'] except Exception as e: res['response'][ 'text'] = ':/ Ошибка в запросе. Попробуйте указать организацию точнее. Ошибка: ' + str( e) finally: return toponyms = get_all_toponyms(req) if toponyms and 'покажи' in req['request']['nlu']['tokens']: try: image = show_on_map(toponyms, map_type) image_id = post_image(image) sessionStorage[user_id]['image_id'].append(image_id) res['response'][ 'text'] = 'Карта со всеми топонимами, указанными в вашем сообщении' res['response']['card'] = {} res['response']['card']['type'] = 'BigImage' res['response']['card']['image_id'] = image_id res['response']['card'][ 'title'] = 'Карта со всеми топонимами, указанными в вашем сообщении' except Exception as e: res['response']['text'] = ':/ Что-то пошло не так. Ошибка: ' + str( e) finally: return else: res['response']['text'] = choice(nothing_message)
def play_game(res, req): user_id = req['session']['user_id'] first_name = sessionStorage[user_id]['first_name'].title() attempt = sessionStorage[user_id]['attempt'] if attempt == 1: # если попытка первая, то случайным образом выбираем город для гадания city = random.choice(list(cities)) # выбираем его до тех пор пока не выбираем город, которого нет в sessionStorage[user_id]['guessed_cities'] while city in sessionStorage[user_id]['guessed_cities']: city = random.choice(list(cities)) # записываем город в информацию о пользователе sessionStorage[user_id]['city'] = city # добавляем в ответ картинку res['response']['card'] = {} res['response']['card']['type'] = 'BigImage' res['response']['card']['title'] = f'Что это за город, {first_name}?' res['response']['card']['image_id'] = cities[city][attempt - 1] res['response']['text'] = f'Тогда сыграем, {first_name}!' else: # сюда попадаем, если попытка отгадать не первая city = sessionStorage[user_id]['city'] country = get_country(city.title()).lower() # если город уже отгадан и мы ждем страну if city in sessionStorage[user_id]['guessed_cities']: if country in req['request']['nlu']['tokens']: res['response'][ 'text'] = f'Правльно, {first_name}! Сыграем еще?' else: res['response'][ 'text'] = f'{first_name}, нет, {city.title()} находится в {country.capitalize()}. Сыграем еще?' res['response']['buttons'].append({'title': 'Да', 'hide': True}) res['response']['buttons'].append({'title': 'Нет', 'hide': True}) res['response']['buttons'].append({ 'title': 'Показать этот город на карте', 'url': f'https://yandex.ru/maps/?mode=search&text={city.title()}', 'hide': True }) sessionStorage[user_id]['game_started'] = False return if get_city(req) == city: # если да, то добавляем город к sessionStorage[user_id]['guessed_cities'] и # отправляем пользователя на второй круг. Обратите внимание на этот шаг на схеме. res['response'][ 'text'] = f'Правильно, {first_name}! А в какой стране этот город?' sessionStorage[user_id]['guessed_cities'].append(city) return else: # если нет if attempt == 3: # если попытка третья, то значит, что все картинки мы показали. # В этом случае говорим ответ пользователю, # добавляем город к sessionStorage[user_id]['guessed_cities'] и отправляем его на второй круг. # Обратите внимание на этот шаг на схеме. res['response'][ 'text'] = f'{first_name}, вы пытались. Это {city.title()}. Сыграем ещё?' sessionStorage[user_id]['game_started'] = False sessionStorage[user_id]['guessed_cities'].append(city) return else: # иначе показываем следующую картинку res['response']['card'] = {} res['response']['card']['type'] = 'BigImage' res['response']['card'][ 'title'] = f'{first_name}, неправильно. Вот тебе дополнительное фото' res['response']['card']['image_id'] = cities[city][attempt - 1] res['response']['text'] = 'А вот и не угадал!' # увеличиваем номер попытки доля следующего шага sessionStorage[user_id]['attempt'] += 1
def handle_dialog(res, req): global photos user_id = req['session']['user_id'] # если пользователь новый, то просим его представиться. if req['session']['new']: res['response']['card'] = {} res['response']['card']['type'] = 'BigImage' res['response']['card']['title'] = 'Привет! Я Алиса.Гид,'\ + ' а тебя как зовут?' res['response']['card']['image_id'] = photos['alica'] # текст если нету экрана res['response']['text'] = 'Привет! Я Алиса-Гид,'\ + ' а тебя как зовут?' # создаём словарь в который в будущем положим имя пользователя sessionStorage[user_id] = {'first_name': None} return # если пользователь не новый, то попадаем сюда. # если поле имени пустое, то это говорит о том, # что пользователь ещё не представился. if sessionStorage[user_id]['first_name'] is None: # в последнем его сообщение ищем имя. first_name = get_first_name(req) # если не нашли, то сообщаем пользователю что не расслышали. if first_name is None: res['response']['text'] = \ 'Не расслышала имя. Повтори, пожалуйста!' # если нашли, то приветствуем пользователя else: sessionStorage[user_id]['first_name'] = first_name res['response'][ 'text'] = 'Приятно познакомиться, ' + first_name.title()\ + '.\nВот что я умею:\n1. Играть в горо'\ + 'да (Просто скажите: "Давай сыграем в города")\n'\ + '2. Найти точное расстаяние между городами '\ + '(Просто скажите: "Отмерь расстояние")\n'\ + '3. Найти в какой стране город '\ + '(Просто скажите: "В какой стране город?")\n'\ + '4. Перевести на любой язык '\ + '(Просто скажите: "Перевод")\n'\ + '5. Определить язык '\ + '(Просто скажите: "Определи язык")\n'\ + '6. Произвести поиск '\ + '(Просто скажите: "Поиск")' else: # преобразовываем все нужные переменные в глобальные global city_game global used_cities global cities global distance_city_game global country_game global trans_lg global language global translate_lg global search_lg global detect_lg global ya_serch global happ global hello # ИГРА В ГОРОДА if 'давай сыграем в города' in req['request']['command'].lower(): city_game = [True, 'а'] # фотография Алисы с тайтлами res['response']['card'] = {} res['response']['card']['type'] = 'BigImage' res['response']['card']['title'] = '*Чтобы прекратить игру напиш'\ + 'ите Хватит* Я начну, Москв'\ + 'а - тебе на "а"' res['response']['card']['image_id'] = photos['alica_city_game'] # текст если нету экрана res['response']['text'] = '*Чтобы прекратить игру напишите Хвати'\ + 'т* Я начну, Москва - тебе на "а"' res['response']['buttons'] = [{'title': 'Хватит', 'hide': True}] elif city_game[0] is True: if 'где это' in req['request']['command'].lower(): res['response']['text'] = 'Это замечательное место. Ваш ход...' res['response']['buttons'] = [{ 'title': 'Хватит', 'hide': True }] elif 'хватит' in req['request']['command'].lower(): res['response']['text'] = 'С тобой было приятно играть!\n'\ + '-Если хочешь узнать, что я могу,'\ + ' напиши: "Что ты можешь?" ' city_game = [False, ''] used_cities = [] elif sorted(cities) == sorted(used_cities): res['response']['text'] = 'С тобой приятно играть, но я устал'\ + 'а!\n-Если хочешь узнать, что '\ + 'я могу, напиши: "Что ты можешь?"' city_game = [False, ''] used_cities = [] elif city_game[1] == req['request']['command'].lower()[0]: if req['request']['command'].lower().title() in used_cities: res['response']['text'] = 'Повторяться нельзя!\nТы проиг'\ + 'рал. Но ничего в следующий раз '\ + 'обязательно всё получится!\n'\ + '-Если хочешь узнать, что я могу,'\ + ' напиши: "Что ты можешь?" ' city_game = [False, ''] used_cities = [] elif req['request']['command'].lower().title() not in cities: res['response']['text'] = 'Такого города я не знаю!\nКа'\ + 'жется ты проиграл. Но ничего в с'\ + 'ледующий раз обязательно всё пол'\ + 'учится!\n-Если хочешь узнать, чт'\ + 'о я могу, напиши:"Что ты можешь?"' city_game = [False, ''] used_cities = [] else: word = req['request']['command'].lower().title() used_cities.append(word) if req['request']['command'].lower()[-1] != 'ь'\ and req['request']['command'].lower()[-1] != 'ъ'\ and req['request']['command'].lower()[-1] != 'ы': city_game[1] = req['request']['command'].lower()[-1] else: city_game[1] = req['request']['command'].lower()[-2] for i in cities: if i[0].lower() == city_game[1].lower()\ and i not in used_cities: used_cities.append(i) res['response']['text'] = str(i) city_n = str(i) if i[-1] != 'ь'\ and i[-1] != 'ъ'\ and i[-1] != 'ы': city_game[1] = i[-1] else: city_game[1] = i[-2] break url = 'https://yandex.ru/maps/?ll=86.026101%2C46.958498&m'\ + 'ode=search&sll=52.395874%2C55.743583&sspn=0.3137'\ + '97%2C0.105549&text={}&z=2.7'.format(city_n) res['response']['buttons'] = [{ 'title': 'Где это?', 'hide': True, 'url': url }, { 'title': 'Хватит', 'hide': True }] else: res['response']['text'] = 'Упс... Кажется ты проиграл\n'\ + 'Но ничего в следующий раз '\ + 'обязательно всё получится!\n'\ + '-Если хочешь узнать, что я могу,'\ + ' напиши: "Что ты можешь?" ' city_game = [False, ''] used_cities = [] # НАХОЖДЕНИЕ РАССТОЯНИЯ ГОРОДОВ elif 'отмерь расстояние' in req['request']['command'].lower(): res['response']['card'] = {} res['response']['card']['type'] = 'BigImage' res['response']['card']['title'] = '*Чтобы прекратить напишите '\ + 'Хватит* Каких двух городо'\ + 'в нужно узнать расстояние'\ + '? (Пример: Москва Питер)' name_photo = 'alica_distance_city_game' res['response']['card']['image_id'] = photos[name_photo] distance_city_game = True # текст если нету экрана res['response']['text'] = '*Чтобы прекратить напишите Хватит*'\ + '\nКаких двух городов нужно узнать'\ + ' расстояние?\n (Пример: Москва Питер)' res['response']['buttons'] = [{'title': 'Хватит', 'hide': True}] elif distance_city_game is True: cities_d = get_cities(req) if 'хватит' in req['request']['command'].lower(): res['response']['text'] = 'Закончили!\n'\ + '-Если хочешь узнать, что я могу,'\ + ' напиши: "Что ты можешь?" ' distance_city_game = False elif len(cities_d) == 0: res['response']['text'] = 'Ты не написал название'\ + ' не одного города!' res['response']['buttons'] = [{ 'title': 'Хватит', 'hide': True }] elif len(cities_d) == 2: distance = get_distance(get_coordinates(cities_d[0]), get_coordinates(cities_d[1])) res['response']['text'] = 'Расстояние между этими городами: '\ + str(round(distance)) + ' км.\n'\ + '-Если хочешь узнать, что я могу,'\ + ' напиши: "Что ты можешь?" ' distance_city_game = False else: res['response']['text'] = 'Не то количество городов!\n'\ + 'Попробуй ещё раз.' res['response']['buttons'] = [{ 'title': 'Хватит', 'hide': True }] # В КАКОЙ СТРАНЕ ГОРОД elif 'в какой стране город' in req['request']['command'].lower(): country_game = True res['response']['card'] = {} res['response']['card']['type'] = 'BigImage' res['response']['card']['title'] = '*Чтобы прекратить напишите '\ + 'Хватит* Какого города нуж'\ + 'но узнать страну?' res['response']['card']['image_id'] = photos['alica_country_game'] # текст если нету экрана res['response']['text'] = '*Чтобы прекратить напишите Хватит*'\ + '\nКакого города нужно узнать страну?' res['response']['buttons'] = [{'title': 'Хватит', 'hide': True}] elif country_game is True: cities_d = get_cities(req) if 'хватит' in req['request']['command'].lower(): res['response']['text'] = 'Закончили!\n'\ + '-Если хочешь узнать, что я могу,'\ + ' напиши: "Что ты можешь?" ' country_game = False elif len(cities_d) == 0: res['response']['text'] = 'Ты не написал название города!' res['response']['buttons'] = [{ 'title': 'Хватит', 'hide': True }] elif len(cities_d) == 1: res['response']['text'] = 'Этот город в стране - '\ + get_country(cities_d[0])\ + '\n-Если хочешь узнать, что я '\ + 'могу, напиши: "Что ты можешь?" ' country_game = False else: res['response']['text'] = 'Слишком много городов!\n'\ + 'Попробуй ещё раз.' res['response']['buttons'] = [{ 'title': 'Хватит', 'hide': True }] # ПЕРЕВОДЧИК elif 'перевод' == req['request']['command'].lower(): trans_lg = True language = '' res['response']['card'] = {} res['response']['card']['type'] = 'BigImage' res['response']['card']['title'] = '*Чтобы прекратить напишите '\ + 'Хватит* На какой язык пер'\ + 'евести? Если вы не знаете'\ + ' язык в какой-то стране, '\ + 'напиши страну, я помогу!' res['response']['card']['image_id'] = photos['alica_trans_lg'] # текст если нету экрана res['response']['text'] = '*Чтобы прекратить напишите Хватит*'\ + '\nНа какой язык вы хотите перевести?'\ + '\nЕсли вы не знаете язык в какой-то '\ + 'стране, напиши страну, я тебе помогу!' res['response']['buttons'] = [{'title': 'Хватит', 'hide': True}] elif trans_lg is True: word = req['request']['command'].lower().strip().title() if 'хватит' in req['request']['command'].lower(): res['response']['text'] = 'Закончили!\n'\ + '-Если хочешь узнать, что я могу,'\ + ' напиши: "Что ты можешь?" ' trans_lg = False elif word in count_lg.COUNTRY_LG: ans = req['request']['command'].lower().strip().title() ans = count_lg.COUNTRY_LG[ans] ans = count_lg.SIM_LG[ans] language = count_lg.LG_SIM[ans] res['response']['text'] = 'Я определила язык, это - ' + ans\ + '\nЧто вы хотите перевести?' res['response']['buttons'] = [{ 'title': 'Хватит', 'hide': True }] elif req['request']['command'].lower().strip() in count_lg.LG_SIM: res['response']['text'] = 'Что вы хотите перевести?' ans = req['request']['command'].lower().strip() language = count_lg.LG_SIM[ans] res['response']['buttons'] = [{ 'title': 'Хватит', 'hide': True }] elif language == '': res['response']['text'] = 'Не понимаю! Попробуйте ещё раз...' res['response']['buttons'] = [{ 'title': 'Хватит', 'hide': True }] else: text = str(req['request']['command']) res['response']['text'] = 'Перевод: ' + str( translate_lg(text, language)) res['response']['buttons'] = [{ 'title': 'Хватит', 'hide': True }] # ОПРЕДЕЛЕНИЕ ЯЗЫКА elif 'определи язык' == req['request']['command'].lower(): search_lg = True res['response']['card'] = {} res['response']['card']['type'] = 'BigImage' res['response']['card']['title'] = '*Чтобы прекратить напишите '\ + 'Хватит* Напишите что-нибу'\ + 'дь, а я определю, что за'\ + ' язык!' res['response']['card']['image_id'] = photos['alica_search_lg'] # текст если нету экрана res['response']['text'] = '*Чтобы прекратить напишите Хватит*'\ + '\nНапишите что-нибудь, '\ + 'а я определю, что за язык!' res['response']['buttons'] = [{'title': 'Хватит', 'hide': True}] elif search_lg: if 'хватит' in req['request']['command'].lower(): res['response']['text'] = 'Закончили!\n'\ + '-Если хочешь узнать, что я могу,'\ + ' напиши: "Что ты можешь?" ' search_lg = False else: text = str(req['request']['command']) ans = detect_lg(text) ans = count_lg.SIM_LG[ans] res['response']['text'] = 'Я знаю! Это -' + ans\ + '\nНапиши что-нибудь ещё!' res['response']['buttons'] = [{ 'title': 'Хватит', 'hide': True }] # ПОИСК elif 'поиск' == req['request']['command'].lower(): ya_serch = True res['response']['card'] = {} res['response']['card']['type'] = 'BigImage' res['response']['card']['title'] = '*Чтобы прекратить напишите'\ + ' Хватит* Напишите что ну'\ + 'жно найти, после нажмите'\ + ' кнопку "Искать"!' res['response']['card']['image_id'] = photos['alica_ya_serch'] # текст если нету экрана res['response']['text'] = '*Чтобы прекратить напишите Хватит*'\ + '\nНапишите что нужно найти, '\ + 'после нажмите кнопку "Искать"!' res['response']['buttons'] = [{'title': 'Хватит', 'hide': True}] elif ya_serch: if 'хватит' in req['request']['command'].lower(): res['response']['text'] = 'Закончили искать!\n'\ + '-Если хочешь узнать, что я могу,'\ + ' напиши: "Что ты можешь?" ' ya_serch = False elif 'нет' == req['request']['command'].lower(): res['response']['text'] = 'Попробуйте искать по другому'\ + ' запросу...' res['response']['buttons'] = [{ 'title': 'Хватит', 'hide': True }] elif 'да' == req['request']['command'].lower(): res['response']['text'] = 'Отлично!\n'\ + '-Если хочешь узнать, что я могу,'\ + ' напиши: "Что ты можешь?" ' ya_serch = False elif 'искать' == req['request']['command'].lower(): res['response']['text'] = 'Нашли что хотели?' res['response']['buttons'] = [{ 'title': 'Да', 'hide': True }, { 'title': 'Нет', 'hide': True }, { 'title': 'Хватит', 'hide': True }] else: ans = '%20'.join(req['request']['command'].split()) url = 'https://yandex.ru/search/?text={}&lr=236'.format(ans) res['response']['buttons'] = [{ 'title': 'Искать', 'hide': True, 'url': url }, { 'title': 'Хватит', 'hide': True }] res['response']['text'] = 'Произвожу поиск...' # СПОНТАННОЕ ПРИВЕТСТВИЕ elif 'привет' == req['request']['command'].lower()\ or 'здравствуй' == req['request']['command'].lower()\ or 'здравствуйте' == req['request']['command'].lower()\ or 'хай' == req['request']['command'].lower()\ or 'хеллоу' == req['request']['command'].lower(): answer = str(random.choice(hello)) res['response']['text'] = answer # СПОНТАННО СТРОСИЛИ КАК ДЕЛА elif 'как дела?' in req['request']['command'].lower()\ or 'как дела' in req['request']['command'].lower()\ or 'как у тебя дела?' in req['request']['command'].lower()\ or 'как у тебя дела' in req['request']['command'].lower(): answer = str(random.choice(happ)) res['response']['text'] = answer # ЕСЛИ НЕТ ПОДХОДЯЩЕГО НАВЫКА ИЛИ ОТВЕТА НА ЗАПРОС else: res['response']['text'] = 'Я могу:\n1. Играть в города (Просто'\ + ' скажите: "Давай сыграем в города'\ + '")\n2. Найти точное расстаяние ме'\ + 'жду городами (Просто скажите: "От'\ + 'мерь расстояние")\n3. Найти в как'\ + 'ой стране город (Просто скажите: '\ + '"В какой стране город?")\n4. Пере'\ + 'вести на любой язык (Просто скажи'\ + 'те: "Перевод")\n5. Определить язы'\ + 'к (Просто скажите: "Определи язык'\ + '")\n6. Произвести поиск (Просто с'\ + 'кажите: "Поиск")'