def ingredients_set_all_stock(): error = sql_request("UPDATE ingredients SET stock = TRUE") if error: return ask(SqlErrorMessage(error)) else: return ask( "Super! J'ai noté que vous avez tous vos ingrédients en stock.")
def when_eaten(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: result, error = get_from_sql( "SELECT strftime('%s','now') - strftime('%s',last_eat) from Plats WHERE name = ?", (plat, )) if error: return ask(SqlErrorMessage(error)) else: days = result[0][0] / 86400 if days < 0.7: return ask( "Vous avez mangé " + plat + " pour la dernière fois aujourd'hui. Autre chose ?") else: return ask("Vous avez mangé " + plat + " pour la dernière fois il y a " + str(round(days)) + " jours. Autre chose ?") else: return ask("Le plat " + plat + " n'est pas enregistré. Essayez autre chose.")
def add_ingredient(ingredient): plat = context_manager.get_param("current_plat", "name") result, error = get_from_sql( "SELECT ingredients from Plats WHERE name = ?", (plat, )) if error: return ask(SqlErrorMessage(error)) else: brut_ingredients = result[0][0] ingredients = brut_ingredients.split("|") if ingredient in ingredients: return ask("Cet ingrédient est déjà ajouté. Essayez autre chose.") else: if brut_ingredients == "": new_ingredients = ingredient else: new_ingredients = brut_ingredients + "|" + ingredient error = sql_request( "UPDATE Plats SET ingredients = ? WHERE name = ?", (new_ingredients, plat)) error = sql_request( "INSERT OR IGNORE INTO ingredients (name) VALUES (?)", (ingredient, )) if error: return ask(SqlErrorMessage(error)) else: return ask("OK, un autre ingrédient ?")
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)
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)
def r_trendingposts(CTG, Tag): global posts if (Tag != '') or ( CTG != 'trending' ): # If a certain tag is specified or another category -posts- will be reloaded into the top 8 trending posts of that tag posts = eval('s.get_discussions_by_' + CTG)({"tag": Tag, "limit": "8"}) if Tag == '': Tag = 'all tags' # To keep a proper resp statment even when no tag is specified if CTG == 'created': resp = ask( ('Here are the newest posts in %s') % (Tag)).build_carousel() else: resp = ask(('Here are the top %s posts in %s') % (CTG, Tag)).build_carousel() # To make a new carousel for i in range(8): # Add each post to the carousel try: resp.add_item( posts[i]['title'], key=( str(i) ), # This key will be used if the user chooses a certain post img_url=getpostimg(i)) except IndexError: # If the available posts are less than 8 (mostly promoted ones) break return resp
def retrieve_employees_places(): if request.headers['Content-Type'] != "application/json; charset=UTF-8": print(request.headers['Content-Type']) return jsonify(res='error'), 400 baseUrl = "http://leow.tk" apiUrl = baseUrl + "/" + "employees_position" result = requests.get(apiUrl) if result.status_code != 200: speech = "職員が一人も見つかりませんでした" return ask(speech) employees = result.json() logging.debug("{}".format(employees)) places = dict() for employee in employees: if employee["position"] not in places: places[employee["position"]] = [employee["family_name"]] continue places[employee["position"]].append(employee["family_name"]) # print(places.keys()) speech = "" for place, all_employees in places.items(): speech += place + "にいるのは" logging.debug(place, all_employees) for employee in all_employees: speech += "," + employee + "さん" speech += ". " speech += "です" return ask(speech)
def r_check(): if sc.access_token == None: # No access token return ask('Error, Please try to connect your account') else: return ask( 'Hello %s ! You can now use commands such as follow, unfollow, mute ...' % sc.me()["name"])
def confirm_transport(answer): if 'n' in answer: return ask( 'I dont think I understood. What transportation do you want to take?' ) else: return ask('Ok, is this going to be a one-way trip or round ticket?')
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 + " ?")
def confirm_category(category_confirmation): category = context_manager.get_param('search_context', 'search_category') print("Confirm-category: category: {}".format(category)) if 'n' in category_confirmation: return ask('I dont think I understood. What do you want to look for?').suggest( 'smartphone', 'laptop', 'bike') else: return ask('OK. What exactly are you looking for?')
def putObject(Object): global inHand if (Object == inHand): ser.write('d') #put down inHand = "Nothing" else: return ask("I am not holding " + str(Object)) time.sleep(3) return ask("The " + str(Object) + " has been put down.")
def talk(self): round = len(self.players[0].history) + 1 opp = self.players[0].name turns = self.turns if opp == '$\phi$': opp = 'phi' elif opp == '$\pi$': opp = 'pi' elif opp == '$e$': opp = 'e' if round == 1: msg = ask( "Starting a {} round match between you and {}. Round 1, would you like to cooperate or defect?" .format(turns, opp)) elif round > 1 and round < turns: move, opp_move = self._last_round_moves() msg = ask( "In round {}, you played {}, {} played {}. Round {}, would you like to cooperate or defect?" .format(round - 1, move, opp, opp_move, round)) elif round == turns: move, opp_move = self._last_round_moves() msg = ask( "In round {}, you played {}, {} played {}. Final round, would you like to cooperate or defect?" .format(round - 1, move, opp, opp_move)) elif round > turns: self.result = list( zip(self.players[0].history, self.players[1].history)) score = self.final_score() winner = self.winner() if winner == False: msg = tell( "End of the match, you scored {}, and {} scored {}, meaning the match is a draw." .format(score[1], opp, score[0])) elif str(winner) == '$\phi$': msg = tell( "End of the match, you scored {}, and {} scored {}, meaning phi is the winner. Better luck next time." .format(score[1], opp, score[0])) elif str(winner) == '$\pi$': msg = tell( "End of the match, you scored {}, and {} scored {}, meaning pi is the winner. Better luck next time." .format(score[1], opp, score[0])) elif str(winner) == '$e$': msg = tell( "End of the match, you scored {}, and {} scored {}, meaning e is the winner. Better luck next time." .format(score[1], opp, score[0])) elif str(winner) == 'you: you': msg = tell( "End of the match, you scored {}, and {} scored {}, meaning you are the winner." .format(score[1], opp, score[0])) else: msg = tell( "End of the match, you scored {}, and {} scored {}, meaning {} is the winner. Better luck next time." .format(score[1], opp, score[0], winner)) return msg
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)
def attempt2(): db_user = SessionLocal() time.sleep(3.4) wiz_db_resp = db_user.query(models.UserQuery).order_by(models.UserQuery.id.desc()).first().wizard_response db_user.close() if(wiz_db_resp== "No Response"): return ask("Sorry, I couldn't find any response to that. Could you please repeat?") else: return ask(str(wiz_db_resp))
def get_meal(): result, error = get_from_sql("SELECT name from Plats") if error: return ask(SqlErrorMessage(error)) else: plats = [] for column in result: plats.append(column[0]) ouput = ", ".join(plats) return ask("Voici la liste des plats: " + ouput)
def get_all_ingredients(): result, error = get_from_sql("SELECT name from ingredients") if error: return ask(SqlErrorMessage(error)) else: plats = [] for column in result: plats.append(column[0]) ouput = ", ".join(plats) return ask("Voici la liste de tous les ingrédients: " + ouput)
def get_calories(product, attr): print(product, attr) if not product or not attr: speech = "I couldn't understand that, please try with another product" return ask(speech) result = getProductAttrByParam(product, attr) #speech = getProductAttrByParam(product, 'calories') speech = att_speech[attr].format(product=product, result=result) return ask(speech)
def r_claim(): try: user = Steemian(sc.me()["name"]) claim_reward_balance = ClaimRewardBalance('account', user.rewards[0], user.rewards[1], user.rewards[2]) sc.broadcast([claim_reward_balance.to_operation_structure()]) return ask('You have sucessfully claimed %s, %s and %s' % (user.rewards[0], user.rewards[1], user.rewards[2])) except: # If the user didn't connect his account return ask('Please connect your account before using this command')
def r_reguser(): try: with open('usernames.json') as old: database = json.load(old) name = {sc.me()['name']: sc.me()['name']} database.update(name) with open('usernames.json', 'w') as new: json.dump(database, new) return ask('Done %s was sucessfully added.' % sc.me()['name']) except: return ask('Please connect your account before using this command')
def r_price(currency): user = Steemian(St_username) if currency == 'steem': # Is used to get the price of STEEM return ask('Steem is now worth $' + str(round(user.steemprice, 2)) + ' according to coinmarketcap.') elif currency == 'sbd': # Is used to get the price of SBD return ask('Steem Dollars is now worth $' + str(round(user.sbdprice, 2)) + ' according to coinmarketcap.') else: return ask('Error! Please try again')
def r_broadcastupvote(yon): try: global percent, posts, Option, votetype vote = Vote(sc.me()['name'], posts[Option]["author"], posts[Option]["permlink"], int(percent)) sc.broadcast([vote.to_operation_structure()]) if votetype == 'upvote': return ask('broadcasting upvote to %s' % posts[Option]['title']) else: return ask('broadcasting downvote to %s' % posts[Option]['title']) except: # If the user didn't connect his account return ask('Please connect your account before using this command')
def r_delegation(number, username): check = eligible_delegation(St_username, number) if check == 'eligible': resp = ask('You can use the link below to delegate using Steemconnect') link = ( "https://steemconnect.com/sign/delegate-vesting-shares?delegator=" + St_username + "&delegatee=" + username + "&vesting_shares=" + str(number) + "%20SP") resp.link_out('Click here', link) return resp else: return ask("Error: " + check) # To show the type of error
def get_meal_eaten(date): result, error = get_from_sql( "SELECT name from Plats WHERE date(last_eat) = date(?)", (date, )) if error: return ask(SqlErrorMessage(error)) else: plats = [] for data in result: plats.append(data[0]) if len(plats) > 0: return ask("Vous avez mangé " + ", ".join(plats)) else: return ask("Aucun plat trouvé pour cette date.")
def endlist(): print("*********WEBHOOK CALL**************", flush=True) if len(listBuy.getProds()) > 0: list_buy = ', '.join(listBuy.getProds()) speech = "Perfecto, tienes en la lista " + list_buy + ". ¿Me dejas que te sugiera algo?. Una amborgesa" else: speech = "No tienes productos en la lista..." resp = ask(speech) print(resp, flush=True) #list_to_buy = [] return ask(speech)
def r_upvote(number, vote): if (int(number) <= 100) and (0 <= int(number)): global percent, votetype votetype = vote if votetype == 'upvote': percent = int(number) return ask('Would you like to confirm this upvote: %s percent' % percent).suggest('Yes', 'No') else: percent = -int(number) return ask('Would you like to confirm this downvote: %s percent' % (-1 * percent)).suggest('Yes', 'No') else: return ask('Please make sure to enter a valid percent')
def get_food(product): context = context_manager.get('await_for_food') if context is None: speech = "sorry, can you please remind me what is your allergy?" return ask(speech) product = context.parameters['product'] allergy = context.parameters['allergan'] #TODO: need to check here what is happening if they have two allergies product = EngineClient.findProductByName(product) allergans_in_product = EngineClient.checkAllergies(product) if allergy in allergans_in_product: speech = "This food is not safe for you" else: speech = "I couldn't find any allergans in this food related to your allergies" return ask(speech)
def say_response(): """Ok so this is a baaaad hack, but basically its reading a really long response. """ global interrupt_counter interrupt_counter += 1 print(interrupt_counter) ## if you interrupt the google home too many times, it will tell you off. if interrupt_counter >= 3: speech = get_random_tell_off() interrupt_counter = 0 return ask("{0}".format(speech)) else: speech = get_random_code() print(speech) return ask("{0}".format(speech))
def count_eaten(plat): result, error = get_from_sql( "SELECT name, number_eat from Plats WHERE name = ?", (plat, )) if error: return ask(SqlErrorMessage(error)) else: exist = False for data in result: exist = True if exist: return ask("Vous avez mangé " + plat + " " + str(result[0][1]) + " fois au total. Autre chose ?") else: return ask("Le plat " + plat + " n'est pas enregistré. Essayez autre chose.")
def oneway_or_round(ticket_type, transport): context_manager.add( ticket_type) # set context for one way/round trip dialogues context_manager.add('departure') speech = 'Cool, what city do you want to leave from for your {} {} trip?'.format( ticket_type, transport) return ask(speech)
def err(option): if option == 'choice': err_msg = "Your response is invalid, I require you cooperate or defect. Which one will it be?" elif option == 'play': err_msg = """That stategy does not exist, you can use any strategy currently in the Axelrod Python library. Take a look if you want I can wait...""" elif option == 'round': err_msg = "You haven`t given me the number of rounds that you want to play. Canceling match. What would you like to do?" return ask(err_msg)
def talk(self): round = len(self.players[0].history) + 1 opp = self.players[0].name turns = self.turns if opp == '$\phi$': opp = 'phi' elif opp == '$\pi$': opp = 'pi' elif opp == '$e$': opp = 'e' if round == 1: msg = ask("Starting a {} round match between you and {}. Round 1, would you like to cooperate or defect?".format(turns, opp)) elif round > 1 and round < turns: move, opp_move = self._last_round_moves() msg = ask("In round {}, you played {}, {} played {}. Round {}, would you like to cooperate or defect?".format(round - 1, move, opp, opp_move, round)) elif round == turns: move, opp_move = self._last_round_moves() msg = ask("In round {}, you played {}, {} played {}. Final round, would you like to cooperate or defect?".format(round - 1, move, opp, opp_move)) elif round > turns: self.result = list(zip(self.players[0].history, self.players[1].history)) score = self.final_score() winner = self.winner() if winner == False: msg = tell("End of the match, you scored {}, and {} scored {}, meaning the match is a draw.".format(score[1], opp, score[0])) elif str(winner) == '$\phi$': msg = tell("End of the match, you scored {}, and {} scored {}, meaning phi is the winner. Better luck next time.".format(score[1], opp, score[0])) elif str(winner) == '$\pi$': msg = tell("End of the match, you scored {}, and {} scored {}, meaning pi is the winner. Better luck next time.".format(score[1], opp, score[0])) elif str(winner) == '$e$': msg = tell("End of the match, you scored {}, and {} scored {}, meaning e is the winner. Better luck next time.".format(score[1], opp, score[0])) elif str(winner) == 'you: you': msg = tell("End of the match, you scored {}, and {} scored {}, meaning you are the winner.".format(score[1], opp, score[0])) else: msg = tell("End of the match, you scored {}, and {} scored {}, meaning {} is the winner. Better luck next time.".format(score[1], opp, score[0], winner)) return msg
def welcome(): welcome_msg = 'Welcome to the Axelrod tournament. Do you want to play a game?' return ask(welcome_msg)
def help_intent(): help_msg = """Using this skill you are able to start a 2 player match against one of 161 different strategies in the Axelrod library. You define how many rounds you want to go for, who you want to challenge, then tell me to cooperate or defect when it is your turn. Why not give a 3 round game against tit for tat a go, or, if your feeling adventurous, try a 23 round game against EvolvedANN. So... what would you like to do?""" return ask(help_msg)