Example #1
0
    def test_share_button(self):
        btn = elements.Button(
            button_type='web_url',
            title='Web button',
            url='http://facebook.com'
        )
        element = elements.Element(
            title='Element',
            item_url='http://facebook.com',
            image_url='http://facebook.com/image.jpg',
            subtitle='Subtitle',
            buttons=[
                btn
            ]
        )
        template = GenericTemplate(
            elements=[element],
        )

        res = elements.Button(
            button_type='element_share',
            share_contents=template.to_dict()
        )
        expected = {
            'type': 'element_share',
            'share_contents': {
                'attachment': {
                    'type': 'template',
                    'payload': {
                        'template_type': 'generic',
                        'sharable': False,
                        'elements': [
                            {
                                'title': 'Element',
                                'item_url': 'http://facebook.com',
                                'image_url': 'http://facebook.com/image.jpg',
                                'subtitle': 'Subtitle',
                                'buttons': [
                                    {
                                        'type': 'web_url',
                                        'title': 'Web button',
                                        'url': 'http://facebook.com'
                                    }
                                ]
                            },
                        ]
                    }
                }
            }
        }
        assert expected == res.to_dict()
Example #2
0
def process_message(message):
    app.logger.debug('Message received: {}'.format(message))

    if 'attachments' in message['message']:
        if message['message']['attachments'][0]['type'] == 'location':
            app.logger.debug('Location received')
            response = Text(text='{}: lat: {}, long: {}'.format(
                message['message']['attachments'][0]['title'],
                message['message']['attachments'][0]['payload']['coordinates']
                ['lat'], message['message']['attachments'][0]['payload']
                ['coordinates']['long']))
            return response.to_dict()

    if 'text' in message['message']:
        msg = message['message']['text'].lower()
        response = Text(text='Sorry didn\'t understand that: {}'.format(msg))
        if 'text' in msg:
            response = Text(text='This is an example text message.')
        if 'image' in msg:
            response = Image(url='https://unsplash.it/300/200/?random')
        if 'video' in msg:
            response = Video(
                url='http://techslides.com/demos/sample-videos/small.mp4')
        if 'quick replies' in msg:
            qr1 = quick_replies.QuickReply(title='Location',
                                           content_type='location')
            qr2 = quick_replies.QuickReply(title='Payload',
                                           payload='QUICK_REPLY_PAYLOAD')
            qrs = quick_replies.QuickReplies(quick_replies=[qr1, qr2])
            response = Text(text='This is an example text message.',
                            quick_replies=qrs)
        if 'payload' in msg:
            txt = 'User clicked {}, button payload is {}'.format(
                msg, message['message']['quick_reply']['payload'])
            response = Text(text=txt)
        if 'webview-compact' in msg:
            btn = get_button(ratio='compact')
            elem = get_element(btn)
            response = GenericTemplate(elements=[elem])
        if 'webview-tall' in msg:
            btn = get_button(ratio='tall')
            elem = get_element(btn)
            response = GenericTemplate(elements=[elem])
        if 'webview-full' in msg:
            btn = get_button(ratio='full')
            elem = get_element(btn)
            response = GenericTemplate(elements=[elem])

        return response.to_dict()
Example #3
0
def process_message(message):
    print(message)

    qrs = make_qrs_set()

    sender = message["sender"]["id"]
    save_customer_data(sender)

    if "text" in message["message"]:
        msg = message["message"]["text"]
        if msg == "최신 패치 내역":
            # DB에서 패치 내역 불러와서 contents 처럼 한 str로 처리해주면 됨
            recentData = get_recent_patch()
            contents = make_text_from_data(recentData)
            response = Text(text=contents, quick_replies=qrs)
        elif msg == "최신 패치 내역 링크":
            recentData = get_recent_patch()
            # DB에서 title, subtitle, image_url, item_url(게시글 id 만 가져오면 됨)
            elem = get_element(
                recentData["subject"],
                recentData["date"],
                recentData["thumbnail_src"],
                recentData["notification_id"],
            )
            response = GenericTemplate(elements=[elem], quick_replies=qrs)
        elif msg == "기능 설명":
            contents = "입력창 위의 버튼을 눌러\n⚡최신 패치 내역⚡을 보거나\n📢카트라이더 패치 안내 게시판📢으로 이동할 수 있습니다😍"
            response = Text(text=contents, quick_replies=qrs)
        else:
            contents = "버튼을 눌러 내용을 확인해주세요!😊"
            response = Text(text=contents, quick_replies=qrs)
    return response.to_dict()
Example #4
0
    def test_share_button(self):
        btn = elements.Button(button_type='web_url',
                              title='Web button',
                              url='http://facebook.com')
        element = elements.Element(title='Element',
                                   item_url='http://facebook.com',
                                   image_url='http://facebook.com/image.jpg',
                                   subtitle='Subtitle',
                                   buttons=[btn])
        template = GenericTemplate(elements=[element], )

        res = elements.Button(button_type='element_share',
                              share_contents=template.to_dict())
        expected = {
            'type': 'element_share',
            'share_contents': {
                'attachment': {
                    'type': 'template',
                    'payload': {
                        'template_type':
                        'generic',
                        'sharable':
                        False,
                        'elements': [
                            {
                                'title':
                                'Element',
                                'item_url':
                                'http://facebook.com',
                                'image_url':
                                'http://facebook.com/image.jpg',
                                'subtitle':
                                'Subtitle',
                                'buttons': [{
                                    'type': 'web_url',
                                    'title': 'Web button',
                                    'url': 'http://facebook.com'
                                }]
                            },
                        ]
                    }
                }
            }
        }
        assert expected == res.to_dict()
def process_postback(messenger, payload):
    """Function to process postbacks

    Args:
        messenger ([Messenger]): a Messenger Object
        payload ([Payload]): the payload sent by the user
    """
    init_user_preference(messenger)

    if "START" in payload:
        send_start_messages(messenger)
        return True

    if "MAIN_MENU" in payload:
        text = {
            "text": _(u"This is the main menu, select what you need below 👇🏼"),
            "quick_replies": get_main_menu().to_dict(),
        }
        messenger.send(text, "RESPONSE")
        return True

    if "OPEN_SOURCE" in payload:
        qr1 = quick_replies.QuickReply(title=_("✔️ Yes"),
                                       payload="KNOW_OS_YES_FULL")
        qr2 = quick_replies.QuickReply(title=_("❌ Not yet"),
                                       payload="KNOW_OS_NO")
        qrs = quick_replies.QuickReplies(quick_replies=[qr1, qr2])
        text = {
            "text":
            _(
                u"So, tell me %(first_name)s do you know what Open source"
                " is? 👇🏼", **user),
            "quick_replies":
            qrs.to_dict(),
        }
        messenger.send(text, "RESPONSE")
        return True

    if payload.startswith("KNOW_OS_YES"):
        if "KNOW_OS_YES_FULL" in payload:
            messenger.send({"text": _(u"Amazing!")}, "RESPONSE")
            messenger.send_action(typing_on)
            sleep(3)

        qr1 = quick_replies.QuickReply(title=_("✔️ Yes"), payload="CVS_YES")
        qr2 = quick_replies.QuickReply(title=_("❌ Not yet"), payload="CVS_NO")
        qrs = quick_replies.QuickReplies(quick_replies=[qr1, qr2])
        text = {
            "text":
            _(u"An important component in Open Source contribution is"
              " version control tools. Are you familiar with the concept of"
              " version control? 👇🏼"),
            "quick_replies":
            qrs.to_dict(),
        }
        messenger.send(text, "RESPONSE")
        return True

    if "KNOW_OS_NO" in payload:
        text = _(
            u"According to the dictionary, Open-source 🔓 software, denotes"
            " software for which the original source code is made freely 🆓"
            " available and may be redistributed and modified"
            " according to the requirement of the user 👨‍💻.")
        messenger.send({"text": text}, "RESPONSE")
        messenger.send_action(typing_on)
        sleep(3)

        qr = quick_replies.QuickReply(title=_("👉🏽 Next"),
                                      payload="KNOW_OS_YES")
        qrs = quick_replies.QuickReplies(quick_replies=[qr])
        text = {
            "text":
            _(u'👩🏽‍🏫 You know ...\n✔️ Wordpress,\n✔️ Notepad++,\n✔️ Ubuntu\n'
              'and thousands of common software started out as Open-source'
              ' software? 👇🏼'),
            "quick_replies":
            qrs.to_dict(),
        }
        messenger.send(text, "RESPONSE")
        return True

    if "CVS_NO" in payload:
        text = {
            "text":
            _(u"😎 Worry not!\n\n"
              "Version control allows you to manage changes to files over"
              " time ⏱️ so that you can recall specific versions later.")
        }
        messenger.send(text, "RESPONSE")
        messenger.send_action(typing_on)
        sleep(3)
        text = {
            "text":
            _(u"You can use version control to version code, binary files,"
              " and digital assets 🗄️.")
        }
        messenger.send(text, "RESPONSE")
        messenger.send_action(typing_on)
        sleep(3)
        text = {
            "text":
            _(u"This includes version control software, version control"
              " systems, or version control tools 🧰.")
        }
        messenger.send(text, "RESPONSE")
        messenger.send_action(typing_on)
        sleep(3)
        text = {
            "text":
            _(u"Version control is a component of software configuration"
              " management 🖥️.")
        }
        messenger.send(text, "RESPONSE")
        messenger.send_action(typing_on)
        sleep(3)
        qr = quick_replies.QuickReply(title=_("👉🏽 Next"), payload="CVS_YES")
        qrs = quick_replies.QuickReplies(quick_replies=[qr])
        text = {
            "text":
            _(u"😎 Now that you understand what Version control is,"
              " let's explore another important topic."),
            "quick_replies":
            qrs.to_dict(),
        }
        messenger.send(text, "RESPONSE")
        return True

    if "CVS_YES" in payload:
        qr1 = quick_replies.QuickReply(title=_("What is Git❔"),
                                       payload="GIT_1")
        qr2 = quick_replies.QuickReply(title=_("What is GitHub❔"),
                                       payload="GITHUB_1")
        qrs = quick_replies.QuickReplies(quick_replies=[qr1, qr2])
        text = {
            "text": _(u"What do you want to start with⁉️ 👇🏼"),
            "quick_replies": qrs.to_dict(),
        }
        messenger.send(text, "RESPONSE")
        return True

    if "GITHUB_1" in payload:
        qr = quick_replies.QuickReply(title=_("👉🏽 Next"), payload="GITHUB_2")
        qrs = quick_replies.QuickReplies(quick_replies=[qr])
        text = {
            "text":
            _(u"GitHub is a code hosting platform for version control and"
              " collaboration. It lets you and others work together on"
              " projects from anywhere."),
            "quick_replies":
            qrs.to_dict(),
        }
        messenger.send(text, "RESPONSE")
        return True

    if "GITHUB_2" in payload:
        btn1 = Button(button_type="web_url",
                      title=_("Official Website"),
                      url="https://github.com")
        btn2 = Button(
            button_type="web_url",
            title=_("GitHub Tutorial"),
            url="https://guides.github.com/activities/hello-world/",
        )
        btn3 = Button(button_type="postback",
                      title=_("👩‍💻 Make a PR"),
                      payload="CONTR_1")
        app_url = os.environ.get("APP_URL", "localhost")
        elems = Element(
            title=_(u"Discover GitHub"),
            image_url=app_url + "/static/img/github.jpg",
            subtitle=_(
                u"Discover GitHub official website, or follow a beginner"
                " tutorial", ),
            # Messenger only accepts 3 buttons, hard choice to make!
            buttons=[btn1, btn2, btn3],
        )
        res = GenericTemplate(elements=[elems])
        logger.debug(res.to_dict())
        messenger.send(res.to_dict(), "RESPONSE")
        return True

    if payload.startswith("GIT_"):
        if "GIT_1" in payload:
            messenger.send({"text": _("Good question 👌🏽")}, "RESPONSE")
            messenger.send_action(typing_on)
            sleep(3)

            text = _(
                u"Git is a type of version control system (VCS) that makes"
                " it easier to track changes to files. ")
            messenger.send({"text": text}, "RESPONSE")
            messenger.send_action(typing_on)
            sleep(3)

            text = _(
                u"For example, when you edit a file, Git can help you"
                " determine exactly what changed, who changed it, and why.")
            messenger.send({"text": text}, "RESPONSE")
            messenger.send_action(typing_on)
            sleep(3)

            qr1 = quick_replies.QuickReply(title=_("👶🏽 Install Git"),
                                           payload="INSTALL_GIT")
            qr2 = quick_replies.QuickReply(title=_("🤓 I've Git Installed"),
                                           payload="CONF_GIT")
            qrs = quick_replies.QuickReplies(quick_replies=[qr1, qr2])
            text = {
                "text": _(u"Want to learn more about Git?"),
                "quick_replies": qrs.to_dict(),
            }
            messenger.send(text, "RESPONSE")
            return True

    ###################################
    # FIRST TIME CONTRIBUTION SECTION #
    ###################################
    # Guiding users to this first time contribution
    if payload.startswith("CONTR_"):

        if "CONTR_1" in payload:
            messenger.send({"text": _("Good decision 👌🏽")}, "RESPONSE")
            messenger.send_action(typing_on)
            sleep(3)

            text = _(u"We are going to split the process into 5 steps: \n"
                     "🛵 Fork, Clone, Update, Push and Merge. ")
            messenger.send({"text": text}, "RESPONSE")
            messenger.send_action(typing_on)
            sleep(3)

            qr = quick_replies.QuickReply(title=_("🥢 1. Fork"),
                                          payload="CONTR_2")
            qrs = quick_replies.QuickReplies(quick_replies=[qr])
            text = {
                "text": _(u"Ready for the first step?!"),
                "quick_replies": qrs.to_dict(),
            }
            messenger.send(text, "RESPONSE")
            return True

        # Fork Step
        if "CONTR_2" in payload:
            messenger.send({"text": _("Awesome 👌🏽")}, "RESPONSE")
            messenger.send_action(typing_on)
            sleep(3)

            text = _(
                u"Open this link in a new window: \n"
                "https://github.com/fbdevelopercircles/open-source-edu-bot")
            messenger.send({"text": text}, "RESPONSE")
            messenger.send_action(typing_on)
            sleep(3)
            text = _(
                u"Now, click `Fork` on the top right corner of your screen")
            messenger.send({"text": text}, "RESPONSE")
            image = Image(
                url="https://docs.github.com/assets/images/help/repository/"
                "fork_button.jpg")
            messenger.send(image.to_dict(), "RESPONSE")
            messenger.send_action(typing_on)
            text = _(u"A copy of the original project will be created in your"
                     " account.")
            messenger.send({"text": text}, "RESPONSE")
            messenger.send_action(typing_on)
            sleep(3)
            qr = quick_replies.QuickReply(title=_("🚃 2. Clone"),
                                          payload="CONTR_3_1")
            qrs = quick_replies.QuickReplies(quick_replies=[qr])
            text = {
                "text": _(u"Ready for the next step?!"),
                "quick_replies": qrs.to_dict(),
            }
            messenger.send(text, "RESPONSE")
            return True

        # Clone Step
        if "CONTR_3_1" in payload:
            messenger.send({"text": _("Great 👌🏽")}, "RESPONSE")
            messenger.send_action(typing_on)
            sleep(3)

            text = _(
                u"Right now, you have a fork of the `open-source-edu-bot`"
                " repository, but you don't have the files in that repository"
                " on your computer.")
            messenger.send({"text": text}, "RESPONSE")
            messenger.send_action(typing_on)
            sleep(3)
            text = _(
                u"Let's create a clone of your fork locally on your computer."
                "\nOn GitHub, in your newly forked project, Click on `Code`"
                " above the list of files")
            messenger.send({"text": text}, "RESPONSE")
            image = Image(
                url="https://docs.github.com/assets/images/help/repository/"
                "code-button.png")
            messenger.send(image.to_dict(), "RESPONSE")

            qr = quick_replies.QuickReply(title=_("👉🏽 Next"),
                                          payload="CONTR_3_2")
            qrs = quick_replies.QuickReplies(quick_replies=[qr])
            text = {
                "text": _(u"When you feel Ready🔥, hit Next to continue."),
                "quick_replies": qrs.to_dict(),
            }
            messenger.send(text, "RESPONSE")
            return True
        if "CONTR_3_2" in payload:
            text = _(
                u'To clone the repository using HTTPS, under'
                ' "Clone with HTTPS", click copy icon.\n'
                'To clone the repository using an SSH key click "Use SSH", '
                'then click on copy icon.')
            messenger.send({"text": text}, "RESPONSE")
            image = Image(url="https://docs.github.com/assets/"
                          "images/help/repository/https-url-clone.png")
            messenger.send(image.to_dict(), "RESPONSE")
            messenger.send_action(typing_on)
            sleep(3)
            text = _(
                u"Now open a terminal, change the current working directory"
                " to the location where you want the cloned directory.")
            messenger.send({"text": text}, "RESPONSE")
            messenger.send_action(typing_on)
            sleep(3)
            text = _(
                u"Type `git clone`, and then paste the URL you copied "
                "earlier.\nPress Enter. Your local clone will be created.")
            messenger.send({"text": text}, "RESPONSE")
            messenger.send_action(typing_on)
            qr = quick_replies.QuickReply(title=_("🥯 3. Update"),
                                          payload="CONTR_4")
            qrs = quick_replies.QuickReplies(quick_replies=[qr])
            text = {
                "text":
                _(u"Now, you have a local copy of the project, Let's update"
                  " it!"),
                "quick_replies":
                qrs.to_dict(),
            }
            messenger.send(text, "RESPONSE")
            return True

        # Update Step
        if "CONTR_4" in payload:
            messenger.send({"text": _("Amazing 👌🏽")}, "RESPONSE")
            messenger.send_action(typing_on)
            sleep(3)

            text = _(u"Open the project using your favorite IDE, and look for"
                     " `contributors.yaml` file")
            messenger.send({"text": text}, "RESPONSE")
            messenger.send_action(typing_on)
            sleep(3)
            text = _(u"This Yaml file contains list of project contributors,"
                     " just like you.")
            messenger.send({"text": text}, "RESPONSE")
            messenger.send_action(typing_on)
            image = Image(
                url="https://media.giphy.com/media/UsBYak2l75W5VheVPF/"
                "giphy.gif")
            messenger.send(image.to_dict(), "RESPONSE")
            text = _(
                u"Following the same scheme, add your name, country and github"
                " username to the list.")
            messenger.send({"text": text}, "RESPONSE")
            messenger.send_action(typing_on)
            sleep(3)
            qr = quick_replies.QuickReply(title=_("🚲 4. Push"),
                                          payload="CONTR_5")
            qrs = quick_replies.QuickReplies(quick_replies=[qr])
            text = {
                "text": _(u"Ready to commit & Push your changes?!"),
                "quick_replies": qrs.to_dict(),
            }
            messenger.send(text, "RESPONSE")
            return True

        # Push Step
        if "CONTR_5" in payload:
            messenger.send({"text": _("Way to go 👌🏽")}, "RESPONSE")
            messenger.send_action(typing_on)
            sleep(3)
            text = _(
                u"Open your Terminal.\nChange the current working directory"
                " to your local repository."
                "\nStage the file by commiting it to your"
                " local repository using: `git add .`")
            messenger.send({"text": text}, "RESPONSE")
            messenger.send_action(typing_on)
            sleep(3)
            text = _(u'Commit the file that you\'ve staged in your local'
                     ' repository:\n'
                     '`git commit -m "Add YOUR_NAME to contributors list"`\n'
                     "Make sure to add your name :D")
            messenger.send({"text": text}, "RESPONSE")
            messenger.send_action(typing_on)
            sleep(3)
            text = _(u"Finally, Push the changes in your local repository to "
                     " GitHub: `git push origin master`")
            messenger.send({"text": text}, "RESPONSE")
            messenger.send_action(typing_on)
            sleep(3)
            qr = quick_replies.QuickReply(title=_("🔐 5. Merge"),
                                          payload="CONTR_6")
            qrs = quick_replies.QuickReplies(quick_replies=[qr])
            text = {
                "text": _(u"Ready to make your first PR?!"),
                "quick_replies": qrs.to_dict(),
            }
            messenger.send(text, "RESPONSE")
            return True

        # Merge Step
        if "CONTR_6" in payload:
            messenger.send({"text": _("Proud of you 👌🏽")}, "RESPONSE")
            messenger.send_action(typing_on)
            sleep(3)
            text = _(
                u"Now go back to the original repo:"
                " https://github.com/fbdevelopercircles/open-source-edu-bot \n"
                "Above the list of files, click `Pull request`.")
            messenger.send({"text": text}, "RESPONSE")
            primg = Image(url="https://docs.github.com/assets/images/help/"
                          "pull_requests/pull-request-start-review-button.png")
            messenger.send(primg.to_dict(), "RESPONSE")
            messenger.send_action(typing_on)
            sleep(3)
            text = _(
                u'Make sure that "base branch" & "head fork" drop-down menus'
                ' both are pointing to `master`.')
            messenger.send({"text": text}, "RESPONSE")
            messenger.send_action(typing_on)
            sleep(3)
            prdesc = Image(url="https://docs.github.com/assets/images/help/"
                           "pull_requests/pullrequest-description.png")
            messenger.send(prdesc.to_dict(), "RESPONSE")
            text = _(u"Type a title and description for your pull request."
                     " Then click `Create Pull Request`.")
            messenger.send({"text": text}, "RESPONSE")
            messenger.send_action(typing_on)
            qr = quick_replies.QuickReply(title=_("✅ Done"), payload="CONTR_7")
            qrs = quick_replies.QuickReplies(quick_replies=[qr])
            text = {
                "text": _(u"Have you created your first PR?"),
                "quick_replies": qrs.to_dict(),
            }
            messenger.send(text, "RESPONSE")
            return True

        # Merge Step
        if "CONTR_7" in payload:
            messenger.send({"text": _("🙌🎉 Bravo %(first_name)s 🙌🎉", **user)},
                           "RESPONSE")
            messenger.send_action(typing_on)
            sleep(3)
            response = Image(
                url="https://media.giphy.com/media/MOWPkhRAUbR7i/giphy.gif")
            messenger.send(response.to_dict(), "RESPONSE")
            messenger.send(
                {
                    "text":
                    _("Now the team will review your PR and merge it ASAP :D")
                },
                "RESPONSE",
            )
            messenger.send_action(typing_on)
            sleep(3)
            text = {
                "text":
                _(u"Given below are other interesting stuff"
                  " that we can explore together:"),
                "quick_replies":
                get_main_menu().to_dict(),
            }
            messenger.send(text, "RESPONSE")
            return True

    if payload.startswith("GIT_"):
        if "GIT_1" in payload:
            messenger.send({"text": _("Good question 👌🏽")}, "RESPONSE")
            messenger.send_action(typing_on)
            sleep(3)

        text = _(u"Git is a type of version control system (VCS) that makes it"
                 " easier to track changes to files. ")
        messenger.send({"text": text}, "RESPONSE")
        messenger.send_action(typing_on)
        sleep(3)

        text = _(
            u"For example, when you edit a file, Git can help you determine"
            " exactly what changed, who changed it, and why.")
        messenger.send({"text": text}, "RESPONSE")
        messenger.send_action(typing_on)
        sleep(3)

        qr1 = quick_replies.QuickReply(title=_("👶🏽 Install Git"),
                                       payload="INSTALL_GIT")
        qr2 = quick_replies.QuickReply(title=_("🤓 I've Git Installed"),
                                       payload="CONF_GIT")
        qrs = quick_replies.QuickReplies(quick_replies=[qr1, qr2])
        text = {
            "text": _(u"Want to learn more about Git?"),
            "quick_replies": qrs.to_dict(),
        }
        messenger.send(text, "RESPONSE")
        return True

    if "INSTALL_GIT" in payload:

        text = _(u"Time to get Git installed in your machine ⭕!")
        messenger.send({"text": text}, "RESPONSE")
        messenger.send_action(typing_on)
        sleep(3)
        btn = Button(
            button_type="web_url",
            title=_("Download Git"),
            url="https://git-scm.com/downloads",
        )
        elems = Element(
            title=_(u"Head over here, and download Git"
                    " Client based on your OS."),
            buttons=[btn],
        )
        res = GenericTemplate(elements=[elems])
        logger.debug(res.to_dict())
        messenger.send(res.to_dict(), "RESPONSE")
        messenger.send_action(typing_on)
        sleep(3)
        qr2 = quick_replies.QuickReply(title=_("Configure Git ⚒️"),
                                       payload="CONF_GIT")
        qrs = quick_replies.QuickReplies(quick_replies=[qr2])
        text = {
            "text": _(u"🧑‍🚀 Once done, let's configure Git"),
            "quick_replies": qrs.to_dict(),
        }
        messenger.send(text, "RESPONSE")
        return True

    if "CONF_GIT" in payload:

        text = _(u"Great Progress so far 👨🏽‍🎓!")
        messenger.send({"text": text}, "RESPONSE")
        messenger.send_action(typing_on)
        sleep(2)
        text = _(u"Now let's configure your Git username and email using the"
                 " following commands")
        messenger.send({"text": text}, "RESPONSE")
        messenger.send_action(typing_on)
        sleep(2)
        text = _(u'`$ git config --global user.name "Steve Josh"`')
        messenger.send({"text": text}, "RESPONSE")
        messenger.send_action(typing_on)
        sleep(2)
        text = _(u'`$ git config --global user.email "*****@*****.**"`')
        messenger.send({"text": text}, "RESPONSE")
        messenger.send_action(typing_on)
        sleep(2)
        text = _(
            u"Don't forget to replace Steve's  name and email with your own.")
        messenger.send({"text": text}, "RESPONSE")
        messenger.send_action(typing_on)
        sleep(2)
        text = _(u"These details will be associated with any commits that you"
                 " create")
        messenger.send({"text": text}, "RESPONSE")
        messenger.send_action(typing_on)
        sleep(2)
        qr = quick_replies.QuickReply(title=_("GitHub"), payload="GITHUB_1")
        qrs = quick_replies.QuickReplies(quick_replies=[qr])
        text = {
            "text": _(u"Now let's check, what is Github?👇🏼"),
            "quick_replies": qrs.to_dict(),
        }
        messenger.send(text, "RESPONSE")
        return True

    if "FB_OS" in payload:
        text = _(u"Facebook 🧡 Open Source!")
        messenger.send({"text": text}, "RESPONSE")
        sleep(3)

        text = _(u"Facebook manages many Open Source projects in the following"
                 " areas:\n"
                 "✔️ Android\n"
                 "✔️ Artificial Intelligence\n"
                 "✔️ Data Infrastructure\n"
                 "✔️ Developer Operations\n"
                 "✔️ Development Tools\n"
                 "✔️ Frontend\n"
                 "✔️ iOS\n"
                 "✔️ Languages\n"
                 "✔️ Linux\n"
                 "✔️ Security\n"
                 "✔️ Virtual Reality\n"
                 "...")
        messenger.send({"text": text}, "RESPONSE")
        sleep(3)

        btn = Button(
            button_type="web_url",
            title=_("Explore them"),
            url="https://opensource.facebook.com/projects",
        )
        elems = Element(title=_(u"Explore Facebook Open Source projects"),
                        buttons=[btn])
        res = GenericTemplate(elements=[elems])
        logger.debug(res.to_dict())
        messenger.send(res.to_dict(), "RESPONSE")

        return True

    if "FORK_ON_GITHUB" in payload:
        text = _(u"🤓 You know what? This chatbot code is Open Source 🔓, it's"
                 " developed by Facebook Developers Circles members around the"
                 " world.")
        messenger.send({"text": text}, "RESPONSE")
        sleep(5)

        text = _(
            u"%(first_name)s we welcome contributors, or simply feel free to"
            " fork the code on GitHub, and create your own chatbot.", **user)
        messenger.send({"text": text}, "RESPONSE")
        sleep(5)

        btn1 = Button(
            button_type="web_url",
            title=_("The Source Code"),
            url="https://github.com/fbdevelopercircles/open-source-edu-bot",
        )
        btn2 = Button(
            button_type="web_url",
            title=_("Join a circle"),
            url="https://developers.facebook.com/developercircles",
        )
        btn3 = Button(button_type="postback",
                      title=_("🚶🏽‍♀️ Main Menu 🗄️"),
                      payload="MAIN_MENU")
        elems = Element(title=_(u"Select an option 👇🏼"),
                        buttons=[btn1, btn2, btn3])
        res = GenericTemplate(elements=[elems])
        logger.debug(res.to_dict())
        messenger.send(res.to_dict(), "RESPONSE")

        return True

    # the default action
    qr = quick_replies.QuickReply(title=_("🚶🏽‍♀️ Main Menu 🗄️"),
                                  payload="MAIN_MENU")
    qrs = quick_replies.QuickReplies(quick_replies=[qr])
    text = {"text": _(u"Coming soon!"), "quick_replies": qrs.to_dict()}
    messenger.send(text, "RESPONSE")
    return False
Example #6
0
def display_recipe_hits(elastic_hits):
    """Displays hits in form of generic templates"""

    elements = get_recipe_hits(elastic_hits)
    qrs = process_quick_rpls(['Edit search', 'Load more'])
    return GenericTemplate(elements=elements, quick_replies=qrs)
Example #7
0
def process_postback(messenger, payload):
    """Function to process postbacks

    Args:
        messenger ([Messenger]): a Messenger Object
        payload ([Payload]): the payload sent by the user
    """
    init_user_preference(messenger)

    if 'START' in payload:
        send_start_messages(messenger)
        return True

    if 'MAIN_MENU' in payload:
        text = {
            "text":
            _(u'This is the main menu, select what you need bellow 👇🏼'),
            "quick_replies": get_main_menu().to_dict()
        }
        messenger.send(text, 'RESPONSE')
        return True

    if 'OPEN_SOURCE' in payload:
        qr1 = quick_replies.QuickReply(title=_('✔️ Yes'),
                                       payload='KNOW_OS_YES_FULL')
        qr2 = quick_replies.QuickReply(title=_('❌ Not yet'),
                                       payload='KNOW_OS_NO')
        qrs = quick_replies.QuickReplies(quick_replies=[qr1, qr2])
        text = {
            "text":
            _(
                u'So tell me %(first_name)s do you know what Open source'
                ' is? 👇🏼', **user),
            "quick_replies":
            qrs.to_dict()
        }
        messenger.send(text, 'RESPONSE')
        return True

    if payload.startswith('KNOW_OS_YES'):
        if 'KNOW_OS_YES_FULL' in payload:
            messenger.send({'text': _(u'Amazing!')}, 'RESPONSE')
            messenger.send_action(typing_on)
            sleep(3)

        qr1 = quick_replies.QuickReply(title=_('✔️ Yes'), payload='CVS_YES')
        qr2 = quick_replies.QuickReply(title=_('❌ Not yet'), payload='CVS_NO')
        qrs = quick_replies.QuickReplies(quick_replies=[qr1, qr2])
        text = {
            "text":
            _(u'An important component in Open Source contribution is'
              ' version control tools. Are you familiar with the concept of'
              ' version control? 👇🏼'),
            "quick_replies":
            qrs.to_dict()
        }
        messenger.send(text, 'RESPONSE')
        return True

    if 'KNOW_OS_NO' in payload:
        text = _(
            u'According to the dictionary, Open-source 🔓 software, denotes'
            ' software for which the original source code is made freely 🆓'
            ' available and may be redistributed and modified.')
        messenger.send({'text': text}, 'RESPONSE')
        messenger.send_action(typing_on)
        sleep(3)

        qr = quick_replies.QuickReply(title=_('👉🏽 Next'),
                                      payload='KNOW_OS_YES')
        qrs = quick_replies.QuickReplies(quick_replies=[qr])
        text = {
            "text":
            _(u'👩🏽‍🏫 You know ...\n✔️ Wordpress,\n✔️ Notepad++,\n✔️ Ubuntu\n'
              'and thousand of common software started out as open source'
              ' software? 👇🏼'),
            "quick_replies":
            qrs.to_dict()
        }
        messenger.send(text, 'RESPONSE')
        return True

    if 'CVS_NO' in payload:
        text = {
            "text":
            _(u'😎 Worry not!\n\n'
              'Version control allows you to manage changes to files over'
              ' time ⏱️.')
        }
        messenger.send(text, 'RESPONSE')
        messenger.send_action(typing_on)
        sleep(3)
        text = {
            "text":
            _(u'You can use version control to version code, binary files,'
              ' and digital assets 🗄️.')
        }
        messenger.send(text, 'RESPONSE')
        messenger.send_action(typing_on)
        sleep(3)
        text = {
            "text":
            _(u'This includes version control software, version control'
              ' systems, or version control tools 🧰.')
        }
        messenger.send(text, 'RESPONSE')
        messenger.send_action(typing_on)
        sleep(3)
        text = {
            "text":
            _(u'Version control is a component of software configuration'
              ' management 🖥️.')
        }
        messenger.send(text, 'RESPONSE')
        messenger.send_action(typing_on)
        sleep(3)
        qr = quick_replies.QuickReply(title=_('👉🏽 Next'), payload='CVS_YES')
        qrs = quick_replies.QuickReplies(quick_replies=[qr])
        text = {
            "text":
            _(u'😎 Now That you understand what Version control is,'
              ' let\'s explore another important topic'),
            "quick_replies":
            qrs.to_dict()
        }
        messenger.send(text, 'RESPONSE')
        return True

    if 'CVS_YES' in payload:
        qr1 = quick_replies.QuickReply(title=_('What is Git❔'),
                                       payload='GIT_1')
        qr2 = quick_replies.QuickReply(title=_('What is GitHub❔'),
                                       payload='GITHUB_1')
        qrs = quick_replies.QuickReplies(quick_replies=[qr1, qr2])
        text = {
            "text": _(u'What do you want to start with⁉️ 👇🏼'),
            "quick_replies": qrs.to_dict()
        }
        messenger.send(text, 'RESPONSE')
        return True

    if 'GITHUB_1' in payload:
        qr = quick_replies.QuickReply(title=_('👉🏽 Next'), payload='GITHUB_2')
        qrs = quick_replies.QuickReplies(quick_replies=[qr])
        text = {
            "text":
            _(u'GitHub is a code hosting platform for version control and'
              ' collaboration. It lets you and others work together on'
              ' projects from anywhere.'),
            "quick_replies":
            qrs.to_dict()
        }
        messenger.send(text, 'RESPONSE')
        return True

    if 'GITHUB_2' in payload:
        btn1 = Button(button_type='web_url',
                      title=_('Official Website'),
                      url='http://github.com')
        btn2 = Button(button_type='web_url',
                      title=_('GitHub Tutorial'),
                      url='https://guides.github.com/activities/hello-world/')
        btn3 = Button(button_type='postback',
                      title=_('🚶🏽‍♀️ Main Menu 🗄️'),
                      payload='MAIN_MENU')
        app_url = os.environ.get('APP_URL', 'localhost')
        elems = Element(
            title=_(u'Discover GitHub'),
            image_url=app_url + '/static/img/github.jpg',
            subtitle=_(
                u'Discover GitHub official website, or follow a beginner'
                ' tutorial', ),
            buttons=[btn1, btn2, btn3])
        res = GenericTemplate(elements=[elems])
        logger.debug(res.to_dict())
        messenger.send(res.to_dict(), 'RESPONSE')
        return True

    if payload.startswith('GIT_'):
        if 'GIT_1' in payload:
            messenger.send({'text': _('Good question 👌🏽')}, 'RESPONSE')
            messenger.send_action(typing_on)
            sleep(3)

        text = _(u'Git is a type of version control system (VCS) that makes'
                 ' it easier to track changes to files. ')
        messenger.send({'text': text}, 'RESPONSE')
        messenger.send_action(typing_on)
        sleep(3)

        text = _(
            u'For example, when you edit a file, Git can help you determine'
            ' exactly what changed, who changed it, and why.')
        messenger.send({'text': text}, 'RESPONSE')
        messenger.send_action(typing_on)
        sleep(3)

        qr1 = quick_replies.QuickReply(title=_('👶🏽 Install Git'),
                                       payload='INSTALL_GIT')
        qr2 = quick_replies.QuickReply(title=_('🤓 I\'ve Git Installed'),
                                       payload='CONF_GIT')
        qrs = quick_replies.QuickReplies(quick_replies=[qr1, qr2])
        text = {
            "text": _(u'Want to learn more about Git?'),
            "quick_replies": qrs.to_dict()
        }
        messenger.send(text, 'RESPONSE')
        return True

    if 'INSTALL_GIT' in payload:

        text = _(u'Time to get git installed in your machine ⭕!.')
        messenger.send({'text': text}, 'RESPONSE')
        messenger.send_action(typing_on)
        sleep(3)
        btn = Button(button_type='web_url',
                     title=_('Download Git'),
                     url='https://git-scm.com/downloads')
        elems = Element(title=_(
            u'Head over here, and donload git client based on your OS.'),
                        buttons=[btn])
        res = GenericTemplate(elements=[elems])
        logger.debug(res.to_dict())
        messenger.send(res.to_dict(), 'RESPONSE')
        messenger.send_action(typing_on)
        sleep(3)
        qr2 = quick_replies.QuickReply(title=_('Configure Git ⚒️'),
                                       payload='CONF_GIT')
        qrs = quick_replies.QuickReplies(quick_replies=[qr2])
        text = {
            "text": _(u'🧑‍🚀 Once done, let\'s configure Git'),
            "quick_replies": qrs.to_dict()
        }
        messenger.send(text, 'RESPONSE')
        return True

    if 'CONF_GIT' in payload:

        text = _(u'Great Progress so far 👨🏽‍🎓!.')
        messenger.send({'text': text}, 'RESPONSE')
        messenger.send_action(typing_on)
        sleep(2)
        text = _(u'Now let\'s configure your Git username and email using the'
                 ' following commands')
        messenger.send({'text': text}, 'RESPONSE')
        messenger.send_action(typing_on)
        sleep(2)
        text = _(u'`$ git config --global user.name "Steve Josh"`')
        messenger.send({'text': text}, 'RESPONSE')
        messenger.send_action(typing_on)
        sleep(2)
        text = _(u'`$ git config --global user.email "*****@*****.**"`')
        messenger.send({'text': text}, 'RESPONSE')
        messenger.send_action(typing_on)
        sleep(2)
        text = _(u'don\'t forget to replace Steve\'s name with your own.')
        messenger.send({'text': text}, 'RESPONSE')
        messenger.send_action(typing_on)
        sleep(2)
        text = _(u'These details will be associated with any commits that'
                 ' you create')
        messenger.send({'text': text}, 'RESPONSE')
        messenger.send_action(typing_on)
        sleep(2)
        qr = quick_replies.QuickReply(title=_('GitHub'), payload='GITHUB_1')
        qrs = quick_replies.QuickReplies(quick_replies=[qr])
        text = {
            "text": _(u'Now let\'s check what is Github👇🏼'),
            "quick_replies": qrs.to_dict()
        }
        messenger.send(text, 'RESPONSE')
        return True

    if 'FB_OS' in payload:
        text = _(u'Facebook 🧡 Open Source!')
        messenger.send({'text': text}, 'RESPONSE')
        sleep(3)

        text = _(u'Facebook manages many Open Source projects in the following'
                 ' areas:\n'
                 '✔️ Android\n'
                 '✔️ Artificial Intelligence\n'
                 '✔️ Data Infrastructure\n'
                 '✔️ Developer Operations\n'
                 '✔️ Development Tools\n'
                 '✔️ Frontend\n'
                 '✔️ iOS\n'
                 '✔️ Languages\n'
                 '✔️ Linux\n'
                 '✔️ Security\n'
                 '✔️ Virtual Reality\n'
                 '...')
        messenger.send({'text': text}, 'RESPONSE')
        sleep(3)

        btn = Button(button_type='web_url',
                     title=_('Explore them'),
                     url='https://opensource.facebook.com/projects')
        elems = Element(title=_(u'Explore Facebook Open Source projects'),
                        buttons=[btn])
        res = GenericTemplate(elements=[elems])
        logger.debug(res.to_dict())
        messenger.send(res.to_dict(), 'RESPONSE')

        return True

    if 'FORK_ON_GITHUB' in payload:
        text = _(u'🤓 You know what? This chatbot code is Open Source 🔓, it\'s'
                 ' developed by Facebook Developers Circles members around the'
                 ' world.')
        messenger.send({'text': text}, 'RESPONSE')
        sleep(5)

        text = _(
            u'%(first_name)s we welcome contributors, or simply feel free to'
            ' fork the code on GitHub, and create your own chatbot.', **user)
        messenger.send({'text': text}, 'RESPONSE')
        sleep(5)

        btn1 = Button(
            button_type='web_url',
            title=_('The Source Code'),
            url='https://github.com/fbdevelopercircles/open-source-edu-bot')
        btn2 = Button(button_type='web_url',
                      title=_('Join a circle'),
                      url='https://developers.facebook.com/developercircles')
        btn3 = Button(button_type='postback',
                      title=_('🚶🏽‍♀️ Main Menu 🗄️'),
                      payload='MAIN_MENU')
        elems = Element(title=_(u'Select an option 👇🏼'),
                        buttons=[btn1, btn2, btn3])
        res = GenericTemplate(elements=[elems])
        logger.debug(res.to_dict())
        messenger.send(res.to_dict(), 'RESPONSE')

        return True

    # the default action
    qr = quick_replies.QuickReply(title=_('🚶🏽‍♀️ Main Menu 🗄️'),
                                  payload='MAIN_MENU')
    qrs = quick_replies.QuickReplies(quick_replies=[qr])
    text = {"text": _(u'Coming soon!'), "quick_replies": qrs.to_dict()}
    messenger.send(text, 'RESPONSE')
    return False
Example #8
0
    def message(self, message):
        app.logger.debug(message)
        global dialogue
        if 'text' in message['message']:
            msg = message['message']['text'].lower()
            if len(dialogue) == 6:
                dialogue = set()

            # Greetings
            if msg in [
                    "hi", "hi there", "hello", "sain bainuu", "сайн уу", "hey",
                    "yo"
            ]:
                user_info = self.get_user()
                response = Image(
                    url='https://i.ytimg.com/vi/penG2V8bMBE/maxresdefault.jpg')
                self.send(response.to_dict(), 'RESPONSE')
                response = Text(
                    text=
                    'Hello {}! I’m SMART CITY chatbot 🤖, I can offer you municipality service everywhere at any time. You can message me about road issues. '
                    .format(user_info['first_name']))
                self.send(response.to_dict(), 'RESPONSE')
                qr1 = quick_replies.QuickReply(title='Open issue',
                                               payload='open_issue')
                qr2 = quick_replies.QuickReply(title='Live city',
                                               payload='live_city')
                qrs = quick_replies.QuickReplies(quick_replies=[qr1, qr2])
                response = Text(text='How can I help you today?',
                                quick_replies=qrs)
                self.send(response.to_dict(), 'RESPONSE')
                dialogue.add('Greetings')

            # Phone number
            if dialogue == {'Greetings', 'Name'}:
                response = Text(text='Please enter your phone number:')
                self.send(response.to_dict(), 'RESPONSE')
                dialogue.add('Phone')

            # Problem description
            elif dialogue == {'Greetings', 'Name', 'Phone'}:
                response = Text(text='Please describe the problem:')
                self.send(response.to_dict(), 'RESPONSE')
                dialogue.add('Problem')

            # Location
            elif dialogue == {'Greetings', 'Name', 'Phone', 'Problem'}:
                qr = quick_replies.QuickReply(title='Location',
                                              content_type='location')
                qrs = quick_replies.QuickReplies(quick_replies=[qr])
                response = Text(text='Please send the location of problem:',
                                quick_replies=qrs)
                self.send(response.to_dict(), 'RESPONSE')

        # Name
        if message['message'].get('quick_reply'):
            if message['message']['quick_reply'].get(
                    'payload') == 'open_issue' and 'Greetings' in dialogue:
                response = Text(text='Please enter your full name:')
                self.send(response.to_dict(), 'RESPONSE')
                dialogue.add('Name')

        # Live city
        if message['message'].get('quick_reply'):
            if message['message']['quick_reply'].get(
                    'payload') == 'live_city' and 'Greetings' in dialogue:
                btn = get_button(ratio='compact')
                elem = get_element(btn)
                response = GenericTemplate(elements=[elem])
                self.send(response.to_dict(), 'RESPONSE')

        # Picture
        if message['message'].get('attachments'):
            if message['message']['attachments'][0].get('type') == 'location':
                response = Text(text='Please send a picture of a problem:')
                self.send(response.to_dict(), 'RESPONSE')
                dialogue.add('Location')
            # Final state
            elif message['message']['attachments'][0].get('type') == 'image':
                response = Text(
                    text=
                    'Your ticket has been opened and we will get on it as fast as possible. If you '
                    'want to add another issue, please just greet again. Thank you!. '
                )
                self.send(response.to_dict(), 'RESPONSE')
                dialogue.add('Image')