def recommendation(bot, update, message): while '\\end' not in message[0]: if message[0] == "": message = "a" message = [ messaggio.sendTelegramMessage(update.message.chat.id, message) ] if "\\end tipologia" in message: r = Recommendation(update.message.chat.id) b = [] for t in r.getTopFiveRecommendation(): text = t.replace("_", " ") b.append(text) custom_keyboard = [[b[0], b[1]], [b[2], b[3]], [b[4]], ["Non mi interessa"]] reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard) sendMessageToUser(bot, update, [ "Vorresti mangiare qualcosa in particolare?", "Puoi scegliere tra i miei consigli oppure specificarmi una tipologia di cucina da te preferita!" ], reply_markup) elif "\\end time" in message: custom_keyboard = [["Pranzo"], ["Cena"], ["Non lo so"]] reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard) sendMessageToUser(bot, update, ["Vuoi andare al ristorante a pranzo o a cena?"], reply_markup) else: reply_markup = telegram.ReplyKeyboardRemove(remove_keyboard=True) r = Recommendation(update.message.chat.id) sendMessageToUser(bot, update, [ "Ok, ho bisogno della tua posizione per raccomandarti dei ristoranti" ], reply_markup)
def firstLocation(bot, update): text = messaggio.sendTelegramMessage(update.message.chat.id, "\location") text = text.split("\m") #estrazione #aggiorno recommendation #messaggio.sendTelegramMessage(update.message.chat.id,"\\risultati") if controllaMessaggio("annullare la raccomandazione", text): #print(controllaMessaggio("annullare la raccomandazione", text)) custom_keyboard = [["Annulla raccomandazione"]] reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard) sendMessageToUser(bot, update, text, reply_markup) else: sendMessageToUser(bot, update, text, None) if not controllaMessaggio( "Se vuoi che ti consiglio dei ristoranti, devi chiedermelo esplicitamente!", text) and not controllaMessaggio("annullare la raccomandazione", text): location = { 'longitude': str(update.message.location.longitude), 'latitude': str(update.message.location.latitude) } saveRecommendationResults(update.message.chat.id, 50, 10) recommendation = Recommendation(str(update.message.chat.id)) recommendation.setLocation(location) rFB = ResturantFacebook.RestaurantFacebook() rFB.extractForRecommendation(recommendation) sendRecommendation(bot, update, recommendation)
def button(bot, update): query = update.callback_query data = format(query.data).split(",") scelta = int(data[0]) index = int(data[1]) indexPhoto = 0 if len(data) > 2: indexPhoto = int(data[2]) if scelta is 1: raccomandazione = Recommendation(query.message.chat_id) fbRestaurants = raccomandazione.getFacebookRestaurants() restaurant = fbRestaurants[index] saveRecommendation(query.message.chat_id, restaurant) speech = "Hai scelto " + restaurant['name'] + "!" bot.edit_message_text(text=speech, chat_id=query.message.chat_id, message_id=query.message.message_id) messaggio.sendTelegramMessage(query.message.chat_id, "\\reset") if scelta is 2: text = messaggio.sendTelegramMessage(query.message.chat_id, "\\reset") bot.edit_message_text(text=text, chat_id=query.message.chat_id, message_id=query.message.message_id) if scelta is 3: esito = getPhoto(bot, query.message.chat_id, query.message.message_id, index, indexPhoto) if not esito: bot.answer_callback_query(callback_query_id=query.id, text="Nessuna foto presente") else: bot.answer_callback_query(query.id) if scelta is 4: if index >= 0: nextRecommendation(bot, query.message.chat_id, query.message.message_id, index) bot.answer_callback_query(query.id) if scelta is 5: bot.answer_callback_query(query.id) if scelta is 6: esito = getPhoto(bot, query.message.chat_id, query.message.message_id, index, indexPhoto) if not esito: bot.answer_callback_query(callback_query_id=query.id, text="Nessuna foto presente") else: bot.answer_callback_query(query.id) if scelta is 7: removePhoto(query.message.chat_id) returnRestaurant(bot, query.message.chat_id, query.message.message_id, index) bot.answer_callback_query(query.id)
def nextRecommendation(bot, chatid, messageid, index): recommendation = Recommendation(str(chatid)) res = recommendation.getFacebookRestaurants() r = dumps(res[index], indent=4) restaurant = "" totExtraction = len(res) keyboard = [] backInlineKeyboard = InlineKeyboardButton("< " + str(index), callback_data="4," + str(index - 1)) centerInlineKeyboard = InlineKeyboardButton("• " + str(index + 1) + " •", callback_data="5," + str(index)) nextInlineKeyboard = InlineKeyboardButton(str(index + 2) + " >", callback_data="4," + str(index + 1)) nullInlineKeyboard = InlineKeyboardButton(" ", callback_data="5,0") if index - 1 >= 0: keyboard.append(backInlineKeyboard) else: keyboard.append(nullInlineKeyboard) keyboard.append(centerInlineKeyboard) if index + 1 < totExtraction: keyboard.append(nextInlineKeyboard) else: keyboard.append(nullInlineKeyboard) selectInlineKeyboard = InlineKeyboardButton("Scegli questo ristorante", callback_data="1," + str(index)) annullaInlineKeyboard = InlineKeyboardButton("Annulla raccomandazione", callback_data="2," + str(index)) fotoInlineKeyboard = InlineKeyboardButton("Mostra Foto", callback_data="3," + str(index)) reply_markup = InlineKeyboardMarkup([ keyboard, [selectInlineKeyboard], [fotoInlineKeyboard], [annullaInlineKeyboard] ]) if index in range(0, totExtraction): restaurant = Restaurant(json.loads(r)) #print(str(restaurant.about)) bot.edit_message_text(chat_id=chatid, message_id=messageid, text=str(restaurant), parse_mode=telegram.ParseMode.MARKDOWN, disable_web_page_preview=True, reply_markup=reply_markup)
def fetch_recommendations_for_city(self, city, criteria): # define extra parameters extra = { C.foursquareParamterKeys['Near']: city, C.foursquareParamterKeys['Intent']: C.foursquareParamterKeysValues['Intent_ID'], C.foursquareParamterKeys['Radius']: C.foursquareParamterKeysValues['Radius_ID'], C.foursquareParamterKeys['Query']: criteria } # concatenate with base parameters parameters = dict(self.baseparameters) parameters.update(extra) # add the method to the url exploreURL = self.baseurl + C.foursquareMethodKeys['Explore'] # init APIClient api = APIClient() # make the url call and retrieve a json Response jsonResponse = api.fetch(exploreURL, parameters) # check if the jsonResponse contains an object and pass it to the recommendation model if len(jsonResponse['response']['groups'][0]['items']) > 0: # empty array to store the recommendations dictionary recommendations = [] # init a recommendation model with an object and pass that to the array [ recommendations.append(Recommendation(place)) for place in jsonResponse['response']['groups'][0]['items'] ] # return the array of all recommendations models return recommendations else: # return the jsonResponse return jsonResponse
def getPhoto(bot, chatid, messageid, index, indexPhoto): recommendation = Recommendation(str(chatid)) res = recommendation.getFacebookRestaurants() r = dumps(res[index], indent=4) rId = json.loads(r)['id'] photoLinks = savePhoto(chatid, rId) totExtraction = len(photoLinks) if totExtraction > 0: photoLink = photoLinks[indexPhoto] #creo bottoni id,index ristorante, index foto keyboard = [] backInlineKeyboard = InlineKeyboardButton( "< " + str(indexPhoto), callback_data="6," + str(index) + "," + str(indexPhoto - 1)) centerInlineKeyboard = InlineKeyboardButton( "• " + str(indexPhoto + 1) + " •", callback_data="5," + str(index)) nextInlineKeyboard = InlineKeyboardButton( str(indexPhoto + 2) + " >", callback_data="6," + str(index) + "," + str(indexPhoto + 1)) nullInlineKeyboard = InlineKeyboardButton(" ", callback_data="5,0") if indexPhoto - 1 >= 0: keyboard.append(backInlineKeyboard) else: keyboard.append(nullInlineKeyboard) keyboard.append(centerInlineKeyboard) if indexPhoto + 1 < totExtraction: keyboard.append(nextInlineKeyboard) else: keyboard.append(nullInlineKeyboard) restaurantInlineKeyboard = InlineKeyboardButton( "<-- Torna al ristorante", callback_data="7," + str(index)) reply_markup = InlineKeyboardMarkup( [keyboard, [restaurantInlineKeyboard]]) bot.sendPhoto(chat_id=chatid, photo=photoLink, reply_markup=reply_markup) bot.delete_message(chat_id=chatid, message_id=messageid) return True else: removePhoto(chatid) return False
def filterResultCucina(req, chatid): p = req.get("result").get("contexts")[0].get("parameters") command = p.get("any.original") lun = len(p.get("any")) typeR = p.get("cucina") if lun == 1: if command == "\\next": typeR = [] raccomandazione = Recommendation(chatid) raccomandazione.setCucina(typeR) tp = raccomandazione.getTime_Pasto() if tp == "": return { "speech": "\\end time", "displayText": "\\end time", } else: return { "speech": "Ok, ho bisogno della tua posizione per raccomandarti dei ristoranti", "displayText": "Ok, ho bisogno della tua posizione per raccomandarti dei ristoranti", "contextOut": [{ "name": "raccomandazione2", "lifespan": 0, "parameters": {} }, { "name": "specifiche", "lifespan": 0, "parameters": {} }, { "name": "controllaorario", "lifespan": 0, "parameters": {} }, { "name": "controllaOrario", "lifespan": 0, "parameters": {} }, { "name": "location", "lifespan": 1, "parameters": {} }] }
def filterResultOrario(req, chatid): p = req.get("result").get("contexts")[0].get("parameters") command = p.get("any.original") lun = len(p.get("any")) typeR = p.get("time_pasto") if lun == 1: if command == "\\next": typeR = "" raccomandazione = Recommendation(chatid) raccomandazione.setTime_Pasto(typeR) tp = raccomandazione.getTime_Pasto() return { "speech": "Ok, ho bisogno della tua posizione per raccomandarti dei ristoranti", "displayText": "Ok, ho bisogno della tua posizione per raccomandarti dei ristoranti", }
def selectRestaurant(req, chatid): p = req.get("result").get("parameters") raccomandazione = Recommendation(chatid) number = int(p.get("number")) - 1 fbRestaurants = raccomandazione.getFacebookRestaurants() if number < 0 or number > len(fbRestaurants) - 1: speech = "Scelta non valida" return { "speech": speech, "displayText": speech, "contextOut": [{ "name": "estrazione", "lifespan": 5, "parameters": {} }, { "name": "risultati-followup", "lifespan": 5, "parameters": {} }] } restaurant = fbRestaurants[number] mongoDriver.saveRecommendation(chatid, restaurant) speech = "Hai scelto " + restaurant['name'] + "!" return { "speech": speech, "displayText": speech, "contextOut": [{ "name": "estrazione", "lifespan": 0, "parameters": {} }, { "name": "risultati-followup", "lifespan": 0, "parameters": {} }] }
def recommendation(self): page = int(self.get_argument('pageNum', 1)) psize = int(self.get_argument('numPerPage', 100)) tody = self.get_date(1) + datetime.timedelta(days=1) start = self.get_argument('start', '') appid = self.get_argument('appid', '') action = self.get_argument('action', '') type = self.get_argument('type', '') yest = tody - datetime.timedelta(days=1) if not start: start = tody - datetime.timedelta(days=7) else: start = datetime.datetime.strptime(start, '%Y-%m-%d') end = yest count, stats = 0, [] stats = [] _start, days = start, [] while _start <= end: _end = _start + datetime.timedelta(days=1) stat, appids = Recommendation.mgr( ).get_recommendation_one_day_stat(_start, appid) stat = self.data_process(stat, appids, _start) stat = self.bubblesort(stat, 'download') stats.extend(stat) days.append(_start) _start = _end for stat in stats: stat['time'] = stat['time'].strftime('%Y-%m-%d') stats = Service.inst().fill_app_info(stats) count = len(stats) if action == 'export': title = [('time', '时间'), ('appid', 'appid'), ('appname', 'app名字'), ('download', '下载'), ('install', '安装')] xls = Excel().generate(title, stats, 1) filename = 'recommendation_%s.xls' % (yest.strftime('%Y-%m-%d')) self.set_header('Content-Disposition', 'attachment;filename=%s' % filename) self.finish(xls) else: stats = stats[(page - 1) * psize:page * psize] self.render('data/recommendation.html', appid=appid, type=type, date=yest.strftime('%Y-%m-%d'), start=start.strftime('%Y-%m-%d'), page=page, psize=psize, count=count, stats=stats)
def recommendation(self): page = int(self.get_argument('pageNum',1)) psize = int(self.get_argument('numPerPage',100)) tody = self.get_date(1) + datetime.timedelta(days=1) start = self.get_argument('start','') appid = self.get_argument('appid','') action = self.get_argument('action','') type = self.get_argument('type','') yest = tody - datetime.timedelta(days=1) if not start: start = tody - datetime.timedelta(days=7) else: start = datetime.datetime.strptime(start,'%Y-%m-%d') end = yest count,stats = 0,[] stats = [] _start,days = start,[] while _start <= end: _end = _start + datetime.timedelta(days=1) stat, appids = Recommendation.mgr().get_recommendation_one_day_stat(_start,appid) stat = self.data_process(stat,appids,_start) stat = self.bubblesort(stat,'download') stats.extend(stat) days.append(_start) _start = _end for stat in stats: stat['time'] = stat['time'].strftime('%Y-%m-%d') stats = Service.inst().fill_app_info(stats) count = len(stats) if action == 'export': title = [('time','时间'),('appid','appid'),('appname','app名字'),('download','下载'),('install','安装')] xls = Excel().generate(title,stats,1) filename = 'recommendation_%s.xls' % (yest.strftime('%Y-%m-%d')) self.set_header('Content-Disposition','attachment;filename=%s'%filename) self.finish(xls) else: stats = stats[(page-1)*psize:page*psize] self.render('data/recommendation.html',appid=appid,type=type, date=yest.strftime('%Y-%m-%d'),start=start.strftime('%Y-%m-%d'),page=page,psize=psize,count=count,stats=stats)
def raccomandazioneIntent(req, chatid): user = User(chatid) if user.isNewUser(): speech = "Ciao! Purtroppo ancora non ci conosciamo.\mPrima di chiedermi una raccomandazione devo farti alcune domande.\nPosso?" return { "speech": speech, "displayText": speech, "contextOut": [{ "name": "raccomandazione2", "lifespan": 0, "parameters": {} }, { "name": "Intent-Di-Benvenuto-followup", "lifespan": 5, "parameters": {} }] } if 'raccomandazione2' in req.get("result").get('fulfillment').get( 'speech'): mongoDriver.removeRecommendation(chatid) raccomandazione = Recommendation(chatid) return { "speech": "\\raccomandazione2", "displayText": "\\raccomandazione2" } raccomandazione = Recommendation(chatid) p = req.get("result").get("contexts")[0].get("parameters") cucina = p.get("cucina.original") if len(p.get("cucina")) <= 1: cucina = [cucina] time_pasto = p.get("time_pasto.original") speech = req.get("result").get("resolvedQuery") # print(len(cucina)) # print(time) # print (time_pasto) if len(p.get("cucina")) is not 0: raccomandazione.setCucina(p.get("cucina")) for cOriginal in cucina: speech = str(speech.replace(cOriginal, "")) return {"speech": speech, "displayText": speech} elif len(time_pasto) is not 0: raccomandazione.setTime_Pasto(p.get("time_pasto")) speech = speech.replace(time_pasto, "") return {"speech": speech, "displayText": speech} else: typeP = raccomandazione.getCucina() timeP = raccomandazione.getTime_Pasto() if len(typeP) is 0: #\end return { "speech": "\end tipologia", "displayText": "\end tipologia", "contextOut": [{ "name": "raccomandazione2", "lifespan": 0, "parameters": {} }, { "name": "specifiche", "lifespan": 0, "parameters": {} }, { "name": "controllaTipologia", "lifespan": 2, "parameters": {} }] } elif timeP == "": return { "speech": "\end time", "displayText": "\end time", "contextOut": [{ "name": "raccomandazione2", "lifespan": 0, "parameters": {} }, { "name": "specifiche", "lifespan": 0, "parameters": {} }, { "name": "controllaOrario", "lifespan": 2, "parameters": {} }] } else: return { "speech": "\end", "displayText": "\end", "contextOut": [{ "name": "raccomandazione2", "lifespan": 0, "parameters": {} }, { "name": "specifiche", "lifespan": 0, "parameters": {} }, { "name": "location", "lifespan": 1, "parameters": {} }] }