示例#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 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")
示例#3
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")
示例#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_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")
示例#6
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, "希望你能繼續保持下去~加油!")
示例#7
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)
示例#8
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()
示例#9
0
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 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
示例#11
0
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)
示例#12
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))
示例#13
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)))
示例#14
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)
    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)
示例#16
0
def send_gif(recipient):
    page.send(recipient, Attachment.Image(CONFIG['SERVER_URL'] + "/assets/instagram_logo.gif"))
示例#17
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"))
示例#18
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
示例#19
0
def send_image(recipient):
    page.send(recipient,
              Attachment.Image(CONFIG['SERVER_URL'] + "/assets/rift.png"))
示例#20
0
def send_gif(recipient):
    page.send(recipient, Attachment.Image(CONFIG['SERVER_URL'] + "/assets/despedida.gif"))
示例#21
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")
示例#22
0
def chat(message_text, sender_id, recipient_id):
    '''if TaiwanTrainRemainTicketSql_fun.bool_sender_id_first(sender_id) != 1:
        print('no first')
    elif TaiwanTrainRemainTicketSql_fun.bool_sender_id_first(sender_id) == 1:
        text = '歡迎使用台鐵訂票機器人,\n以下是訂票範例'
        MessageFun.send_message(sender_id, text)
        Chatbot2Sql.update(text,sender_id,recipient_id,'server')
        
        url = "http://114.34.138.146/train_ticket_png/"
        
        image_url = url + 'train_example.png'
        page.send(sender_id, Attachment.Image(image_url) )          
        
        return 1'''

    if '取消訂票' in message_text:
        print('cancel')
        MessageFun.send_message(sender_id, '請稍等')
        try:
            # sender_id = '1928838193857487'; recipient_id = '1833003783417644'
            CancelTaiwanTrainTicket.main(sender_id, recipient_id, 0)
            return 1
        except:
            return 0
    elif (tem_function.text_in_set(
            Chatbot2Sql.get_last_message(sender_id, 1, 'server', recipient_id),
            '請問要取消以下哪張票')):
        print('cancel mulit ticket')
        if re.search('[0-9]', message_text):
            try:
                message_text = re.search('[0-9]', message_text)[0]
                i = int(message_text)
                CancelTaiwanTrainTicket.main(sender_id, recipient_id, i)

                return 1
            except:
                123
                return 0
    elif '我的車票' in message_text or '我的票' in message_text:
        print('my ticket')
        try:
            MT = MyTicket(sender_id, recipient_id)
            MT.load_data()
            MT.chatdesign()

            return 1
        except:
            123
            return 0
    elif '訂火車票' in message_text or '訂票' in message_text:
        TaiwanTrainRemainTicketSql.clear(sender_id)
        text = "歡迎使用訂票服務, "
        MessageFun.send_message(sender_id, text)
        Chatbot2Sql.update(text, sender_id, recipient_id, 'server')

        if TaiwanTrainRemainTicketSql_fun.load_user_id(sender_id) == 0:
            text = "第一次使用,請先輸入身分證字號\n( 只會在該系統使用,不會進行其他用途 )"
            MessageFun.send_message(sender_id, text)
            Chatbot2Sql.update(text, sender_id, recipient_id, 'server')
            return 1
        else:
            text = '請輸入訂票資訊'
            MessageFun.send_message(sender_id, text)
            Chatbot2Sql.update(text, sender_id, recipient_id, 'server')
            return 1
    elif tem_function.text_in_set(
            Chatbot2Sql.get_last_message(sender_id, 1, 'server', recipient_id),
            '身分證字號'):
        # message_text = '我的身分證是u121726696'
        user_id = re.findall("[a-zA-Z][0-9]{9}", message_text)
        if (len(user_id) == 1):
            text = '請輸入訂票資訊'
            MessageFun.send_message(sender_id, '請輸入訂票資訊')
            Chatbot2Sql.update(text, sender_id, recipient_id, 'server')

            TaiwanTrainRemainTicketSql_fun.update_user_id(sender_id, user_id)
            return 1

        elif (len(user_id) == 0):
            print('error')
            MessageFun.send_message(sender_id, '輸入錯誤,請重新輸入')
            return 1

        # sender_id = str( 1668007999939769 );recipient_id = str( 1581238015253059 )
    elif (tem_function.text_in_set(
            Chatbot2Sql.get_last_message(sender_id, 1, 'server', recipient_id),
            '請輸入訂票資訊')
          and tem_function.set_in_text(station_set, message_text)):
        print('begin to order_ticket_by_remain_ticket')
        MessageFun.send_message(sender_id, '請稍等')
        # message_text = '花蓮到台北 3/4 下午5點'
        tem = MessageFun.message2order_info(message_text)
        #tem = message2order_info(message_text)
        order_info = tem.main()
        user_id = TaiwanTrainRemainTicketSql_fun.load_user_id(sender_id)

        # begin selenium
        text = search_remain_ticket.main(order_info, user_id, sender_id)
        if text == '該時段、該車種已訂票額滿':
            print('out')
            MessageFun.send_message(sender_id, 'sorry, ' + text)
            Chatbot2Sql.update(text, sender_id, recipient_id, 'server')
            return 1
        else:
            ticket_info = text

        text1 = '以下時段有車'
        MessageFun.send_message(sender_id, text1)

        for i in range(len(ticket_info.set)):  #
            from_time = ticket_info.set.T.loc['from_time'][i]
            to_time = ticket_info.set.T.loc['to_time'][i]
            #cost = cost_time(from_time,to_time)

            from_time = from_time.split(' ')[1]
            to_time = to_time.split(' ')[1]

            kinds = ticket_info.set.T.loc['others'][i]
            text = str(i + 1) + ':' + from_time + ' → ' + to_time + ' ' + kinds
            print(text)
            MessageFun.send_message(sender_id, text)

        text2 = '請問你想要哪個時段:輸入數字(1 or 2 ...)'
        MessageFun.send_message(sender_id, text2)
        Chatbot2Sql.update(text1 + text2, sender_id, recipient_id, 'server')

        return 1
    # order ticket
    elif (tem_function.text_in_set(
            Chatbot2Sql.get_last_message(sender_id, 2, 'server', recipient_id),
            '以下時段有車請問你想要哪個時段:輸入數字(1 or 2 ...)')):
        #print('final')
        MessageFun.send_message(sender_id, '請稍等')
        if TaiwanTrainRemainTicketSql_fun.check_input_is_train_no(
                message_text, sender_id) == 1:
            try:
                message_text = re.search('[0-9]', message_text)[0]
                i = str(int(message_text))

                png_name = order_ticket.main(sender_id, i)
                url = "http://" + host + "/train_ticket_png/"

                image_url = url + png_name
                page.send(sender_id, Attachment.Image(image_url))

                TaiwanTrainRemainTicketSql.clear(sender_id)
                Chatbot2Sql.update('order ticket success', sender_id,
                                   recipient_id, 'server')
                Chatbot2Sql.update('order ticket success', sender_id,
                                   recipient_id, 'server')
                #print('final ok')
                return 1
            except:
                #print('000')
                return 0
        elif (TaiwanTrainRemainTicketSql_fun.check_input_is_train_no(
                message_text, sender_id) == 0
              and 'order ticket success' not in Chatbot2Sql.get_last_message(
                  sender_id, 1, 'server', recipient_id)):
            text = '輸入錯誤, 如再次錯誤, 將跳出訂票系統'
            MessageFun.send_message(sender_id, text)
            Chatbot2Sql.update(text, sender_id, recipient_id, 'server')
            return 1

    return 0
示例#23
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']))
示例#24
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))
示例#25
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:
        ...
示例#26
0
	def on_enter_year(self, event):
		print("I'm entering year")
		sender_id = event['sender']['id']
		page.send(sender_id, Attachment.Image("https://i.imgur.com/ozyA7lf.gif"))
		quick_replies = [QuickReply(title="好 拜拜~", payload="PICK_bye")]
		page.send(sender_id, "新年快樂~恭喜發財<3" ,quick_replies=quick_replies,metadata="DEVELOPER_DEFINED_METADATA")
示例#27
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期末考不讀書 只會讓學校發財啦")