def Intents_parser(receivedent, user): if receivedent['intent'][0]['value'] == "department_info": return department_info(receivedent, user) elif receivedent['intent'][0]['value'] == "faculty_profile": if first_entity_value(receivedent, 'department_name'): send_generic_faculty(user, receivedent['faculty_name'][0]['value'], receivedent['department_name'][0]['value']) return "Here you go" else: send_generic_faculty(user, receivedent['faculty_name'][0]['value']) return "Here you go" elif receivedent['intent'][0]['value'] == "admission_info": page.send( user, Template.Buttons('Admissions', [ Template.ButtonWeb( "Private Admissions", "https://uos.edu.pk/examination/Admissions_Schedule"), Template.ButtonWeb( "Regular Admissions", "https://admissions.uos.edu.pk/importantdates") ])) return "Here you can Find All Admisison Related Info" elif receivedent['intent'][0]['value'] == "merit_info": page.send( user, Template.Buttons('Merit Info', [ Template.ButtonWeb("Merit Lists", "https://uos.edu.pk/examination/merits") ])) return "Here you can Find All info Related To Merit" elif receivedent['intent'][0]['value'] == "junk": return "that was the junk" else: return "nothing but intents"
def send_generic_program(recipient, data): data = urllib.parse.quote_plus(data) response = requests.get('https://uos.edu.pk/about/bot_program/' + data) result = response.json() if result: send_message(recipient, 'Duration : ' + result[0]['duration']) send_message(recipient, 'Credit Hours ' + result[0]['credit_hour']) send_message(recipient, 'Eligibility ' + result[0]['requirement']) page.send( recipient, Template.Buttons(result[0]['name'], [ Template.ButtonWeb( "See More Detail", "https://uos.edu.pk/department/academic_programs/" + result[0]['dpartment']), Template.ButtonWeb( "Prospectus Jump", "https://uos.edu.pk/uploads/faculties/covers/" + result[0]['scheme_file']), Template.ButtonWeb( "Scheme of Study", "https://uos.edu.pk/uploads/faculties/schemes/" + result[0]['detail_scheme']) ])) else: send_message(recipient, 'Sorry, but i am unable to Find' + data) send_typing_off(recipient)
def challenge(turn, total_turn, mark, sender_id): if turn == 0: with open("resource/questions.json") as f: questions = json.load(f) else: with open("questions.pickle", 'rb') as pinfile: questions = pickle.load(pinfile) random_question = sample(questions, 1) question = random_question[0]["question"] choices = random_question[0]["choices"] answer = random_question[0]["answer"] print("question: ", question) for i in questions: if i["question"] == question: questions.remove(i) with open("questions.pickle", "wb") as poutfile: pickle.dump(questions, poutfile) print("questions: ", questions) buttons = [] for i in range(len(choices)): buttons.append( Template.ButtonPostBack( choices[i], str(turn) + "_" + str(total_turn) + "_" + str(i) + "_" + str(answer) + "_" + str(mark))) g_page.send(sender_id, Template.Buttons(question, buttons))
def handle_project_name(sender_id, message_text): """Handles message text for naming user's new project.""" # user can't call project project from lib.utilities import check_stock_count if message_text: project = add_project(sender_id=sender_id, name=message_text.strip()) crafter[sender_id]['project_id'] = project.project_id if check_stock_count(stock_type='pattern', sender_id=sender_id) != 0: page.send( sender_id, Template.Buttons( "Please upload your pattern photo to start a new project or click to open stock gallery.", [{ 'type': 'web_url', 'title': 'Open Stock Gallery', 'value': server_host + '/user/{}/pattern'.format(sender_id) }])) else: page.send( sender_id, "Please upload your pattern photo to start a new project") else: page.send(sender_id, "Sorry, didn't catch that.\nPlease add a project name")
def add_next_stock_response(sender_id, stock_type): """If the user select an item from stock galleries return correct response.""" if stock_type == 'pattern': if check_stock_count(stock_type='fabric', sender_id=sender_id) != 0: page.send(sender_id, Template.Buttons("If you have the material upload you next photo or pick something from your exisiting stock.", [{'type': 'web_url', 'title': 'Open Fabric Gallery', 'value': server_host + '/user/{}/fabric'.format(sender_id)}])) else: page.send(sender_id, "If you have the material upload you next photo") else: page.send(sender_id, "Success, How many weeks do you want to do this project?")
def send_button(recipient): page.send( recipient, Template.Buttons("hello", [ Template.ButtonWeb("Open Web URL", "https://www.oculus.com/en-us/rift/"), Template.ButtonPostBack("trigger Postback", "DEVELOPED_DEFINED_PAYLOAD"), Template.ButtonPhoneNumber("Call Phone Number", "+16505551234") ]))
def send_button(recipient): """ Shortcuts are supported page.send(recipient, Template.Buttons("hello", [ {'type': 'web_url', 'title': 'Open Web URL', 'value': 'https://www.oculus.com/en-us/rift/'}, {'type': 'postback', 'title': 'tigger Postback', 'value': 'DEVELOPED_DEFINED_PAYLOAD'}, {'type': 'phone_number', 'title': 'Call Phone Number', 'value': '+16505551234'}, ])) """ page.send(recipient, Template.Buttons("hello", [ Template.ButtonWeb("Open Web URL", "https://www.oculus.com/en-us/rift/"), Template.ButtonPostBack("trigger Postback", "DEVELOPED_DEFINED_PAYLOAD"), Template.ButtonPhoneNumber("Call Phone Number", "+16505551234") ]))
def customer_care(payload, event): click_menu = payload.split('/')[1] buttons = [ { "type": "phone_number", "title": "Call Representative", "payload": "01244414888" }, { 'type': 'postback', 'title': 'Share your experience through me', 'payload': 'REVIEW' }, ] page.send(event.sender_id, Template.Buttons("Need Assistance", buttons))
def callback_clicked_no_note(payload, event): """User selects no note button""" from lib.utilities import extract_data sender_id, message, message_text, message_attachments, quick_reply, = extract_data( event) page.send( sender_id, Template.Buttons( "Your project has been saved. If you would like to get back to main menu type 'craftybot' again.", [{ 'type': 'web_url', 'title': 'Open Projects Home', 'value': server_host + '/user/{}/projects'.format(sender_id) }])) crafter[sender_id] = dict()
def lambda_handler(event, context): if 'params' in event.keys(): params = event['params']['querystring'] if params and params['hub.mode'] == 'subscribe': if params['hub.verify_token'] == verify_token: return int(params['hub.challenge']) else: return "Verification error" else: messaging = json.loads(event['body']) messaging = messaging['entry'][0]['messaging'][0] if 'message' in messaging.keys( ) and 'text' in messaging['message'].keys(): sender, message = messaging['sender']['id'], messaging['message'][ 'text'] sender = int(sender) page = fbmq.Page(PAGE_ACCESS_TOKEN) if message == 'next': connectDb() pet = getRandomPet() page.send(sender, "This is {}!".format(pet.name)) #page.send(sender, "(DEBUG pet_id ={})".format(pet.pet_id)) description, img = parsePetFromId(pet.pet_id) attachment = Attachment.Image(img) page.send(sender, attachment) buttons = [ Template.ButtonWeb("Support {}".format(pet.name), "https://www.google.com") ] if description: page.send(sender, description) page.send( sender, Template.Buttons(naturalLanguage("emphatic"), buttons)) else: print(messaging) response = { 'statusCode': 200, 'body': json.dumps({'success': True}), 'headers': { 'Content-Type': 'application/json', } } return response
def choose_category(payload, event): click_menu = payload.split('/')[1] buttons = [{ 'type': 'postback', 'title': 'T-Shirts', 'payload': 'TSHIRT' }, { 'type': 'postback', 'title': 'Electronics', 'payload': 'ELECTRONICS' }, { 'type': 'postback', 'title': 'Footwear', 'payload': 'FOOTWEAR' }] page.send(event.sender_id, Template.Buttons("Please choose a category", buttons))
def send_generic_program_dep(recipient, data): data = urllib.parse.quote_plus(data) print(data) response = requests.get('https://uos.edu.pk/about/bot_department/' + data) result = response.json() print(result) if result: print(result[0]['name']) page.send( recipient, Template.Buttons(result[0]['name'], [ Template.ButtonWeb( "See All Programs", "https://uos.edu.pk/department/academic_programs/" + result[0]['id']) ])) else: send_message(recipient, 'Sorry, but i am unable to Find' + data) send_typing_off(recipient)
def handle_project_notes(sender_id, message_text): """Handles any notes the user inputs to their new project.""" from lib.utilities import update_project_notes if message_text: project_id = crafter[sender_id].get('project_id') project = update_project_notes(project_id=project_id, message_text=message_text) page.send( sender_id, Template.Buttons( "Your note has been added to your project. If you would like to get back to main menu type 'craftybot' again or click to view your projects page.", [{ 'type': 'web_url', 'title': 'Open Projects Home', 'value': server_host + '/user/{}/projects'.format(sender_id) }])) crafter[sender_id] = dict() else: page.send(sender_id, 'Did you want to leave a note?')
def handle_status_image(sender_id, image_url): """Handles message attachment for user's update photo.""" from lib.utilities import add_status_update image = add_image(sender_id=sender_id, image_url=image_url) project_id = crafter[sender_id].get('project_id') update_status = add_status_update(project_id, image) project = Project.query.filter(Project.project_id == project_id).first() status = Status.query.filter( Status.status_id == update_status.status_id).first() due_date = datetime.strftime(project.due_at, "%A, %B %d, %Y") crafter[sender_id] = dict() page.send( sender_id, Template.Buttons( "YAY! You're {status}. Just a reminder, this project is due by {due_date}. To update another project say 'craftybot'" .format(status=status.name, due_date=due_date), [{ 'type': 'web_url', 'title': 'Open Projects Home', 'value': server_host + '/user/{}/projects'.format(sender_id) }]))
def handle_stock_image(sender_id, image_url, stock_type): """Handles message attachment for user's pattern photo.""" image = add_image(sender_id=sender_id, image_url=image_url) stock = add_stock(image=image, stock_type=stock_type) project_id = crafter[sender_id].get('project_id') crafter[sender_id][stock_type + '_id'] = getattr(stock, stock_type + '_id') if project_id: project = add_stock_to_project(stock=stock, project_id=project_id) add_next_stock_response(sender_id=sender_id, stock_type=stock_type) else: page.send( sender_id, Template.Buttons( "This image has been add to your {} stock photos.To update a project say 'craftybot' or click to open your projects page" .format(stock_type), [{ 'type': 'web_url', 'title': 'Open Projects Home', 'value': server_host + '/user/{}/projects'.format(sender_id) }])) crafter[sender_id] = dict()
# Also supported regex, it works corretly # @page.callback(['PICK_(.+)']) buttons = [ Templates.ButtonWeb("Open Web URL", "https://www.oculus.com/en-us/rift/"), Templates.ButtonPostBack("trigger Postback", "DEVELOPED_DEFINED_PAYLOAD"), Templates.ButtonPhoneNumber("Call Phone Number", "+16505551234") ] # you can use a dict instead of a Button class # # buttons = [{'type': 'web_url', 'title': 'Open Web URL', 'value': 'https://www.oculus.com/en-us/rift/'}, # {'type': 'postback', 'title': 'trigger Postback', 'value': 'DEVELOPED_DEFINED_PAYLOAD'}, # {'type': 'phone_number', 'title': 'Call Phone Number', 'value': '+16505551234'}] page.send(recipient_id, Template.Buttons("hello", buttons)) ########################################## # generic button template page.send( recipient_id, Template.Generic([ Template.GenericElement( "rift", subtitle="Next-generation virtual reality", item_url="https://www.oculus.com/en-us/rift/", image_url=CONFIG['SERVER_URL'] + "/assets/rift.png", buttons=[ Template.ButtonWeb("Open Web URL", "https://www.oculus.com/en-us/rift/"), Template.ButtonPostBack("tigger Postback",
def received_postback(event): sender_id = event.sender_id recipient_id = event.recipient_id time_of_postback = event.timestamp payload = event.postback_payload print('-------------------------postback_payload----------------------------------------') print(payload) print("Received postback for user %s and page %s with payload '%s' at %s" % (sender_id, recipient_id, payload, time_of_postback)) if payload == 'hoteles_playa': page.send(sender_id, "Tengo dos promociones para ti") page.send(sender_id, Template.Generic([ Template.GenericElement("Hotel Cancún", subtitle="Reserva ahora tu hotel en Cancún", item_url="http://www.mariachi.io/", image_url=CONFIG['SERVER_URL'] + "/assets/hotel_cancun.jpg", buttons=[ Template.ButtonPostBack("reservar", "hotel_cancun") ]), Template.GenericElement("Hotel Cabo", subtitle="Reserva ahora tu hotel en los Cabos", item_url="http://www.mariachi.io/", image_url=CONFIG['SERVER_URL'] + "/assets/hotel_cabo.jpg", buttons=[ Template.ButtonPostBack("reservar", "hotel_cabo") ]) ])) page.send(sender_id, "La cuarta noche es gratis si reservas desde el chatbot!!!") elif payload == 'hotel_cancun' or payload == 'hotel_cabo': page.send(sender_id, "Reservación exitosa!!") elif payload == 'hotel_ibis' or payload == 'hotel_francia': page.send(sender_id, Template.Buttons("Selecciona tu método de pago", [ Template.ButtonWeb("Tarjeta crédito", "https://akrocard.com/wp-content/uploads/2015/05/tarjeta-pvc-chip-CPU.png"), Template.ButtonWeb("Tarjeta débito", "https://akrocard.com/wp-content/uploads/2015/05/tarjeta-pvc-chip-CPU.png") ])) elif payload == 'reservar_habitacion': page.send(sender_id, "Por favor indícame separando con comas, ciudad, estado, fecha de llegada y fecha de partida iniciando por día, mes y año (01, 02, 17)") elif payload == 'hoteles_cercanos': page.send(sender_id, "Claro que sí, será un placer hospedarte.") page.send(sender_id, "Compartir ubicacion?", quick_replies=[QuickReply(title="compartir", payload="compartir"), QuickReply(title="en otro momento", payload="en otro momento")], metadata="DEVELOPER_DEFINED_METADATA") elif payload == 'servicios_hotel': page.send(sender_id, "Hola, tambien puedo ayudarte con servicio directo a tu habitación") page.send(sender_id, "En que te podemos servir?") else: page.send(sender_id, "Postback called")
def message_handler(event): clf = pickle.load(open("resource/model/pre_post_model.pkl", "rb")) sender_id = event.sender_id message = event.message_text global timestamp if event.quick_reply: pass elif message.lower() == "tabot": quick_replies = [ QuickReply(title="quiz", payload="GAME"), QuickReply(title="explore", payload="D_SEARCH"), QuickReply(title="ask question", payload="Q_SEARCH") ] page.send(sender_id, "Hi, What would you like to do?", quick_replies=quick_replies) # use timestamp to trace whether user had choose to ask question or just normal questioning elif timestamp != 0: question = event.message_text question_type = classify.predict_pre_post(clf, question, 0.7) tfidf = pickle.load(open("resource/model/tfidf.pkl", "rb")) tf_model = "resource/model/model.ckpt.meta" with tf.Session() as sess: saver = tf.train.import_meta_graph(tf_model) saver.restore(sess, tf.train.latest_checkpoint('resource/model/')) formatted_question = clean_question(question) formatted_question = tfidf.transform([formatted_question]) question_location = classify.predict_web_com( sess, formatted_question, 0.75) # print(question_type) # print(question_location) if question_location == "community": base_url = "https://community.celcom.com.my/t5/forums/searchpage/tab/message?" params = { "advanced": "false", "allow_punctuation": "false", "q": question } search_url = base_url + urlencode(params) page.send( sender_id, Template.Generic([ Template.GenericElement( question, item_url=search_url, buttons=[Template.ButtonWeb("Get Answer", search_url)]) ])) elif question_location == "website": if question_type == "prepaid": quick_replies = [ QuickReply(title="yes", payload="PREPAID_YES"), QuickReply(title="no", payload="PREPAID_NO") ] page.send(sender_id, "Are you asking question about prepaid plan?", quick_replies=quick_replies) elif question_type == "postpaid": quick_replies = [ QuickReply(title="yes", payload="POSTPAID_YES"), QuickReply(title="no", payload="POSTPAID_NO") ] page.send(sender_id, "Are you asking question about postpaid plan?", quick_replies=quick_replies) else: # format the question payload_question = question.replace(" ", "-") page.send( sender_id, "😅 I do not understand the question! But I am improving every day, and hopefully I can answer this question in near future." ) page.typing_on(sender_id) buttons = [ Template.ButtonPostBack("prepaid", "PREPAID" + "-" + payload_question), Template.ButtonPostBack( "postpaid", "POSTPAID" + "-" + payload_question), Template.ButtonPostBack("other", "OTHER" + "-" + payload_question) ] # TODO kawkawsquad format cannot pass page.send( sender_id, Template.Buttons( "The question that you are asking, is it about prepaid plan or postpaid plan or other?", buttons)) else: page.send(sender_id, "😱 cannot find any answer related to the question!") page.typing_on(sender_id) page.send(sender_id, "🤔 Maybe you can ask the question in our community") page.send( sender_id, Template.Generic([ Template.GenericElement( "Ask Question", subtitle="Ask New Question", item_url="https://community.celcom.com.my/", image_url= "https://smpiu66958.i.lithium.com/html/assets/placeholder-banner.png", buttons=[ Template.ButtonWeb( "Ask question", "https://community.celcom.com.my/") ]) ])) timestamp = 0 elif message.lower() == "help": page.typing_on(sender_id) sleep(2) page.send( sender_id, "👋 I am Tabot, a 🤖 to help you find answer for some of the questions and provide more information about the celcom package to you." ) page.typing_on(sender_id) sleep(1) page.send( sender_id, "to start any conversation with me, just text \"tabot\" to me") page.typing_on(sender_id) sleep(1) page.send( sender_id, "then you can choose from one of the following actions\n➡️explore\n➡️ask question\n➡️game" ) page.typing_on(sender_id) sleep(1) page.send(sender_id, "feel free to explore yourself.") page.typing_on(sender_id) sleep(1) page.send(sender_id, "💤 resting now...") else: page.typing_on(sender_id) sleep(1) page.send(sender_id, "😅 I'm not sure what you are saying.") page.typing_on(sender_id) sleep(1) page.send( sender_id, "You can always text \"tabot\" to start the conversation! Cheer 😎")
def object_search(payload, event): sender_id = event.sender_id subject, predicate = payload.split("_") answers = query.search_objects(subject, predicate) if answers: send_payload = [] for answer in answers: answer_split = answer.split("#") if answer_split[0] == "http://www.celcom.com.my/ontology": send_payload.append(answer_split[1]) elif len(answer_split) == 1: # this will handle end of conversation with datatype if answer_split[0].startswith("http"): page.send( sender_id, Template.Generic([ Template.GenericElement( format_sentence.format_answer(subject), subtitle=format_sentence.format_answer(subject) + " " + format_sentence.format_answer(predicate), image_url= "https://www.celcom.com.my/sites/default/files/images/banner/xpax_product_bemorewalla_md.jpg", buttons=[ Template.ButtonWeb("Click me 😆", answer_split[0]) ]) ])) elif not query.search_objects(predicate, "subPropertyOf"): page.send( sender_id, format_sentence.format_answer(predicate) + " is " + format_sentence.format_answer(answer_split[0])) else: if query.search_objects( predicate, "subPropertyOf")[0].split("#")[1] == "dial": page.send( sender_id, format_sentence.format_answer(predicate) + " by dialing " + format_sentence.format_answer(answer_split[0])) if not send_payload: page.send( sender_id, "If you still have any question, type 'tabot' to start the conversation again" ) else: send_pretty_list = [ format_sentence.format_answer(text) for text in send_payload ] page.send( sender_id, "🤗 these are the answers: " + ", ".join(send_pretty_list)) # this will mark the end of message if user ask about NRIC or passport if 'nric' in send_payload or 'passport' in send_payload: page.send( sender_id, "If you still have any question, type 'tabot' to start the conversation again" ) else: yes_payload = "YES_" + "_".join(send_payload) buttons = [ Template.ButtonPostBack("Yes", yes_payload), Template.ButtonPostBack("No", "NO") ] page.send(sender_id, Template.Buttons("Continue to explore?", buttons)) else: page.send(sender_id, "No information to show anymore!!")
def send_button(recipient): page.send(recipient, Template.Buttons(".", [ Template.ButtonWeb("Open Web URL", "https://www.oculus.com/en-us/rift/"), Template.ButtonPostBack("Opción de tránsito", "OPCION_DE_TRANSITO"), Template.ButtonPhoneNumber("Call Phone Number", "+16505551234") ]))
def enviar_reglamento(recipient): page.send(recipient, Template.Buttons("¡Hola "+page.get_user_profile(recipient)["first_name"]+" "+page.get_user_profile(recipient)["last_name"]+"! Bienvenido a TransiBot" ,[ Template.ButtonWeb("Reglamento de tránsito CDMX", "http://data.ssp.cdmx.gob.mx/reglamentodetransito/documentos/nuevo_reglamento_transito.pdf"), ]))