Skip to content

isarphilipp/workbench

Repository files navigation

img

Botomatic v1.0

The MIT License (MIT)

Copyright (c) Links der Isar http://www.linksderisar.com

Botomatic is a web application framework designed to help build chatbots for Messenger Platform. Before reading this guide it is recommended to read the official documentation of Messenger Platform for a better understanding of chatbots development.

Depending on your development environment it is recommended to use either Laravel Valet on Mac or Laravel Homestead on other systems


Quick guide

This guide contains only the essentials to get you started fast, for a comprehensive understandig and advanced topics please read the official docs.

  1. Installation and configuration
  2. Test locally
  3. Basics
  4. States
  5. Message Handler
  6. Response Handler
  7. Templates
  8. Default Bot
  9. Register with Facebook

1. Installation and configuration

1.1 Clone the repository

git clone https://github.com/Botomatic-PHP/Workbench.git Botomatic

1.2 Environment configuration

  • Move .env.example to .env
  • Make sure BOTOMATIC_FACEBOOK_DEBUG is set to true
  • Set BOTOMATIC_FACEBOOK_TEST_URL to your project's url
  • Setup any needed env. variables like database connection

1.3 Install Botomatic

  • Install the framework with dependencies: composer install
  • Generate an application key: php artisan key:generate

2. Test locally

To test the bot locally, you have to use the CLI Bot. Keep in mind it's very limited and made to be used only for development purposes

artisan bf:cli

You should see "Starting CLI Bot...:"

Type hi

It should respond with "Hello Test Test"


3. Basics

3.1 Folder structure

All Bot related files are in app/Bot/Facebook except for the configuration file which is located under config/botomatic/facebook.php

3.2 States

Botomatic structures the conversation in states. A state receives the message from the user and either responds or moves to another state.

Each state will have an additional 2 objects: Handlers/Message and Handlers/Reponses used to structure the code more efficiently, a simple process will look like this:

	if ($this->message->saysHi())
	{
	    return $this->response->responseDefault();
	}

Any domain logic can be stored here but it is recommended to use a sepparate file to keep the code more readable.

The flow of the bot is controlled by the response, this returns \Botomatic\Engine\Facebook\Abstracts\States\Response\Handler

3.3 Templates

Messenger Platform supports different Templates like buttons, tiles, lists etc.

Templates are stored in app/Bot/Facebook/Templates/*Type*, to send them as a response you simply "attach" them to the response object:

    return $this->response
        ->addQuickReplies(new \App\Bot\Facebook\Templates\QuickReplies\General\Options())
        ->sendResponse()
        ->setStatusActive();

More infromation on how to generate templates and their usage under Response and Templates.


4. States

There are 4 types of States: Listener, Workflow, Fallback, Filters, and Background.

You can easily generate a state using this commands:

Workflow

artisan bf:state {namespace} {name}

Filter

artisan bf:filter {namespace} {name}

Where namespace is the folder within the category, for example the default bot has all it's state's in Test folder.

A state contains by default the following folders and files:

  • StateName
    • Handlers
      • Message.php
      • Responses.php
    • StateName.php

4.1 Listener

This is the default State that handles the start of the conversation. There can only be 1 Listener.

4.2 Workflow

Most of the conversation is handle by this type of State, the routing or "mapping" of them is defined in app/Bot/Facebook/Routes/Workflow.php.

By default, the status of a State is "active", whenever it is changed, based on the mapping defined it moves to the next state.

4.3 Fallback

Whenever the conversation fails by whatever reason the Fallback State is called. There can only be 1 Fallback State.

4.4 Filters

Simple States through which the incoming message passes through, they can stop the flow and respond with a message or "move" to another Workflow state regardless of the current "active state".

There are 2 types of filters:

  • Regular filters through which all messages go
  • Postback filters that only capture messages that contain a Postback

Postbacks are sent when a user clicks on a button within a template with the exception of Quick Replies which are sent as regular messages!

Filters are mapped in app/Bot/Facebook/Routes/Filters.php and app/Bot/Facebook/Routes/Postbacks.php. The order in the array is the same order in which the message will go through.

4.5 Background

Background states are used to push a message to user(s) outside the context of a conversation, it can be a regular message or "jump" to a workflow state.


5. Message Handler

The message handler is a simple object that extend \Botomatic\Engine\Facebook\Abstracts\States\Message\Handler.

This object contains the message (text, image, postback etc) received from the user. The following methods are available:

Check if it's a text message

$this->message()->isCallbackMessage()

Get the text message

$this->message()->getMessage()

Get the text quick reply (payload) if available

$this->message()->getQuickReply()

Check if it's a Postback

$this->message()->isCallbackPostback()

Get the postback

$this->message()->postback()

Check for attachments

$this->message()->hasAttachment()

Get attachments

$this->message()->getAttachment()

Check for location

$this->message()->hasLocation()

Get location

$this->message()->location()

6. Response Handler

The response handler contains "responses" defined as methods, it always returns \Botomatic\Engine\Facebook\Entities\Response. This is the object States use to respond to the user. The object moves from state to state until it's returned to the user and any state can add or remove from it.

Response example:

    public function responseDefault() : \Botomatic\Engine\Facebook\Entities\Response
    {
          return $this->response->addMessage('Hi there')
              ->setStatusActive()
              ->sendResponse();
    }

Available methods:

Add a message

addMessage(string $message)

You can add as many messages as you like (keep in mind Facebook's limitations), they will be sent in the same order they are called.

Add Image (url)

addImage(string $image)

Ask for location

askForLocation($title = 'Please share your location:')

Stop the flow and respond to the user

sendResponse()

Delay the message

delay($seconds = 1)

You can add several delays, the data is sent to facebook in the same order it's being defined.

Practical example:

      return $this->response->addMessage('Hi there')
          ->delay(5)
          ->addMessage('Second message, sent after 5s')
          ->sendResponse();

Add a quick reply

addQuickReplies(new \App\Bot\Facebook\Templates\QuickReplies\General\Options())

7. Templates

Botomatic supports all Templates available for Messenger Platform.

For examples, check default bot.

Generate new Quick Reply

artisan bf:qr {namespace} {name}

Generate Generic Template

artisan bf:gt {namespace} {name}

Generate Button Template

artisan bf:bt {namespace} {name}

8. Default bot and CLI Bot

For practical examples on how a Bot is structured and various functionalities check the default bot located in app/Bot/Facebook

To play around, you can use the CLI Bot (artisan bf:cli).

Buttons in CLI Bot

Whenever the bot responds with a template, it will be displayed like this:

Quick Replies:  [Templates]  [Conversation]

To "press" one of the buttons simply type the button name. e.g. Templates


9. Register your bot with Facebook

Chatbots for Messenger Platform are Apps that are connected to specific Facebook pages.

1. Create Facebook App

Go to Facebook Apps and create a new one. From the Products selection choose Messenger

2. Setup Webhook

The webhook is the URL where Facebook will send messages from users, for development purposes it is recommeded you use services like ngrok to publicly share a local url. If you use Laravel Valet it's very easy, simply run valet share

Follow these steps to register your bot:

  • set "BOTOMATIC_FACEBOOK_CONFIRMATION" to true in .env file
  • click on Setup Webhooks from the App's settings and add this url: https://ngrok-url/webhook/facebook
  • inside "Verify Token" type "botomatic"
  • from "Subscription Fields" select "messages" and "messaging_postbacks"
  • click "Verify and Save"
  • set BOTOMATIC_FACEBOOK_CONFIRMATION to false
  • set BOTOMATIC_FACEBOOK_DEBUG to false

Next, you need a Facebook page where the bot will be accesibly from, under "Token Generation" select the Facebook page you want to link your bot; a "Page Access Token" is now generated.

Next we need to tell botomatic to what pages it responds, go to and under pages we store all pages that the bot has access to, grab the Facebook Page ID (you find this on Page's about section) and add it to the array with the access token

   'pages' => [
        'page-id' => "Page Access Token"
    ],

Finally, we need to subscribe the Webhook to this page, under Webhooks select the proper Facebook Page.

Now go to Facebook page and send a message.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published