Beispiel #1
0
def hello_world():

    google_data = request
    contextsList = google_data["result"]["contexts"]
    for context in contextsList:
        if context["name"] == "playstart":
                currentTrack = context["parameters"]["currentTrack"]
                break
        else:
                currentTrack = "1"
                continue 

    if currentTrack == "32":
        newTrack = "1"
    else:
        newTrack = str(int(currentTrack) + 1)
   
 
    context_manager.add("playstart")
    context_manager.set('playstart', 'currentTrack', newTrack)
    speech = """
<speak>
Now Playing """ + tracksData[newTrack]["name"] + """ . 
<break time="1000ms"/>
<audio src=" """ + tracksData[newTrack]["url"] + """ ">
    <desc>""" + tracksData[newTrack]["name"] + """</desc>
    Sorry, there is some problem
  </audio>
<break time="1000ms"/>
Would you like to play the quiz now?

</speak>
                """
    return ask(speech)
Beispiel #2
0
def get_allergies(allergan):
    context_manager.set('await_for_food', 'allergy', allergan)
    if not allergan:
        speech = "I couldn't understand that, please repeat"
        return ask(speech)
    speech = "Ok, and what food you would like to check?"
    return ask(speech)
Beispiel #3
0
def store_address(address):
    speech = "Ok, and can I have your name?"

    context_manager.add('delivery-info', lifespan=10)
    context_manager.set('delivery-info', 'address', address)

    return ask(speech)
Beispiel #4
0
def add_meal(plat):
    result, error = get_from_sql("SELECT name from Plats WHERE name = ?",
                                 (plat, ))
    if error:
        return ask(SqlErrorMessage(error))
    else:
        exist = False
        for data in result:
            exist = True
        if exist:
            return ask(
                "Ce plat existe déjà dans votre liste. Essayez autre chose.")
        else:
            #list_ingre = ingredients.split(" et ")
            #final_ingre = "|".join(list_ingre)
            error = sql_request(
                "INSERT INTO Plats (name, ingredients) VALUES (?, '')",
                (plat, ))
            if error:
                return ask(SqlErrorMessage(error))
            else:
                context_manager.add("current_plat")
                context_manager.set("current_plat", "name", plat)
                return ask("D'accord, quel est le premier ingrédient de " +
                           plat + " ?")
Beispiel #5
0
def hello_world():
    google_data = request
    contextsList = google_data["result"]["contexts"]
    for context in contextsList:
        if context["name"] == "playstart":
                currentTrack = context["parameters"]["currentTrack"]
                answerByUser = context["parameters"]["any.original"]
                break
        else:
                currentTrack = "1"
                answerByUser = "******"
                continue 

   
 
    context_manager.add("playstart")
    context_manager.set('playstart', 'currentTrack', currentTrack)
    speech = """
<speak>
Sorry, I could not understand that
<break time="1000ms"/>
Now Playing """ + tracksData[currentTrack]["name"] + """ . 
<break time="1000ms"/>
<audio src=" """ + tracksData[currentTrack]["url"] + """ ">
    <desc>""" + tracksData[currentTrack]["name"] + """</desc>
    Sorry, there is some problem
  </audio>
<break time="1000ms"/>
Would you like to play the quiz now?

</speak>
                """
    return ask(speech)
Beispiel #6
0
def retrieve_employees():
    if request.headers['Content-Type'] != "application/json; charset=UTF-8":
        print(request.headers['Content-Type'])
        return jsonify(res='error'), 400

    position = request.json["result"]["parameters"]["position"]

    baseUrl = "http://leow.tk"
    apiUrl = baseUrl + "/" + position + "/employees"
    result = requests.get(apiUrl)
    if result.status_code != 200:
        speech = position + "はどこなのかがわかりません"
        return ask(speech)

    speech = "エントランスには"
    employees = result.json()
    for employee in employees:
        speech += employee["family_name"] + ","
    number_of_employees = str(len(employees))

    speech += "がいます。"
    context_manager.add('number-of-employees', lifespan=1)
    context_manager.set('number-of-employees', 'num', number_of_employees)
    context_manager.set('number-of-employees', 'employees', employees)
    return ask(speech)
Beispiel #7
0
def hello_world():
    google_data = request
    contextsList = google_data["result"]["contexts"]
    for context in contextsList:
        if context["name"] == "playstart":
                currentTrack = context["parameters"]["currentTrack"]
                break
        else:
                currentTrack = "1"
                continue
    my_context = context_manager.get('playstart', 'currentTrack')
    context_manager.add("playstart")
    context_manager.set('playstart', 'currentTrack', currentTrack)
    if tracksData[currentTrack]["que"] == "X":
            google_data = request
            contextsList = google_data["result"]["contexts"]
            for context in contextsList:
                if context["name"] == "playstart":
                        currentTrack = context["parameters"]["currentTrack"]
                        break
                else:
                        currentTrack = "1"
                        continue 

            if currentTrack == "32":
                newTrack = "1"
            else:
                newTrack = str(int(currentTrack) + 1)
           
         
            context_manager.add("playstart")
            context_manager.set('playstart', 'currentTrack', newTrack)
            speech = """
        <speak>
        There is no question for this song. Now Playing """ + tracksData[newTrack]["name"] + """ . 
        <break time="1000ms"/>
        <audio src=" """ + tracksData[newTrack]["url"] + """ ">
            <desc>""" + tracksData[newTrack]["name"] + """</desc>
            Sorry, there is some problem
          </audio>
        <break time="1000ms"/>
        Would you like to play the quiz now?

        </speak>
                        """
            return ask(speech)
    else:
            speech = """
        <speak>
        Ok, so here is your question,
         """ + tracksData[currentTrack]["que"] +  """. Your options are, """ + tracksData[currentTrack]["optionOne"] +  """ ,
        """ + tracksData[currentTrack]["optionTwo"] +  """ ,
        """ + tracksData[currentTrack]["optionThree"] +  """ , or , 
        """ + tracksData[currentTrack]["optionFour"] +  """ .
        </speak>
                        """
            return ask(speech)
Beispiel #8
0
def prompt_capital_base(quote_currency):
    current_app.logger.debug(f"Setting quote currency as {quote_currency}")
    context_manager.set("strat-config-data", "quote_currency", quote_currency)
    speech = f"How much {quote_currency.upper()} would you like to allocate as the capital base?"

    exchange = context_manager.get("strat-config-data").get("exchange")
    # enqueue base_currency options
    current_app.logger.debug("enqueing for base currencies")
    task.get_available_base_currencies(exchange, quote_currency)
    return ask(speech)
Beispiel #9
0
def hello_world():
    google_data = request
    contextsList = google_data["result"]["contexts"]
    for context in contextsList:
        if context["name"] == "playstart":
                currentTrack = context["parameters"]["currentTrack"]
                answerByUser = context["parameters"]["any.original"]
                break
        else:
                currentTrack = "1"
                answerByUser = "******"
                continue 

    answer = tracksData[currentTrack]["ans"][0]
    if answerByUser == "default answer":
        sOut = "There was some problem in fetching the answer"
 
    elif answerByUser == answer:
        sOut = """
<audio src="https://s3.amazonaws.com/bobthetraincanatech/CHILDREN-cheering+VE+2.mp3"><desc></desc></audio>
<audio src="https://s3.amazonaws.com/bobthetraincanatech/Claping+5Sec.mp3"><desc></desc></audio>
Yes, """ + answer + """ is the correct answer.
"""
    else:
        sOut = """
<audio src="https://s3.amazonaws.com/bobthetraincanatech/sfx_1.wav"><desc></desc></audio>
<audio src="https://s3.amazonaws.com/bobthetraincanatech/sfx_2.wav"><desc></desc></audio>
Oops, the correct answer is, """ + answer
    my_context = context_manager.get('playstart', 'currentTrack')
    if currentTrack == "32":
        newTrack = "1"
    else:
        newTrack = str(int(currentTrack) + 1)
   
 
    context_manager.add("playstart")
    context_manager.set('playstart', 'currentTrack', newTrack)
    speech = """
<speak>
""" + sOut + """

<break time="1000ms"/>
. Now Playing """ + tracksData[newTrack]["name"] + """ . 
<break time="1000ms"/>
<audio src=" """ + tracksData[newTrack]["url"] + """ ">
    <desc>""" + tracksData[newTrack]["name"] + """</desc>
    Sorry, there is some problem
  </audio>
<break time="1000ms"/>
Would you like to play the quiz now?

</speak>
                """
    return ask(speech)
Beispiel #10
0
def respond():
    context_manager.add('dialogue')
    handler = ConversationHandler(conf, logger)
    user_query = request['queryResult']['queryText']

    # restore dialogue
    dialogue = context_manager.get('dialogue').parameters.get('serialized')
    dialogue = deserialize_dialogue(dialogue)

    resp, isend = handler.get_response(dialogue, user_query)
    context_manager.set('dialogue', 'serialized', serialize_dialogue(dialogue))
    return tell(resp)
Beispiel #11
0
def store_phone(
        name,
        address):  # address can be pulled from existing delivery-info context
    speech = """Thanks, {} ... Ok, that's all I need for your delivery info.
        With your address being {}, delivery time should be about 20 minutes.
        So would you like a special or custom pizza?""".format(name, address)

    context_manager.add('delivery-info', lifespan=10)
    context_manager.set('delivery-info', 'name', name)
    context_manager.add('build')

    return ask(speech)
Beispiel #12
0
def prompt_exchange(existing_strategy):
    current_app.logger.debug(f"Building strategy for {existing_strategy}")
    context_manager.set("strat-config-data", "existing_strategy",
                        existing_strategy)
    speech = "Which exchange would you like to trade on?"
    resp = inline_keyboard(dedent(speech))
    for e in build.EXCHANGES:
        resp.add_button(*e)
        current_app.logger.debug("Engqueuing exchange option jobs")
        # enqueue job to be ready when needed
        task.get_exchange_asset_pairs(e[1])
        task.get_exchange_quote_currencies(e[1])

    return resp
Beispiel #13
0
def prompt_quote_currency(exchange):
    current_app.logger.debug(f"Setting exchange as {exchange}")
    context_manager.set("strat-config-data", "exchange", exchange)
    speech = f"""\
    Which currency would you like to use as the quote currency?
    This is the currency you will sell when making a buy order, and recieve when making a sell order.

    You must also allocate an amount of this currency to the strategy as capital base
    This means you must hold the currency on {exchange} for live trading.
    """
    resp = inline_keyboard(dedent(speech))
    quotes = task.get_exchange_quote_currencies(exchange)

    for q in quotes:
        resp.add_button(q.lower(), q)
    return resp
Beispiel #14
0
def prompt_trade_currency(capital_base):
    current_app.logger.debug(f"Setting capital base as {capital_base}")
    context_manager.set("strat-config-data", "captial_base", capital_base)

    speech = "Which asset would you like to trade?"
    resp = inline_keyboard(speech)

    exchange = context_manager.get("strat-config-data").get("exchange")
    quote_currency = context_manager.get("strat-config-data").get(
        "quote_currency")

    options = task.get_available_base_currencies(exchange, quote_currency)

    for o in options:
        resp.add_button(o, o)
    return resp
Beispiel #15
0
def handle_recipes(recipes, participants, recipe_name):

    context_manager.add("make-food", lifespan=LIFESPAN)
    context_manager.set("make-food", "recipes", recipes)
    context_manager.set("make-food", "current_recipe_index", -1)
    context_manager.set("make-food", "participants", participants)
    context_manager.set("make-food", "recipe_name", recipe_name)

    return choose_another()
Beispiel #16
0
def choose_another():
    context = context_manager.get('make-food')
    recipes = context.parameters.get('recipes')
    current_recipe = int(context.parameters.get('current_recipe_index') + 1)
    context_manager.set("make-food", "current_recipe_index", current_recipe)
    recipe_id = int(recipes[current_recipe]['id'])
    if len(recipes) <= current_recipe + 1:
        return tell(
            "Sorry but I don't have any more recipes to make, please ask for another recipe"
        )

    # RECIPE WITH 2 STEPS SECTIONS: recipe_id = 324694
    if not is_recipe_has_single_step_section(recipe_id):
        return choose_another()

    speech = "Do you want to make {choice}?".format(
        choice=recipes[current_recipe]['title'])
    return ask(speech)
Beispiel #17
0
def hello_world():
    google_data = request
    my_context = context_manager.get('testContext', 'param1')
    context_manager.add("playstart")
    context_manager.set('playstart', 'currentTrack', "1")
    speech = """
<speak>
Playing """ + tracksData["1"]["name"] + """ . 
<break time="1000ms"/>
<audio src=" """ + tracksData["1"]["url"] + """ ">
    <desc>""" + tracksData["1"]["name"] + """</desc>
    Sorry, there is some problem
  </audio>
<break time="1000ms"/>
Would you like to play the quiz now?
</speak>
                """
    return ask(speech)
Beispiel #18
0
def hello_world():
    google_data = request
    contextsList = google_data["result"]["contexts"]
    for context in contextsList:
        if context["name"] == "playstart":
                currentTrack = context["parameters"]["currentTrack"]
                break
        else:
                currentTrack = "1"
                continue
    my_context = context_manager.get('playstart', 'currentTrack')
    context_manager.add("playstart")
    context_manager.set('playstart', 'currentTrack', currentTrack)
    if tracksData[currentTrack]["que"] == "X":
            google_data = request
            contextsList = google_data["result"]["contexts"]
            for context in contextsList:
                if context["name"] == "playstart":
                        currentTrack = context["parameters"]["currentTrack"]
                        break
                else:
                        currentTrack = "1"
                        continue 

            speech = """
        <speak>
        <break time="1000ms"/>
        There is no question for this song. Say, play all to play all the songs, or , say , the name of the song you want to play.
        </speak>
                        """
            return ask(speech)


    else:
            speech = """
        <speak>
        Ok, so here is your question,
         """ + tracksData[currentTrack]["que"] +  """ . Your options are,  """ + tracksData[currentTrack]["optionOne"] +  """ ,
        """ + tracksData[currentTrack]["optionTwo"] +  """ ,
        """ + tracksData[currentTrack]["optionThree"] +  """ , or , 
        """ + tracksData[currentTrack]["optionFour"] +  """ .
        </speak>
                        """
            return ask(speech)
Beispiel #19
0
def hello_world():
    google_data = request
    contextsList = google_data["result"]["contexts"]
    for context in contextsList:
        if context["name"] == "playstart":
                currentTrack = context["parameters"]["currentTrack"]
                break
        else:
                currentTrack = "1"
                continue
    answerByUser = google_data["result"]["parameters"]["any1"]

    answer = tracksData[currentTrack]["ans"][0]
    if answerByUser == "default answer":
        sOut = "There was some problem in fetching the answer. "
    elif answerByUser == answer:
        sOut = """
<audio src="https://s3.amazonaws.com/bobthetraincanatech/CHILDREN-cheering+VE+2.mp3"><desc></desc></audio>
<audio src="https://s3.amazonaws.com/bobthetraincanatech/Claping+5Sec.mp3"><desc></desc></audio>
Yes, """ + answer + """ is the correct answer.
"""
    else:
        sOut = """
<audio src="https://s3.amazonaws.com/bobthetraincanatech/sfx_1.wav"><desc></desc></audio>
<audio src="https://s3.amazonaws.com/bobthetraincanatech/sfx_2.wav"><desc></desc></audio>
Oops, the correct answer is, """ + answer
    my_context = context_manager.get('playstart', 'currentTrack')
    if currentTrack == "32":
        newTrack = "1"
    else:
        newTrack = str(int(currentTrack) + 1)
   
 
    context_manager.add("playstart")
    context_manager.set('playstart', 'currentTrack', newTrack)
    speech = """
<speak>
""" + sOut + """

Say, play all, to play all the songs, or , say the name of the song you want to play.
</speak>
                """
    return ask(speech)
Beispiel #20
0
def get_step(step_number):
    print("The step number to get is {}".format(step_number))
    context = context_manager.get('make-food')
    requested_step = step_number
    steps = json.loads(str(context.parameters.get('recipe_steps')))
    if int(requested_step) >= len(steps[0].get("steps")):
        # no more steps
        speech = "You finished the recipe! bonappetit. Can I help with anything else?"
        return ask(speech)
    if int(requested_step) < 0:
        requested_step = requested_step + 1

    context_manager.set('make-food', 'current_step', int(requested_step))
    pre_speach = ""
    if int(requested_step) == 0:
        pre_speach = "I will now tell you how to make this recipe. " \
                     "You can ask for the next, previous or current step. Let's start with the first step! \n"

    return ask(pre_speach +
               steps[0].get("steps")[int(requested_step)].get("step"))
Beispiel #21
0
def modif_ingredient(plat):
    result, error = get_from_sql("SELECT name from Plats WHERE name = ?",
                                 (plat, ))
    if error:
        return ask(SqlErrorMessage(error))
    else:
        exist = False
        for data in result:
            exist = True
        if exist:
            error = sql_request(
                "UPDATE Plats SET ingredients = '' WHERE name = ?", (plat, ))
            if error:
                return ask(SqlErrorMessage(error))
            else:
                context_manager.add("current_plat")
                context_manager.set("current_plat", "name", plat)
                return ask("D'accord, quel est le premier ingrédient de " +
                           plat + " ?")
        else:
            return ask("Le plat " + plat +
                       " n'est pas enregistré. Essayez autre chose.")
Beispiel #22
0
def hello_world():
    google_data = request

    track = google_data["result"]["parameters"]["songsNames"]
    track = track.strip().lower()
    if track.strip() in tracksList:
        for index in range(1, tracksLength + 1):
                data = tracksData[str(index)]
                if data["name"].lower() == track:
                        
                        trackIndex = str(index)
                        break
                else:
                        trackIndex = "99"
                        continue
    if trackIndex == "99":
            speech = """
<speak>
Sorry, I could not find a track by that name. Say , play all to play all the songs, or , say, the name of the song you want to play.
</speak>
                """
    else:               

            my_context = context_manager.get('testContext', 'param1')
            context_manager.add("playstart")
            context_manager.set('playstart', 'currentTrack', trackIndex)
            speech = """
        <speak>
        Playing """ + tracksData[trackIndex]["name"] + """ . 
        <break time="1000ms"/>
        <audio src=" """ + tracksData[trackIndex]["url"] + """ ">
            <desc>""" + tracksData[trackIndex]["name"] + """</desc>
            Sorry, there is some problem
          </audio>
        <break time="1000ms"/>
        Would you like to play the quiz now?
        </speak>
                        """
    return ask(speech)
Beispiel #23
0
def choose_current():
    context = context_manager.get('make-food')
    recipes = context.parameters.get('recipes')
    current_recipe = int(context.parameters.get('current_recipe_index'))
    recipe_id = int(recipes[current_recipe]['id'])
    recipe_info_response = SpoonacularUtils.get_recipe_information(recipe_id)
    recipe_info = json.loads(r'' + recipe_info_response.text + '')
    context_manager.set("make-food", "chosen_recipe", recipe_info)

    amount_coefficient = get_amount_coefficient(
        recipe_info['servings'], context.parameters.get('participants'))
    # steps = re.split('[;.]', recipe_info['instructions'])
    print(recipe_id)
    steps_response = SpoonacularUtils.get_steps(recipe_id)
    context_manager.set("make-food", "recipe_steps", steps_response.text)

    speech = "{random} choice! We found a recipe for {recipe}. The ingredients are: {ingredients}." \
                 " Do you want to start making it?".format(
            random=choice(AWESOME_LIST),
            recipe=recipes[current_recipe]['title'],
            ingredients=get_ingredients_to_speech(recipe_info['extendedIngredients'], amount_coefficient))

    return ask(speech)
Beispiel #24
0
def search_anything(search_item):
    synonyms_list = [['one', 'first'], ['two', 'second'], ['three', 'third'],
                     ['four', 'fourth'], ['five', 'fifth'], ['six', 'sixth'],
                     ['seven', 'seventh'], ['eight'], ['nine'], ['ten']]
    category = context_manager.get_param('search_context', 'search_category')
    logger.debug('search_category: --{}--'.format(category))
    sc = 0
    # TODO - this is crucial part - associating category with right category
    if category == 'bike':
        sc = 3919
    elif category == 'laptop':
        sc = 491
    elif category == 'smartphone':
        sc = 165
    else:
        sc = 0
    # Basic speech/text response
    resp = ask("Let's see what is available")
    searchResult = alleSearch("{}".format(search_item), category=sc, size=5)
    logger.debug("{}".format(searchResult))
    # context_manager.add('search_results', lifespan=5)
    context_manager.set('search_context', 'search_result', searchResult)
    # Create a list with a title
    mylist = resp.build_list('Results')
    i = 0
    for item in searchResult:
        i += 1
        mylist.add_item(
            title="option {}".format(
                synonyms_list[i - 1][0]),  # title sent as query for Actions
            # key sent as query for API.AI
            key='option {}'.format(i),
            img_url=item['zdjęcie'],
            description="{} zł {}".format(item['cena'], item['aukcja']),
            synonyms=synonyms_list[i - 1])

    return mylist
Beispiel #25
0
def review_config(hours):
    current_app.logger.debug(f"Setting hours as {hours}")
    context_manager.set("strat-config-data", "hours", hours)
    context = context_manager.get("strat-config-data")

    strat = context.get("existing_strategy")
    exchange = context.get("exchange").title()
    base_currency = context.get("trade_currency").upper()
    quote_currency = context.get("quote_currency").upper()
    capital_base = context.get("capital_base")
    trade_pair = f"{base_currency}_{quote_currency}".lower()

    speech = """\
        Great, does this look right?

        Strategy: {}
        Exchange: {}
        Trade Pair: {}
        Capital Base: {} ({})
        Run for: {} hours
    """.format(strat, exchange, trade_pair, capital_base, quote_currency,
               hours)

    return ask(dedent(speech)).with_quick_reply("yes", "no")
Beispiel #26
0
def book_hotel(answer):
    context_manager.set('arrival', 'book_hotel', answer)
    if 'y' in answer:
        hotel_speech = 'Ok, your room will be ready for you.'
    else:
        hotel_speech = 'No hotel needed, got it.'
Beispiel #27
0
def get_destination(city):
    context_manager.set('arrival', 'city', city)
    speech = 'Would you like to book a room at the McHotelFace hotel in {}?'.format(
        city)
    return ask(speech)
Beispiel #28
0
def departure_location(city):
    context_manager.set('departure', 'city', city)
    return ask('What day would you like to leave?')
Beispiel #29
0
def departure_date(day):
    context_manager.set('departure', 'day', day)
    context_manager.add('arrival')
    speech = 'Ok would you like to confrim your booking details?'
    return ask(speech)
Beispiel #30
0
def search_category(search_category):
    speech = "Ok, you chose {} right?".format(search_category)
    context_manager.add('search_context', lifespan=3)
    context_manager.set('search_context', 'search_category', search_category) 
    return ask(speech)