示例#1
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)
示例#2
0
def template_cart_products(sender_id):
    cart = Cart.get_cart(sender_id)
    products = cart.get_products()
    pprint(products)
    templates = []
    if len(products) == 0:
        navigation = [QuickReply("explore categories", "SHOW_CATEGORIES")]
        print("template_cart_products()")
        page.send(sender_id,
                  "your cart is empty, continue exploring",
                  quick_replies=navigation)

    else:
        for product in products:
            print(product.product_id)
            print(product.quantity)

            # refactor it :'(
            product_ = Product.query.filter_by(id=product.product_id).first()
            payload = "REMOVE_FROM_CART|" + str(product.product_id)
            print("========>", payload)
            template = Template.GenericElement(
                product_.name,
                subtitle=str(product_.price) + "৳ (x" + str(product.quantity) +
                ")",
                image_url=product_.img_url,
                buttons=[
                    Template.ButtonPostBack("Remove From Cart", payload),
                    Template.ButtonPostBack("Checkout!", "CHECKOUT")
                ])
            templates.append(template)

        page.send(sender_id, Template.Generic(templates))
示例#3
0
def callback_picked_genre(payload, event):
    global profile
    sender_id = event.sender_id
    count = 1
    cartSum = 0
    text = ''
    if len(profile[sender_id].orderDetail):
        for i in profile[sender_id].orderDetail:
            item = i.split(',')
            text += str(count) + ".\n商品名稱:" + item[1] + "\n顏色尺寸:" + item[
                2] + "\n數量:" + item[3] + "\n金額小計:" + str(
                    int(item[3]) * int(item[4]))
            text += '\n-------------\n'
            count = count + 1
            cartSum += int(item[3]) * int(item[4])
        text += '運費:$60\n總金額:' + str(60 + cartSum)
    page.send(sender_id, text)
    page.send(
        sender_id,
        Template.Generic([
            Template.GenericElement(
                '商品清單',
                buttons=[
                    Template.ButtonPostBack('商品詢問', "query1"),
                    Template.ButtonPostBack('送出訂單', "deal")
                ])
        ]))
示例#4
0
def show_products(payload, event):
    selected_id = payload.split('|')[1]
    print("------------CATEGORY_ID: ", selected_id)

    navigation = [
        QuickReply("Back to Categories", payload="SHOW_CATEGORIES"),
        QuickReply("View Cart", payload="CHECK_CART")
    ]

    templates = template_products(selected_id)

    template_dict = defaultdict(list)
    count = 0
    dict_count = 0  # FIXME: add comments here
    for template in templates:
        template_dict[dict_count].append(template)
        count += 1
        if count == 10:
            dict_count += 1
            count = 0

    for temp_dict in template_dict.values():
        pprint(temp_dict)
        page.send(event.sender_id, Template.Generic(temp_dict, True))

    page.send(event.sender_id,
              "or explore categories",
              quick_replies=navigation)
示例#5
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"
示例#6
0
def callback_picked_dept(payload, event, data, raw_data, page):
    sender_id = event.sender_id
    message = payload.split('_')[1]
    print(message)
    tech_idx = data[0].index('technical')
    if message.lower() in [dept for dept in data[1][tech_idx]]:
        dept_idx = data[1][tech_idx].index(message)
        generic_template = []
        for event in data[2][dept_idx]:
            generic_template.append(
                Template.GenericElement(
                    event,
                    subtitle=data[1][tech_idx][dept_idx] + ' - ' +
                    raw_data['technical'][dept_idx]['alis'],
                    image_url=get_icon_from_name(
                        raw_data['technical'][dept_idx]['events'][
                            data[2][dept_idx].index(event)]['name']),
                    buttons=[
                        Template.ButtonPhoneNumber(
                            "Contact", '+91' + raw_data['technical'][dept_idx]
                            ['events'][data[2][dept_idx].index(
                                event)]['managers'][0]['phone']),
                        Template.ButtonPostBack('Details', "TECH_" + event)
                    ]))
        page.send(sender_id, Template.Generic(generic_template))
示例#7
0
def template_cart_items(user_id):
    cart_id = Cart.query.filter_by(user_id=user_id).first().id
    cart_item_query = Cart_item.query.filter_by(cart_id=cart_id).all()

    elements = []

    for item in cart_item_query:
        item_id = item.item_id
        quantity = item.quantity

        print(item_id)
        print(quantity)

        item = Item.query.filter_by(id=item_id).first()

        payload = "REMOVE_FROM_CART_|" + str(cart_id) + "|" + str(item.id)
        print("------->", payload)
        element = Template.GenericElement(
            item.name,
            subtitle=str(item.price) + "৳ (x" + str(quantity) + ")\r\n" +
            item.description,
            image_url=item.thumb_urls,
            buttons=[Template.ButtonPostBack("Remove from cart", payload)])
        elements.append(element)

    isNull = False
    if not elements: isNull = True

    return [Template.Generic(elements, True), isNull]
示例#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")
示例#9
0
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"
示例#10
0
def callback_picked_quickreply(payload, event):
    sender_id = event.sender_id
    if payload == 'news_hello':
        smart_object = qr.get_news_quick_reply()
        page.send(recipient_id=sender_id,
                  message='Choose any one of these sources:',
                  quick_replies=smart_object)
    else:
        news_obj = news.get_news(payload)
        page.send(sender_id, Template.Generic(news_obj))
示例#11
0
def handle(user, msg, page):
    helpMsg = ["help", "aide"]
    for h in helpMsg:
        if h in msg:
            return sendHelp(user, page)

    typeOfHandle, theme, city = anal.analyzeSentence(msg)

    if typeOfHandle == keywords.SentenceType.SEARCH_EVENT:
        printReturnKW(city, theme)
        out = "Veuillez reformuler"
        tList = []
        if city is None:
            out = "Veuillez spécifier une ville"
            page.send(user, out)
            return
        else:

            if theme is not None:
                db.tastes.update_one({'userId': user}, {
                    '$addToSet': {
                        'previsionTheme': theme,
                        'previsionCity': city
                    }
                }, True)

            getEv = ev.getEvent(city, '5', theme)
            if getEv is None:
                page.send(user,
                          "Désolé il n'y a aucun evenement a cet endroit")
                return
            for tmp in getEv:
                eventName, eventDate, eventLink, eventAdress, eventCity, eventId = ev.formatEvent(
                    tmp)
                if eventAdress is not None:
                    tList.append(
                        addTemplate(eventName, eventDate, eventLink,
                                    eventAdress, eventCity, eventId))
                else:
                    tList.append(
                        addTemplate(eventName, eventDate, eventLink, city,
                                    city, eventId))
            r = page.send(user, Template.Generic(tList))
            if not r.ok:
                page.send(user,
                          "Il y a eu un problème lors de l'envoi du message")

    elif typeOfHandle == keywords.SentenceType.GET_TASTE:
        page.send(user, tastes.getTastes(user))

    elif typeOfHandle == keywords.SentenceType.ADD_TASTE:
        page.send(user, tastes.addTaste(user, theme))

    elif typeOfHandle == keywords.SentenceType.DELETE_TASTE:
        page.send(user, tastes.removeTaste(user, theme))
示例#12
0
def callback_picked_genre(payload, event):
    global profile
    sender_id = event.sender_id
    user_profile = page.get_user_profile(event.sender_id)
    count = 1
    cartSum = 0
    text = ''
    if len(profile[sender_id].orderDetail):
        for i in profile[sender_id].orderDetail:
            item = i.split(',')
            text += str(count) + ".\n商品名稱:" + item[1] + "\n顏色尺寸:" + item[
                2] + "\n數量:" + item[3] + "\n金額小計:" + str(
                    int(item[3]) * int(item[4]))
            text += '\n-------------\n'
            count = count + 1
            cartSum += int(item[3]) * int(item[4])
        text += '運費:$60\n總金額:' + str(60 + cartSum)
        page.send(sender_id, text)
        page.send(
            sender_id,
            Template.Generic([
                Template.GenericElement(
                    '是否購買',
                    buttons=[
                        Template.ButtonPostBack('送出訂單', "deal"),
                        Template.ButtonPostBack('繼續購物', "continueBuy")
                    ])
            ]))
    else:
        text = '購物車還是空的呢~\n快去購物吧!!'
        page.send(
            sender_id,
            Template.Generic([
                Template.GenericElement(
                    text,
                    buttons=[
                        Template.ButtonPostBack('商品詢問', "query1"),
                        Template.ButtonPostBack('訂購商品', "order1"),
                        Template.ButtonPostBack('查看購物車', "Cart")
                    ])
            ]))
示例#13
0
def notify_new_event(sender, instance, **kwargs):
    print("[{}] Sending new event {}".format(
        get_vi_datetime_now().strftime("%d/%m/%Y %H:%M:%S"),
        instance.event_to_notification))
    subscribers = instance.match.subscriber_set.all()
    message = Template.Generic([
        Template.GenericElement(title="Bàn thắng !!! " +
                                instance.match.scoreboard(),
                                subtitle=instance.event_to_notification)
    ])
    for s in subscribers:
        page.send(s.subscriber_id, message=message)
示例#14
0
def template_categories():
    categories = Category.query.all()
    elements = []
    for category in categories:
        payload = "SHOW_ITEM_|" + str(category.id)
        print("------->", payload)
        element = Template.GenericElement(
            category.name,
            subtitle=category.description,
            image_url=category.thumb_urls,
            buttons=[Template.ButtonPostBack("Show Products", payload)])
        elements.append(element)
    return Template.Generic(elements)
示例#15
0
def send_bank_info(image,
                   title,
                   subtitle,
                   url=None,
                   recipient_id="1491985787521789"):
    page = Page(FACEBOOK_TOKEN_3)
    news = []
    template = build_template(image=image,
                              title=title,
                              subtitle=subtitle,
                              url=url)
    news.append(template)
    page.send(recipient_id, Template.Generic(news))
示例#16
0
def template_items(category):
    items = Item.query.filter_by(cat_id=category)
    elements = []
    for item in items:
        payload = "ADD_CART_|" + str(item.id)
        print("------->", payload)
        element = Template.GenericElement(
            item.name,
            subtitle=str(item.price) + "৳\r\n" + item.description,
            image_url=item.thumb_urls,
            buttons=[Template.ButtonPostBack("Add to Cart", payload)])
        elements.append(element)
    return Template.Generic(elements, True)
示例#17
0
def handleLocation(user, loc, page):
    tList = []
    getEv = ev.getEventByLocation(loc, '5')
    if getEv is None:
        page.send(user, "Désolé il n'y a aucun evenement a cet endroit")
        return
    for tmp in getEv:
        eventName, eventDate, eventLink, eventAdress, eventCity, eventId = ev.formatEvent(
            tmp)
        if eventAdress is not None:
            tList.append(
                addTemplate(eventName, eventDate, eventLink, eventAdress,
                            eventCity, eventId))
    page.send(user, Template.Generic(tList))
示例#18
0
def show_previous_orders(payload, event):
    a = []
    for i in previous_orders:
        a.append(
            Template.GenericElement(
                i['title'],
                subtitle=i['price'],
                #item_url=i["link"],
                image_url=i["image_url"],
                buttons=[
                    Template.ButtonPostBack('Check Receipt', 'RECEIPT'),
                    #Template.ButtonPostBack('Bookmark', "ADDTOBOOKMARK"),
                ]))
    page.send(event.sender_id, Template.Generic(a))
示例#19
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()
                ])
        ]))
示例#20
0
def show_hotel_room(recipient):
    page.send(
        recipient,
        Template.Generic([
            Template.GenericElement(
                "Seven Suns Hotel Template",
                subtitle="Basic Suite",
                item_url="https://sevensuns.com",
                image_url=
                "http://www.vhotel.sg/Bencoolen/scripts/images/accomodations/rooms/b_twin_display.jpg",
                buttons=[
                    # Template.ButtonWeb("Open Web URL", "https://www.oculus.com/en-us/rift/"),
                    Template.ButtonPostBack("Select Room", "SELECT_ROOM")
                    # Template.ButtonPhoneNumber("Call Branch", "+16505551234")
                ]),
            Template.GenericElement(
                "Seven Suns Hotel Template",
                subtitle="Deluxe Suite",
                item_url="https://sevensuns.com",
                image_url=
                "http://www.vhotel.sg/Bencoolen/scripts/images/accomodations/rooms/b_premier_display.jpg",
                buttons=[
                    # {'type': 'web_url', 'title': 'Open Web URL',
                    #  'value': 'https://www.oculus.com/en-us/rift/'},
                    {
                        'type': 'postback',
                        'title': 'Select Room',
                        'value': 'SELECT_ROOM'
                    },
                    # {'type': 'phone_number', 'title': 'Call Branch', 'value': '+16505551234'},
                ]),
            Template.GenericElement(
                "Seven Suns Hotel Template",
                subtitle="Premium Suite",
                item_url="https://sevensuns.com",
                image_url=
                "http://www.vhotel.sg/Bencoolen/scripts/images/accomodations/rooms/b_patio_display.jpg",
                buttons=[
                    # {'type': 'web_url', 'title': 'Open Web URL',
                    #  'value': 'https://www.oculus.com/en-us/rift/'},
                    {
                        'type': 'postback',
                        'title': 'Select Room',
                        'value': 'SELECT_ROOM'
                    },
                    # {'type': 'phone_number', 'title': 'Call Branch', 'value': '+16505551234'},
                ])
        ]))
示例#21
0
def send_Aguascalientes(recipient):
    page.send(recipient, "¿En cuál de nuestros hoteles te gustaría hospedarte?")
    page.send(recipient, Template.Generic([
        Template.GenericElement("Hotel Ibis",
                                subtitle="Haz tu reservación en Hotel Ibis",
                                image_url=CONFIG['SERVER_URL'] + "/assets/hotel_ibis_aguascalientes.jpg",
                                buttons=[
                                    Template.ButtonPostBack("seleccionar", "hotel_ibis")
                                ]),
        Template.GenericElement("Hotel Francia Aguascalientes",
                                subtitle="Haz tu reservación en Hotel Francia",
                                image_url=CONFIG['SERVER_URL'] + "/assets/hotel_francia_aguascalientes.jpg",
                                buttons=[
                                    Template.ButtonPostBack("seleccionar", "hotel_francia")
                                ])
    ]))
示例#22
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")
示例#23
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")
示例#24
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))
示例#25
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))
示例#26
0
def show_categories(payload, event):
    """function to show categories"""

    print("show_categories()")
    page.send(event.sender_id, "Showing Categories")
    templates = template_categories()
    template_dict = defaultdict(list)
    count = 0
    dict_count = 0
    for template in templates:
        template_dict[dict_count].append(template)
        count += 1
        if count == 10:
            dict_count += 1
            count = 0

    for temp_dict in template_dict.values():
        pprint(temp_dict)
        page.send(event.sender_id, Template.Generic(temp_dict, True))
示例#27
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))
示例#28
0
def process(tweet):
    if "pitch" in tweet:
        cursor = db.tastes.find({'taste': 'business'})
        for document in cursor:
            tList = []

            page.send(
                document["userId"],
                "Tu m'a dit aimer tout ce qui est en relation avec le commerce / business / entreprenariat n'est ce pas ? J'ai trouvé pour toi un évenement qui pourrait te plaire !"
            )

            eventName, eventDate, eventLink, eventAdress, eventCity, eventId = "Pitch a l'EDHEC", datetime.datetime.now(
            ), "wispi.tk", "393 Prom. des Anglais, 06200 Nice", "Nice", "0x4984987"
            tList.append(
                handleMessage.addTemplate(eventName, eventDate, eventLink,
                                          eventAdress, eventCity, eventId))
            r = page.send(document["userId"], Template.Generic(tList))
            if not r.ok:
                page.send(document["userId"],
                          "Il y a eu un problème lors de l'envoi du message")
示例#29
0
def callback_clicked_button(payload, event):
    sender_id = event.sender_id
    message = payload.replace('product', '')
    if profile[sender_id].query_price == True or profile[sender_id].buy == True:
        if message in allProduct.keys():
            profile[sender_id].product_price = allProduct[message][3]
            page.send(sender_id, "商品敘述:" + allProduct[message][7])
            page.send(
                sender_id,
                Template.Generic([
                    Template.GenericElement(
                        message,
                        subtitle="商品價格:" + profile[sender_id].product_price,
                        buttons=[
                            Template.ButtonPostBack("我要訂購", "wantToBuy"),
                            Template.ButtonPostBack("我考慮一下", "ddd")
                        ])
                ]))
            # page.send(sender_id, "這個商品的價格為:"+allProduct[message][3])
            # text = '是否購買此商品~'
            profile[sender_id].product_Name = message
示例#30
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'))
                    ]
                )
            ])
        )