Setup a Facebook Messenger chatbot in Laravel
#There is a new PHP library called BotMan that makes it super easy to setup a Facebook Messenger chatbot in Laravel. Let's do this.
Welcome BotMan
BotMan is framework agnostic PHP library for creating chatbots. It supports multiple messenger platforms like Telegram
, Slack
, Microsoft
, Facebook
and more. It is built by Marcel Pociot and it makes developing chatbots super easy. We are going to use it in Laravel to setup a Facebook Messenger chatbot.
BotMan ❤️ Laravel
BotMan works perfectly together with Laravel. Marcel has provided a BotMan Laravel Starter which we are going to use here.
Install the Laravel application
First we need to clone the repository and install the dependencies.
git clone git@github.com:mpociot/botman-laravel-starter.git
cd botman-laravel-starter
php composer install
And of course, like with every Laravel project, we create our environment config file and generate an application key.
mv .env.example .env
php artisan key:generate
Configuration
Now we are ready to copy our Facebook Messenger tokens to our .env
file. We need the Page Access Token
which is linked to the Facebook page you want to use and the Verify Token
which is used to hook up this application and the Messenger application.
// ...inside .env file
FACEBOOK_TOKEN=your-facebook-page-token
TOKEN_VERIFY=your-wehbook-verify-token
FACEBOOK_APP_SECRET=your-facebook-app-secret
Also make sure you have these Facebook settings inside you config/services.php
:
// ..
'botman' => [
// ...
'facebook_token' => env('FACEBOOK_TOKEN'),
'facebook_app_secret' => env('FACEBOOK_APP_SECRET')
],
// ..
Your application needs to be available for the Facebook webhook. I am using Laravel valet to generate a public HTTPS URL.
valet share
Chat
Now type test
in your Messenger chat of the used page and you should get back "hello!". Also try out Start conversation
and see an example of a BotMan conversation
. This should look like this:
Awesome right? When you take a look at the botman.php
file in the routes directory you will see why the two messages already worked out of the box.
<?php
use App\Http\Controllers\BotManController;
// Don't use the Facade in here to support the RTM API too :)
$botman = resolve('botman');
$botman->hears('test', function($bot){
$bot->reply('hello!');
});
$botman->hears('Start conversation', BotManController::class.'@startConversation');
Checkout the BotMan documentation to learn more about the features.
Conclusion
Wasn't that easy? Now you got a chatbot running, try to create conversations yourself. This year will be full of chatbots and it is great to see more and more great tools like BotMan out there to help use building them.