コード例 #1
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"
コード例 #2
0
def callback_answer(payload, event):
    "A callback for any ANSWER payload we get. "
    sender_id = event.sender_id
    page.typing_on(sender_id)
    prefix, metadata = decode_payload(payload)
    app.logger.debug('Got ANSWER: {} (correct? {})'.format(
        metadata, 'YES' if metadata['correct'] else 'NON'))
    if random.random() > 0.9:  # ten percent of the time, send a gif
        giph = get_giphy('CORRECT' if metadata['correct'] else 'WRONG')
        if giph is not None:
            page.send(sender_id, Attachment.Image(giph.url))

    # TODO check how many we have correct
    if not metadata['correct']:
        # wrong answer
        menu(event, menutext=_("Ouch. Wrooooong!:poop: ... Try again!"))
    else:
        # answer is correct, you may continue
        page.send(sender_id, _("Right on!"))
        _prev = metadata['previous']
        notfinished = 7 > len(_prev)
        if notfinished:
            page.send(
                sender_id,
                _("You have {} correct questions, only {} to go!").format(
                    len(_prev), 7 - len(_prev)))
        quiz(event, _prev)
コード例 #3
0
	def on_enter_24hr(self, event):
		print("I'm entering 24hr")

		sender_id = event['sender']['id']
		page.send(sender_id, Attachment.Image("https://i.imgur.com/DQMhbLG.png"))
		quick_replies = [QuickReply(title="好 拜拜~", payload="PICK_bye")]
		page.send(sender_id, "......希望你還有起床的一天><",quick_replies=quick_replies,metadata="DEVELOPER_DEFINED_METADATA")
コード例 #4
0
	def on_enter_dessert(self, event):
		print("I'm entering dessert")

		sender_id = event['sender']['id']
		page.send(sender_id, Attachment.Image("https://i.imgur.com/JKvLLSq.png"))
		quick_replies = [QuickReply(title="好 拜拜~", payload="PICK_bye")]
		page.send(sender_id, "小心胖死><\n不要再吃了~",quick_replies=quick_replies,metadata="DEVELOPER_DEFINED_METADATA")
コード例 #5
0
	def on_enter_12hr(self, event):
		print("I'm entering 12hr")

		sender_id = event['sender']['id']
		page.send(sender_id, Attachment.Image("https://i.imgur.com/WfO1GfO.png"))
		quick_replies = [QuickReply(title="好 拜拜~", payload="PICK_bye")]
		page.send(sender_id, "你還有很多作業跟考試><\n你要被當了QQ",quick_replies=quick_replies,metadata="DEVELOPER_DEFINED_METADATA")
コード例 #6
0
	def on_enter_game(self, event):
		print("I'm entering game")

		sender_id = event['sender']['id']
		page.send(sender_id, Attachment.Image("https://i.imgur.com/KqnRW1R.png"))
		quick_replies = [QuickReply(title="好 拜拜~", payload="PICK_bye")]
		page.send(sender_id, "要小心變臭宅宅哦><\n(但可以找我一起玩!)",quick_replies=quick_replies,metadata="DEVELOPER_DEFINED_METADATA")
コード例 #7
0
    def on_enter_state7(self, event):
        print("I'm entering state7")

        sender_id = event['sender']['id']
        page.send(sender_id,
                  Attachment.Image("https://i.imgur.com/t56acky.jpg"))
        page.send(sender_id, "希望你能繼續保持下去~加油!")
コード例 #8
0
ファイル: main.py プロジェクト: geordanSoapros/soapros-bot
def send_message(token, recipient, text):
    if text == 'Solo puedo manejar texto por ahora':
        print("Mensaje por defecto")
        bot_response = text
    else:
        req_name = requests.get(
            "https://graph.facebook.com/v2.6/{0}?fields=first_name&access_token={1}"
            .format(recipient, PAGE_ACCESS_TOKEN))
        name = json.loads(req_name.text)

        kernel.setPredicate("name", name["first_name"], recipient)
        print(kernel.getPredicate("name", recipient))

        bot_response = kernel.respond(text, recipient)

        dni = kernel.getPredicate("dni", recipient)
        print(dni)
        print(bot_response.find("Se adjuntara su pdf"))

    if bot_response.find("Se adjuntara su pdf") >= 0:
        print("entro if")
        page.send(recipient, bot_response)
        page.send(
            recipient,
            Attachment.File(
                "http://7223bd7f.ngrok.io/documents?dni=012345678"))
    else:
        print("entro else")
        page.send(recipient, bot_response)
コード例 #9
0
ファイル: server.py プロジェクト: team-anything/highOnBot
def callback_clicked_button(payload, event):
    sender_id = event.sender_id
    news_id = int(payload[25:])  # bug
    print(dummy)
    print(news_id)
    # do something with these text   -> To add Headline
    page.send(sender_id, Attachment.Image(image_url))
    page.send(sender_id, summ_ary)
コード例 #10
0
    def on_enter_state3(self, event):
        print("I'm entering state3")

        sender_id = event['sender']['id']
        page.send(sender_id,
                  Attachment.Image("https://i.imgur.com/syy1Cu4.jpg"))
        page.send(sender_id, "不行喔!給我去上課!")
        self.go_back()
コード例 #11
0
def send_prize(event, previous=None):
    "send a prize"
    sender_id = event.sender_id
    message = event.message_text
    page.typing_on(sender_id)
    page.send(sender_id, _("Wow, you're on a nice streak. Here's a prize!"))
    for p in quizprizes:
        app.logger.debug('Prize: {!r}: {} is_embargoed: {}'.format(
            p.url, p.embargo, p.is_embargoed))
    # Send a gif prize
    try:
        prize = random.choice([q for q in quizprizes if not q.is_embargoed])
    except IndexError:
        app.logger.warning('No prizes that are not embargoed!')
        page.send(sender_id, '8)')
    if prize.media_type == 'image':
        att = Attachment.Image(prize.url)
    elif prize.media_type == 'video':
        att = Attachment.Video(prize.url)
    elif prize.media_type == 'text':
        att = prize.url
    page.send(sender_id, att)
コード例 #12
0
    def bot_send_attachment(self,
                            user_model,
                            file_url,
                            file_type,
                            keyboard=None):

        if file_type and file_type.startswith('image'):
            return self._service.send(user_model.conversation_id,
                                      Attachment.Image(file_url),
                                      quick_replies=keyboard)

        if file_type and file_type.startswith('video'):
            return self._service.send(user_model.conversation_id,
                                      Attachment.Video(file_url),
                                      quick_replies=keyboard)

        if file_type and file_type.startswith('audio'):
            return self._service.send(user_model.conversation_id,
                                      Attachment.Audio(file_url),
                                      quick_replies=keyboard)

        return self._service.send(user_model.conversation_id,
                                  Attachment.File(file_url),
                                  quick_replies=keyboard)
コード例 #13
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
コード例 #14
0
ファイル: app.py プロジェクト: chienjchienj/keepbot
def message_handler(event):
    """:type event: fbmq.Event"""
    sender_id = event.sender_id
    message = event.message_text
    attachments = event.message_attachments
    print(attachments)
    type(attachments)
    if attachments:
        for attachment_item in attachments:
            print(attachment_item)
            type(attachment_item)
            if attachment_item.get('type', None) == 'image':
                file_url = attachment_item.get('payload').get('url')
                page.send(sender_id, Attachment.Image(file_url))
                print("saved==>" + file_url)

    else:
        page.send(sender_id, "thank you! your message is '%s'" % message)
コード例 #15
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))
コード例 #16
0
def received_message(event):
    sender_id = event.sender_id
    recipient_id = event.recipient_id
    time_of_message = event.timestamp
    message = event.message
    print("Received message for user %s and page %s at %s with message:" %
          (sender_id, recipient_id, time_of_message))
    print(message)

    seq = message.get("seq", 0)
    message_id = message.get("mid")
    app_id = message.get("app_id")
    metadata = message.get("metadata")

    message_text = message.get("text")
    message_attachments = message.get("attachments")
    quick_reply = message.get("quick_reply")

    seq_id = sender_id + ':' + recipient_id
    if USER_SEQ.get(seq_id, -1) >= seq:
        print("Ignore duplicated request")
        return None
    else:
        USER_SEQ[seq_id] = seq

    if quick_reply:
        quick_reply_payload = quick_reply.get('payload')
        print("quick reply for message %s with payload %s" %
              (message_id, quick_reply_payload))

        page.send(sender_id, "Quick reply tapped")

    if message_text:
        send_message(sender_id, message_text)
    elif message_attachments:
        # page.send(sender_id, "Message with attachment received")
        page.send(
            sender_id,
            Attachment.Image(CONFIG['SERVER_URL'] +
                             random.choice(hodor_images)))
コード例 #17
0
def send_file(recipient):
    #page.send(recipient, Attachment.File(CONFIG['SERVER_URL'] + "/assets/test.txt"))
    page.send(recipient, Attachment.File("https://www.qa.dineroexpress.com.mx/img/137435869.jpg"))
コード例 #18
0
def send_audio(recipient):
    page.send(recipient, Attachment.Audio(CONFIG['SERVER_URL'] + "/assets/sample.mp3"))
コード例 #19
0
def send_video(recipient):
    page.send(recipient, Attachment.Video(CONFIG['SERVER_URL'] + "/assets/allofus480.mov"))
コード例 #20
0
def send_image(recipient):
    print('00000000000000000000000000000000000000000000000000000000000000')
    print(recipient)
    print('00000000000000000000000000000000000000000000000000000000000000')
    #page.send(recipient, Attachment.Image(CONFIG['SERVER_URL'] + "https://www.qa.dineroexpress.com.mx/img/137435869.jpg"))
    page.send(recipient, Attachment.Image("https://www.qa.dineroexpress.com.mx/img/137435869.jpg"))
コード例 #21
0
def send_gif(recipient):
    page.send(recipient, Attachment.Image(CONFIG['SERVER_URL'] + "/assets/instagram_logo.gif"))
コード例 #22
0
def send_file(recipient):
    page.send(recipient,
              Attachment.File(CONFIG['SERVER_URL'] + "/assets/test.txt"))
コード例 #23
0
ファイル: app.py プロジェクト: catiagd/fbbot
def webhook():
    # Processa msg
    data = request.get_json()
    log(data)
    if data["object"] == "page":
        for entry in data["entry"]:
            for messaging_event in entry["messaging"]:
                exemplos = [
                    "Peço imensa desculpa, não pense que sou um bot burro.....DITO ISTO.... Não faço ideia do que disse... sorry :D",
                    "Não sei essa palavra :c Desculpa! Mas os nossos donos foram avisados!",
                    "Bolas, peço imensa desculpa mas não consigo lhe ajudar..."
                ]
                if messaging_event.get("message"):  # Alguem mandou algo
                    if messaging_event['message'].get('text'):
                        sender_id = messaging_event["sender"][
                            "id"]  # the facebook ID da pessoa
                        recipient_id = messaging_event["recipient"][
                            "id"]  # the recipient's ID da pagina
                        message_text = messaging_event["message"][
                            "text"]  # the text
                        page.typing_on(sender_id)
                        if message_text == "Ajuda!":
                            page.send(sender_id, "Com o que podemos ajudar?")
                        elif message_text == "Que dia e hoje?":
                            page.send(sender_id, ("{}".format(
                                datetime.now().strftime("%d/%m/%Y"))))
                        elif message_text == "Publica-me isto sff":

                            page.send(sender_id, "Ok! :D")
                            #print friends_and_education
                        else:
                            msg = random.choice(exemplos)
                            page.send(sender_id, msg)
                    if messaging_event['message'].get('attachments'):
                        sender_id = messaging_event["sender"][
                            "id"]  # O facebook ID da pessoa
                        recipient_id = messaging_event["recipient"][
                            "id"]  # O recipient's ID da pagina
                        teste = messaging_event["message"][
                            "attachments"]  #Para ver o type
                        if 'image' in str(teste[0]):
                            if random.choice(numbergen) == 1:
                                msg = get_message('image')
                                page.send(sender_id, msg)
                            else:
                                image_url = get_att('image')
                                page.send(sender_id,
                                          Attachment.Image(image_url))
                        elif 'file' in str(teste[0]):
                            msg = "Files são dubios"
                            page.send(sender_id, msg)
                        elif 'video' in str(teste[0]):
                            msg = get_message('video')
                            page.send(sender_id, msg)
                        elif 'audio' in str(teste[0]):
                            msg = get_message('audio')
                            page.send(sender_id, msg)
                        else:
                            msg = "Já o vou ver"
                            page.send(sender_id, msg)
                            #page.send(sender_id,Attachment.Image(image_url))
                if messaging_event.get("delivery"):  # delivery confirmation
                    pass

                if messaging_event.get("optin"):  # optin confirmation
                    pass

                if messaging_event.get(
                        "postback"
                ):  # user clicked/tapped "postback" button in earlier message
                    pass

    return "ok", 200
コード例 #24
0
	def on_exit_year(self, event):
		print('Leaving year')
		sender_id = event['sender']['id']
		page.send(sender_id, Attachment.Image("https://i.imgur.com/4w2XREA.png"))
		page.send(sender_id, "87期末考不讀書 只會讓學校發財啦")
コード例 #25
0
def send_image(recipient):
    page.send(recipient,
              Attachment.Image(CONFIG['SERVER_URL'] + "/assets/rift.png"))
コード例 #26
0
def message_handler(event): #Trabalha as msg
    sender_id = event.sender_id #O id da pessoa que envia a msg
    timestamp = event.timestamp #timestamp
    message = event.message #A mensagem
    page.typing_on(sender_id) #Faz com que aquelas bolinhas fancy aparecam
    page_id = page.page_id #O id da nossa pagina
    page_name = page.page_name #O nome da nossa pagina
    user_profile = page.get_user_profile(sender_id) #Infos do user em formato de dicionario
    nomeuser=(user_profile.get("first_name")+" "+user_profile.get("last_name")) #Log sobre o user
    print(user_profile)
    if message.get("attachments"): #se a msg é um attachments
        if 'image' in str(message.get("attachments")): #Se e uma imaghem
            if '369239263222822' in str(message.get("attachments")): #Se e o fixezinho
                image_url=Handle.get_att('thumbs')
                page.send(sender_id,Attachment.Image(image_url))
            else: #Imagem normal
                if Handle.get_num() == 1: #Envia txt
                    msg=Handle.get_message('image')
                    page.send(sender_id,msg)
                else: #Envai imagem
                    image_url=Handle.get_att('image')
                    page.send(sender_id,Attachment.Image(image_url))
        elif 'video' in str(message.get("attachments")): #Se for video
            msg=Handle.get_message('video')
            page.send(sender_id,msg)
        elif 'audio' in str(message.get("attachments")): #Se for audio
            msg=Handle.get_message('audio')
            page.send(sender_id,msg)
        elif 'file' in str(message.get("attachments")): #Se for file
            page.send(sender_id,"Files são dubios")
        else: #Fault tolerance
            page.send(sender_id,"Já o vou ver! :D")
    elif message.get("quick_reply"): #Se for um quick_reply
        if "PICK_MENU" in str(message.get("quick_reply")): #Se tiver escolhido o menu
            page.send(sender_id,Template.Buttons("Nosso menu",buttons.btnmenu))
        elif "PICK_MUS" in str(message.get("quick_reply")): #Se tiver escolhido o menu de musica
            page.send(sender_id,"Qual é o seu genero de música favorito?",quick_replies=quickReply.quick_musica,metadata="TEST")
        elif "PICK_PRECO" in str(message.get("quick_reply")): #Se tiver escolhido o Preço
            page.send(sender_id,"Deste momento não disponibilizamos preços. Obrigado.")
        else: #Se for de um genero musical
            video_url=quickReply.get_music((message.get("quick_reply")).get('payload'))
            page.send(sender_id,video_url)
    elif message.get("text"): #Se for texto
        message = event.message_text #Guarda o texto
        print(message)
        message = unicodedata.normalize('NFKD', message).encode('ASCII', 'ignore').decode().lower() #nomralliza a string
        if message.upper() in smile:
            page.send(sender_id,Handle.get_message('smile'))
        elif message in QuestaoPreco:
            page.send(sender_id,"o range é de 10 a 100 euros")
        elif message in saudacoes:
            page.send(sender_id,"Saudações")
        elif message in vidal:
            page.send(sender_id, "a resposta é sempre DARIO\n https://www.youtube.com/watch?v=vTIIMJ9tUc8")
        elif message in nome:
            page.send(sender_id, "eu sou o Bot, um robot simpático")
        elif message == ('gostas de pigoitinhas?'):
            page.send(sender_id, "eu sim, o marco só deles duros")
        elif message in perg_area:
            page.send(sender_id, "estamos na area da diversão, vendemos produtos recriativos :)")
        elif message in perg_servc:
           page.send(sender_id, "questões mais especificas serão remetidas para os administradores da págida e respondidas com a maior brevidade possivel")
        elif message == "menu":
            page.send(sender_id,Template.Buttons("Nosso menu",buttons.btnmenu))
        else: #Mensagem default caso o bot nao saiba o que fazer
            msg = Handle.get_message('text')
            page.send(sender_id,msg,quick_replies=quickReply.default_menu,metadata="TEST")
コード例 #27
0
ファイル: server.py プロジェクト: team-anything/highOnBot
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("=" * 100)

    if "username" in message.lower():
        hostname, username, password = message.split("\n")
        hostname = hostname[9:]
        password = password[9:]
        username = username[9:]

        print(hostname, username, password, sender_id)
        current_path = str(
            shell_commands(hostname, username, password,
                           "pwd").decode("utf-8"))[:-1]
        addUser(sender_id, hostname, username, password, current_path)

        page.send(sender_id, "Go Ahead! Have Fun! ")
    elif "help" in message:
        page.send(sender_id, "Just 3 easy steps to follow 🚶")
        page.send(
            sender_id,
            Template.Generic([
                Template.GenericElement(
                    "Connect 🤝",
                    subtitle="",
                    item_url="",
                    image_url="https://i.imgur.com/xXy4kib.png",
                    buttons=[
                        Template.ButtonWeb(
                            "Step 1", "https://www.oculus.com/en-us/rift/")
                    ]),
                Template.GenericElement(
                    "Add ➕",
                    subtitle="",
                    item_url="",
                    image_url="https://i.imgur.com/RzjPKZM.png",
                    buttons=[
                        Template.ButtonWeb(
                            "Step 2", "https://www.oculus.com/en-us/rift/")
                    ]),
                Template.GenericElement(
                    "Go ✅",
                    subtitle="",
                    item_url="",
                    image_url="https://i.imgur.com/NmNXnc7.png",
                    buttons=[
                        Template.ButtonWeb(
                            "Step 3", "https://www.oculus.com/en-us/rift/")
                    ])
            ]))
    else:
        response = getUser(sender_id)

        if not response:
            quick_replies = [
                QuickReply(title="Yeah !", payload="PICK_SSH"),
                QuickReply(title="Nah ", payload="PICK_NSSH")
            ]
            page.send(sender_id,
                      "Would you like to configure your ssh ",
                      quick_replies=quick_replies,
                      metadata="DEVELOPER_DEFINED_METADATA")
        else:
            # print(hostname,username,password,message)
            hostname, username, password, current_path = response

            if message[:2] == "cd":
                # add cd
                need_path = message[3:]
                current_path = os.path.join(current_path, need_path)
                try:
                    new_path = str(
                        shell_commands(hostname, username, password,
                                       "cd " + current_path +
                                       "; pwd").decode("utf-8"))[:-1]
                    updatePath(sender_id, new_path)
                    page.send(sender_id,
                              "Your Current Directory:\n" + new_path)
                except:
                    page.send(sender_id, "Path doesn't exist")
            elif "send" in message:
                file_name = message.split()[-1]
                if send_commands(current_path + "/" + file_name, file_name,
                                 hostname, username, password):
                    debug(659)
                    print(CONFIG['SERVER_URL'] + "/" + file_name)
                    os.rename("./" + file_name, "./static/" + file_name)
                    page.send(sender_id, "Here You Go!")
                    page.send(
                        sender_id,
                        Attachment.File(CONFIG['SERVER_URL'] + "/static/" +
                                        file_name))
                else:
                    page.send(sender_id, "Error Accessing the file !!")
            elif message != "Nah ":
                try:
                    result = str(
                        shell_commands(hostname, username, password,
                                       "cd " + current_path + "; " +
                                       message).decode("utf-8"))
                    result = result[:min(150, len(result))]
                    page.send(sender_id, result)
                except:
                    page.send(sender_id, "Unknown Output!")

            print("Bot results!")
コード例 #28
0
ファイル: app.py プロジェクト: ArthurG/Byke
def process_string_message(event):
    user = get_user_or_signup(event.sender_id)
    msg_string = event.message_text
    if msg_string == "unlock bike":
        bikes = user.bikes
        if (user.signed_out_bike != None):
            page.send(
                user.fb_id,
                "Please return all bikes before signing out another one")
            return
        quick_replies = [
            QuickReply(title=bike.name, payload="UNLOCK_BIKE_" + str(bike.id))
            for bike in bikes if not bike.signed_out
        ]
        if (len(quick_replies) == 0):
            page.send(user.fb_id,
                      "You do not have any bikes avaliable for rent!")
            return
        page.send(user.fb_id,
                  "Which bike are you looking to unlock?",
                  quick_replies=quick_replies)
    elif msg_string == "lock bike":
        bike = user.signed_out_bike
        if bike == None:
            page.send(user.fb_id,
                      "I can't seem to find a signed out bike for you")
            return
        location = QuickReply("Send Location", "LOCK_LOCATION")
        location.content_type = "location"
        quick_replies = [location]
        bike.signed_out = False
        user.past_action = "lock_bike"
        db.session.commit()
        page.send(user.fb_id,
                  "Got it! Can I get the location that you're currently at?",
                  quick_replies=quick_replies)
    elif len(event.message_attachments
             ) > 0 and event.message_attachments[0].get("payload", {}).get(
                 "coordinates", False):
        coords = (event.message_attachments[0].get("payload", {}).get(
            "coordinates", False))
        if (user.past_action == "lock_bike"):
            bike = user.signed_out_bike
            if bike == None:
                return
            bike.stored_lat = coords.get("lat", 0)
            bike.stored_lng = coords.get("long", 0)
            bike.signed_out = False
            user.signed_out_bike = None
            user.past_action = ""
            db.session.commit()

            page.send(user.fb_id, "Successfully locked your bike")
        elif (user.past_action == "find_bike"):
            google_url = "https://maps.googleapis.com/maps/api/staticmap"
            data = {}
            data["center"] = str(coords["lat"]) + "," + str(coords["long"])
            data["zoom"] = "17"
            data["size"] = "2000x2000"
            data["markers"] = []
            for bike in user.bikes:
                if not bike.signed_out:
                    data["markers"].append("color:red|{},{}".format(
                        bike.stored_lat, bike.stored_lng))
            r = requests.get(google_url, params=data)
            user.past_action = ""
            db.session.commit()
            page.send(user.fb_id, "Here are the bikes I found near you")
            page.send(user.fb_id, Attachment.Image(r.url))
    elif msg_string == "register bike":
        bike = Bike()
        number = int(random.random() * 100) + 1
        bike.name = "bike_" + str(number)
        bike.signed_out = True
        bike.signed_out_user_id = user.id
        user.bikes.append(bike)
        db.session.add(bike)
        db.session.commit()
        page.send(
            user.fb_id,
            "Registration successful. You currently have {} signed out. Please lock it back in"
            .format(bike.name))
    elif msg_string == "find bike":
        location = QuickReply("Send Location", "FIND_LOCATION")
        location.content_type = "location"
        quick_replies = [location]
        user.past_action = "find_bike"
        db.session.commit()
        page.send(
            user.fb_id,
            "So you want a bike huh? Can I get the location that you're currently at?",
            quick_replies=quick_replies)
    else:
        ...
コード例 #29
0
def parse_array(array, sender_id):
    for i in array:
        if "imageUrl" in i.keys():
            page.send(sender_id, Attachment.Image(i['imageUrl']))
        elif "speech" in i.keys():
            page.send(sender_id, str(i['speech']))
コード例 #30
0
def message_handler(event):
    sender_id = event.sender_id
    message = event.message_text

    ## 讓機器人在使用者傳送訊息後立刻已讀訊息並開啟輸入指示器(點點點符號)
    page.mark_seen(sender_id)
    page.typing_on(sender_id)
    
    ## 子特色字典,等一下會用到
    sub_features = {'高額現金回饋': [{'title': '國內現金回饋', 'payload': 'in'},
                                {'title': '國外現金回饋', 'payload': 'out'}],
                    '旅遊交通': [{'title': '里程累積', 'payload': 'meter'},
                                {'title': '旅遊優惠', 'payload': 'travel'},
                                {'title': '國外刷卡優惠', 'payload': 'outside'},
                                {'title': '高鐵', 'payload': 'hsr'},
                                {'title': '加油停車', 'payload': 'oil'},
                                {'title': 'eTag', 'payload': 'etag'}],
                    '休閒娛樂': [{'title': '美食', 'payload': 'food'},
                                {'title': '電影', 'payload': 'movie'}],
                    '購物': [{'title': '通路聯名', 'payload': 'chain'},
                            {'title': '網路購物', 'payload': 'shopee'}]}
    sub_features_all = ['國內現金回饋', '國外現金回饋', '里程累積', '旅遊優惠', '國外刷卡優惠', '高鐵', '加油停車', 'eTag', '美食', '電影', '通路聯名', '網路購物', '電子支付功能(悠遊卡、一卡通)', '宗教']

    ## 當使用者一開始回答'想!'的回應
    if message == '想!' or message == '想':
        text = '首先先問問你希望想擁有的信用卡特色?'
        page.send(sender_id, text, quick_replies=[{'title': '高額現金回饋', 'payload': 'cash'},
                                                  {'title': '旅遊交通', 'payload': 'traffic'},
                                                  {'title': '休閒娛樂', 'payload': 'entertain'},
                                                  {'title': '購物', 'payload': 'shopping'},
                                                  {'title': '電子支付功能(悠遊卡、一卡通)', 'payload': 'easycard'},
                                                  {'title': '宗教', 'payload': 'religion'}])
    
    ## 當使用者回答不想時的回應
    elif message == '不想':
        text = '相信我,卡奴也是可以過得很快樂的,給你最後一次機會,你想不想成為卡奴?'
        page.send(sender_id, text, quick_replies=[{'title':'想!', 'payload':'Y'}])

    ## 當使用者回答了主要特色,且該特色有子特色的回應
    elif message in sub_features:
        text = '再選擇一個子項目吧'
        page.send(sender_id, text, quick_replies=sub_features[message])

    ## 當使用者回答了子特色的回應
    elif message in sub_features_all:

        ## 宗教卡可觸發特殊開關
        if message == '宗教':
            page.send(sender_id, '嗯,看來你觸發了開關。')
            img = ['https://i.imgur.com/XdUQHNs.jpg', 'http://i.imgur.com/uZ8Kccr.jpg', 'http://i.imgur.com/Sug8VqH.jpg', 'http://i.imgur.com/VVIpqY3.jpg', 'http://i.imgur.com/CbBZu4i.jpg']
            for i in img:
                page.send(sender_id, Attachment.Image(i))

        text = '以下是推薦給你的四張卡片!按詳細資訊查看卡片資訊,按我要辦卡連結至銀行官網。如果想要重新查詢,請打開選單,點選「重新查詢」即可!'
        answer = recommend_card(message)
        card1, card2, card3, card4 = answer[0][0], answer[0][1], answer[0][2], answer[0][3]

        page.send(sender_id, text)
        page.send(sender_id, Template.Generic([
                Template.GenericElement(answer[0][0],
                                subtitle=answer[0][0],
                                item_url=answer[2][0],
                                image_url=answer[1][0],
                                buttons=[{'type': 'postback', 'title': '詳細資訊', 'value': card1},
                                        {'type': 'web_url', 'title': '我要辦卡', 'value': answer[2][0]}]),
                Template.GenericElement(answer[0][1],
                                subtitle=answer[0][1],
                                item_url=answer[2][1],
                                image_url=answer[1][1],
                                buttons=[{'type': 'postback', 'title': '詳細資訊', 'value': card2},
                                        {'type': 'web_url', 'title': '我要辦卡', 'value': answer[2][1]}]),
                Template.GenericElement(answer[0][2],
                                subtitle=answer[0][2],
                                item_url=answer[2][2],
                                image_url=answer[1][2],
                                buttons=[{'type': 'postback', 'title': '詳細資訊', 'value': card3},
                                        {'type': 'web_url', 'title': '我要辦卡', 'value': answer[2][2]}]),
                Template.GenericElement(answer[0][3],
                                subtitle=answer[0][3],
                                item_url=answer[2][3],
                                image_url=answer[1][3],
                                buttons=[{'type': 'postback', 'title': '詳細資訊', 'value': card4},
                                        {'type': 'web_url', 'title': '我要辦卡', 'value': answer[2][3]}])
            ]))
    
    ## 若使用者輸入其他訊息,則從以下這些話中隨機回覆。
    else:
        rand = ['你當我是AI?', 
                '樓下rrro。噢不對,樓上rrro。', 
                '你的訊息被藏在光頭葛格的紅色內褲裡,我找不到。', 
                '[問卦] 有沒有邊緣到只能和聊天機器人聊天的八卦?',
                '早安我的朋友,窩看不懂尼在說什麼。']

        page.send(sender_id, random.choice(rand))