Create a Get Started button and Quick Replies for Facebook messenger bot

This blog is part of the chatbot blog series, https://www.idiotinside.com/2017/12/22/create-fb-messenger-bot-aws-lambda/

Get started button

The welcome screen is the first thing people see when they find your Messenger bot. The welcome screen displays information like name, responsiveness of your bot, the profile picture and cover photo, an optional greeting message, and a get started button.

When the ‘get started button’ is tapped, It starts a conversation with your Messenger bot, then your bot is granted permission to send messages to that user.

Technically, when the get started button is tapped, It sends a messaging_postbacks event to your webhook. Both greeting text and get_started button are saved as part of the facebook page’s messenger profile. So when making changes to greeting message and get started button we can directly call our webhook url to manually trigger this messenger profile update.

To set the get started button, you must have the Administrator role for the Facebook Page associated with the bot.

Setting greeting text and get started button

messenger_profile = MessengerProfile()

greeting_text = GreetingText('Welcome to weather bot')
get_started = GetStartedButton(payload='start')

messenger_profile = MessengerProfile(greetings=[greeting_text], get_started=get_started)
messenger.set_messenger_profile(messenger_profile.to_dict())

This piece of code is called when the bot is verified on facebook console, To update the messenger profile we can manually call the webhook.

Quick Replies

Quick replies provide a way to present a set of up to 11 buttons in-conversation that contain a title and optional image, and appear prominently above the composer. You can also use quick replies to request a person’s location.

Sending quick replies

Quick replies gives handy options to the user, to reply back faster or it can be used to send location. We will user quick reply to get current location of the user.

quick_reply_1 = quick_replies.QuickReply(title='Location', content_type='location')
quick_replies_set = quick_replies.QuickReplies(quick_replies=[
    quick_reply_1
])
text = {'text': 'Share your location'}
text['quick_replies'] = quick_replies_set.to_dict()
self.send(text)

Putting it all together, When user taps “Get started”, the bot will send a quick reply option to get location information.

main.py

import os
from flask import Flask, request
from fbmessenger import BaseMessenger
from fbmessenger import quick_replies
from fbmessenger.elements import Text
from fbmessenger.thread_settings import GreetingText, GetStartedButton, MessengerProfile

class Messenger(BaseMessenger):
    def __init__(self, page_access_token):
        self.page_access_token = page_access_token
        super(Messenger, self).__init__(self.page_access_token)

    def message(self, message):
        response = Text(text= str(message['message']['text']))
        action = response.to_dict()
        res = self.send(action)
        app.logger.debug('Response: {}'.format(res))

    def delivery(self, message):
        pass

    def read(self, message):
        pass

    def account_linking(self, message):
        pass

    def postback(self, message):
        payload = message['postback']['payload']

        if 'start' in payload:
            quick_reply_1 = quick_replies.QuickReply(title='Location', content_type='location')
            quick_replies_set = quick_replies.QuickReplies(quick_replies=[
                quick_reply_1
            ])
            text = {'text': 'Share your location'}
            text['quick_replies'] = quick_replies_set.to_dict()
            self.send(text)

    def optin(self, message):
        pass

    def init_bot(self):
        greeting_text = GreetingText('Welcome to weather bot')
        messenger_profile = MessengerProfile(greetings=[greeting_text])
        messenger.set_messenger_profile(messenger_profile.to_dict())

        get_started = GetStartedButton(payload='start')

        messenger_profile = MessengerProfile(get_started=get_started)
        messenger.set_messenger_profile(messenger_profile.to_dict())


app = Flask(__name__)
app.debug = True
messenger = Messenger(os.environ.get('FB_PAGE_TOKEN'))


@app.route('/webhook', methods=['GET', 'POST'])
def webhook():
    if request.method == 'GET':
        if request.args.get('hub.verify_token') == os.environ.get('FB_VERIFY_TOKEN'):
            messenger.init_bot()
            return request.args.get('hub.challenge')
        raise ValueError('FB_VERIFY_TOKEN does not match.')
    elif request.method == 'POST':
        messenger.handle(request.get_json(force=True))
    return ''


if __name__ == '__main__':
    app.run(host='0.0.0.0')