Beispiel #1
0
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"
Beispiel #2
0
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)
Beispiel #3
0
def send_generic_faculty(recipient, data, dep=""):
    data = urllib.parse.quote_plus(data)
    dep = urllib.parse.quote_plus(dep)
    if (dep):
        response = requests.get('https://uos.edu.pk/about/bot_faculty/' +
                                data + "/" + dep)
        result = response.json()
        if result:
            page.send(
                recipient,
                Template.Generic([
                    Template.GenericElement(
                        result[0]['name'],
                        subtitle=result[0]['designation'],
                        item_url="https://uos.edu.pk/faculty/profile/" +
                        result[0]['username'],
                        image_url="https://uos.edu.pk/uploads/faculty/profiles/"
                        + result[0]['picture'],
                        buttons=[
                            Template.ButtonWeb(
                                "Open Profile",
                                "https://uos.edu.pk/faculty/profile/" +
                                result[0]['username']),
                            Template.ButtonPhoneNumber("Contact",
                                                       '+92 48 9230879')
                        ])
                ]))
        else:
            send_message(
                recipient,
                'Sorry, but i am unable to Find' + data + " in " + dep)
            send_typing_off(recipient)
    else:
        response = requests.get('https://uos.edu.pk/about/bot_faculty/' + data)
        result = response.json()

        if result:
            page.send(
                recipient,
                Template.Generic([
                    Template.GenericElement(
                        result[0]['name'],
                        subtitle=result[0]['designation'],
                        item_url="https://uos.edu.pk/faculty/profile/" +
                        result[0]['username'],
                        image_url="https://uos.edu.pk/uploads/faculty/profiles/"
                        + result[0]['picture'],
                        buttons=[
                            Template.ButtonWeb(
                                "Open Profile",
                                "https://uos.edu.pk/faculty/profile/" +
                                result[0]['username']),
                            Template.ButtonPhoneNumber("Contact",
                                                       '+92 48 9230879')
                        ])
                ]))
        else:
            send_message(recipient, 'Sorry, but i am unable to Find' + data)
            send_typing_off(recipient)
def fb_receive_message():
    message_entries = json.loads(request.data.decode('utf8'))['entry']
    for entry in message_entries:
        for message in entry['messaging']:
            if message.get('message'):
                user_id = "{sender[id]}".format(**message)
                text = "{message[text]}".format(**message)
                res = bt.response(text, user_id)
                if res == "De rien":
                    client.send_image(user_id, conf.deRien)
                elif res == "merci":
                    client.send_image(user_id, conf.happy)
                elif res == "no":
                    client.send_image(user_id, conf.angry)
                elif res == "ah":
                    client.send_image(user_id, conf.bored)
                elif res == "quoi":
                    client.send_image(user_id, conf.busy)
                elif res == "lol":
                    client.send_image(user_id, conf.grand)
                elif (res == "ok"):
                    page.send(
                        user_id,
                        Template.Generic([
                            Template.GenericElement(
                                "rift",
                                subtitle="Next-generation virtual reality",
                                item_url="https://www.oculus.com/en-us/rift/",
                                image_url=conf.deRien,
                                buttons=[
                                    Template.ButtonWeb(
                                        "Open Web URL",
                                        "https://www.oculus.com/en-us/rift/"),
                                    Template.ButtonPostBack(
                                        "tigger Postback",
                                        "DEVELOPED_DEFINED_PAYLOAD"),
                                    Template.ButtonPhoneNumber(
                                        "Call Phone Number", "+16505551234")
                                ]),
                            Template.GenericElement(
                                "touch",
                                subtitle="Your Hands, Now in VR",
                                item_url="https://www.oculus.com/en-us/touch/",
                                image_url=conf.deRien,
                                buttons=[
                                    Template.ButtonWeb(
                                        "Open Web URL",
                                        "https://www.oculus.com/en-us/rift/"),
                                    Template.ButtonPostBack(
                                        "tigger Postback",
                                        "DEVELOPED_DEFINED_PAYLOAD"),
                                    Template.ButtonPhoneNumber(
                                        "Call Phone Number", "+16505551234")
                                ])
                        ]))
                else:
                    client.send_text(user_id, res)
    return "Ok"
Beispiel #5
0
    def get(self, request, *args, **kwargs):
        page.show_persistent_menu([
            Template.ButtonWeb('University of Sargodha',
                               'https://uos.edu.pk/'),
            Template.ButtonWeb('ORIC', 'https://oric.uos.edu.pk'),
            Template.ButtonWeb('File a Complaint',
                               'https://uos.edu.pk/complaint')
        ])

        page.show_starting_button("Start Asking Your Queries")
        page.greeting(
            "University Enquiring Chatbot is here to answer your queries About University"
        )
        return HttpResponse('yaayyyyy')
Beispiel #6
0
def show_jeans(recipient):
    page.send(
        recipient,
        Template.Generic([
            Template.GenericElement(
                "ONSWARP CAMP - Jeans Skinny Fit - dark ",
                subtitle="by Only & Sons for £99.99",
                item_url=
                "https://www.zalando.co.uk/only-and-sons-onswarp-camp-jeans-skinny-fit-os322g04j-k11.html?wmc=AFF49_IG_DE.51977_60804..",
                image_url=
                "https://mosaic01.ztat.net/vgs/media/pdp-gallery/OS/32/2G/03/9K/21/[email protected]",
                buttons=[
                    Template.ButtonWeb(
                        "Details & Buy 🛍️🛍",
                        "https://www.zalando.co.uk/only-and-sons-onswarp-camp-jeans-skinny-fit-os322g04j-k11.html?wmc=AFF49_IG_DE.51977_60804.."
                    ),
                    Template.ButtonShare()
                    # Template.ButtonPhoneNumber("Call Branch", "+16505551234")
                ]),
            Template.GenericElement(
                "MICK - Jeans Skinny Fit - seismology",
                subtitle="by J Brand for £259.99",
                item_url=
                "https://www.zalando.co.uk/converse-trainers-athletic-navyblackobsidian-co412b06r-k11.html?wmc=AFF49_IG_DE.51977_60804..",
                image_url=
                "https://mosaic01.ztat.net/vgs/media/pdp-zoom/JB/22/2G/00/OK/11/[email protected]",
                buttons=[
                    Template.ButtonWeb(
                        "Details & Buy 🛍️🛍",
                        "https://www.zalando.co.uk/j-brand-jeans-skinny-fit-seismology-jb222g00o-k11.html?wmc=AFF49_IG_DE.51977_60804.."
                    ),
                    Template.ButtonShare()
                ]),
            Template.GenericElement(
                "ONSWARP RAW EDGE - Jeans Skinny Fit - light blue denim",
                subtitle="by Only & Sons for £25.99",
                item_url=
                "https://www.zalando.co.uk/only-and-sons-onswarp-raw-edge-jeans-skinny-fit-light-blue-denim-os322g04o-k11.html?wmc=AFF49_IG_DE.51977_60804..",
                image_url=
                "https://mosaic01.ztat.net/vgs/media/pdp-zoom/OS/32/2G/04/OK/11/[email protected]",
                buttons=[
                    Template.ButtonWeb(
                        "Details & Buy 🛍️🛍",
                        "https://www.zalando.co.uk/only-and-sons-onswarp-raw-edge-jeans-skinny-fit-light-blue-denim-os322g04o-k11.html?wmc=AFF49_IG_DE.51977_60804.."
                    ),
                    Template.ButtonShare()
                ])
        ]))
Beispiel #7
0
def send_reddit_post(recipient_id, microarticle, microarticle_type):
    #sends user the text message provided via input response parameter
    print("[i] Formatting Article...")
    response = article_Service.format_article(microarticle, microarticle_type)

    print("[i] " + microarticle_type + " SRC:\t" + str(microarticle.domain))
    if microarticle_type == "image":
        image_formats = ['.gif','.jpg','.jpeg','.png']
        if microarticle.url[-4:] in image_formats:
            page.send(recipient_id, Attachment.Image(str(microarticle.url)))
        elif microarticle.url[-4:] == ".gifv":
            page.send(recipient_id, Attachment.Video(str(microarticle.url)))
        else:
            page.send(recipient_id, Attachment.Image(str(microarticle.url)))

    elif microarticle_type == "video":
        page.send(recipient_id, Attachment.Video(str(microarticle.url)))

    elif microarticle_type == "article":
        print("[i] Response:")
        pprint.pprint(response)
        page.send(recipient_id, Template.Generic([
            Template.GenericElement(microarticle.title,
                                    subtitle= response[0].get('subtitle'),
                                    item_url= microarticle.url,
                                    image_url= microarticle.thumbnail,
                                    buttons=[
                                        Template.ButtonShare(),
                                        Template.ButtonWeb("Open Web URL", microarticle.url)
                                    ]),
        ]))

    print("[i] Response sent...")
    return "success"
Beispiel #8
0
	def on_enter_talking(self, event):
		print("I'm entering talking")
		sender_id = event['sender']['id']

		url = "https://www.youtube.com/results?search_query=%E9%82%8A%E7%B7%A3%E4%BA%BA&sp=EgQQARgB"
		res = requests.get(url, verify=False)
		soup = BeautifulSoup(res.text,'html.parser')
		arr_titles = []
		arr_urls = []
		i = 0
		for all_mv in soup.select(".yt-lockup-video"):
    	# 抓取 Title & Link
			data = all_mv.select("a[rel='spf-prefetch']")
			print(data[0].get("href")[-11:])
			arr_titles.append(data[0].get("title"))
			arr_urls.append(data[0].get("href")[-11:])
			i += 1
		select = random.randint(0,i-1)
		print(arr_titles[select])
		print(arr_urls[select])
		page.send(sender_id, Template.Generic([
			Template.GenericElement(arr_titles[select],
							subtitle = "邊緣人專用",
							item_url = "https://www.youtube.com/watch?v=" + arr_urls[select],
							image_url = "https://img.youtube.com/vi/" + arr_urls[select] + "/hqdefault.jpg",
							buttons = [
								Template.ButtonWeb("Open Web URL", "https://www.youtube.com/watch?v=" + arr_urls[select])
							])
		]))
		quick_replies = [QuickReply(title="好 拜拜~", payload="PICK_bye")]
		page.send(sender_id, "邊緣人就去看跟邊緣人相關的影片啦><" ,quick_replies=quick_replies,metadata="DEVELOPER_DEFINED_METADATA")
Beispiel #9
0
def show_shirts(result, sender_id):
    a = []
    for i in shirts:
        a.append(
            Template.GenericElement(
                i['name'],
                subtitle=i['price'],
                item_url=i["link"],
                image_url=i["image"],
                buttons=[
                    Template.ButtonWeb("Open Web URL", i["link"]),
                    Template.ButtonWeb("Share", i["link"]),
                    #Template.ButtonPostBack('Bookmark', "ADDTOBOOKMARK"),
                    Template.ButtonPostBack('Buy', "BUY")
                ]))
    page.send(sender_id, Template.Generic(a))
Beispiel #10
0
def callback_footwear(payload, event):
    a = []
    for i in footwear:
        a.append(
            Template.GenericElement(
                i['name'],
                subtitle=i['price'],
                item_url=i["link"],
                image_url=i["image"],
                buttons=[
                    Template.ButtonWeb("Open Web URL", i["link"]),
                    Template.ButtonWeb("Share", i["link"]),
                    #Template.ButtonPostBack('Bookmark', "ADDTOBOOKMARK"),
                    Template.ButtonPostBack('Buy', "BUY")
                ]))
    page.send(event.sender_id, Template.Generic(a))
Beispiel #11
0
def callback_offers(payload, event):
    a = []
    for i in offers:
        a.append(
            Template.GenericElement(
                i['name'],
                subtitle=i['price'],
                item_url=i["link"],
                image_url=i["image"],
                buttons=[
                    Template.ButtonWeb("Explore", i["link"]),
                    Template.ButtonWeb("Share", i["link"]),
                    #Template.ButtonPostBack('Bookmark', "ADDTOBOOKMARK"),
                ]))
    page.send(
        event.sender_id,
        Attachment.Image(
            "https://media.giphy.com/media/Ejn6xH5mnmtMI/giphy.gif"))
    page.send(event.sender_id, Template.Generic(a))
Beispiel #12
0
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")
        ]))
Beispiel #13
0
def build_template(image, title, subtitle, url=None, postback=None):
    buttons = []
    if url:
        buttons.append(Template.ButtonWeb(url["text"], url["content"]))
    if postback:
        buttons.append(
            Template.ButtonPostBack(postback["text"], postback["content"]))
    return Template.GenericElement(title,
                                   subtitle=subtitle,
                                   image_url=image,
                                   item_url=url,
                                   buttons=buttons)
Beispiel #14
0
def addTemplate(eventName, eventDate, eventLink, eventAdress, eventCity,
                idEvent):
    if eventAdress is None:
        return
    urlOfAddress = "http://wispi.tk"
    try:
        urlOfAddress = "https://www.google.fr/maps/place/" + urllib.parse.quote(
            eventAdress)
    except Exception as e:
        alog.error("Cant parse adress " + eventAdress + str(e))

    return Template.GenericElement(
        eventName,
        subtitle=arrow.get(eventDate).humanize(),
        item_url=eventLink,
        image_url=searchImage.getImageUrl(eventName),
        buttons=[
            Template.ButtonWeb("Open in Map", urlOfAddress),
            Template.ButtonWeb("Open Event", eventLink),
            Template.ButtonShare()
        ])
Beispiel #15
0
def init():
    global page
    TABOT_ACCESS_TOKEN = "EAANbYW2bhcwBAHprKcgSrs86S3MFVdVv37auFZBAo4EPzAMTjKNDQuLj9227ai1Agbryvs2QXcHQgf7vHs2Xv0YynvT7XDo4wPAjSHabFyvbJVQfkUkZCJP7PZBRZBcLctaT7MG0aDSJDFZCBbnxcfR8KB48i9YAWLiIAmSmRevoiIfLGWUIY"
    page = Page(TABOT_ACCESS_TOKEN)
    page.show_starting_button("GET_START")
    page.greeting(
        "Hi {{user_first_name}}! TaBot is Messenger Bot to help you know more about Celcom Prepaid Package. Let's Get Started!"
    )
    page.show_persistent_menu([
        Template.ButtonPostBack("Available command ⚛️", 'COMMAND'),
        Template.ButtonWeb("Celcom website 📱", "https://www.celcom.com.my"),
        Template.ButtonPostBack("tabot", 'START')
    ])
Beispiel #16
0
def send_location(recipient):
    print('-----------------------------enviar---ubicacion-------------------------------------------------')
    page.send(recipient, "Estos son los resultados que encontramos")
    page.send(recipient, Template.Generic([
        Template.GenericElement("Hotel San Francisco",
                                subtitle="Haz tu reservación",
                                image_url=CONFIG['SERVER_URL'] + "/assets/hotel_san_francisco.jpg",
                                buttons=[
                                    Template.ButtonWeb("Ruta", "https://www.google.com.mx/maps/dir/19.2963254,-99.1855357/Hotel+San+Francisco+Centro+Hist%C3%B3rico,+Luis+Moya,+Cuauht%C3%A9moc,+Ciudad+de+M%C3%A9xico,+CDMX/@19.3615022,-99.2475501,12z/data=!3m1!4b1!4m9!4m8!1m1!4e1!1m5!1m1!1s0x85d1fa2819fbd205:0x459bfda439d1d2aa!2m2!1d-99.1449614!2d19.434211")
                                ]),
        Template.GenericElement("Grand Hotel Ciudad de Mexico",
                                subtitle="Haz tu reservación",
                                image_url=CONFIG['SERVER_URL'] + "/assets/hotel_ciudad_mexico.jpg",
                                buttons=[
                                    Template.ButtonWeb("Ruta", "https://www.google.com.mx/maps/dir/19.2963254,-99.1855357/Gran+Hotel+Ciudad+de+M%C3%A9xico,+Av.+16+de+Septiembre+82,+Centro,+06000+Cuauht%C3%A9moc,+CDMX/@19.3610787,-99.246697,12z/data=!3m1!4b1!4m9!4m8!1m1!4e1!1m5!1m1!1s0x85ce0157191d1341:0xd6e6ab909104fb4c!2m2!1d{{longitude}}!2d{{latitude}}")
                                ]),
        Template.GenericElement("Hotel Isabel la Catolica",
                                subtitle="Haz tu reservación",
                                image_url=CONFIG['SERVER_URL'] + "/assets/hotel_isabel.jpg",
                                buttons=[
                                    Template.ButtonWeb("Ruta", "https://www.google.com.mx/maps/dir/19.2961852,-99.1855789/Hotel+Isabel,+Isabel+la+Cat%C3%B3lica+63,+Centro+Hist%C3%B3rico,+Centro,+06000+Ciudad+de+M%C3%A9xico,+CDMX/@19.3593533,-99.2125291,13z/data=!3m1!4b1!4m9!4m8!1m1!4e1!1m5!1m1!1s0x85d1fed2ef819f19:0x65f5a7cded682f87!2m2!1d{{longitude}}!2d{{latitude}}")])
    ]))
Beispiel #17
0
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")
    ]))
Beispiel #18
0
def generate_summaries(name,sentences):
    # NOTE : we don't need to store summary , instead storing the links would be enough .

    articles = subscribe.subscribe_model(name)      # link , headline , date==None , image_url , sentences(list)
    if articles == None :
        return False
    results = []
    '''
    Set a "View More Articles" Option Over here instead of max_articles
    '''
    for article in articles:
        # breakpoint tests
        '''
        Issue : Default use of Generic Template <subtitle section> 60chars, <title section> 60 chars ,List view( No - Image ) 640 chars

        '''
        article_url = article[0]
        headline = article[1]
        publish_date = article[2]
        top_image_url  = article[3]
        summary_list = []
        concate_news = headline
        if len(article)==5:
            concate_news = article[4]

        # recheck TODO
        sum_keys = sorted(SUMMARIES.keys())

        if len(sum_keys) > max_local_summaries :
            del SUMMARIES[sum_keys[0]]

        if not len(sum_keys):
            hash_index = 0
        else:
            hash_index = sum_keys[-1]

        results.append(Template.GenericElement(headline,
                subtitle = name ,
                image_url = top_image_url,
                buttons=[
                        Template.ButtonWeb("Read More", article_url),
                        Template.ButtonPostBack("Summarize", "DEVELOPED_DEFINED_PAYLOAD" + str(hash_index+1)),    #     maybe a SHARE button ?
                            # Template.ButtonPhoneNumber("Call Phone Number", "+16505551234")
                        ])
                )
        SUMMARIES[hash_index+1] = [top_image_url,concate_news]
    print("reached Line:227")
    return results
Beispiel #19
0
	def on_enter_man(self, event):
		print("I'm entering man")
		sender_id = event['sender']['id']
		responses = ["atGbcYTjZCY", "KEgOrgcLu0s", "Dnj5Tcpev0Q", "s-CcFyyPJiY", "wFqUAw_NYvs", "JfnQ8qtcDyQ"]
		select = random.choice(responses)
		page.send(sender_id, Template.Generic([
			Template.GenericElement("男歌手歌曲",
							subtitle ="  ",
							item_url = "https://www.youtube.com/watch?v=" + select,
							image_url = "https://img.youtube.com/vi/" + select + "/hqdefault.jpg",
							buttons = [
								Template.ButtonWeb("Open Web URL", "https://www.youtube.com/watch?v=" + select)
							])
		]))
		quick_replies = [QuickReply(title="好 拜拜~", payload="PICK_bye")]
		page.send(sender_id, "隨機推薦你一位男歌手的歌囉~" ,quick_replies=quick_replies,metadata="DEVELOPER_DEFINED_METADATA")
Beispiel #20
0
	def on_enter_woman(self, event):
		print("I'm entering woman")
		sender_id = event['sender']['id']
		responses = ["P8uJ4gFjJGE", "3mEeKAdXAo4", "ma7r2HGqwXs", "VGHLqi_mxnk", "NYYuVnjg0SQ", "FqrzCxSWaZY", "k8jAqe9QZ7I", "BRcudpJzy1I"]
		select = random.choice(responses)
		page.send(sender_id, Template.Generic([
			Template.GenericElement("女歌手歌曲",
							subtitle ="  ",
							item_url = "https://www.youtube.com/watch?v=" + select,
							image_url = "https://img.youtube.com/vi/" + select + "/hqdefault.jpg",
							buttons = [
								Template.ButtonWeb("Open Web URL", "https://www.youtube.com/watch?v=" + select)
							])
		]))
		quick_replies = [QuickReply(title="好 拜拜~", payload="PICK_bye")]
		page.send(sender_id, "隨機推薦你一位女歌手的歌囉~" ,quick_replies=quick_replies,metadata="DEVELOPER_DEFINED_METADATA")
Beispiel #21
0
def get_news(sources):
    NEWS_API_KEY='1bae2e39f2b540f3a15dbbcb269eba9b'
    articles=Articles(API_KEY=NEWS_API_KEY)
    info=articles.get(source=sources)
    news_array=[]
    news_objects=[]
    length_of_articles=len(info['articles'])
    for i in range(0,int(length_of_articles)):
        headline=info['articles'][i]['title']
        body=info['articles'][i]['description']
        url_web=info['articles'][i]['url']
        image=info['articles'][i]['urlToImage']
        time=info['articles'][i]['publishedAt']
        news_objects.append(Template.GenericElement(title=headline,subtitle=body,item_url=url_web,
        image_url=image,buttons=[Template.ButtonWeb(title='Open in web',url=url_web)]))
    return news_objects
Beispiel #22
0
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
Beispiel #23
0
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)
Beispiel #24
0
def message_handler(event):
    restaurant = facebook.receive_message(event)
    if restaurant is None:
        page.send(event.sender_id, 'Sorry, I couldn\'t find a place with that '
            'description')
    else:
        page.send(event.sender_id,
            Template.Generic([
                Template.GenericElement(
                    restaurant.name,
                    subtitle='\n'.join(restaurant.raw_yelp_data.get('display_address', [])),
                    image_url=restaurant.raw_yelp_data.get('image_url'),
                    buttons=[
                        Template.ButtonWeb("View in Yelp",
                                           restaurant.raw_yelp_data['url']),
                        Template.ButtonPhoneNumber("Call",
                                                   restaurant.raw_yelp_data.get('phone'))
                    ]
                )
            ])
        )
Beispiel #25
0
def send_generic(recipient):
    page.send(
        recipient,
        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",
                                            "DEVELOPED_DEFINED_PAYLOAD"),
                    Template.ButtonPhoneNumber("Call Phone Number",
                                               "+16505551234")
                ]),
            Template.GenericElement(
                "touch",
                subtitle="Your Hands, Now in VR",
                item_url="https://www.oculus.com/en-us/touch/",
                image_url=CONFIG['SERVER_URL'] + "/assets/touch.png",
                buttons=[
                    {
                        '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'
                    },
                ])
        ]))
Beispiel #26
0
def message_handler(event):
    """:type event: fbmq.Event"""
    sender_id = event.sender_id
    message = event.message_text

    # try Menu
    buttons = [
        Template.ButtonWeb("Open Web URL", "https://www.codeforces.com"),
        Template.ButtonPostBack("Subscribe", "www.nytimes.com"),
        Template.ButtonPhoneNumber("Call Phone Number", "+91")
    ]

    user_profile = page.get_user_profile(sender_id)

    page.typing_on(sender_id)
    page.typing_off(sender_id)

    #print(user_profile)
    if bot(message,sender_id):
        print("Bot results")
    else:
        page.send(sender_id,"Didn't get you ")
Beispiel #27
0
def callback_menu(payload, event):
    "A callback for any MENU payload we get. "
    sender_id = event.sender_id
    page.typing_on(sender_id)
    prefix, metadata = decode_payload(payload)
    app.logger.debug('Got MENU: {} '.format(metadata['menu']))
    if metadata['menu'] == 'startquiz':
        quiz(event)
    elif metadata['menu'] == 'watchshow':
        tpl = Template.Generic([
            Template.GenericElement(env('WEBPAGE_TITLE'),
                                    subtitle=env('WEBPAGE_SUBTITLE'),
                                    item_url=env('WEBPAGE_URL'),
                                    image_url=env('WEBPAGE_LOGO'),
                                    buttons=[
                                        Template.ButtonWeb(
                                            _('Watch it now'),
                                            env('WEBPAGE_URL'))
                                    ])
        ])
        page.send(sender_id, tpl)
    elif metadata['menu'] == 'talk':
        # TODO: Figure out how to make a dialogue work
        page.send(sender_id, _("Yes. What do you want to say?"))
Beispiel #28
0
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")
Beispiel #29
0
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 😎")
Beispiel #30
0
def determine_web_com(payload, event):
    sender_id = event.sender_id
    plan = payload.split("_")[0]

    if "YES" in payload:
        page.send(sender_id, "Ok, wait a minute. I will get the answer now")
        page.typing_on(sender_id)
        if plan == "PREPAID":
            page.send(
                sender_id,
                Template.Generic([
                    Template.GenericElement(
                        "Prepaid FAQ",
                        subtitle="Faq about prepaid plan",
                        item_url=
                        "https://www.celcom.com.my/support/faq/personal",
                        buttons=[
                            Template.ButtonWeb(
                                "Get Answer",
                                "https://www.celcom.com.my/support/faq/personal"
                            )
                        ])
                ]))
        elif plan == "POSTPAID":
            page.send(
                sender_id,
                Template.Generic([
                    Template.GenericElement(
                        "Postpaid FAQ",
                        subtitle="Faq about postpaid plan",
                        item_url=
                        "https://www.celcom.com.my/support/faq/personal#personal-postpaid-plans-first-gold",
                        buttons=[
                            Template.ButtonWeb(
                                "Get Answer",
                                "https://www.celcom.com.my/support/faq/personal#personal-postpaid-plans-first-gold"
                            )
                        ])
                ]))
    else:
        if plan == "PREPAID":
            page.send(sender_id,
                      "Then, I am assuming you ask about postpaid plan!")
            page.typing_on(sender_id)
            page.send(
                sender_id,
                Template.Generic([
                    Template.GenericElement(
                        "Postpaid FAQ",
                        subtitle="Faq about postpaid plan",
                        item_url=
                        "https://www.celcom.com.my/support/faq/personal#personal-postpaid-plans-first-gold",
                        buttons=[
                            Template.ButtonWeb(
                                "Get Answer",
                                "https://www.celcom.com.my/support/faq/personal#personal-postpaid-plans-first-gold"
                            )
                        ])
                ]))
        elif plan == "POSTPAID":
            page.send(sender_id,
                      "Then, I am assuming you ask about prepaid plan!")
            page.typing_on(sender_id)
            page.send(
                sender_id,
                Template.Generic([
                    Template.GenericElement(
                        "Prepaid FAQ",
                        subtitle="Faq about prepaid plan",
                        item_url=
                        "https://www.celcom.com.my/support/faq/personal",
                        buttons=[
                            Template.ButtonWeb(
                                "Get Answer",
                                "https://www.celcom.com.my/support/faq/personal"
                            )
                        ])
                ]))