├── events.md ├── documentation.md ├── nlp.md ├── driver-hangouts-chat.md ├── storing-information.md ├── driver-ms-bot-framework.md ├── cache-drivers.md ├── user-information.md ├── driver-wechat.md ├── driver-nexmo.md ├── driver-hipchat.md ├── faq.md ├── upgrade.md ├── driver-web.md ├── driver-telegram.md ├── releases.md ├── botman-studio.md ├── driver-cisco-spark.md ├── driver-twilio.md ├── driver-amazon-alexa.md ├── receiving-additional-content.md ├── installation.md ├── welcome.md ├── receiving.md ├── sending.md ├── driver-slack.md ├── middleware.md ├── drivers.md ├── testing.md ├── conversations.md ├── web-widget.md └── driver-facebook-messenger.md /events.md: -------------------------------------------------------------------------------- 1 | # Events 2 | 3 | - [Introduction](#introduction) 4 | - [Listening To Driver Events](#listening) 5 | - [Available Events](#available-events) 6 | 7 | 8 | ## Introduction 9 | BotMan gives you the ability to listen to driver specific events, such as when a person joins your Slack channel or a Facebook message gets read. You can then perform various tasks when these events happen and reply to your chatbot users. 10 | 11 | 12 | ## Listening To Driver Events 13 | 14 | You may listen to driver events using a simple and easy API. The BotMan object provides an `on` method that takes an event name and a closure/callable to execute once the event occurs. 15 |

16 | All callbacks will receive the event payload and the BotMan instance as parameters. 17 | 18 | ```php 19 | $botman->on('event', function($payload, $bot) { 20 | 21 | }); 22 | ``` 23 | 24 | 25 | ## Available Events 26 | Please refer to each messaging service documentation to get a list of available events. -------------------------------------------------------------------------------- /documentation.md: -------------------------------------------------------------------------------- 1 | - Prologue 2 | - [Release Notes](/__version__/releases) 3 | - [Upgrade Guide](/__version__/upgrade) 4 | 5 | - Setup 6 | - [Installation](/__version__/installation) 7 | - [Cache drivers](/__version__/cache-drivers) 8 | - [Web Widget](/__version__/web-widget) 9 | 10 | - Core Concepts 11 | - [Hearing Messages](/__version__/receiving) 12 | - [Hearing Attachments](/__version__/receiving-additional-content) 13 | - [Sending Messages](/__version__/sending) 14 | - [Conversations](/__version__/conversations) 15 | - [Events](/__version__/events) 16 | 17 | - Advanced Topics 18 | - [Natural Language Processing](/__version__/nlp) 19 | - [User Information](/__version__/user-information) 20 | - [Storing Information](/__version__/storing-information) 21 | 22 | - Extending BotMan 23 | - [Middleware](/__version__/middleware) 24 | - [Drivers](/__version__/drivers) 25 | 26 | - Drivers 27 | - [Amazon Alexa](/__version__/driver-amazon-alexa) 28 | - [Cisco Spark](/__version__/driver-cisco-spark) 29 | - [Facebook Messenger](/__version__/driver-facebook-messenger) 30 | - [Hangouts Chat](/__version__/driver-hangouts-chat) 31 | - [HipChat](/__version__/driver-hipchat) 32 | - [Microsoft Bot Framework](/__version__/driver-ms-bot-framework) 33 | - [Nexmo](/__version__/driver-nexmo) 34 | - [Slack](/__version__/driver-slack) 35 | - [Telegram](/__version__/driver-telegram) 36 | - [Twilio](/__version__/driver-twilio) 37 | - [Web](/__version__/driver-web) 38 | - [WeChat](/__version__/driver-wechat) 39 | - [Testing](/__version__/testing) 40 | - [FAQ](/__version__/faq) -------------------------------------------------------------------------------- /nlp.md: -------------------------------------------------------------------------------- 1 | # Natural Language Processing 2 | 3 | - [Introduction](#introduction) 4 | - [Dialogflow (previously known as API.ai)](#dialogflow) 5 | 6 | 7 | ## Introduction 8 | 9 | Natural Language Processing - or short "NLP" - is the process of extracting structured data from a sentence or paragraph. 10 | The information is usually separated into `intents` and `entities`. 11 | 12 | For example, NLP tools take a sentence like this: 13 | 14 | ``` 15 | Hey Calendar, schedule dinner with Nicole at 8 pm tomorrow. 16 | ``` 17 | 18 | and returns structured data that BotMan can process: 19 | 20 | ```javascript 21 | { 22 | "intent": "create_meeting", 23 | "entities": { 24 | "name" : "Dinner with Nicole", 25 | "invitees" : ["Nicole"], 26 | "time": "2017-02-05 20:00:00" 27 | } 28 | } 29 | ``` 30 | 31 | Now this makes a perfect usage scenario for BotMan, as you are no longer tied to static text inputs that need to be exact matches. 32 | Instead you can make use of BotMan's middleware support and retrieve information from third party services like wit.ai or Dialogflow. 33 | 34 | 35 | ## Dialogflow 36 | 37 | BotMan has built-in support for the [Dialogflow](https://dialogflow.com/) NLP service. 38 | Please refer to the [Dialogflow documentation](https://dialogflow.com/docs/getting-started/basics) on how to set up your account and get started with the service. 39 | 40 | To listen in BotMan for certain Dialogflow actions, you can use the ApiAi middleware class. 41 | 42 | ```php 43 | use BotMan\BotMan\Middleware\ApiAi; 44 | 45 | $dialogflow = ApiAi::create('your-api-ai-token')->listenForAction(); 46 | 47 | // Apply global "received" middleware 48 | $botman->middleware->received($dialogflow); 49 | 50 | // Apply matching middleware per hears command 51 | $botman->hears('my_api_action', function (BotMan $bot) { 52 | // The incoming message matched the "my_api_action" on Dialogflow 53 | // Retrieve Dialogflow information: 54 | $extras = $bot->getMessage()->getExtras(); 55 | $apiReply = $extras['apiReply']; 56 | $apiAction = $extras['apiAction']; 57 | $apiIntent = $extras['apiIntent']; 58 | 59 | $bot->reply("this is my reply"); 60 | })->middleware($dialogflow); 61 | ``` 62 | -------------------------------------------------------------------------------- /driver-hangouts-chat.md: -------------------------------------------------------------------------------- 1 | # Hangouts Chat 2 | 3 | - [Installation & Setup](#installation-setup) 4 | - [Supported Features](#supported-features) 5 | 6 | 7 | ## Installation & Setup 8 | 9 | First you need to pull in the Hangouts Driver. 10 | 11 | ```sh 12 | composer require botman/driver-hangouts 13 | ``` 14 | 15 | Then load the driver before creating the BotMan instance (**only when you don't use BotMan Studio**): 16 | 17 | ```php 18 | DriverManager::loadDriver(\BotMan\Drivers\Hangouts\HangoutsDriver::class); 19 | 20 | // Create BotMan instance 21 | BotManFactory::create($config); 22 | ``` 23 | 24 | Or if you use BotMan Studio: 25 | 26 | ```sh 27 | php artisan botman:install-driver hangouts 28 | ``` 29 | 30 | This driver requires a valid and secure URL in order to set up webhooks and receive events and information from the users. This means your application should be accessible through an HTTPS URL. 31 | 32 | > {callout-info} [ngrok](https://ngrok.com/) is a great tool to create such a public HTTPS URL for your local application. If you use Laravel Valet, you can create it with "valet share" as well. 33 | 34 | To connect BotMan with Hangouts Chat, create a bot and configure your HTTPS endpoint, as described in the [official documentation](https://developers.google.com/hangouts/chat/how-tos/bots-publish?authuser=1). 35 | Take note of the verification token and place it in your Hangouts configuration. 36 | 37 | If you use BotMan Studio, you can find the configuration file located under `config/botman/hangouts.php`. 38 | 39 | If you dont use BotMan Studio, add these line to $config array that you pass when you create the object from BotManFactory. 40 | 41 | ```php 42 | 'hangouts' => [ 43 | 'token' => 'YOUR-WEBHOOK-TOKEN', 44 | ] 45 | ``` 46 | 47 | 48 | 49 | ## Supported Features 50 | This is a list of features that the driver supports. 51 | If a driver does not support a specific action, it is in most cases a limitation from the messaging service - not BotMan. 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 |
FeatureSupported?
Question-Buttons
Image Attachment
Video Attachment
Audio Attachment
Location Attachment
-------------------------------------------------------------------------------- /storing-information.md: -------------------------------------------------------------------------------- 1 | # Storing Information 2 | 3 | - [Introduction](#introduction) 4 | - [User Storage](#user-storage) 5 | - [Channel Storage](#channel-storage) 6 | - [Driver Storage](#driver-storage) 7 | - [Write To Storage](#write-storage) 8 | - [Read From Storage](#read-storage) 9 | - [Delete Items In Storage](#delete-storage) 10 | 11 | 12 | ## Introduction 13 | BotMan has a builtin storage system, which you can use to store user, "channel" or driver specific information without having the need for conversations. 14 | By default, BotMan will use a simple JSON file storage to keep the data in the filesystem. 15 | 16 | 17 | ## User Storage 18 | 19 | The user storage is - as the name suggests - scoped to users. You can place user related information in there and also easily access stored elements for the current chatbot user, that you are interacting with: 20 | 21 | ```php 22 | $storage = $botman->userStorage(); 23 | ``` 24 | 25 | 26 | ## Channel Storage 27 | 28 | The channel storage can be used to save and retrieve "channel" related information. This is especially useful in combination with messaging services that support the concept of "channels" - such as Slack channels or Telegram group chts. 29 | 30 | ```php 31 | $storage = $botman->channelStorage(); 32 | ``` 33 | 34 | 35 | ## Driver Storage 36 | 37 | The driver storage is even more generic than the channel storage, as it is only restricted to the messaging service that is currently used. You can use this storage to store messaging service related information. 38 | 39 | ```php 40 | $storage = $botman->driverStorage(); 41 | ``` 42 | 43 | 44 | ## Write To Storage 45 | You can write simple elements to the storage by using the `save` method on your storage instance. 46 | 47 | ```php 48 | $bot->userStorage()->save([ 49 | 'name' => $name 50 | ]); 51 | ``` 52 | 53 | 54 | ## Read From Storage 55 | You can read elements from the storage in multiple ways. 56 | 57 | The `all` method will return all entries on the storage. 58 | 59 | ```php 60 | $bot->userStorage()->all(); 61 | ``` 62 | 63 | If you only want to select one specific entry / ID, you can use the `find` method: 64 | 65 | ```php 66 | $bot->userStorage()->find($id); 67 | ``` 68 | 69 | Once you have received an item from the storage, call the `get` method to retrieve specific keys: 70 | 71 | ```php 72 | $userinformation = $bot->userStorage()->find($id); 73 | $element = $userinformation->get('my-custom-stored-element'); 74 | ``` 75 | 76 | 77 | ## Delete Items In Storage 78 | To delete existing entries from the storage, use the `delete` method on the storage instance. This will delete 79 | every information associated with the selected storage. 80 | 81 | ```php 82 | $bot->userStorage()->delete(); 83 | ``` 84 | -------------------------------------------------------------------------------- /driver-ms-bot-framework.md: -------------------------------------------------------------------------------- 1 | # Microsoft Bot Framework / Skype 2 | 3 | - [Installation & Setup](#installation-setup) 4 | - [Supported Features](#supported-features) 5 | 6 | 7 | ## Installation & Setup 8 | 9 | First you need to pull in the Bot Framework Driver. 10 | 11 | ```sh 12 | composer require botman/driver-botframework 13 | ``` 14 | 15 | Then load the driver before creating the BotMan instance (**only when you don't use BotMan Studio**): 16 | 17 | ```php 18 | DriverManager::loadDriver(\BotMan\Drivers\BotFramework\BotFrameworkDriver::class); 19 | 20 | // Create BotMan instance 21 | BotManFactory::create($config); 22 | ``` 23 | 24 | Or if you use BotMan Studio: 25 | 26 | ```sh 27 | php artisan botman:install-driver botframework 28 | ``` 29 | 30 | This driver requires a valid and secure URL in order to set up webhooks and receive events and information from the chat users. This means your application should be accessible through an HTTPS URL. 31 | 32 | > {callout-info} [ngrok](https://ngrok.com/) is a great tool to create such a public HTTPS URL for your local application. If you use Laravel Valet, you can create it with "valet share" as well. 33 | 34 | Register a developer account with the [Bot Framework Developer Portal](https://dev.botframework.com/) and follow [this guide](https://docs.botframework.com/en-us/csharp/builder/sdkreference/gettingstarted.html#registering) to register your first bot with the Bot Framework. 35 |

36 | When you set up your bot, you will be asked to provide a public accessible endpoint for your bot. 37 | Place the URL that points to your BotMan logic / controller in this field. 38 |

39 | Take note of your App ID and App Key assigned to your new bot and place it in your BotMan configuration. 40 | If you use BotMan Studio, you can find the configuration file located under `config/botman/botframework.php`. 41 | 42 | If you dont use BotMan Studio, add these line to $config array that you pass when you create the object from BotManFactory. 43 | ```php 44 | 'botframework' => [ 45 | 'app_id' => 'YOUR-MICROSOFT-APP-ID', 46 | 'app_key' => 'YOUR-MICROSOFT-APP-KEY', 47 | ] 48 | ``` 49 | 50 | 51 | ## Supported Features 52 | This is a list of features that the driver supports. 53 | If a driver does not support a specific action, it is in most cases a limitation from the messaging service - not BotMan. 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 |
FeatureSupported?
Question-Buttons
Image Attachment
Video Attachment
Audio Attachment
Location Attachment
-------------------------------------------------------------------------------- /cache-drivers.md: -------------------------------------------------------------------------------- 1 | # Cache drivers 2 | 3 | - [PSR6 Cache](#psr6) 4 | - [Laravel Cache](#laravel) 5 | - [Doctrine Cache](#doctrine) 6 | - [CodeIgniter Cache](#codeigniter) 7 | - [Redis Cache](#redis) 8 | - [Symfony Cache](#symfony) 9 | 10 | If you want to make use of BotMans Conversation feature, you need to use a persistent cache driver, where BotMan can store and retrieve the conversations. 11 | If not specified otherwise, BotMan will use the ``array`` cache which is non-persistent. 12 | 13 | > {callout-info} If you use [BotMan Studio](/__version__/botman-studio) it is **not** required to specify cache drivers manually, as Laravel handles this for you. 14 | 15 | 16 | 17 | 18 | ### PSR-6 Cache 19 | If your framework / cache driver is not explicitly supported by BotMan, you can see if your cache driver supports the [PSR-6 Caching Interface](http://www.php-fig.org/psr/psr-6/). With the PSR-6 BotMan cache driver, you can use all supported cache drivers with BotMan. 20 | 21 | ```php 22 | use BotMan\BotMan\Cache\Psr6Cache; 23 | 24 | $adapter = new MyCustomPsr6CacheAdapter(); 25 | $botman = BotManFactory::create($config, new Psr6Cache($adapter)); 26 | ``` 27 | 28 | 29 | ### Laravel Cache 30 | When using botman in an existing Laravel project, you can use the Botman's built in LaravelCache. 31 | 32 | ```php 33 | use BotMan\BotMan\Cache\LaravelCache; 34 | 35 | $botman = BotManFactory::create($config, new LaravelCache()); 36 | ``` 37 | 38 | 39 | ### Doctrine Cache 40 | Use any [Doctrine Cache](http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/caching.html) driver by passing it to the factory: 41 | 42 | ```php 43 | use BotMan\BotMan\Cache\DoctrineCache; 44 | 45 | $botman = BotManFactory::create($config, new DoctrineCache($doctrineCacheDriver)); 46 | ``` 47 | 48 | 49 | ### CodeIgniter Cache 50 | Use any [CodeIgniter Cache](https://www.codeigniter.com/userguide3/libraries/caching.html) adapter by passing it to the factory: 51 | 52 | ```php 53 | use BotMan\BotMan\Cache\CodeIgniterCache; 54 | 55 | $this->load->driver('cache'); 56 | $botman = BotManFactory::create($config, new CodeIgniterCache($this->cache->file)); 57 | ``` 58 | 59 | 60 | ### Redis Cache 61 | Use your [Redis](https://redis.io) in-memory data structure to cache BotMan conversation information. If you have the [igbinary module](https://github.com/igbinary/igbinary) available, it will be used instead of standard PHP serializer: 62 | 63 | ```php 64 | use BotMan\BotMan\Cache\RedisCache; 65 | 66 | $botman = BotManFactory::create($config, new RedisCache('127.0.0.1', 6379)); 67 | ``` 68 | 69 | 70 | ### Symfony Cache 71 | Use any [Symfony Cache](http://symfony.com/doc/current/components/cache.html) component by passing it to the factory: 72 | 73 | ```php 74 | use BotMan\BotMan\Cache\SymfonyCache; 75 | use Symfony\Component\Cache\Adapter\FilesystemAdapter; 76 | 77 | $adapter = new FilesystemAdapter(); 78 | $botman = BotManFactory::create($config, new SymfonyCache($adapter)); 79 | ``` 80 | -------------------------------------------------------------------------------- /user-information.md: -------------------------------------------------------------------------------- 1 | # User Information 2 | 3 | - [Introduction](#introduction) 4 | - [Retrieving User Information](#retrieving-user-information) 5 | - [Retrieve The User's First Name](#retrieving-user-firstname) 6 | - [Retrieve The User's Last Name](#retrieving-user-lastname) 7 | - [Retrieve The User-ID](#retrieving-user-id) 8 | - [Retrieve The Username](#retrieving-username) 9 | - [Retrieve The Raw User Information](#retrieving-raw-user-information) 10 | - [Caching User Information](#caching-user-information) 11 | 12 | ## Introduction 13 | BotMan makes it simple to access your chatbot user information. Which user fields are available purely depend on the messaging service you use. Some services offer more information than others do. Yet you can access them using the same API with BotMan. 14 | 15 | 16 | 17 | ## Retrieving User Information 18 | BotMan has a simple way to let you retrieve user relevant information. Once you listened to a command and are in either a conversation or a message callback, you can use the `getUser` method on the BotMan instance. 19 | 20 | 21 | ### Retrieve The User's First Name 22 | You can access the user's first name using: 23 | 24 | ```php 25 | // Access user 26 | $user = $bot->getUser(); 27 | // Access first name 28 | $firstname = $user->getFirstName(); 29 | ``` 30 | 31 | 32 | ### Retrieve The User's Last Name 33 | You can access the user's last name using: 34 | 35 | ```php 36 | // Access user 37 | $user = $bot->getUser(); 38 | // Access last name 39 | $lastname = $user->getLastName(); 40 | ``` 41 | 42 | 43 | ### Retrieve The User-ID 44 | You can access the user ID using: 45 | 46 | ```php 47 | // Access user 48 | $user = $bot->getUser(); 49 | // Access ID 50 | $id = $user->getId(); 51 | ``` 52 | 53 | 54 | ### Retrieve The Username 55 | You can access the user Username using: 56 | 57 | ```php 58 | // Access user 59 | $user = $bot->getUser(); 60 | // Access Username 61 | $id = $user->getUsername(); 62 | ``` 63 | Be aware that you might not receive any username data if the user hasn't set a username in their messenger settings. 64 | 65 | 66 | ### Retrieve The Raw User Information 67 | You can access also access the unprocessed raw messaging service user information that BotMan receives using: 68 | 69 | ```php 70 | // Access user 71 | $user = $bot->getUser(); 72 | // Access Information 73 | $info = $user->getInfo(); 74 | ``` 75 | 76 | 77 | ### Caching User Information 78 | 79 | BotMan will cache user information for a duration of 30 minutes by default. This is especially useful for drivers like 80 | Facebook where it takes an additional request to retrieve this information. In the BotMan config you are able to 81 | change this duration with the `user_cache_time`. You can also set it to zero in order to prevent BotMan from caching the user information at all. 82 | 83 | ```php 84 | 'botman' => [ 85 | 'user_cache_time' => 30 86 | ], 87 | ``` 88 | -------------------------------------------------------------------------------- /driver-wechat.md: -------------------------------------------------------------------------------- 1 | # WeChat 2 | 3 | - [Installation & Setup](#installation-setup) 4 | - [Supported Features](#supported-features) 5 | 6 | 7 | ## Installation & Setup 8 | 9 | First you need to pull in the WeChat Driver. 10 | 11 | ```sh 12 | composer require botman/driver-wechat 13 | ``` 14 | 15 | Then load the driver before creating the BotMan instance (**only when you don't use BotMan Studio**): 16 | 17 | ```php 18 | DriverManager::loadDriver(\BotMan\Drivers\WeChat\WeChatDriver::class); 19 | 20 | // Create BotMan instance 21 | BotManFactory::create($config); 22 | ``` 23 | 24 | Or if you use BotMan Studio: 25 | 26 | ```sh 27 | php artisan botman:install-driver wechat 28 | ``` 29 | 30 | This driver requires a valid and secure URL in order to set up webhooks and receive events and information from the chat users. This means your application should be accessible through an HTTPS URL. 31 | 32 | > {callout-info} [ngrok](https://ngrok.com/) is a great tool to create such a public HTTPS URL for your local application. If you use Laravel Valet, you can create it with "valet share" as well. 33 | 34 | Login to your [developer sandbox account](http://admin.wechat.com/debug/cgi-bin/sandbox?t=sandbox/login) and take note of your appId and appSecret. This is your test bot. 35 | 36 | There is a section called "API Config" where you need to provide a public accessible endpoint for your bot. 37 | Place the URL that points to your BotMan logic / controller in the URL field. 38 | 39 | This URL needs to validate itself against WeChat. Choose a unique 40 | verify token, which you can check against in your verify controller and place it in the Token field. 41 | 42 | Pass the WeChat App ID and App Key to the `BotManFactory` upon initialization. If you use BotMan Studio, you can find the configuration file located under `config/botman/wechat.php`. 43 | 44 | ```php 45 | [ 46 | 'wechat' => [ 47 | 'app_id' => 'YOUR-WECHAT-APP-ID', 48 | 'app_key' => 'YOUR-WECHAT-APP-KEY', 49 | 'verification' => 'YOUR-WECHAT-VERIFICATION-TOKEN', 50 | ] 51 | ] 52 | ``` 53 | 54 | Last you need to connect the test bot with your WeChat user account. Use the `Test account QR Code` from your sandbox page to add the bot to your contacts. And that's it - you can now use BotMan with WeChat to create interactive bots! 55 | 56 | 57 | 58 | ## Supported Features 59 | This is a list of features that the driver supports. 60 | If a driver does not support a specific action, it is in most cases a limitation from the messaging service - not BotMan. 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 |
FeatureSupported?
Question-Buttons
Image Attachment
Video Attachment
Audio Attachment
Location Attachment
-------------------------------------------------------------------------------- /driver-nexmo.md: -------------------------------------------------------------------------------- 1 | # Nexmo 2 | 3 | - [Installation & Setup](#installation-setup) 4 | - [Register Your Webhook](#register-webhook) 5 | - [Supported Features](#supported-features) 6 | 7 | 8 | ## Installation & Setup 9 | 10 | First you need to pull in the Nexmo Driver. 11 | 12 | ```sh 13 | composer require botman/driver-nexmo 14 | ``` 15 | 16 | Then load the driver before creating the BotMan instance (**only when you don't use BotMan Studio**): 17 | 18 | ```php 19 | DriverManager::loadDriver(\BotMan\Drivers\Nexmo\NexmoDriver::class); 20 | 21 | // Create BotMan instance 22 | BotManFactory::create($config); 23 | ``` 24 | 25 | Or if you use BotMan Studio: 26 | 27 | ```sh 28 | php artisan botman:install-driver nexmo 29 | ``` 30 | 31 | This driver requires a valid and secure URL in order to set up webhooks and receive events and information from the users. This means your application should be accessible through an HTTPS URL. 32 | 33 | > {callout-info} [ngrok](https://ngrok.com/) is a great tool to create such a public HTTPS URL for your local application. If you use Laravel Valet, you can create it with "valet share" as well. 34 | 35 | To connect BotMan with Nexmo, you first need to create a Nexmo account [here](https://dashboard.nexmo.com/sign-up) and [buy a phone number](https://dashboard.nexmo.com/buy-numbers), which is capable of sending SMS. 36 |

37 | Go to the Nexmo dashboard at [https://dashboard.nexmo.com/settings](https://dashboard.nexmo.com/settings) and copy your API key and API secret into your BotMan configuration. 38 | If you use BotMan Studio, you can find the configuration file located under `config/botman/nexmo.php`. 39 | 40 | If you dont use BotMan Studio, add these line to $config array that you pass when you create the object from BotManFactory. 41 | 42 | ```php 43 | 'nexmo' => [ 44 | 'key' => 'YOUR-NEXMO-APP-KEY', 45 | 'nexmo_secret' => 'YOUR-NEXMO-APP-SECRET', 46 | ] 47 | ``` 48 | 49 | 50 | ## Register Your Webhook 51 | 52 | To let Nexmo send your bot notifications when incoming SMS arrive at your numbers, you have to register the URL where BotMan is running at, 53 | with Nexmo. 54 | 55 | You can do this by visiting your Nexmo dashboard at [https://dashboard.nexmo.com/settings](https://dashboard.nexmo.com/settings). 56 | 57 | There you will find an input field called `Callback URL for Inbound Message` - place the URL that points to your BotMan logic / controller in this field. 58 | 59 | 60 | 61 | ## Supported Features 62 | This is a list of features that the driver supports. 63 | If a driver does not support a specific action, it is in most cases a limitation from the messaging service - not BotMan. 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 |
FeatureSupported?
Question-Buttons
Image Attachment
Video Attachment
Audio Attachment
Location Attachment
-------------------------------------------------------------------------------- /driver-hipchat.md: -------------------------------------------------------------------------------- 1 | # HipChat 2 | 3 | - [Installation & Setup](#installation-setup) 4 | - [Supported Features](#supported-features) 5 | 6 | 7 | ## Installation & Setup 8 | 9 | First you need to pull in the HipChat Driver. 10 | 11 | ```sh 12 | composer require botman/driver-hipchat 13 | ``` 14 | 15 | Then load the driver before creating the BotMan instance (**only when you don't use BotMan Studio**): 16 | 17 | ```php 18 | DriverManager::loadDriver(\BotMan\Drivers\HipChat\HipChatDriver::class); 19 | 20 | // Create BotMan instance 21 | BotManFactory::create($config); 22 | ``` 23 | 24 | Or if you use BotMan Studio: 25 | 26 | ```sh 27 | php artisan botman:install-driver hipchat 28 | ``` 29 | 30 | This driver requires a valid and secure URL in order to set up webhooks and receive events and information from the chat users. This means your application should be accessible through an HTTPS URL. 31 | 32 | > {callout-info} [ngrok](https://ngrok.com/) is a great tool to create such a public HTTPS URL for your local application. If you use Laravel Valet, you can create it with "valet share" as well. 33 | 34 | To connect BotMan with your HipChat team, you need to create an integration in the room(s) you want your bot to be in. 35 | After you have created the integration, take note of the URL HipChat presents you at "Send messages to this room by posting to this URL". 36 | 37 | This URL will be used to send the BotMan replies to your rooms. 38 | 39 | > Note: If you want your bot to live in multiple channels, you need to add the integration multiple times. This is a HipChat limitation. 40 | 41 | Next, you need to add webhooks to each channel that you have added an integration to. 42 | 43 | The easiest way to do this is: 44 | 45 | 1. As a HipChat Administrator, go to `https://YOUR-HIPCHAT-TEAM.hipchat.com/account/api` and create an API token that has the "Administer Room" scope. 46 | 2. With this token, perform a `POST` request against the API to create a webhook: 47 | 48 | ```bash 49 | curl -X POST -H "Authorization: Bearer YOUR-API-TOKEN" \ 50 | -H "Content-Type: application/json" \ 51 | -d '{ 52 | "url": "https://MY-BOTMAN-CONTROLLER-URL/", 53 | "event": "room_message" 54 | }' \ 55 | "https://botmancave.hipchat.com/v2/room/YOUR-ROOM-ID/webhook" 56 | ``` 57 | > If you want your bot to live in multiple channels, you need to add the webhook to each channel. This is a HipChat limitation. 58 | 59 | Once you've set up the integration(s) and webhook(s), add them to your BotMan configuration. 60 | 61 | 62 | ## Supported Features 63 | This is a list of features that the driver supports. 64 | If a driver does not support a specific action, it is in most cases a limitation from the messaging service - not BotMan. 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 |
FeatureSupported?
Question-Buttons
Image Attachment
Video Attachment
Audio Attachment
Location Attachment
96 | -------------------------------------------------------------------------------- /faq.md: -------------------------------------------------------------------------------- 1 | # FAQs 2 | 3 | - [What can I use BotMan for?](#what-can-i-use-botman-for) 4 | - [Which Messenger drivers are supported?](#which-messenger-drivers-are-supported) 5 | - [Can I create my own driver?](#can-i-create-my-own-driver) 6 | - [Can I use NLP platforms like Wit.ai or Dialogflow?](#can-i-use-nlp-platforms-like-witai-or-dialogflow) 7 | - [Does it work without Laravel?](#does-it-work-without-laravel) 8 | - [Which PHP version do I need?](#which-php-version-do-i-need) 9 | - [How does BotMan save the state of a conversation?](#how-does-botman-save-the-state-of-a-conversation) 10 | - [Why when I change the webhook URL to something other than /botman does it stop working?](#change-web-hook-url) 11 | 12 | 13 | ## What can I use BotMan for? 14 | 15 | BotMan is a framework agnostic PHP library that is designed to simplify the task of developing innovative bots for multiple messaging platforms, known as chatbots today. You can use it to build simple command-bots as well as advanced conversational interfaces. 16 | 17 | 18 | ## Which messenger drivers are supported? 19 | 20 | Right now these messengers are included: Slack, Telegram, Microsoft Bot Framework, Nexmo, HipChat, Facebook Messenger and WeChat. 21 | 22 | 23 | ## Can I create my own driver? 24 | 25 | Yes you can. Build your own driver to connect BotMan with other messengers or to use it as an API. 26 | 27 | 28 | ## Can I use NLP platforms like Wit.ai or Dialogflow? 29 | 30 | Both platforms are available through given middlewares. They help you to understand the user's message and provide information about their intent. You can of course create your own middleware. 31 | 32 | 33 | ## Does it work without Laravel? 34 | 35 | As already mentioned BotMan is a framework agnostic PHP library. So yes, it works without Laravel too. If you do want use Laravel, checkout the [BotMan Studio](https://github.com/botman/studio) project. 36 | 37 | 38 | ## Which PHP version do I need? 39 | 40 | BotMan requires PHP >=7.0. 41 | 42 | 43 | ## How does BotMan save the state of a conversation? 44 | 45 | BotMan provides a Conversation object that is used to string together several messages, including questions for the user, into a cohesive unit. In order to always know the current state of the conversation, the object gets saved through the cache. 46 | 47 | If not specified otherwise, BotMan will use array cache which is non-persistent. When using the Laravel facade it will automatically use the Laravel Cache component. Symfony and Codeigniter caches are also supported. 48 | 49 | 50 | ## Why when I change the webhook URL to something other than /botman does it stop working? 51 | 52 | Laravel protects your application from cross-site request forgery (CSRF) attacks and as a result all requests are subject to a CSRF token verification. As the token is not passed along with the request from Facebook you need to exclude your webhook from CSRF checks. 53 | 54 | You can exclude the routes by adding their URIs to the $except property of the VerifyCsrfToken middleware. 55 | -------------------------------------------------------------------------------- /upgrade.md: -------------------------------------------------------------------------------- 1 | # Upgrade Guide 2 | 3 | - [Upgrading To 2.0 From 1.5](#upgrade-2.0) 4 | 5 | 6 | 7 | ## Upgrading To 2.0 From 1.5 8 | 9 | The BotMan 2.0 release is a new major version release. While the first version of BotMan was provided under the personal vendor namespace `mpociot`, the project is now moved into a separate [GitHub organization](https://github.com/botman/). This results in a change of all BotMan classes, since they now live in a different namespace than in version 1.5. 10 | 11 | ### Changing Dependencies 12 | 13 | Change your `mpociot/botman` dependency to `botman/botman` with version `2.0.*` in your `composer.json` file. 14 | 15 | ### Removed Drivers 16 | In favor of the new [driver events](/__version__/driver-events), we have removed the following drivers: 17 | 18 | `- FacebookOptinDriver`
19 | `- FacebookReferralDriver` 20 |

21 | To react to Optin or Referral events, use the new driver event syntax: 22 | 23 | ```php 24 | // FacebookReferralDriver 25 | $botman->on('messaging_referrals', function($payload, $bot) { 26 | 27 | }); 28 | // FacebookOptinDriver 29 | $botman->on('messaging_optins', function($payload, $bot) { 30 | 31 | }); 32 | ``` 33 | 34 | ### Installing Drivers 35 | BotMan 2.0 does no longer have the messaging service specific drivers included in the core repository. This allows easier maintenance and bugfixing of the BotMan core, while also speeding up the development of individual messaging service drivers. 36 | 37 | You can find a complete list of the available drivers in the [BotMan GitHub organization](https://github.com/botman?utf8=%E2%9C%93&q=driver-&type=&language=). 38 | 39 | Install all needed drivers via composer as a separate package. Please note that the driver configuration structure also changed. Take a look at the individual driver section in the documentation to verify the new configuration array structure for your driver. 40 | 41 | Make sure to load all manually installed drivers via the `DriverManager::loadDriver` method in order to make it accessible to BotMan. 42 | 43 | ### Command `channel` Group 44 | The `channel` command group has been renamed to `recipient`. 45 | 46 | ### Sending Messages And Attachments 47 | The `Message` class was renamed to `BotMan\BotMan\Messages\Outgoing\OutgoingMessage`. Instead of providing `image`, `video`, etc. methods for attachments, those attachments are now separated in different classes and can be sent using the `withAttachment` method. 48 |

49 | Take a look at the [Sending Messages](/__version__/sending#attachments) documentation for code examples. 50 | 51 | ### Storage `get` Method 52 | The Storage classes now have a `find` method, that replaces the `get` method. This allows easier access of default entry keys. 53 | Replace all your `get` occurences with `find`. 54 | 55 | ### Middleware 56 | The middleware system of BotMan 2.0 is completely rewritten and provides a lot more flexibility than the 1.x version did. 57 | 58 | ### API.ai 59 | If you use API.ai in combination with your BotMan commands, initialize the middleware and pass it to the new global `received` middlewares on BotMan. 60 | You can then use the middleware inside your `hears` methods as usual. 61 | 62 | ```php 63 | $middleware = ApiAi::create('your-api-ai-token')->listenForAction(); 64 | 65 | // Apply global "received" middleware 66 | $botman->middleware->received($middleware); 67 | ``` 68 | -------------------------------------------------------------------------------- /driver-web.md: -------------------------------------------------------------------------------- 1 | # Web 2 | 3 | - [Installation & Setup](#installation-setup) 4 | - [Web Widget](#web-widget) 5 | - [Supported Features](#supported-features) 6 | 7 | 8 | ## Installation & Setup 9 | 10 | First you need to pull in the Web Driver. 11 | 12 | ```sh 13 | composer require botman/driver-web 14 | ``` 15 | 16 | Then load the driver before creating the BotMan instance (**only when you don't use BotMan Studio**): 17 | 18 | ```php 19 | DriverManager::loadDriver(\BotMan\Drivers\Web\WebDriver::class); 20 | 21 | // Create BotMan instance 22 | BotManFactory::create($config); 23 | ``` 24 | 25 | Or if you use BotMan Studio: 26 | 27 | ```sh 28 | php artisan botman:install-driver web 29 | ``` 30 | 31 | This driver can be used as a starting point to add BotMan to your website or API. The driver itself receives the incoming requests and responds with a JSON representing the message result. So you can for example build your own chat-interface that talks to BotMan through the WebDriver. 32 | 33 | ### Example incoming request 34 | 35 | This is a basic and valid incoming JSON request for the WebDriver. In BotMan Studio it works as GET or POST request, but it depends on your BotMan setup. 36 | 37 | ```json 38 | { 39 | "driver": "web", 40 | "userId": "1234", 41 | "message": "hi" 42 | } 43 | ``` 44 | 45 | The `driver` value is used to validate the request for this specific driver. Read more about that below. The `userId` is the sender of the request and used for connecting requests to conversations. And finally the `message` is the content of the user's message obviously. 46 | 47 | > {callout-info} You can send more values along the request and use them in you application as well. 48 | 49 | ### Example Response 50 | This is an example response from BotMan. It contains a `message` array that holds all messages that BotMan replies. 51 | 52 | ```json 53 | { 54 | "status":200, 55 | "messages":[ 56 | { 57 | "type":"text", 58 | "text":"I have no idea what you are talking about!", 59 | "attachment":{ 60 | "type":"image", 61 | "url":"https:\/\/botman.io\/img\/logo.png", 62 | "title":null 63 | } 64 | } 65 | ] 66 | } 67 | ``` 68 | The driver configuration allows you to define which request parameters need to be present in order for BotMan to detect the incoming request as a request for the "web" driver. By default, all HTTP requests to your BotMan controller need to contain a `driver` attribute with the value `web`. 69 | Pass the driver configuration to the `BotManFactory` upon initialization. If you use BotMan Studio, you can find the configuration file located under `config/botman/web.php`. 70 | 71 | ```php 72 | [ 73 | 'web' => [ 74 | 'matchingData' => [ 75 | 'driver' => 'web', 76 | ], 77 | ] 78 | ] 79 | ``` 80 | 81 | 82 | ## Web Widget 83 | The most common use case for the BotMan web driver is probably to use it in combination with a frontend widget and provide a chat interface on your existing website. To make this as easy as possible, BotMan ships with a ready-to-use web widget, that you can add to your website. 84 | You can find the documentation [here](/__version__/web-widget). 85 | 86 | 87 | 88 | ## Supported Features 89 | Since this is a "naked" web-driver implementation, it is up to you to implement the features that you need. 90 | -------------------------------------------------------------------------------- /driver-telegram.md: -------------------------------------------------------------------------------- 1 | # Telegram 2 | 3 | - [Installation & Setup](#installation-setup) 4 | - [Supported Features](#supported-features) 5 | - [Register Your Webhook](#register-webhook) 6 | 7 | 8 | ## Installation & Setup 9 | 10 | First you need to pull in the Telegram Driver. 11 | 12 | ```sh 13 | composer require botman/driver-telegram 14 | ``` 15 | 16 | Then load the driver before creating the BotMan instance (**only when you don't use BotMan Studio**): 17 | 18 | ```php 19 | DriverManager::loadDriver(\BotMan\Drivers\Telegram\TelegramDriver::class); 20 | 21 | // Create BotMan instance 22 | BotManFactory::create($config); 23 | ``` 24 | 25 | Or if you use BotMan Studio: 26 | 27 | ```sh 28 | php artisan botman:install-driver telegram 29 | ``` 30 | 31 | This driver requires a valid and secure URL in order to set up webhooks and receive events and information from the chat users. This means your application should be accessible through an HTTPS URL. 32 | 33 | > {callout-info} [ngrok](https://ngrok.com/) is a great tool to create such a public HTTPS URL for your local application. If you use Laravel Valet, you can create it with "valet share" as well. 34 | 35 | 36 | To connect BotMan with your Telegram Bot, you first need to follow the [official guide](https://core.telegram.org/bots#3-how-do-i-create-a-bot) to create your Telegram Bot and an access token. 37 | 38 | Once you have obtained the access token, place it in your `.env` file like `TELEGRAM_TOKEN=YOUR-TELEGRAM-TOKEN-HERE`. There it gets automatically loaded to your `config/botman/telegram.php` file. 39 | 40 | 41 | If you don't use BotMan Studio, add these line to $config array that you pass when you create the object from BotManFactory. 42 | 43 | ```php 44 | 'telegram' => [ 45 | 'token' => 'YOUR-TELEGRAM-TOKEN-HERE', 46 | ] 47 | ``` 48 | 49 | 50 | 51 | ## Supported Features 52 | This is a list of features that the driver supports. 53 | If a driver does not support a specific action, it is in most cases a limitation from the messaging service - not BotMan. 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 |
FeatureSupported?
Question-Buttons
Image Attachment
Video Attachment
Audio Attachment
Location Attachment
85 | 86 | 87 | ## Register Your Webhook 88 | 89 | To let your Telegram Bot know, how it can communicate with your BotMan bot, you have to register the URL where BotMan is running at, with Telegram. 90 | 91 | You can do this by sending a `POST` request to this URL: 92 | 93 | `https://api.telegram.org/bot/setWebhook` 94 | 95 | This POST request needs only one parameter called `url` with the URL that points to your BotMan logic / controller. 96 | If you use [BotMan Studio](/__version__/botman-studio) it will be: 97 | `https://yourapp.domain/botman`. HTTPS is a must, because of security reasons. 98 | 99 | Instead of manually sending the request to Telegram you can use a console command to register your Webhook. 100 | 101 | `$ php artisan botman:telegram:register` 102 | 103 | Optionally you can pass the `--output` flag to see the json that Telegram returns. 104 | -------------------------------------------------------------------------------- /releases.md: -------------------------------------------------------------------------------- 1 | # BotMan Release Notes 2 |

3 | ## 2.0 4 | BotMan 2.0 is a new major release and continues the ideas of BotMan 1.5 by adding a new middleware system, support for messaging service events, painless driver installation and listing, a chatbot testing framework on top of PHPUnit, custom exception handling, automatic messaging service verification, extended messaging service user information, support for additional drivers such as Kik, Discord or Cisco Spark, sending file attachments, and more. 5 | 6 | ## Driver Events 7 | BotMan 2.0 gives you the ability to listen not only for incoming messages of your users, but also for service events. 8 | Need some inspiration? 9 | You can greet new users that join a Slack channel, or perform a specific task, whenever your Facebook messages were read. 10 | 11 | BotMan 2.0 makes this really easy. Just call the `on` method on the BotMan instance: 12 | 13 | ```php 14 | /** 15 | * Greet a new user when he joins a Slack channel. 16 | */ 17 | $botman->on('team_join', function($payload, $botman) { 18 | $botman->reply('Hello!'); 19 | }); 20 | 21 | /** 22 | * Perform an action when a message was read on Facebook. 23 | */ 24 | $botman->on('messaging_reads', function($payload, $botman) { 25 | // a message was read. 26 | }); 27 | ``` 28 | 29 | For more information on driver events, check out the driver event documentation. 30 | 31 | ## Testing 32 | With BotMan 2.0 you have the ability to write fluent, expressive unit tests for your chatbots on top of PHPUnit. BotMan Studio will automatically include example tests for you to look at. Take a look at the following test: 33 | 34 | ```php 35 | public function testUserGreeting() 36 | { 37 | $this->bot->receives('My name is Marcel') 38 | ->assertQuestion('Hello Marcel. How old are you?') 39 | ->receives('32') 40 | ->assertReply('Got it - you are 32 years old, Marcel.'); 41 | } 42 | ``` 43 | 44 | For more information on testing, check out the testing documentation. 45 | 46 | ## Middleware 47 | The concept of middleware has drastically improved with BotMan 2.0. Where 1.5 was very limited in the available entry points of your webhooks, 2.0 gives you the flexibility you need to extend the lifecircle of your chatbot application. 48 | 49 | This also means, that you can now limit where in your chatbot you want to add middlewares. 50 | The available entry points are: `sending`, `received`, `heard`. 51 | 52 | Since these entrypoints are not dependenat on your command, they will be applied to all messages. 53 | 54 | ```php 55 | /** 56 | * Middleware will be applied when your chatbot sends out messages. 57 | */ 58 | $this->botman->middleware->sending(new SendingMiddleware()); 59 | 60 | /** 61 | * Middleware will be applied when your chatbot receives incoming messages. 62 | */ 63 | $this->botman->middleware->received(new ReceivedMiddleware()); 64 | 65 | /** 66 | * Middleware will be applied when your chatbot successfully heard/matched a messages. 67 | */ 68 | $this->botman->middleware->heard(new HeardMiddleware()); 69 | ``` 70 | 71 | For more information on middleware, check out the middleware documentation. 72 | 73 | ## Exception Handling 74 | We have to admit it - exceptions in our code happen from time to time. But we need to catch them properly and notify the chatbot users if they happen. This becomes super simple with BotMan 2.0, as it provides a fluent and expressive API to hook into the exception handling during your chatbot lifetime. 75 | 76 | ```php 77 | $botman->exception(Exception::class, function($exception, $bot) { 78 | $bot->reply('Sorry, something went wrong'); 79 | }); 80 | ``` 81 | 82 | For more information on exception, check out the exception documentation. -------------------------------------------------------------------------------- /botman-studio.md: -------------------------------------------------------------------------------- 1 | # BotMan Studio 2 | 3 | - [Introduction](#introduction) 4 | - [Installation](#installation) 5 | - [Tinker](#tinker) 6 | - [List All Drivers](#list-drivers) 7 | - [Install New Drivers](#install-drivers) 8 | 9 | ## Introduction 10 | 11 | While BotMan itself is framework agnostic, BotMan is also available as a bundle with the great [Laravel](http://laravel.com) PHP framework. This bundled version is called BotMan Studio and makes the chatbot development experience even better, by providing testing tools, an out of the box web driver implementation to get you started and additional tools like easier driver installation and configuration support. 12 | If you are not yet familiar with Laravel, you may take a look at the Laracasts [free introduction to Laravel](https://laracasts.com/series/laravel-from-scratch-2017) video course. 13 | 14 | 15 | ## Installation 16 | 17 | First, download the BotMan installer using Composer: 18 | 19 | ```sh 20 | composer global require "botman/installer" 21 | ``` 22 | 23 | Make sure to place the `$HOME/.composer/vendor/bin` directory (or the equivalent directory for your OS) in your $PATH so the `botman` executable can be located by your system. 24 |

25 | Once installed, the `botman new` command will create a fresh BotMan Studio installation in the directory you specify. For instance, `botman new weatherbot` will create a directory named `weatherbot` containing a fresh BotMan Studio installation with all of BotMan's dependencies already installed: 26 | 27 | ```sh 28 | botman new weatherbot 29 | ``` 30 | 31 | Alternatively, you may also install BotMan Studio by issuing the Composer create-project command in your terminal: 32 | 33 | ```sh 34 | composer create-project --prefer-dist botman/studio weatherbot 35 | ``` 36 | 37 | 38 | ## Tinker 39 | 40 | Chatbot development should be easy to get started with. Picking a messaging service and taking care of all the developer account pre-requisites is not. 41 | That's why BotMan Studio comes with a ready-to-use BotMan web driver implementation. 42 | This allows you to develop your chatbot locally and test it using your local BotMan Studio installation. 43 | Your newly installed BotMan Studio project will contain a `/botman/tinker` route, where you will see a very simple VueJS based chat widget, that let's you communicate with your chatbot. 44 |

45 | If you want to disable the built-in tinker route, just remove the line from your `routes/web.php` file: 46 | 47 | ```php 48 | Route::get('/botman/tinker', 'BotManController@tinker'); 49 | ``` 50 | 51 | If you want to modify the pre-installed VueJS component, you may modify the `BotManTinker.vue` file located at `resources/assets/js/components` in your BotMan Studio folder structure. 52 | 53 | 54 | ## List All Drivers 55 | 56 | BotMan Studio makes Driver installation as easy as possible. To get an overview of all core drivers that are available and installed in your application, you can use the BotMan Studio artisan command: 57 | 58 | ```sh 59 | php artisan botman:list-drivers 60 | ``` 61 | 62 | 63 | ## Install New Drivers 64 | 65 | Just like listing all available and installed drivers, you may also install new drivers using the `botman:install-driver` artisan command. It takes the driver name as an argument and will perform a `composer require` of the selected BotMan messaging driver. 66 | 67 | So if you want to install the Facebook driver for BotMan, you can do this by using this artisan command: 68 | 69 | ```sh 70 | php artisan botman:install-driver facebook 71 | ``` 72 | 73 | After composer has downloaded all the driver dependencies, a new configuration file will automatically be published inside your `config/botman` directory. -------------------------------------------------------------------------------- /driver-cisco-spark.md: -------------------------------------------------------------------------------- 1 | # Cisco Spark 2 | 3 | - [Installation & Setup](#installation-setup) 4 | - [Supported Features](#supported-features) 5 | - [Register Your Webhook](#register-webhook) 6 | 7 | 8 | ## Installation & Setup 9 | 10 | First you need to pull in the Cisco Spark Driver. 11 | 12 | ```sh 13 | composer require botman/driver-cisco-spark 14 | ``` 15 | 16 | Then load the driver before creating the BotMan instance (**only when you don't use BotMan Studio**): 17 | 18 | ```php 19 | DriverManager::loadDriver(\BotMan\Drivers\CiscoSpark\CiscoSparkDriver::class); 20 | 21 | // Create BotMan instance 22 | BotManFactory::create($config); 23 | ``` 24 | 25 | Or if you use BotMan Studio: 26 | 27 | ```sh 28 | php artisan botman:install-driver cisco-spark 29 | ``` 30 | 31 | This driver requires a valid and secure URL in order to set up webhooks and receive events and information from the chat users. This means your application should be accessible through an HTTPS URL. 32 | 33 | > {callout-info} [ngrok](https://ngrok.com/) is a great tool to create such a public HTTPS URL for your local application. If you use Laravel Valet, you can create it with "valet share" as well. 34 | 35 | 36 | To connect BotMan with your Cisco Spark Bot, you first need to follow the [official guide](https://developer.ciscospark.com/bots.html) to create your Cisco Spark Bot and an access token. 37 | 38 | Once you have obtained the access token and secret, place it in your BotMan configuration. If you use BotMan Studio, you can find the configuration file located under `config/botman/cisco-spark.php`. 39 | 40 | If you dont use BotMan Studio, add these line to $config array that you pass when you create the object from BotManFactory. 41 | 42 | ```php 43 | 'cisco-spark' => [ 44 | 'token' => 'YOUR-CISCO-SPARK-TOKEN-HERE', 45 | 'secret' => 'YOUR-CISCO-SPARK-SECRET-HERE', 46 | ] 47 | ``` 48 | 49 | 50 | 51 | ## Supported Features 52 | This is a list of features that the driver supports. 53 | If a driver does not support a specific action, it is in most cases a limitation from the messaging service - not BotMan. 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 |
FeatureSupported?
Question-Buttons
Image Attachment
Video Attachment
Audio Attachment
Location Attachment
85 | 86 | 87 | ## Register Your Webhook 88 | 89 | To let your Cisco Spark Bot know, how it can communicate with your BotMan bot, you have to register the URL where BotMan is running at, 90 | with Cisco Spark. 91 | 92 | You can do this by sending a `POST` request to this URL: 93 | 94 | ```url 95 | curl -X POST -H "Accept: application/json" -H "Authorization: Bearer --YOUR-CISCO-SPARK-TOKEN--" -H "Content-Type: application/json" -d '{ 96 | "name": "BotMan Webhook", 97 | "targetUrl": "--YOUR-URL--", 98 | "resource": "all", 99 | "event": "all" 100 | }' "https://api.ciscospark.com/v1/webhooks" 101 | ``` 102 | 103 | Replace `--YOUR-CISCO-SPARK-TOKEN--` with your access token. Replace `--YOUR-URL--` with the URL that points to your BotMan logic / controller. 104 | If you use [BotMan Studio](/__version__/botman-studio) it will be: 105 | `https://yourapp.domain/botman`. -------------------------------------------------------------------------------- /driver-twilio.md: -------------------------------------------------------------------------------- 1 | # Twilio 2 | 3 | - [Installation & Setup](#installation-setup) 4 | - [Register Your Webhook](#register-webhook) 5 | - [Incoming Phone Calls](#incoming-phone-calls) 6 | - [TwiML Support](#twiml-support) 7 | - [Supported Features](#supported-features) 8 | 9 | 10 | ## Installation & Setup 11 | 12 | First you need to pull in the Twilio Driver. 13 | 14 | ```sh 15 | composer require botman/driver-twilio 16 | ``` 17 | 18 | Then load the driver before creating the BotMan instance (**only when you don't use BotMan Studio**): 19 | 20 | ```php 21 | DriverManager::loadDriver(\BotMan\Drivers\Twilio\TwilioVoiceDriver::class); 22 | DriverManager::loadDriver(\BotMan\Drivers\Twilio\TwilioMessageDriver::class); 23 | 24 | // Create BotMan instance 25 | BotManFactory::create($config); 26 | ``` 27 | 28 | Or if you use BotMan Studio: 29 | 30 | ```sh 31 | php artisan botman:install-driver twilio 32 | ``` 33 | 34 | > {callout-info} [ngrok](https://ngrok.com/) is a great tool to create a public URL for your local application. If you use Laravel Valet, you can create it with "valet share" as well. 35 | 36 | To connect BotMan with Twilio, you first need to create a Twilio account [here](https://www.twilio.com/try-twilio) and [buy a phone number](https://www.twilio.com/console/phone-numbers/incoming), which is capable of sending SMS/MMS or making phone calls. 37 | 38 | Place your Twilio auth token in your BotMan configuration. If you use BotMan Studio, you can find the configuration file located under `config/botman/twilio.php`. 39 | 40 | If you dont use BotMan Studio, add these line to $config array that you pass when you create the object from BotManFactory. 41 | 42 | ```php 43 | 'twilio' => [ 44 | 'token' => 'YOUR-TWILIO-TOKEN-HERE', 45 | ] 46 | ``` 47 | 48 | 49 | ## Register Your Webhook 50 | 51 | To let Twilio send your chatbot a notifications when you receive an incoming call or receive a SMS, you have to register the URL where BotMan is running at, with Twilio. 52 | 53 | You can do this on the [configuration page of your phone numbers](https://www.twilio.com/console/phone-numbers/incoming). 54 |

55 | If you want to make use of Twilio's voice services: Place your webhook URL in the input field: `A CALL COMES IN`.
56 | If you want to make use of Twilio's SMS/messaging services: Place your webhook URL in the input field: `A MESSAGE COMES IN`. 57 | 58 | 59 | ## Incoming Phone Calls 60 | 61 | To let your chatbot react to incoming phone calls, you can listen for the `TwilioVoiceDriver::INCOMING_CALL` event. 62 | 63 | ```php 64 | $botman->on(TwilioVoiceDriver::INCOMING_CALL, function($payload, $bot) { 65 | $bot->startConversation(new ExampleConversation); 66 | }); 67 | ``` 68 | 69 | 70 | ## TwiML Support 71 | 72 | If you want total control over the output of your Twilio based chatbot, you can also directly reply any [TwiML response](https://www.twilio.com/docs/api/twiml) using the official Twilio PHP SDK. 73 | ```php 74 | $twiml = new Twiml(); 75 | $twiml->record(['timeout' => 10, 'transcribe' => 'true']); 76 | 77 | $bot->reply($twiml); 78 | ``` 79 | 80 | 81 | ## Supported Features 82 | This is a list of features that the driver supports. 83 | If a driver does not support a specific action, it is in most cases a limitation from the messaging service - not BotMan. 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 |
FeatureSupported?
Question-Buttons
Image Attachment
Video Attachment
Audio Attachment
Location Attachment
-------------------------------------------------------------------------------- /driver-amazon-alexa.md: -------------------------------------------------------------------------------- 1 | # Amazon Alexa 2 | 3 | - [Installation & Setup](#installation-setup) 4 | - [Supported Features](#supported-features) 5 | - [Accessing Alexa Slots](#alexa-slots) 6 | - [Sending Alexa Cards](#sending-alexa-cards) 7 | 8 | The Amazon Alexa driver allows you to listen for pre-configured intents through the Alexa skill builder. You can also reply with custom Amazon Alexa Cards. 9 | 10 | 11 | ## Installation & Setup 12 | 13 | First you need to pull in the Amazon Alexa Driver. 14 | 15 | ```sh 16 | composer require botman/driver-amazon-alexa 17 | ``` 18 | 19 | Then load the driver before creating the BotMan instance (**only when you don't use BotMan Studio**): 20 | 21 | ```php 22 | DriverManager::loadDriver(\BotMan\Drivers\AmazonAlexa\AmazonAlexaDriver::class); 23 | 24 | // Create BotMan instance 25 | BotManFactory::create($config); 26 | ``` 27 | 28 | Or if you use BotMan Studio: 29 | 30 | ```sh 31 | php artisan botman:install-driver amazon-alexa 32 | ``` 33 | 34 | This driver requires a valid and secure URL in order to set up webhooks and receive events and information from the chat users. This means your application should be accessible through an HTTPS URL. 35 | 36 | > {callout-info} [ngrok](https://ngrok.com/) is a great tool to create such a public HTTPS URL for your local application. If you use Laravel Valet, you can create it with "valet share" as well. 37 | 38 | 39 | To connect BotMan with your Amazon Alexa skill, you first need to follow the [official guide](https://developer.amazon.com/docs/ask-overviews/build-skills-with-the-alexa-skills-kit.html) to create your custom Amazon Alexa skill. 40 | 41 | Amazon Alexa does not require any kind of configuration. 42 | 43 | 44 | 45 | ## Supported Features 46 | This is a list of features that the driver supports. 47 | If a driver does not support a specific action, it is in most cases a limitation from the messaging service - not BotMan. 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 |
FeatureSupported?
Conversations
Question-Buttons
Image Attachment✅ - through Cards
Video Attachment
Audio Attachment
Location Attachment
83 | 84 | 85 | ## Accessing Alexa Slots 86 | 87 | Amazon Alexa allows your intents to contain custom arguments - called "slots". Whenever you hear for a Alexa message that contains these slots, they will get stored as a `slot` extra on the IncomingMessage object. To access it, just retrieve it from the message extras: 88 | 89 | ```php 90 | $botman->hears('My-Intent-Name', function($bot) { 91 | $slots = $bot->getMessage()->getExtras('slots'); 92 | }); 93 | ``` 94 | 95 | 96 | ## Sending Alexa Cards 97 | 98 | Amazon Alexa allows your custom skill to reply not only by using voice, but also by adding custom [Skill Cards](https://developer.amazon.com/docs/custom-skills/include-a-card-in-your-skills-response.html) to your replies. These are graphical cards that describe or enhance the voice interaction. 99 | 100 | To create and send such a Card with BotMan, just create a `Card` object and add it as an OutgoingMessage attachment like this: 101 | 102 | ```php 103 | $botman->hears('My-Intent-Name', function($bot) { 104 | $card = Card::create('Your card title', 'Your card subtitle') 105 | ->type(Card::STANDARD_CARD_TYPE) 106 | ->image('https://botman.io/images/foo.png') 107 | ->text('This is a longer text for your card.'); 108 | 109 | $message = OutgoingMessage::create('This is the spoken response')->withAttachment($card) 110 | $bot->reply($message); 111 | }); 112 | ``` 113 | -------------------------------------------------------------------------------- /receiving-additional-content.md: -------------------------------------------------------------------------------- 1 | # Hearing Attachments 2 | 3 | - [Introduction](#introduction) 4 | - [Images](#images) 5 | - [Videos](#videos) 6 | - [Audio](#audio) 7 | - [Files](#files) 8 | - [Locations](#locations) 9 | 10 | 11 | ## Introduction 12 | 13 | Similar to hearing for text input, BotMan also allows you to listen for incoming attachments like images, videos, audio messages or even shared locations. 14 | 15 | 16 | ## Listen for images 17 | 18 | Making your bot listen to incoming images is easy. Just use the `receivesImages` method on the BotMan instance. All received images will be passed to the callback as a second argument. 19 | 20 | The images returned will be an array of `BotMan\BotMan\Messages\Attachments\Image` objects. 21 | 22 | ```php 23 | use BotMan\BotMan\Messages\Attachments\Image; 24 | 25 | $bot->receivesImages(function($bot, $images) { 26 | 27 | foreach ($images as $image) { 28 | 29 | $url = $image->getUrl(); // The direct url 30 | $title = $image->getTitle(); // The title, if available 31 | $payload = $image->getPayload(); // The original payload 32 | } 33 | }); 34 | ``` 35 | 36 | 37 | ## Listen for videos 38 | 39 | Just like images, you can use the `receivesVideos` method on the BotMan instance to listen for incoming video file uploads. All received videos will be passed to the callback as a second argument. 40 | 41 | The videos returned will be an array of `BotMan\BotMan\Messages\Attachments\Video` objects. 42 | 43 | ```php 44 | use BotMan\BotMan\Messages\Attachments\Video; 45 | 46 | $bot->receivesVideos(function($bot, $videos) { 47 | 48 | foreach ($videos as $video) { 49 | 50 | $url = $video->getUrl(); // The direct url 51 | $payload = $video->getPayload(); // The original payload 52 | } 53 | }); 54 | ``` 55 | 56 | 57 | ## Listen for audio 58 | 59 | Just like images, you can use the `receivesAudio` method on the BotMan instance to listen for incoming audio file uploads. All received audio files will be passed to the callback as a second argument. 60 | 61 | The audio files returned will be an array of `BotMan\BotMan\Messages\Attachments\Audio` objects. 62 | 63 | ```php 64 | use BotMan\BotMan\Messages\Attachments\Audio; 65 | 66 | $bot->receivesAudio(function($bot, $audios) { 67 | 68 | foreach ($audios as $audio) { 69 | 70 | $url = $audio->getUrl(); // The direct url 71 | $payload = $audio->getPayload(); // The original payload 72 | } 73 | }); 74 | ``` 75 | 76 | 77 | ## Listen for files 78 | 79 | Just like images, you can use the `receivesFiles` method on the BotMan instance to listen for incoming file uploads. All received files will be passed to the callback as a second argument. 80 | 81 | The files returned will be an array of `BotMan\BotMan\Messages\Attachments\File` objects. 82 | 83 | ```php 84 | use BotMan\BotMan\Messages\Attachments\File; 85 | 86 | $bot->receivesFiles(function($bot, $files) { 87 | 88 | foreach ($files as $file) { 89 | 90 | $url = $file->getUrl(); // The direct url 91 | $payload = $file->getPayload(); // The original payload 92 | } 93 | }); 94 | ``` 95 | 96 | 97 | ## Listen for locations 98 | 99 | Some messaging services also allow your bot users to send their GPS location to your bot. You can listen for these location calls using the `receivesLocation` method on the BotMan instance. 100 | 101 | The method will pass a `BotMan\BotMan\Messages\Attachments\Location` object to the callback method. 102 | 103 | ```php 104 | use BotMan\BotMan\Messages\Attachments\Location; 105 | 106 | $bot->receivesLocation(function($bot, Location $location) { 107 | $lat = $location->getLatitude(); 108 | $lng = $location->getLongitude(); 109 | }); 110 | ``` 111 | 112 | ## Supported Drivers 113 | 114 | Not all drivers support receiving attachments, or because of the lack of reference API, or because it has not yet been implemented in the driver itself. 115 | 116 | | Can (Receive/Send) | Images | Videos | Audio | Files | Locations | 117 | |--------------------|--------|--------|-------|-------|-----------| 118 | | Telegram | ✔/✔ | ✔/✔ | ✔/✔ | ✔/✔ | ✔/✔ | 119 | | Facebook | ✔/✔ | ✔/✔ | ✔/✔ | ✔/✔ | ✔/❌ | 120 | | Slack | ✔/✔ | ✔/❌ | ✔/❌ | ✔/✔ | ❌/❌ | 121 | | Kik | ✔/✔ | ✔/✔ | ❌/❌ | ❌/❌ | ❌/❌ | 122 | | WeChat | ✔/✔ | ✔/❌ | ✔/❌ | ❌/❌ | ✔/❌ | 123 | | HipChat | ❌/❌ | ❌/❌ | ❌/❌ | ❌/❌ | ❌/❌ | 124 | | Nexmo | ❌/❌ | ❌/❌ | ❌/❌ | ❌/❌ | ❌/❌ | 125 | -------------------------------------------------------------------------------- /installation.md: -------------------------------------------------------------------------------- 1 | # Installation 2 | 3 | - [Server Requirements](#requirements) 4 | - [Getting Started](#getting-started) 5 | - [Installing BotMan](#installation) 6 | - [Basic Usage without BotMan Studio](#basic-usage-without-botman-studio) 7 | 8 | BotMan is a framework agnostic PHP library that is designed to simplify the task of developing innovative bots for multiple messaging platforms, including Slack, Telegram, Microsoft Bot Framework, Nexmo, HipChat, Facebook Messenger, WeChat and many more. If you run into any problems while installing, please let us know and join the [Developer Slack community](https://slack.botman.io). 9 | 10 | > {callout-video} Want to get a headstart into chatbot development? Take a look at the [Build A Chatbot](https://buildachatbot.io) video course. 11 | 12 | 13 | ## Technical Requirements 14 | 15 | - PHP >= 7.1.3 16 | - For BotMan Studio checkout [Laravel's requirements](https://laravel.com/docs/5.5/installation#server-requirements) 17 | 18 | 19 | ## Getting Started 20 | 21 | We highly recommend using the BotMan Studio installer, which will give you BotMan on top of a fresh Larvel application. This also gives you advanced development tools, like out-of-box chatbot testing support and CLI tools to quickly create new conversations and middleware classes. If you do not want to use BotMan Studio, you can find some alternatives below. 22 | 23 | 24 | ## 1. BotMan Studio Installation 25 | 26 | To use BotMan studio in the most efficient way, install the BotMan Studio installer globally with: 27 | 28 | ```sh 29 | composer global require "botman/installer" 30 | ``` 31 | 32 | Make sure to place the `$HOME/.composer/vendor/bin` directory (or the equivalent directory for your OS) in your $PATH so the `botman` executable can be located by your system. 33 | 34 | ## 2. Create a new BotMan Project 35 | 36 | You can create a new BotMan project into a new directory with the following command: 37 | 38 | ```sh 39 | botman new 40 | ``` 41 | 42 | Alternatively, you may also create a new BotMan project by issuing the Composer create-project command in your terminal: 43 | 44 | ```sh 45 | composer create-project --prefer-dist botman/studio 46 | ``` 47 | 48 | This will create a new folder, clone the [BotMan Studio application](https://github.com/botman/studio) and install all the necessary dependencies so that you can start working on your chatbot right away. 49 | 50 | ## 3. Testing your Chatbot 51 | 52 | After a successfull installation, you can instantly try out your chatbot application. Go into the directory that you created and use the following command, to start a simple PHP server: 53 | 54 | ```sh 55 | php artisan serve 56 | ``` 57 | 58 | You should see something like: `Laravel development server started: `. 59 | 60 | Next, you can visit this URL and click on the `Tinker` link, which will give you a textinput where you can immediately interact with your bot. 61 | 62 | Try it out, by typing `hi` or `start conversation`. 63 | 64 | You can dig into the logic of this, by looking into the `routes/botman.php` file and take a look at the [hearing messages](/__version__/receiving) documentation next. 65 | 66 | # Alternatives 67 | 68 | To use BotMan without the use of BotMan Studio/Laravel, please see below: 69 | 70 | 71 | ## Installing BotMan 72 | 73 | BotMan utilizes [Composer](https://getcomposer.org/) to manage its dependencies. So, before using BotMan, make sure you have Composer installed on your machine. 74 | 75 | ```sh 76 | composer require botman/botman 77 | ``` 78 | 79 | This will download the BotMan package and all its dependencies. 80 | 81 | 82 | ## Basic Usage without BotMan Studio 83 | 84 | This code shows you the very basics of using BotMan as a standalone composer dependency. 85 | Make sure to place this code in a file that is accessible through the web - like a controller class. 86 | 87 | ```php 88 | [ 97 | // "token" => "TOKEN" 98 | // ] 99 | ]; 100 | 101 | // Load the driver(s) you want to use 102 | DriverManager::loadDriver(\BotMan\Drivers\Telegram\TelegramDriver::class); 103 | 104 | // Create an instance 105 | $botman = BotManFactory::create($config); 106 | 107 | // Give the bot something to listen for. 108 | $botman->hears('hello', function (BotMan $bot) { 109 | $bot->reply('Hello yourself.'); 110 | }); 111 | 112 | // Start listening 113 | $botman->listen(); 114 | ``` 115 | 116 | Pretty simple, right? To dig deeper, you may want to look into the core concept of [hearing messages](/__version__/receiving) next. 117 | -------------------------------------------------------------------------------- /welcome.md: -------------------------------------------------------------------------------- 1 | # BotMan Documentation 2 | 3 | The open-source chatbot development framework for cross platform chat- and voice-applications. 4 | 5 | ## Getting Started 6 |
7 | 24 | 42 | 61 | -------------------------------------------------------------------------------- /receiving.md: -------------------------------------------------------------------------------- 1 | # Hearing Messages 2 | 3 | - [Basic Commands](#basic-commands) 4 | - [Command Parameters](#command-parameters) 5 | - [Matching Regular Expression](#matching-regular-expressions) 6 | - [Command Groups](#command-groups) 7 | - [Drivers](#command-groups-drivers) 8 | - [Middleware](#command-groups-middleware) 9 | - [Recipients](#command-groups-recipients) 10 | - [Fallbacks](#fallbacks) 11 | - [Get full request payload](#payload) 12 | 13 | 14 | ## Basic Commands 15 | 16 | Usually all the commands that your chatbot understands are listed in one location. You can think of it as a `routes` definition, but for your chatbot. The default location when using BotMan Studio is at `routes/botman.php`. 17 | This way, the BotMan framework knows about all the different patterns and messages that your chatbot should listen to. 18 | 19 | > {callout-info} If you are **not** using BotMan Studio, you must call the "$bot->listen();" method at the end of your command definition. 20 | 21 | You can specify these commands by providing a string that your chatbot should listen for, followed by a Closure that will be executed, once the incoming message matches the string you provided. 22 | 23 | In this example, we are listening for the incoming message "Hello" and reply "World" from our bot. 24 | 25 | ```php 26 | $botman->hears('My First Message', function ($bot) { 27 | $bot->reply('Your First Response'); 28 | }); 29 | ``` 30 | Try it out 31 | 32 | In addition to the Closure you can also pass a class and method that will get called if the keyword matches. 33 | 34 | ```php 35 | $botman->hears('foo', 'Some\Namespace\MyBotCommands@handleFoo'); 36 | 37 | class MyBotCommands { 38 | 39 | public function handleFoo($bot) { 40 | $bot->reply('Hello World'); 41 | } 42 | 43 | } 44 | ``` 45 | 46 | 47 | ## Command Parameters 48 | 49 | Listening to basic keywords is fine, but sometimes you will need to capture parts of the information your bot users are providing. 50 | For example, you may need to listen for a bot command that captures a user's name. You may do so by defining command parameters using curly braces inside of the matching string, like this: 51 | 52 | ```php 53 | $botman->hears('call me {name}', function ($bot, $name) { 54 | $bot->reply('Your name is: '.$name); 55 | }); 56 | ``` 57 | Try it out 58 | 59 | Of course you are not limited to only one parameter in your incoming message. You may define as many command parameters as required by your command: 60 | 61 | ```php 62 | $botman->hears('call me {name} the {adjective}', function ($bot, $name, $adjective) { 63 | $bot->reply('Hello '.$name.'. You truly are '.$adjective); 64 | }); 65 | ``` 66 | Try it out 67 | 68 | Command parameters are always encased within `{}` braces and should consist of alphabetic characters only. 69 | 70 | 71 | ## Matching Regular Expressions 72 | 73 | If command parameters do not give you enough power and flexibility for your bot commands, you can also use more complex regular expressions in your bot commands. For example, you may want your bot to only listen for digits. You may do so by defining a regular expression in your command like this: 74 | 75 | ```php 76 | $botman->hears('I want ([0-9]+)', function ($bot, $number) { 77 | $bot->reply('You will get: '.$number); 78 | }); 79 | ``` 80 | Try it out 81 | 82 | Just like the command parameters, each regular expression match group will be passed to the handling Closure. So if you define to regular expression matching groups, you can access them as two different variables: 83 | 84 | ```php 85 | $botman->hears('I want ([0-9]+) portions of (Cheese|Cake)', function ($bot, $amount, $dish) { 86 | $bot->reply('You will get '.$amount.' portions of '.$dish.' served shortly.'); 87 | }); 88 | ``` 89 | Try it out 90 | 91 | In addition to using regular expression matching groups, you can also use regular epxressions to generally match incoming requests. 92 | 93 | Take this example, which listens for either "Hi" or "Hello" anywhere in the incoming message: 94 | 95 | ```php 96 | $botman->hears('.*Bonjour.*', function ($bot) { 97 | $bot->reply('Nice to meet you!'); 98 | }); 99 | ``` 100 | Try it out 101 | 102 | 103 | ## Command Groups 104 | 105 | Command groups allow you to share command attributes, such as middleware or channels, across a large number of commands without needing to define those attributes on each individual command. Shared attributes are specified in an array format as the first parameter to the `$botman->group` method. 106 | 107 | 108 | ### Drivers 109 | A common use-case for command groups is restricting the commands to a specific messaging service using the `driver` parameter in the group array. 110 | Like this, you can limit the chatbot logic for one - or multiple messenger services. In this case, the `keyword` method will only be called when the incoming message comes from Slack or Facebook: 111 | 112 | ```php 113 | $botman->group(['driver' => [SlackDriver::class, FacebookDriver::class]], function($bot) { 114 | $bot->hears('keyword', function($bot) { 115 | // Only listens on Slack or Facebook 116 | }); 117 | }); 118 | ``` 119 | 120 | 121 | ### Middleware 122 | You may also group your commands, to send them through custom middleware classes. These classes can either listen for different parts of the message or extend your message by sending it to a third party service. The most common use-case would be the use of a Natural Language Processor like wit.ai or Dialogflow. To learn more about how to create your own middleware, take a look at the [middleware documentation](/__version__/middleware). 123 | 124 | ```php 125 | $botman->group(['middleware' => new MyCustomMiddleware()], function($bot) { 126 | $bot->hears('keyword', function($bot) { 127 | // Will be sent through the custom middleware object. 128 | }); 129 | }); 130 | ``` 131 | 132 | 133 | ### Recipients 134 | Command groups may also be used to restrict the commands to specific recipients. This can be especially useful, if you have messaging services that have multiple "channels". Then the "recipient" would be the channel/group that you have. 135 | 136 | ```php 137 | $botman->group(['recipient' => '1234567890'], function($bot) { 138 | $bot->hears('keyword', function($bot) { 139 | // Only listens when recipient '1234567890' is receiving the message. 140 | }); 141 | }); 142 | ``` 143 | 144 | You may also use an array of recipients to restrict certain commands. 145 | 146 | ```php 147 | $botman->group(['recipient' => ['1234567890', '2345678901', '3456789012']], function($bot) { 148 | $bot->hears('keyword', function($bot) { 149 | // Only listens when recipient '1234567890', '2345678901' or '3456789012' is receiving the message. 150 | }); 151 | }); 152 | ``` 153 | 154 | 155 | ## Fallbacks 156 | 157 | BotMan allows you to create a fallback method, that gets called if none of your "hears" patterns matches. You may use this feature to give your bot users guidance on how to use your bot. 158 | 159 | ```php 160 | $botman->fallback(function($bot) { 161 | $bot->reply('Sorry, I did not understand these commands. Here is a list of commands I understand: ...'); 162 | }); 163 | ``` 164 | Try it out 165 | 166 | 167 | ## Get full request payload 168 | 169 | BotMan does already a great job in providing you with data from the incoming message requests with helpers like `$bot->getUser();` or `$bot->getDriver();`. But sometimes messenger add extra data to their requests which you can't access directly like that. This is when it gets useful to grab the whole payload of the incoming request with `$bot->getMessage()->getPayload();`. This way you have full access to all the data and can decide for yourself what you need and how to process it. 170 | -------------------------------------------------------------------------------- /sending.md: -------------------------------------------------------------------------------- 1 | # Sending Messages 2 | 3 | - [Introduction](#introduction) 4 | - [Single Message Replies](#single-message-replies) 5 | - [Attachments](#attachments) 6 | - [Type Indicators](#type-indicators) 7 | - [Originating Messages](#originating-messages) 8 | - [Send Low-Level Requests](#sending-low-level-requests) 9 | 10 | ## Introduction 11 | 12 | Bots send messages to deliver information and present an interface for their 13 | functionality. BotMan can send messages in several different ways, depending 14 | on the type and number of messages that will be sent. 15 | 16 | Single message replies to incoming commands can be sent using the `$bot->reply()` function. 17 | 18 | Multi-message replies, particularly those that present questions for the end user to respond to, 19 | are sent using the `$bot->startConversation()` function and the related [conversation](/__version__/conversations) sub-functions. 20 | 21 | Bots can also originate messages - that means, sending messages based on some internal logic or external stimulus - using the `$bot->say()` method. 22 | 23 | 24 | 25 | ## Single Message Replies 26 | 27 | Once a bot has received a message using `hears()`, you may send a response using `$bot->reply()`. 28 | 29 | This is the simplest way to respond to an incoming command: 30 | 31 | ```php 32 | $botman->hears('single response', function (BotMan $bot) { 33 | $bot->reply("Tell me more!"); 34 | }); 35 | ``` 36 | Try it out 37 | 38 | Do you feel like chatting some more? You may also send multiple responses in a single method. 39 | 40 | ```php 41 | $botman->hears('multi response', function (BotMan $bot) { 42 | $bot->reply("Tell me more!"); 43 | $bot->reply("And even more"); 44 | }); 45 | ``` 46 | Try it out 47 | 48 | 49 | 50 | ## Attachments 51 | 52 | A common use case would be including an attachment along with your message. 53 | Depending on the messaging services that you are using, BotMan can send images, videos, audio files, generic files or even location data as attachment information. 54 | 55 | You may do this by composing your message using the `OutgoingMessage` class. This class takes care of transforming your data for each 56 | individual messaging service. 57 | 58 | ```php 59 | use BotMan\BotMan\Messages\Attachments\Image; 60 | use BotMan\BotMan\Messages\Outgoing\OutgoingMessage; 61 | 62 | $botman->hears('image attachment', function (BotMan $bot) { 63 | // Create attachment 64 | $attachment = new Image('https://botman.io/img/logo.png'); 65 | 66 | // Build message object 67 | $message = OutgoingMessage::create('This is my text') 68 | ->withAttachment($attachment); 69 | 70 | // Reply message object 71 | $bot->reply($message); 72 | }); 73 | ``` 74 | Try it out 75 | 76 | ### Images 77 | You may use the `Image` class to attach an image URL to your outgoing message. 78 | It takes an image URL and an optional custom payload as constructor parameters, 79 | 80 | ```php 81 | use BotMan\BotMan\Messages\Attachments\Image; 82 | use BotMan\BotMan\Messages\Outgoing\OutgoingMessage; 83 | 84 | // Create attachment 85 | $attachment = new Image('http://image-url-here.jpg', [ 86 | 'custom_payload' => true, 87 | ]); 88 | 89 | // Build message object 90 | $message = OutgoingMessage::create('This is my text') 91 | ->withAttachment($attachment); 92 | 93 | // Reply message object 94 | $bot->reply($message); 95 | ``` 96 | 97 | ### Videos 98 | You may use the `Video` class to attach a video URL to your outgoing message. 99 | It takes a video URL and an optional custom payload as constructor parameters. 100 | 101 | ```php 102 | use BotMan\BotMan\Messages\Attachments\Video; 103 | use BotMan\BotMan\Messages\Outgoing\OutgoingMessage; 104 | 105 | // Create attachment 106 | $attachment = new Video('http://video-url-here.mp4', [ 107 | 'custom_payload' => true, 108 | ]); 109 | 110 | // Build message object 111 | $message = OutgoingMessage::create('This is my text') 112 | ->withAttachment($attachment); 113 | 114 | // Reply message object 115 | $bot->reply($message); 116 | ``` 117 | 118 | ### Audio 119 | You may use the `Audio` class to attach an audio URL to your outgoing message. 120 | It takes an audio URL and an optional custom payload as constructor parameters. 121 | 122 | ```php 123 | use BotMan\BotMan\Messages\Attachments\Audio; 124 | use BotMan\BotMan\Messages\Outgoing\OutgoingMessage; 125 | 126 | // Create attachment 127 | $attachment = new Audio('http://audio-url-here.mp3', [ 128 | 'custom_payload' => true, 129 | ]); 130 | 131 | // Build message object 132 | $message = OutgoingMessage::create('This is my text') 133 | ->withAttachment($attachment); 134 | 135 | // Reply message object 136 | $bot->reply($message); 137 | ``` 138 | 139 | ### Generic Files 140 | You may use the `File` class to attach a generic file URL to your outgoing message. 141 | It takes a file URL and an optional custom payload as constructor parameters. 142 | 143 | ```php 144 | use BotMan\BotMan\Messages\Attachments\File; 145 | use BotMan\BotMan\Messages\Outgoing\OutgoingMessage; 146 | 147 | // Create attachment 148 | $attachment = new File('http://file-url-here.pdf', [ 149 | 'custom_payload' => true, 150 | ]); 151 | 152 | // Build message object 153 | $message = OutgoingMessage::create('This is my text') 154 | ->withAttachment($attachment); 155 | 156 | // Reply message object 157 | $bot->reply($message); 158 | ``` 159 | 160 | ### Location Information 161 | You may use the `Location` class to attach a GPS location information to your outgoing message. 162 | It takes the latitude, longitude and an optional custom payload as constructor parameters. 163 | 164 | ```php 165 | use BotMan\BotMan\Messages\Attachments\Location; 166 | use BotMan\BotMan\Messages\Outgoing\OutgoingMessage; 167 | 168 | // Create attachment 169 | $attachment = new Location(61.766130, -6.822510, [ 170 | 'custom_payload' => true, 171 | ]); 172 | 173 | // Build message object 174 | $message = OutgoingMessage::create('This is my text') 175 | ->withAttachment($attachment); 176 | 177 | // Reply message object 178 | $bot->reply($message); 179 | ``` 180 | 181 | 182 | 183 | ## Type Indicators 184 | 185 | To make your bot feel and act more human, you can make it send "typing ..." indicators. 186 | 187 | ```php 188 | 189 | $botman->hears('keyword', function (BotMan $bot) { 190 | $bot->typesAndWaits(2); 191 | $bot->reply("Tell me more!"); 192 | }); 193 | ``` 194 | 195 | This will send a typing indicator and sleep for 2 seconds, before actually sending the "Tell me more!" response. 196 | 197 | Please note, that not all messaging services support typing indicators. If it is not supported, it will simply do nothing and just reply the message. 198 | 199 | 200 | 201 | ## Originating Messages 202 | 203 | BotMan also allows you to send messages to your chat users programatically. You could, for example, send out a daily message to your users that get's triggered 204 | by your cronjob. 205 | 206 | The easiest way is to just specify the driver-specific recipient ID when calling the `say` method and the driver to use. 207 | 208 | ```php 209 | $botman->say('Message', 'my-recipient-user-id', TelegramDriver::class); 210 | ``` 211 | 212 | Just as the regular `reply` method, this method also accepts either simple strings or `OutgoingMessage` objects. 213 | 214 | For BotFramework (Skype) you should pass `['serviceUrl' => 'https://smba.trafficmanager.net/apis/']` as fourth parameter. 215 | 216 | 217 | 218 | ## Sending Low-Level Requests 219 | 220 | Sometimes you develop your chatbot and come to the conclusion that you would need to call a particular native messaging service API. As BotMan tries to decouple as many APIs as possible, it is not possible to have all API methods for each messaging service in the core of BotMan. 221 | 222 | For this exact reason, there is the `sendRequest` method on the BotMan instance. What it does is, that it calls the messaging service endpoint with the given arguments and returns a Response object. 223 | 224 | ```php 225 | // Calling the sendSticker API for Telegram 226 | $botman->hears('sticker', function($bot) { 227 | $bot->sendRequest('sendSticker', [ 228 | 'sticker' => '1234' 229 | ]) 230 | }); 231 | ``` 232 | 233 | If your API endpoint needs a Chat-ID, User-ID or Channel-ID that BotMan already knows, it will be passed along in the appropriate format for you, so you do not need to worry about it. 234 | -------------------------------------------------------------------------------- /driver-slack.md: -------------------------------------------------------------------------------- 1 | # Slack 2 | 3 | - [Installation & Setup](#installation-setup) 4 | - [Supported Features](#supported-features) 5 | - [Usage with a Slack App (recommended)](#slack-app) 6 | - [Usage with the Realtime API](#realtime-api) 7 | - [Usage with an outgoing webhook](#outgoing-webhook) 8 | - [Sending Slack Menus](#sending-slack-menus) 9 | 10 | 11 | ## Installation & Setup 12 | 13 | First you need to pull in the Slack Driver. 14 | 15 | ```sh 16 | composer require botman/driver-slack 17 | ``` 18 | 19 | Then load the driver before creating the BotMan instance (**only when you don't use BotMan Studio**): 20 | 21 | ```php 22 | DriverManager::loadDriver(\BotMan\Drivers\Slack\SlackDriver::class); 23 | 24 | // Create BotMan instance 25 | $config = [ 26 | 'slack' => [ 27 | 'token' => 'YOUR-SLACK-BOT-TOKEN' 28 | ] 29 | ]; 30 | BotManFactory::create($config); 31 | ``` 32 | 33 | Or if you use BotMan Studio: 34 | 35 | ```sh 36 | php artisan botman:install-driver slack 37 | ``` 38 | 39 | Slack is a cloud-based set of team collaboration tools and services. 40 | 41 | > {callout-info} If you're using [ngrok](https://ngrok.com/) be aware that Slack has a timeout of 3 seconds. When using ngrok, depending on your location and connection speed, the time it takes for Slack to get a 200 OK can be longer than 3 seconds. In such cases you'll notice that your bot will answer multiple times. If you're facing this issue a possible solution is to deploy your bot to a production server or try to change the ngrok server location. 42 | 43 | 44 | ## Supported Features 45 | This is a list of features that the driver supports. 46 | If a driver does not support a specific action, it is in most cases a limitation from the messaging service - not BotMan. 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 |
FeatureSupported?
Question-Buttons
Image Attachment
Video Attachment
Audio Attachment
Location Attachment
78 | 79 | 80 | ## Usage with a Slack App (recommended) 81 | 82 | The easiest way of making use of all BotMan features in your Slack team, is to create your own Slack app. You can do this at the [Slack API website](https://api.slack.com/apps?new_app=1). 83 | 84 | Once you have created a new Slack app, you need to configure three sections: 85 | 86 | #### Interactive Messages 87 | Interactive messages allow your chatbot to respond to message buttons. If you want to use this feature, just configure it and provide the URL that points to your BotMan logic / controller. 88 | 89 | #### Event Subscriptions 90 | Event subscription is needed, so that your BotMan application receives all incoming messages. You can either use event subscriptions or the Realtime API. 91 | When configuring your Slack app for event subscriptions, provide the URL that points to your BotMan logic / controller in the "Request URL" field. 92 | 93 | Then subscribe for these bot events: 94 | `message.channels` - A message was posted to a channel 95 | `message.im` - A message was posted in a direct message channel 96 | 97 | #### Bots 98 | This is the most obvious part - to communicate with BotMan in your Slack team, you need a bot user. Just give it a nice name. 99 | 100 | After you have configured these sections, go to "Install App" and install the app in your own team. 101 | Take note of the *Bot User OAuth Access Token* and use this token as your `slack_token` configuration parameter. 102 | 103 | That's it. 104 | 105 | 106 | 107 | ## Usage with the Realtime API 108 | 109 | > {callout-info} Please note: The Realtime API requires the additional composer package `mpociot/slack-client` to be installed. 110 | > 111 | > Simply install it using `composer require mpociot/slack-client`. 112 | 113 | Add a new Bot user to your Slack team and take note of the bot token slack gives you. 114 | Use this token as your `slack_token` configuration parameter. 115 | 116 | As the Realtime API needs a websocket, you need to create a PHP script that will hold your bot logic, as you can not use the HTTP controller way for it. 117 | 118 | ```php 119 | [ 133 | 'token' => 'YOUR-SLACK-BOT-TOKEN', 134 | ], 135 | ], $loop); 136 | 137 | $botman->hears('keyword', function($bot) { 138 | $bot->reply('I heard you! :)'); 139 | }); 140 | 141 | $botman->hears('convo', function($bot) { 142 | $bot->startConversation(new ExampleConversation()); 143 | }); 144 | 145 | $loop->run(); 146 | ``` 147 | 148 | Then simply run this file by using `php my-bot-file.php` - your bot should connect to your Slack team and respond to the messages. 149 | 150 | 151 | ## Usage with an outgoing webhook 152 | 153 | Add a new "Outgoing Webhook" integration to your Slack team - this URL needs to point to the controller where your BotMan bot is living in. You will find this integration when you search for `Outgoing WebHooks` in the Slack Apps Directory. 154 | 155 | To let BotMan listen to all incoming messages, do **not** specify a trigger word, but define a channel instead. 156 | 157 | With the Webhook implementation, there is no need to add a `slack_token` configuration. 158 | 159 | 160 | ## Sending Slack Menus 161 | 162 | BotMan supports sending Slack's [interactive message menus](https://api.slack.com/docs/message-menus) through an expressive and easy to use API. 163 | They can be used in combination with BotMan's [conversation questions](/conversations#asking-questions). 164 | 165 | There are multiple ways to define an interactive message menu. You can simply attach a `Menu` object to your question, just as you would with regular Buttons. 166 | 167 | You can access the selected option(s) using `$answer->getValue()` which will then return an array containing the selected option values. 168 | 169 | ### Custom drop down menu 170 | 171 |
172 | 173 |
174 | 175 | ```php 176 | // Inside your conversation 177 | $question = Question::create('Would you like to play a game?') 178 | ->callbackId('game_selection') 179 | ->addAction( 180 | Menu::create('Pick a game...') 181 | ->name('games_list') 182 | ->options([ 183 | [ 184 | 'text' => 'Hearts', 185 | 'value' => 'hearts', 186 | ], 187 | [ 188 | 'text' => 'Bridge', 189 | 'value' => 'bridge', 190 | ], 191 | [ 192 | 'text' => 'Poker', 193 | 'value' => 'poker', 194 | ] 195 | ]) 196 | ); 197 | 198 | $this->ask($question, function (Answer $answer) { 199 | $selectedOptions = $answer->getValue(); 200 | }); 201 | ``` 202 | 203 | ### Allow users to select from a list of team members 204 | 205 |
206 | 207 |
208 | 209 | ```php 210 | // Inside your conversation 211 | $question = Question::create('Who wins the lifetime supply of chocolate?') 212 | ->callbackId('select_users') 213 | ->addAction( 214 | Menu::create('Who should win?') 215 | ->name('winners_list') 216 | ->chooseFromUsers() 217 | ); 218 | 219 | $this->ask($question, function (Answer $answer) { 220 | $selectedOptions = $answer->getValue(); 221 | }); 222 | ``` 223 | 224 | ### Let users choose one of their team's channels 225 | 226 |
227 | 228 |
229 | 230 | ```php 231 | // Inside your conversation 232 | $question = Question::create('It\'s time to nominate the channel of the week') 233 | ->callbackId('select_channel') 234 | ->addAction( 235 | Menu::create('Which channel changed your life this week?') 236 | ->name('channels_list') 237 | ->chooseFromChannels() 238 | ); 239 | 240 | $this->ask($question, function (Answer $answer) { 241 | $selectedOptions = $answer->getValue(); 242 | }); 243 | ``` 244 | 245 | ### Let users choose one of their conversations 246 | 247 | ```php 248 | // Inside your conversation 249 | $question = Question::create('Let\'s get a productive conversation going') 250 | ->callbackId('select_conversation') 251 | ->addAction( 252 | Menu::create('Who did you talk to last?') 253 | ->name('conversations_list') 254 | ->chooseFromConversations() 255 | ); 256 | 257 | $this->ask($question, function (Answer $answer) { 258 | $selectedOptions = $answer->getValue(); 259 | }); 260 | ``` 261 | -------------------------------------------------------------------------------- /middleware.md: -------------------------------------------------------------------------------- 1 | # Middleware 2 | 3 | - [Introduction](#introduction) 4 | - [Lifecycle](#lifecycle) 5 | - [Received Middleware](#received-middleware) 6 | - [Captured Middleware](#captured-middleware) 7 | - [Matching Middleware](#matching-middleware) 8 | - [Heard Middleware](#heard-middleware) 9 | - [Sending Middleware](#sending-middleware) 10 | - [Example](#middleware-example) 11 | 12 | 13 | ## Introduction 14 | BotMan comes with a thorough middleware system, which is flexible and powerful. It allows you to hook custom integration logic into multiple parts of the chatbot lifecycle, such as receiving messages, matching message patterns and sending messages back to the user. Every available middleware comes with an interface that your middleware class can implement, so you can compose your own middleware classes, the way you need them. 15 | 16 | 17 | ## Lifecycle 18 | 19 | This chart shows you the lifecycle of the incoming chatbot requests and each steps they go through: 20 | 21 |
22 |
23 | 24 |
25 |
26 | 27 | 28 | ## Received Middleware 29 | The `received` middleware can be used to manipulate all incoming messaging service requests. This can for example be used to pre-process the incoming data and send it to a natural language processing tool, such as API.ai or RASA NLU. Since the `received` middleware needs to be applied to all incoming requests, it needs to be defined globally. 30 | 31 | ### Example middleware class 32 | 33 | This example `received` middleware takes the incoming message and adds some extra information to it, which can be used later throughout your chatbot application. 34 | As multiple middleware classes can be applied, make sure to return a call to `$next` with the incoming message as a parameter. 35 | 36 | ```php 37 | use BotMan\BotMan\Interfaces\Middleware\Received; 38 | 39 | class CustomReceivedMiddleware implements Received 40 | { 41 | /** 42 | * Handle an incoming message. 43 | * 44 | * @param IncomingMessage $message 45 | * @param callable $next 46 | * @param BotMan $bot 47 | * 48 | * @return mixed 49 | */ 50 | public function received(IncomingMessage $message, $next, BotMan $bot) 51 | { 52 | $message->addExtras('custom_message_information', 'my custom value'); 53 | return $next($message); 54 | } 55 | } 56 | ``` 57 | 58 | ### Applying the middleware 59 | To apply your custom `received` middleware, you may simply add it to the middleware stack using the `$botman->middleware->received` method. 60 | Make sure to call this method before you call the `listen()` method, as the middleware won't be loaded otherwise. 61 | 62 | ```php 63 | $middleware = new CustomReceivedMiddleware(); 64 | $botman->middleware->received($middleware); 65 | ``` 66 | 67 | 68 | ## Captured Middleware 69 | The `captured` middleware processes incoming answers when the current user is inside a conversation flow. This middleware will only be executed when your user is currently in a conversation and gives an answer to one of your conversation questions. 70 | Since the `captured` middleware needs to be applied to all incoming requests, it needs to be defined globally. 71 | 72 | ### Example middleware class 73 | 74 | This example `captured` middleware takes the incoming message and adds some extra information to it, which can be used later throughout your chatbot application. 75 | As multiple middleware classes can be applied, make sure to return a call to `$next` with the incoming message as a parameter. 76 | 77 | ```php 78 | use BotMan\BotMan\Interfaces\Middleware\Captured; 79 | 80 | class CustomCapturedMiddleware implements Captured 81 | { 82 | /** 83 | * Handle a captured message. 84 | * 85 | * @param IncomingMessage $message 86 | * @param callable $next 87 | * @param BotMan $bot 88 | * 89 | * @return mixed 90 | */ 91 | public function captured(IncomingMessage $message, $next, BotMan $bot) 92 | { 93 | $message->addExtras('custom_message_information', 'my custom value'); 94 | return $next($message); 95 | } 96 | } 97 | ``` 98 | 99 | ### Applying the middleware 100 | To apply your custom `captured` middleware, you may simply add it to the middleware stack using the `$botman->middleware->captured` method. 101 | Make sure to call this method before you call the `listen()` method, as the middleware won't be loaded otherwise. 102 | 103 | ```php 104 | $middleware = new CustomCapturedMiddleware(); 105 | $botman->middleware->captured($middleware); 106 | ``` 107 | 108 | 109 | ## Matching Middleware 110 | The `matching` middleware defines how the messages will be matched. It receives the result of the regular expression check and can perform additional checks too. This method is useful when testing incoming messages against natural language processing results - such as intents. This middleware can be applied per message that should be heard from BotMan. 111 | 112 | ### Example middleware class 113 | 114 | This example `matching` middleware takes the incoming message and checks not only for the regular expression match - but also checks that the message was sent from a specific user. Every BotMan commands under this middleware will only be heard, when the correct pattern is sent **and** the correct user sends the message. Otherwise BotMan will not call the command callback. 115 | 116 | ```php 117 | use BotMan\BotMan\Interfaces\Middleware\Matching; 118 | 119 | class CustomMatchingMiddleware implements Matching 120 | { 121 | /** 122 | * @param IncomingMessage $message 123 | * @param string $pattern 124 | * @param bool $regexMatched Indicator if the regular expression was matched too 125 | * @return bool 126 | */ 127 | public function matching(IncomingMessage $message, $pattern, $regexMatched) 128 | { 129 | return $regexMatched && $message->getSender() === 'Administrator'; 130 | } 131 | } 132 | ``` 133 | 134 | ### Applying the middleware 135 | To apply your custom `matching` middleware, you may either group multiple commands to use this middleware using the `group` method, or only apply the middleware to specific commands using the `middleware` method. Unless the other middlewares available, the `matching` middleware is not applied globally, but on a per command level. 136 | 137 | ```php 138 | $middleware = new CustomMatchingMiddleware(); 139 | 140 | // Let single command use this matching middleware 141 | $botman->hears('keyword', function ($bot) { 142 | // 143 | })->middleware($middleware); 144 | 145 | // Let multiple commands use this matching middleware 146 | $botman->group(['middleware' => $middleware], function ($botman) { 147 | $botman->hears('command one', function ($bot) { }); 148 | $botman->hears('command two', function ($bot) { }); 149 | }); 150 | ``` 151 | 152 | 153 | ## Heard Middleware 154 | The `heard` middleware works similar to how the `received` middleware works. It also processes the incoming message, but unlike the `received` middleware, the `heard` middleware will only be executed when the message was actually matched. 155 | 156 | ### Example middleware class 157 | 158 | This example `heard` middleware takes the incoming message and adds some extra information to it, which can be used later throughout your chatbot application. 159 | As multiple middleware classes can be applied, make sure to return a call to `$next` with the incoming message as a parameter. 160 | 161 | ```php 162 | use BotMan\BotMan\Interfaces\Middleware\Heard; 163 | 164 | class CustomHeardMiddleware implements Heard 165 | { 166 | /** 167 | * Handle a message that was successfully heard, but not processed yet. 168 | * 169 | * @param IncomingMessage $message 170 | * @param callable $next 171 | * @param BotMan $bot 172 | * 173 | * @return mixed 174 | */ 175 | public function heard(IncomingMessage $message, $next, BotMan $bot) 176 | { 177 | $message->addExtras('custom_message_information', 'my custom value'); 178 | return $next($message); 179 | } 180 | } 181 | ``` 182 | 183 | ### Applying the middleware 184 | To apply your custom `heard` middleware, you may simply add it to the middleware stack using the `$botman->middleware->heard` method. 185 | Make sure to call this method before you call the `listen()` method, as the middleware won't be loaded otherwise. 186 | 187 | ```php 188 | $middleware = new CustomHeardMiddleware(); 189 | $botman->middleware->heard($middleware); 190 | ``` 191 | 192 | 193 | ## Sending Middleware 194 | The `sending` middleware gets called before each message is sent out to the recipient. You can use this middleware to process outgoing messages and track every message that you send, for example using an analytics service. 195 | You can also manipulate the outgoing payload data before it gets sent to the messaging service. 196 | 197 | ### Example middleware class 198 | 199 | This example `sending` middleware simply logs the outgoing payload data into a file called log.txt. 200 | 201 | ```php 202 | use BotMan\BotMan\Interfaces\Middleware\Sending; 203 | 204 | class CustomCapturedMiddleware implements Sending 205 | { 206 | /** 207 | * Handle an outgoing message payload before/after it 208 | * hits the message service. 209 | * 210 | * @param mixed $payload 211 | * @param callable $next 212 | * @param BotMan $bot 213 | * 214 | * @return mixed 215 | */ 216 | public function sending($payload, $next, BotMan $bot) 217 | { 218 | file_put_contents('log.txt', print_r($payload, true)); 219 | return $next($payload); 220 | } 221 | } 222 | ``` 223 | 224 | ### Applying the middleware 225 | To apply your custom `sending` middleware, you may simply add it to the middleware stack using the `$botman->middleware->sending` method. 226 | Make sure to call this method before you call the `listen()` method, as the middleware won't be loaded otherwise. 227 | 228 | ```php 229 | $middleware = new CustomSendingMiddleware(); 230 | $botman->middleware->sending($middleware); 231 | ``` 232 | -------------------------------------------------------------------------------- /drivers.md: -------------------------------------------------------------------------------- 1 | # Drivers 2 | 3 | - [Introduction](#introduction) 4 | - [Defining a driver](#defining-a-driver) 5 | - [Setup](#setup) 6 | - [Receiving a message](#receiving-a-message) 7 | - [Handling users](#handling-users) 8 | - [Answering conversations](#answering-conversations) 9 | - [Sending a message](#sending-a-message) 10 | - [Typing indicators](#typing-indicators) 11 | - [Activation](#activation) 12 | - [Message templates](#message-templates) 13 | 14 | 15 | ## Introduction 16 | 17 | BotMan ships with support for a number of different messaging channels. Each channel is powered by it's own driver which can be installed either manually or via [BotMan Studio](/__version__/botman-studio). 18 | 19 | Should you need to utilise a messaging channel not supported by BotMan, it is possible to define your own. Below is a step-by-step guide of how to do so. 20 | 21 | 22 | ### Defining a driver 23 | 24 | A driver is a class which extends `BotMan\BotMan\Drivers\HttpDriver`. 25 | 26 | This parent class defines a blueprint by which the driver must adhere to. Succesfully implementing the methods set out in this class, results in a fully working driver. 27 | 28 | ```php 29 | 41 | ### Setup 42 | 43 | When each driver is instantiated by BotMan, the `buildPayload()` method is called. This method is used to carry out the initial setup. In the case of Facebook, it looks like this. 44 | 45 | ```php 46 | 47 | /** 48 | * @param Request $request 49 | */ 50 | public function buildPayload(Request $request) 51 | { 52 | $this->payload = new ParameterBag((array) json_decode($request->getContent(), true)); 53 | $this->event = Collection::make((array) $this->payload->get('entry')[0]); 54 | $this->signature = $request->headers->get('X_HUB_SIGNATURE', ''); 55 | $this->content = $request->getContent(); 56 | $this->config = Collection::make($this->config->get('facebook', [])); 57 | } 58 | ``` 59 | 60 | BotMan needs to be notified whether or not the driver can handle the incoming request. This is handled by the `matchesRequest()` method. 61 | 62 | This method interogates the incoming request to determine whether it contains anything that the driver is expecting and simply returns a boolean. 63 | 64 | In the case of Slack, we know it's a Slack message if the incoming event contains a `user`, `team_domain` or `bot_id`. 65 | 66 | ```php 67 | public function matchesRequest() 68 | { 69 | return ! is_null($this->event->get('user')) || ! is_null($this->event->get('team_domain')) || ! is_null($this->event->get('bot_id')); 70 | } 71 | ``` 72 | 73 | 74 | ### Receiving a message 75 | 76 | Once it has been determined that the driver should handle the request, BotMan needs to have access to the messages that have been received. 77 | 78 | The parent `HttpDriver` class contains a `messages` property that needs to be populated. In order to do this, the `getMessages` method needs to be defined. 79 | 80 | BotMan is expecting the `messages` property to contain an array of `BotMan\BotMan\Messages\Incoming\IncomingMessage` objects. 81 | 82 | It's important to note that even if the request only contains a single message, the `messages` property should be an array. 83 | 84 | ```php 85 | /** 86 | * Retrieve the chat message. 87 | * 88 | * @return array 89 | */ 90 | public function getMessages() 91 | { 92 | if (empty($this->messages)) { 93 | $message = $this->event->get('message'); 94 | $userId = $this->event->get('userId'); 95 | $this->messages = [new IncomingMessage($message, $userId, $userId, $this->payload)]; 96 | } 97 | return $this->messages; 98 | } 99 | ``` 100 | 101 | `IncomingMessage` expects a message string, sender ID, recipient ID and optional payload when instantiating the class. 102 | 103 | 104 | ### Handling users 105 | 106 | BotMan ships with a class for managing users: `BotMan\BotMan\Users\User` 107 | 108 | To set this up simply return a new `User` object from the `getUser` method of the driver. 109 | If your messaging service supports additional information about your user, you can pass these parameters to the user object. 110 | 111 | ```php 112 | ** 113 | * Retrieve User information. 114 | * @param IncomingMessage $matchingMessage 115 | * @return UserInterface 116 | */ 117 | public function getUser(IncomingMessage $matchingMessage) 118 | { 119 | return new User($matchingMessage->getSender()); 120 | } 121 | ``` 122 | 123 | 124 | ### Answering conversations 125 | 126 | For your bot to respond to conversations, the `getConversationAnswer` method needs to be defined. 127 | 128 | From here, simply return an instance of `BotMan\BotMan\Messages\Incoming\Answer` 129 | 130 | ```php 131 | /** 132 | * @param IncomingMessage $message 133 | * @return \BotMan\BotMan\Messages\Incoming\Answer 134 | */ 135 | public function getConversationAnswer(IncomingMessage $message) 136 | { 137 | return Answer::create($message->getText())->setMessage($message); 138 | } 139 | ``` 140 | 141 | If your driver supports interactive replies such as postbacks from buttons, pass a boolean value to the `setInteractiveReply` method of the `Answer object`. This will let BotMan know whether or not it is a standard or interactive message. 142 | 143 | Take a look at the other methods of this class as there may be other features useful for your driver. 144 | 145 | 146 | ### Sending a message 147 | 148 | In order for your bot to send a message, there are two methods that need defining. 149 | 150 | The `buildServicePayload` method receives the message instance to be sent by BotMan. The purpose of this method is to take the message and transform it into the payload required by your driver. 151 | 152 | ```php 153 | /** 154 | * @param string|Question|OutgoingMessage $message 155 | * @param IncomingMessage $matchingMessage 156 | * @param array $additionalParameters 157 | * @return Response 158 | */ 159 | public function buildServicePayload($message, $matchingMessage, $additionalParameters = []) 160 | { 161 | if (! $message instanceof WebAccess && ! $message instanceof OutgoingMessage) { 162 | $this->errorMessage = 'Unsupported message type.'; 163 | $this->replyStatusCode = 500; 164 | } 165 | return [ 166 | 'message' => $message, 167 | 'additionalParameters' => $additionalParameters, 168 | ]; 169 | } 170 | ``` 171 | 172 | Closely coupled with this method is `sendPayload`. The responsibility of this method is to take the payload created above and send it. 173 | 174 | Your driver has access to a HTTP client which can assist with this. 175 | 176 | The example below posts the payload to a given endpoint and handles the addtion of any required headers. 177 | 178 | ```php 179 | /** 180 | * @param mixed $payload 181 | * @return Response 182 | */ 183 | public function sendPayload($payload) 184 | { 185 | $response = $this->http->post($this->endpoint . 'send', [], $payload, [ 186 | "Authorization: Bearer {$this->config->get('token')}", 187 | 'Content-Type: application/json', 188 | 'Accept: application/json', 189 | ], true); 190 | 191 | return $response; 192 | } 193 | ``` 194 | 195 | 196 | ### Activation 197 | 198 | There are two steps required to activate a driver. 199 | 200 | Firstly, define the `isConfigured` method of the driver. This should return a boolean as to whether or not the driver is ready for use. Typically, it's a good idea to check any required configuration has been set for the driver in this method. 201 | 202 | ```php 203 | /** 204 | * @return bool 205 | */ 206 | public function isConfigured() 207 | { 208 | return !empty($this->config->get('token')); 209 | } 210 | ``` 211 | 212 | Now, BotMan needs to be informed that the driver exists. 213 | 214 | If you are using BotMan studio for Laravel, this is easy. Simply open `App\Providers\BotMan\DriverServiceProvider` and add your driver to the `$drivers` array. 215 | 216 | If you are using the package in a different environment, use the `DriverManager` to load your driver as follows: 217 | 218 | ```php 219 | use BotMan\BotMan\BotManFactory; 220 | use BotMan\BotMan\Drivers\DriverManager; 221 | 222 | DriverManager::loadDriver(FacebookDriver::class); 223 | BotManFactory::create(config('botman')); 224 | ``` 225 | 226 | 227 | ## Message templates 228 | 229 | If your driver offers message templates not supported by BotMan out of the box, you may define your own. 230 | 231 | Simply define a class for the template which will be used to build up all of the available elements that comprise it. 232 | 233 | This object is passed to the `buildServicePayload` method of your driver. As such, it's useful to define a method which will transform the object into a format that can be sent to your endpoint. 234 | 235 | Below is an example of a template which contains text and buttons: 236 | 237 | ```php 238 | class ExampleTemplate implements \JsonSerializable 239 | { 240 | /** @var string */ 241 | protected $text; 242 | 243 | /** @var array */ 244 | protected $buttons = []; 245 | 246 | /** 247 | * @param $text 248 | * @return static 249 | */ 250 | public static function create($text) 251 | { 252 | return new static($text); 253 | } 254 | 255 | public function __construct($text) 256 | { 257 | $this->text = $text; 258 | } 259 | 260 | /** 261 | * @param $button 262 | * @return $this 263 | */ 264 | public function addButton(ButtonTemplate $button) 265 | { 266 | $this->buttons[] = $button->toArray(); 267 | return $this; 268 | } 269 | 270 | /** 271 | * @param array $buttons 272 | * @return $this 273 | */ 274 | public function addButtons(array $buttons) 275 | { 276 | foreach ($buttons as $button) { 277 | if ($button instanceof ButtonTemplate) { 278 | $this->buttons[] = $button->toArray(); 279 | } 280 | } 281 | 282 | return $this; 283 | } 284 | 285 | /** 286 | * @return array 287 | */ 288 | public function toArray() 289 | { 290 | return [ 291 | 'type' => 'action', 292 | 'message' => [[ 293 | 'text' => $this->text, 294 | 'buttons' => $this->buttons, 295 | ]], 296 | ]; 297 | } 298 | 299 | /** 300 | * @return array 301 | */ 302 | public function jsonSerialize() 303 | { 304 | return $this->toArray(); 305 | } 306 | } 307 | ``` -------------------------------------------------------------------------------- /testing.md: -------------------------------------------------------------------------------- 1 | # Testing 2 | 3 | - [Introduction](#introduction) 4 | - [Testing Multiple Replies](#testing-multiple-replies) 5 | - [Simulating User Messages](#simulating-user-messages) 6 | - [Available Assertions](#available-assertions) 7 | - [Testing Conversations](#testing-conversations) 8 | - [Testing Events](#testing-events) 9 | - [Advanced Testing](#advanced-testing) 10 | 11 | > {callout-info} The BotMan testing features are only available in combination with [BotMan Studio](/__version__/botman-studio). 12 | 13 | 14 | ## Introduction 15 | 16 | Like Laravel, BotMan is build with testing in mind. Every part of it is well tested and this is the only way to keep such a big project running properly. 17 | 18 | But also your bots should be built with tests and this is why BotMan Studio will help you with that. Testing bots and conversations is very different from your other projects. This is why BotMan Studio provides lots of helper methods for you. This is the basic test example you will find in your `ExampleTest.php` file. 19 | 20 | ```php 21 | public function testBasicTest() 22 | { 23 | $this->bot 24 | ->receives('Hi') 25 | ->assertReply('Hello!'); 26 | } 27 | ``` 28 | 29 | 30 | ### Testing Multiple Replies 31 | All assertion methods can be chained to test cases when your bot responds with more than one message. 32 | 33 | ```php 34 | public function testBasicTest() 35 | { 36 | $this->bot 37 | ->receives('Hi') 38 | ->assertReply('Hello!') 39 | ->assertReply('Nice to meet you'); 40 | } 41 | ``` 42 | 43 | Additionally you can you use the `assertReplies()` method if you want to test multiple replies at once. 44 | 45 | ```php 46 | public function testBasicTest() 47 | { 48 | $this->bot 49 | ->receives('Hi') 50 | ->assertReplies([ 51 | 'Hello!', 52 | 'Nice to meet you', 53 | ]); 54 | } 55 | ``` 56 | 57 | 58 | ## Simulating User Messages 59 | ### Receiving Attachments 60 | 61 | BotMan can receive attachment objects from user and there are methods that help you test those cases. You can use `receivesLocation`, `receivesImages`, `receivesVideos`, `receivesAudio` and `receivesFiles` methods to simulate that user has send valid attachments. 62 | 63 | ```php 64 | public function testBasicTest() 65 | { 66 | $this->bot 67 | ->receivesLocation() 68 | ->assertReply('Thanks for locations'); 69 | } 70 | ``` 71 | 72 | You can pass additional `$latitude` and `$longitude` arguments to `receivesLocation` if necessary. 73 | 74 | ```php 75 | public function testBasicTest() 76 | { 77 | $this->bot 78 | ->receivesLocation($latitude, $longitude) 79 | ->assertReply('Your latidude is ' . $latitude); 80 | } 81 | ``` 82 | 83 | You can pass additional array of urls to `receivesImages`, `receivesVideos`, `receivesAudio` and `receivesFiles` methods if necessary. 84 | 85 | ```php 86 | public function testBasicTest() 87 | { 88 | $this->bot 89 | ->receivesImage(['www.example.com/dog']) 90 | ->assertReply('You sent me dog image'); 91 | } 92 | ``` 93 | 94 | ### Receiving Interactive message 95 | There are cases when we expect our chatbot user to respond to a question with an interactive reply - for example a button click. To simulate that, use the `receivesInteractiveMessage` method. It accepts the button value as an argument. 96 | 97 | ```php 98 | public function testBasicTest() 99 | { 100 | $this->bot 101 | ->receivesInteractiveMessage('dog') 102 | ->assertReply('You chose dog!'); 103 | } 104 | ``` 105 | 106 | 107 | ## Available Assertions 108 | BotMan comes with handful of useful methods to test you chatbots. 109 | 110 | ### assertReply 111 | The `assertReply` method asserts that the chatbot replies with the given message. 112 | 113 | ```php 114 | public function testBasicTest() 115 | { 116 | $this->bot 117 | ->receives('Hi') 118 | ->assertReply('Hello'); 119 | } 120 | ``` 121 | 122 | ### assertReplies 123 | The `assertReplies` method asserts that the chatbot replies with all messages in the given array. 124 | 125 | ```php 126 | public function testBasicTest() 127 | { 128 | $this->bot 129 | ->receives('Hi') 130 | ->assertReplies([ 131 | 'Hello!', 132 | 'Nice to meet you', 133 | ]); 134 | } 135 | ``` 136 | 137 | ### assertReplyIsNot 138 | The `assertReplyIsNot` method asserts that the chatbot does not reply with the given message. 139 | 140 | ```php 141 | public function testBasicTest() 142 | { 143 | $this->bot 144 | ->receives('Hi') 145 | ->assertReplyIsNot('Good bye'); 146 | } 147 | ``` 148 | 149 | ### assertReplyIn 150 | The `assertReplyIn` method asserts that the chatbot replies with one message from the given array. This is helpful if your bot uses random answers. 151 | 152 | ```php 153 | public function testBasicTest() 154 | { 155 | $this->bot 156 | ->receives('Hi') 157 | ->assertReplyIn([ 158 | 'Hi', 159 | 'Hello', 160 | 'Bonjourno' 161 | ]); 162 | } 163 | ``` 164 | 165 | ### assertReplyNotIn 166 | The `assertReplyNotIn` method asserts that the chatbot does not reply with any of the given messages. 167 | 168 | ```php 169 | public function testBasicTest() 170 | { 171 | $this->bot 172 | ->receives('Hi') 173 | ->assertReplyNotIn([ 174 | 'Bye', 175 | 'Good bye', 176 | 'Arrivederci' 177 | ]); 178 | } 179 | ``` 180 | 181 | ### assertReplyNothing 182 | The `assertReplyNothing` method asserts that the chatbot does not reply with any message at all. Useful when chained with other assertion methods to check that the chatbot stopped responding. 183 | 184 | ```php 185 | public function testBasicTest() 186 | { 187 | $this->bot 188 | ->receives('Hi') 189 | ->assertReply('Hello') 190 | ->assertReplyNothing(); 191 | } 192 | ``` 193 | 194 | ### assertQuestion 195 | The `assertQuestion` method asserts that the chatbot replies with a Question object. If you call this method without an argument it just checks for a question occurance. Otherwise it will test for the question text. 196 | 197 | ```php 198 | public function testBasicTest() 199 | { 200 | $this->bot 201 | ->receives('Start conversation') 202 | ->assertQuestion(); 203 | } 204 | 205 | public function testBasicTest() 206 | { 207 | $this->bot 208 | ->receives('Start conversation') 209 | ->assertQuestion('What do you want to talk about'); 210 | } 211 | ``` 212 | 213 | ### assertTemplate 214 | The `assertTemplate` method asserts that the chatbot does reply with a given template class. This is especially useful when testing Facebook reply templates. 215 | 216 | ```php 217 | public function testBasicTest() 218 | { 219 | $this->bot 220 | ->receives('News feed') 221 | ->assertTemplate(GenericTemplate::class); 222 | } 223 | ``` 224 | 225 | You can pass `true` as a second argument to test that the templates are exactly the same (strict mode). 226 | 227 | ```php 228 | public function testStartJokeConversation() 229 | { 230 | $jokeTypeQuestion = ButtonTemplate::create('Please select the kind of joke you wanna hear:') 231 | ->addButtons([ 232 | ElementButton::create('Chuck Norris')->type('payload')->payload('chucknorris'), 233 | ElementButton::create('Children')->type('payload')->payload('children'), 234 | ElementButton::create('Politics')->type('payload')->payload('politics'), 235 | ]); 236 | 237 | $this->bot 238 | ->receives('start joke conversation') 239 | ->assertTemplate($jokeTypeQuestion, true); 240 | } 241 | ``` 242 | 243 | 244 | ## Testing Conversations 245 | When you want to test a longer conversation you can chain the given methods. Just add another `receives()` and an `assertion` afterwards. 246 | 247 | ```php 248 | public function testStartConversation() 249 | { 250 | $this->bot 251 | ->receives('Hi') 252 | ->assertReplies([ 253 | 'Hello!', 254 | 'Nice to meet you. What is your name?', 255 | ])->receives('BotMan') 256 | ->assertReply('BotMan, that is a beautifule name :-)'); 257 | } 258 | ``` 259 | 260 | 261 | ## Testing Events 262 | BotMan supports testing for driver specific events with the `receivesEvent` method. 263 | 264 | ```php 265 | public function testStartConversation() 266 | { 267 | $this->bot 268 | ->receivesEvent('event_name') 269 | ->assertReply('Received event'); 270 | } 271 | ``` 272 | 273 | You can pass a `$payload` array as an additional argument as well. 274 | 275 | ```php 276 | public function testStartConversation() 277 | { 278 | $this->bot 279 | ->receivesEvent('event_name', ['key' => 'value']) 280 | ->assertReply('Received event'); 281 | } 282 | ``` 283 | 284 | 285 | ## Advanced Testing 286 | ### Set Driver 287 | If you are building multi-driver chatbots with BotMan you may have restricted some commands to specific drivers only - for example using the `group` method. 288 | 289 | ```php 290 | $botman->group(['driver' => FacebookDriver::class], function ($bot) { 291 | $bot->hears('Facebook only', function ($bot) { 292 | $bot->reply('You are on messenger'); 293 | }); 294 | }); 295 | ``` 296 | 297 | The BotMan testing environment uses a fake driver class to run the tests, but we can change the name of the driver with the `setDriver` method. 298 | 299 | ```php 300 | public function testStartConversation() 301 | { 302 | $this->bot 303 | ->setDriver(FacebookDriver::class) 304 | ->receives('Facebook only') 305 | ->assertReply('You are on messenger'); 306 | } 307 | ``` 308 | 309 | ### Set User Information 310 | In a similar manner you can set user information with the `setUser` method. 311 | 312 | ```php 313 | public function testStartConversation() 314 | { 315 | $this->bot 316 | ->setUser([ 317 | 'first_name' => 'John' 318 | ]) 319 | ->receives('Hi') 320 | ->assertReply('Hi, John!); 321 | } 322 | ``` 323 | 324 | ### Skip Assertion 325 | 326 | In cases when your bot replies with several messages you can assert only a specific reply using the `reply` method to skip assertion. All tests below will pass. 327 | 328 | ```php 329 | public function testStartConversation() 330 | { 331 | $this->bot 332 | ->receives('Tell me something') 333 | ->assertReply('Hmm..') 334 | ->assertReply('Ok') 335 | ->assertQuestion('Here are some topics we could discuss'); 336 | } 337 | 338 | public function testStartConversation() 339 | { 340 | $this->bot 341 | ->receives('Tell me something') 342 | ->reply() 343 | ->assertReply('Ok') 344 | ->assertQuestion('Here are some topics we could discuss'); 345 | } 346 | 347 | public function testStartConversation() 348 | { 349 | $this->bot 350 | ->receives('Tell me something') 351 | ->reply(2) 352 | ->assertQuestion('Here are some topics we could discuss'); 353 | } 354 | ``` 355 | 356 | ### ReceiveRaw and AssertRaw 357 | 358 | If none of the helper methods can handle your specific test case you can use the `receiveRaw` and `assertRaw` methods. 359 | 360 | ```php 361 | public function testStartConversation() 362 | { 363 | $incoming = new IncomingMessage('Hi', '12345678', 'abcdefgh'); 364 | $outgoing = new OutgoingMessage('Hello'); 365 | 366 | $this->bot 367 | ->receivesRaw($incoming) 368 | ->assertRaw($outgoing); 369 | } 370 | ``` 371 | 372 | -------------------------------------------------------------------------------- /conversations.md: -------------------------------------------------------------------------------- 1 | # Conversations 2 | 3 | - [Start A Conversation](#starting-a-conversation) 4 | - [Asking Questions](#asking-questions) 5 | - [Asking For Images, Videos, Audio Or Location](#asking-for-data) 6 | - [Structured Question With Patterns](#structured-question) 7 | - [Originating Conversations](#originating-conversations) 8 | - [Skip or Stop Conversations](#skip-stop-conversations) 9 | - [Caching Conversations](#caching-conversations) 10 | - [Debugging Conversations](#debugging-conversations) 11 | 12 | When it comes to chat bots, you probably don't want to simply react to single keywords, but instead, you might need to gather information from the user, using a conversation. 13 | Let's say, that you want your chat bot to provide an elegant user onboarding experience for your application users. In the onboarding process we are going to ask the user for their firstname and email address - that's a perfect fit for conversations! 14 | 15 | > {callout-info} If you are **not** using [BotMan Studio](/__version__/botman-studio), you must configure a persistent [Cache Driver](/__version__/cache-drivers) to use BotMan's Conversation, as BotMan will keep the conversation state cached. 16 | 17 | 18 | ## Starting A Conversation 19 | 20 | You can start a conversation with your users using the `startConversation` method inside a keyword callback: 21 | 22 | ```php 23 | $botman->hears('Hello', function($bot) { 24 | $bot->startConversation(new OnboardingConversation); 25 | }); 26 | ``` 27 | Try it out 28 | 29 | Let's take a look at the `OnboardingConversation` class: 30 | 31 | ```php 32 | class OnboardingConversation extends Conversation 33 | { 34 | protected $firstname; 35 | 36 | protected $email; 37 | 38 | public function askFirstname() 39 | { 40 | $this->ask('Hello! What is your firstname?', function(Answer $answer) { 41 | // Save result 42 | $this->firstname = $answer->getText(); 43 | 44 | $this->say('Nice to meet you '.$this->firstname); 45 | $this->askEmail(); 46 | }); 47 | } 48 | 49 | public function askEmail() 50 | { 51 | $this->ask('One more thing - what is your email?', function(Answer $answer) { 52 | // Save result 53 | $this->email = $answer->getText(); 54 | 55 | $this->say('Great - that is all we need, '.$this->firstname); 56 | }); 57 | } 58 | 59 | public function run() 60 | { 61 | // This will be called immediately 62 | $this->askFirstname(); 63 | } 64 | } 65 | ``` 66 | 67 | All conversations that your bot might use need to extend the abstract Conversation class and implement a `run` method. 68 | 69 | This is the starting point of your conversation and get's executed immediately. 70 | 71 | As you can see in the onboarding conversation, we have two questions that get asked one after another. Just like a regular conversation, the bot first asks for the firstname and saves the value in the conversation object itself. Beware that your class variables must be declared as `protected` or `public` so that they can be saved in cache. 72 | 73 | After it retrieves an answer from the user, the callback gets executed and the bot asks the next question, which retrieves the user's email address. 74 | 75 | ### Starting within a conversation 76 | 77 | When you build more and more conversations, you probably also want to connect them. This is when it gets very useful to start a conversation within another one. 78 | 79 | ```php 80 | public function askEmail() 81 | { 82 | $this->ask('One more thing - what is your email?', function(Answer $answer) { 83 | // Save result 84 | $this->email = $answer->getText(); 85 | 86 | $this->say('Great - that is all we need, '.$this->firstname); 87 | 88 | $this->bot->startConversation(new FavouriteLunchConversation()); 89 | }); 90 | } 91 | ``` 92 | 93 | 94 | ## Asking Questions 95 | 96 | BotMan gives you two ways to ask your users questions. The straight forward approach is simply using a string as a question: 97 | 98 | ```php 99 | // ...inside the conversation object... 100 | public function askMood() 101 | { 102 | $this->ask('How are you?', function (Answer $response) { 103 | $this->say('Cool - you said ' . $response->getText()); 104 | }); 105 | } 106 | ``` 107 | 108 | Instead of passing a string to the `ask()` method, it is also possible to create a question object. 109 | The question objects make use of the interactive messages from supported messaging services to present the user buttons to interact with. 110 |

111 | When passing question objects to the `ask()` method, the returned `Answer` object has a method called `isInteractiveMessageReply` to detect, if 112 | the user interacted with the message and clicked on a button or simply entered text. 113 |

114 | Creating a simple Question object: 115 | 116 | ```php 117 | // ...inside the conversation object... 118 | public function askForDatabase() 119 | { 120 | $question = Question::create('Do you need a database?') 121 | ->fallback('Unable to create a new database') 122 | ->callbackId('create_database') 123 | ->addButtons([ 124 | Button::create('Of course')->value('yes'), 125 | Button::create('Hell no!')->value('no'), 126 | ]); 127 | 128 | $this->ask($question, function (Answer $answer) { 129 | // Detect if button was clicked: 130 | if ($answer->isInteractiveMessageReply()) { 131 | $selectedValue = $answer->getValue(); // will be either 'yes' or 'no' 132 | $selectedText = $answer->getText(); // will be either 'Of course' or 'Hell no!' 133 | } 134 | }); 135 | } 136 | ``` 137 | 138 | 139 | ## Asking For Images, Videos, Audio or Location 140 | 141 | With BotMan, you can easily let your bot [receive images, videos, audio files or locations](/__version__/receiving-additional-content). 142 | The same approach can be applied to your conversation. This is especially useful if you only want your bot users to provide you with specific attachment types. 143 | 144 | You might use the `askForImages` method to ask your bot users a question and only accept one or more images as a valid answer: 145 | 146 | ```php 147 | // ...inside the conversation object... 148 | public function askPhoto() 149 | { 150 | $this->askForImages('Please upload an image.', function ($images) { 151 | // $images contains an array with all images. 152 | }); 153 | } 154 | ``` 155 | 156 | The callback will receive an array containing all images the user has sent to the bot. By default, if the user does not provide a valid image, the question will just be repeated. But you can alter it, by specifying a third parameter. This is the callback that will be executed, once the provided message is not a valid image. 157 | 158 | ```php 159 | // ...inside the conversation object... 160 | public function askPhoto() 161 | { 162 | $this->askForImages('Please upload an image.', function ($images) { 163 | // 164 | }, function(Answer $answer) { 165 | // This method is called when no valid image was provided. 166 | }); 167 | } 168 | ``` 169 | 170 | Similar to the `askForImages` method, you might also ask for videos, audio files or even your chatbot user's locations. 171 | 172 | ```php 173 | // ...inside the conversation object... 174 | public function askVideos() 175 | { 176 | $this->askForVideos('Please upload a video.', function ($videos) { 177 | // $videos is an array containing all uploaded videos. 178 | }); 179 | } 180 | 181 | public function askAudio() 182 | { 183 | $this->askForAudio('Please upload an audio file.', function ($audio) { 184 | // $audio is an array containing all uploaded audio files. 185 | }); 186 | } 187 | 188 | public function askLocation() 189 | { 190 | $this->askForLocation('Please tell me your location.', function (Location $location) { 191 | // $location is a Location object with the latitude / longitude. 192 | }); 193 | } 194 | ``` 195 | 196 | 197 | 198 | ## Structured Question With Patterns 199 | 200 | You might also want to ask your user questions, where you already know the answer should be in a fixed set of possible options. 201 | For example a simple yes or no question. 202 | 203 | Instead of passing a closure to the `ask` method, you can simply pass it an array. 204 | BotMan will then look first for a matching pattern, and execute only the callback whose pattern is matched. 205 | 206 | This allows the bot to present multiple choice options, or to proceed only when a valid response has been received. The patterns can have the same placeholders as the `$bot->reply()` method has. All matching parameters will be passed to the callback function. 207 | 208 | ```php 209 | // ...inside the conversation object... 210 | public function askNextStep() 211 | { 212 | $this->ask('Shall we proceed? Say YES or NO', [ 213 | [ 214 | 'pattern' => 'yes|yep', 215 | 'callback' => function () { 216 | $this->say('Okay - we\'ll keep going'); 217 | } 218 | ], 219 | [ 220 | 'pattern' => 'nah|no|nope', 221 | 'callback' => function () { 222 | $this->say('PANIC!! Stop the engines NOW!'); 223 | } 224 | ] 225 | ]); 226 | } 227 | 228 | ``` 229 | 230 | 231 | ## Originating Conversations 232 | 233 | Just like it is possible with BotMan to [originate messages](/__version__/sending#originating-messages), it is also possible to start complete conversations on the bot's behalf. You might, for example, start a new conversation that gets triggered through your cronjob. 234 | 235 | To do so, just use the `startConversation` method, as you would normally do, but pass a user ID and the driver name as additional arguments: 236 | 237 | ```php 238 | $botman->startConversation(new PizzaConversation(), 'my-recipient-user-id', TelegramDriver::class); 239 | ``` 240 | 241 | 242 | ## Skip or Stop Conversations 243 | 244 | While being in a conversation it is sometimes useful to stop it for a certain reason. In order to make this possible there a two methods available in every conversation class: `skipsConversation()` and `stopsConversation()`. Inside those methods you can return true or false to skip or stop a conversation. Skip will stop the conversation just for this one request. Afterwards it will go on as if nothing happened. The stop method will delete the conversation, so there is no turning back. 245 | 246 | The example below will stop the conversation if the message says `stop` and skip it if it says `pause`. 247 | 248 | ```php 249 | class OnboardingConversation extends Conversation 250 | { 251 | protected $firstname; 252 | 253 | protected $email; 254 | 255 | public function stopsConversation(IncomingMessage $message) 256 | { 257 | if ($message->getText() == 'stop') { 258 | return true; 259 | } 260 | 261 | return false; 262 | } 263 | 264 | 265 | public function skipsConversation(IncomingMessage $message) 266 | { 267 | if ($message->getText() == 'pause') { 268 | return true; 269 | } 270 | 271 | return false; 272 | } 273 | 274 | // ... 275 | 276 | } 277 | ``` 278 | 279 | There are several scenarios where this could be handy. For example in Facebook there is a menu in the chat. When the user clicks a menu button you want to leave a current conversation in order to show the new information. But it also possible to use this functionality on a "global" level. 280 | 281 | ```php 282 | $botman->hears('stop', function(BotMan $bot) { 283 | $bot->reply('stopped'); 284 | })->stopsConversation(); 285 | ``` 286 | 287 | Here we are stopping the conversation through a `hears` method, where we are listening for the message `stop`. This comes handy when we want to stop a conversation, not matter which one it is. This also works for skipping. 288 | 289 | ```php 290 | $botman->hears('pause', function(BotMan $bot) { 291 | $bot->reply('stopped'); 292 | })->skipsConversation(); 293 | ``` 294 | 295 | 296 | ## Caching Conversations 297 | 298 | Conversations get persisted in on of the available [cache drivers](/__version__/cache-drivers). This means that the conversation class will be serialized in order to maintain the conversation state. Keep that in mind when developing for BotMan. The default cache duration is set to 30 minutes. If you need to increase or decrease this value, you can set a `conversation_cache_time` key on your BotMan configuration. 299 | 300 | ```php 301 | 'botman' => [ 302 | 'conversation_cache_time' => 30 303 | ], 304 | ``` 305 | 306 | 307 | 308 | ## Debugging Conversations 309 | 310 | As conversations get persisted in the cache, it can happen to you that you fix a bug inside one of your conversation scripts - but when you retry the chat command it still does not work. 311 | One of the reasons for this could be, that BotMan is still using the cached conversation that might still contain the error that you just fixed. 312 | 313 | If you use BotMan Studio you can clear the cache by using: 314 | 315 | ```sh 316 | php artisan cache:clear 317 | ``` 318 | 319 | Then you can try the command again. 320 | 321 | If you do not use BotMan Studio, you have to manually delete the cache entries that BotMan created. -------------------------------------------------------------------------------- /web-widget.md: -------------------------------------------------------------------------------- 1 | # Web Widget 2 | 3 | - [Introduction](#introduction) 4 | - [Requirements & Building](#building) 5 | - [Installation & Setup](#installation-setup) 6 | - [Configuration & Customization](#configuration) 7 | - [API](#api) 8 | 9 | 10 | ## Introduction 11 | 12 | To make it as easy as possible for you, to add a BotMan powered chatbot into your website, BotMan ships with a custom chat widget that you can use out of the box. It uses Preact under the hood, which results in a minimal footprint of only 5kb (gzipped). 13 | 14 | The web widget currently supports buttons, texts, images, videos, audio responses and the Facebook list- and button-template, so that you can just use the web widget, without modifying the code - even if it is specific to a messenger service. 15 | 16 | You can also see it running here in the documentation - most of the code samples work with the web driver, so feel free to just give it a try! 17 | 18 | 19 | ## Requirements & Building 20 | 21 | ### Install nodejs 22 | ``` 23 | apt-get install build-essential libssl-dev 24 | apt-get install nodejs 25 | nodejs -v 26 | apt-get install npm 27 | npm -v 28 | ``` 29 | 30 | ### Install nvm 31 | 32 | To download the nvm installation script from the project's GitHub page, you can use curl. Note that the version number may differ from what is highlighted here: 33 | 34 | ``` 35 | curl -sL https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh -o install_nvm.sh 36 | ``` 37 | 38 | Inspect the installation script with nano: 39 | 40 | ``` 41 | nano install_nvm.sh 42 | ``` 43 | 44 | Run the script with bash: 45 | 46 | ``` 47 | bash install_nvm.sh 48 | ``` 49 | 50 | It will install the software into a subdirectory of your home directory at ~/.nvm. It will also add the necessary lines to your ~/.profile file to use the file. 51 | 52 | To gain access to the nvm functionality, you'll need to either log out and log back in again or source the ~/.profile file so that your current session knows about the changes: 53 | 54 | ``` 55 | source ~/.profile 56 | ``` 57 | 58 | With nvm installed, you can install isolated Node.js versions. For information about the versions of Node.js that are available, type: 59 | 60 | ``` 61 | nvm ls-remote 62 | ``` 63 | 64 | Then you can use nvm to install the node version you need 65 | 66 | ``` 67 | nvm use 68 | ``` 69 | 70 | 71 | ### On Mac via homebrew: 72 | 73 | ``` 74 | brew install npm 75 | brew install nvm 76 | ``` 77 | 78 | ## Build the widget 79 | 80 | ``` 81 | cd 82 | npm install -g grunt-cli 83 | npm install -g webpack 84 | npm install -g bower 85 | npm install -g gulp 86 | npm install preact 87 | npm install 88 | npm run-script build 89 | ``` 90 | 91 | 92 | ## Installation & Setup 93 | 94 | The BotMan Web Widget is a frontend widget to use in combination with the [Web Driver](/__version__/driver-web). Make sure you install the web driver first, before you add the web widget to your website. 95 | 96 | ### Usage with BotMan Studio 97 | 98 | If you use BotMan Studio - using the web widget could not be simpler. It already includes the web driver which comes with a view and route to use in combination with the web widget. 99 | Simply add the Javascript snippet to your website: 100 | 101 | ```html 102 | 103 | ``` 104 | 105 | That's it. You will now see a message icon in the bottom right corner. When you click it, it will open the chat widget. 106 | 107 | > {callout-info} The script is now loading the chat iFrame from the `botman/chat` endpoint, which is automatically being added by the web-driver. 108 | 109 | ### Usage without BotMan Studio 110 | 111 | If you are not using BotMan Studio and want to make use of the BotMan web widget, there are 2 steps involved. 112 | 113 | #### Chat Frame 114 | When you open the web widget, it will load an iframe containing the chat area. In order to load this iframe, create a URL / route that is accessible from your application and contains the chat frame sourcecode: 115 | 116 | ```html 117 | 118 | 119 | 120 | BotMan Widget 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | ``` 130 | 131 | #### Widget 132 | Next you need to add the widget to your website and tell it to use the chat frame URL that you just created. 133 | Simply add the Javascript to your website and configure it using a global config object. Place the URL that you created for the chat frame in the `frameEndpoint` configuration key. 134 | 135 | 136 | ```html 137 | 142 | 143 | ``` 144 | 145 | 146 | ## Configuration & Customization 147 | 148 | When adding the widget to your own website, you probably want to customize the look of the widget, the title that get's displayed in the widget bar, background images etc. 149 | That's why the web widget comes with a detailed set of configuration options. 150 | 151 | To apply these options to your widget, just declare an option called `botmanWidget` before loading the widget's Javascript. 152 | 153 | The UI of the chat widget itself can simply be customized via CSS - take a look at the [default CSS](https://github.com/botman/web-widget/blob/master/src/assets/css/chat.css) to see the available selectors. 154 | 155 | ### Available settings 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 170 | 173 | 176 | 177 | 178 | 181 | 184 | 187 | 188 | 189 | 192 | 195 | 198 | 199 | 200 | 203 | 206 | 209 | 210 | 211 | 214 | 217 | 220 | 221 | 222 | 225 | 228 | 231 | 232 | 233 | 236 | 239 | 242 | 243 | 244 | 247 | 250 | 253 | 254 | 255 | 258 | 261 | 264 | 265 | 266 | 269 | 272 | 275 | 276 | 277 | 280 | 283 | 286 | 287 | 288 | 291 | 294 | 297 | 298 | 299 | 302 | 305 | 308 | 309 | 310 | 313 | 316 | 319 | 320 | 321 | 324 | 327 | 330 | 331 | 332 | 335 | 338 | 341 | 342 | 343 | 346 | 349 | 352 | 353 | 354 | 357 | 360 | 363 | 364 | 365 | 368 | 371 | 374 | 375 | 376 |
KeyDefaultDescription
168 |
chatServer
169 |
171 |
/botman
172 |
174 | The URL of the BotMan route / server to use. 175 |
179 |
frameEndpoint
180 |
182 |
/botman/chat
183 |
185 | The location of your chat frame URL / route. 186 |
190 |
timeFormat
191 |
193 |
HH:MM
194 |
196 | Time format to use 197 |
201 |
dateTimeFormat
202 |
204 |
m/d/yy HH:MM
205 |
207 | Date-Time format to use 208 |
212 |
title
213 |
215 |
BotMan Widget
216 |
218 | The title to use in the widget. 219 |
223 |
introMessage
224 |
226 |
null
227 |
229 | This is a welcome message that every new user sees when the widget is opened for the first time. 230 |
234 |
placeholderText
235 |
237 |
Send a message...
238 |
240 | Input placeholder text 241 |
245 |
displayMessageTime
246 |
248 |
true
249 |
251 | Determine if message times should be shown 252 |
256 |
mainColor
257 |
259 |
#408591
260 |
262 | The main color used in the widget header. 263 |
267 |
bubbleBackground
268 |
270 |
#408591
271 |
273 | The color to use for the bubble background. 274 |
278 |
bubbleAvatarUrl
279 |
281 |

282 |         
284 | The image url to use in the chat bubble. 285 |
289 |
desktopHeight
290 |
292 |
450
293 |
295 | Height of the opened chat widget on desktops. 296 |
300 |
desktopWidth
301 |
303 |
370
304 |
306 | Width of the opened chat widget on desktops. 307 |
311 |
mobileHeight
312 |
314 |
100%
315 |
317 | Height of the opened chat widget on mobile. 318 |
322 |
mobileWidth
323 |
325 |
300
326 |
328 | Width of the opened chat widget on mobile. 329 |
333 |
videoHeight
334 |
336 |
160
337 |
339 | Height to use for embedded videos. 340 |
344 |
aboutLink
345 |
347 |
https://botman.io
348 |
350 | Link used for the "about" section in the widget footer. 351 |
355 |
aboutText
356 |
358 |
Powered by BotMan
359 |
361 | Text used for the "about" section in the widget footer. 362 |
366 |
userId
367 |
369 |

370 |         
372 | Optional user-id that get's sent to BotMan. If no ID is given, a random id will be generated on each page-view. 373 |
377 | 378 | 379 | ## API 380 | 381 | The web widget also comes with an API to programatically send messages from the user or chatbot. You might use this feature when the user clicks on a button on your website to instantly trigger the chatbot, without having the user to type something. 382 | Once the chat widget is initialized, you can access it's API on the `botmanChatWidget` object that get's exposed to the window containing the chat widget. 383 | 384 | ### Available Methods 385 | 386 | 387 | 388 | 389 | 390 | 391 | 392 | 393 | 394 | 395 | 396 | 399 | 402 | 405 | 406 | 407 | 410 | 413 | 416 | 417 | 418 | 421 | 424 | 427 | 428 | 429 | 432 | 435 | 438 | 439 | 440 | 443 | 446 | 449 | 450 | 451 | 454 | 457 | 460 | 461 | 462 |
MethodDescription
397 |
botmanChatWidget.open()
398 |
400 | Open the chat widget. 401 | 403 | Try out 404 |
408 |
botmanChatWidget.close()
409 |
411 | Close the chat widget. 412 | 414 | Try out 415 |
419 |
botmanChatWidget.toggle()
420 |
422 | Toggle the chat widget. 423 | 425 | Try out 426 |
430 |
botmanChatWidget.say(text)
431 |
433 | Say something on behalf of the user.
The given text is visible in the widget. 434 |
436 | Try out 437 |
441 |
botmanChatWidget.whisper(text)
442 |
444 | Similar to say, with the difference that the text is not visible. 445 | 447 | Try out 448 |
452 |
botmanChatWidget.sayAsBot(text)
453 |
455 | Say something on behalf of the chatbot.
The text is visible in the widget. 456 |
458 | Try out 459 |
463 | -------------------------------------------------------------------------------- /driver-facebook-messenger.md: -------------------------------------------------------------------------------- 1 | # Facebook Messenger 2 | 3 | - [Installation & Setup](#installation-setup) 4 | - [Supported Features](#supported-features) 5 | - [Sending Facebook Templates](#sending-facebook-templates) 6 | - [Supported Events](#supported-events) 7 | - [Optin and Referral Events](#optin-referral) 8 | - [Built-in Natural Language Processing](#builtin-nlp) 9 | - [Studio Features](#studio-features) 10 | - [Get Started Command](#get-started-command) 11 | - [Greeting Text Command](#greeting-text-command) 12 | - [Persistent Menu Command](#persistent-menu-command) 13 | - [Whitelist Domains Command](#whitelist-domains-command) 14 | - [Configure Natural Language Processing](#configure-nlp) 15 | 16 | Facebook Messenger is the biggest Messenger out there and therefor a great choice for building a chatbot. There are more than 1 Billion active users per month. 17 | 18 | > {callout-video} Visual learner? Take a look at the [BuildAChatbot Facebook Tutorial](https://buildachatbot.io/video/install-facebook-driver) 19 | 20 | 21 | ## Installation & Setup 22 | 23 | First you need to pull in the Facebook Driver. 24 | 25 | ```sh 26 | composer require botman/driver-facebook 27 | ``` 28 | 29 | Then load the driver before creating the BotMan instance (**only when you don't use BotMan Studio**): 30 | 31 | ```php 32 | DriverManager::loadDriver(\BotMan\Drivers\Facebook\FacebookDriver::class); 33 | 34 | // Create BotMan instance 35 | BotManFactory::create($config); 36 | ``` 37 | 38 | Or if you use BotMan Studio: 39 | 40 | ```sh 41 | php artisan botman:install-driver facebook 42 | ``` 43 | Next you need to add to your .env file the following entries (only if you're using BotMan Studio): 44 | 45 | ``` 46 | FACEBOOK_TOKEN=your-facebook-page-token 47 | FACEBOOK_VERIFICATION=your-facebook-verification-token 48 | FACEBOOK_APP_SECRET=your-facebook-app-secret 49 | ``` 50 | 51 | This driver requires a valid and secure URL in order to set up webhooks and receive events and information from the chat users. This means your application should be accessible through an HTTPS URL. 52 | 53 | > {callout-info} [ngrok](https://ngrok.com/) is a great tool to create such a public HTTPS URL for your local application. If you use Laravel Valet, you can create it with "valet share" as well. 54 | 55 | To connect BotMan with Facebook Messenger, you first need to follow the [official quick start guide](https://developers.facebook.com/docs/messenger-platform/guides/quick-start) to create your Facebook Messenger application and retrieve an access token as well as an app secret. Switch both of them with the dummy values in your BotMan `.env` file. 56 | 57 | 58 | If you don't use BotMan Studio, add these lines to the $config array that you pass when you create the object from BotManFactory. 59 | ```php 60 | 'facebook' => [ 61 | 'token' => 'YOUR-FACEBOOK-PAGE-TOKEN-HERE', 62 | 'app_secret' => 'YOUR-FACEBOOK-APP-SECRET-HERE', 63 | 'verification'=>'MY_SECRET_VERIFICATION_TOKEN', 64 | ] 65 | ``` 66 | 67 | After that you can setup the webhook, which connects the Facebook application with your BotMan application. This is covered in the above mentioned Quick Start Guide as well, as connecting your Facebook application to a Facebook page. 68 | 69 | 70 | 71 | ## Supported Features 72 | This is a list of features that the driver supports. 73 | If a driver does not support a specific action, it is in most cases a limitation from the messaging service - not BotMan. 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 |
FeatureSupported?
Question Buttons
Image Attachment
Video Attachment
Audio Attachment
Location Attachment
105 | 106 | 107 | ## Sending Facebook Templates 108 | 109 | BotMan supports all the main [Facebook templates](https://developers.facebook.com/docs/messenger-platform/send-api-reference/templates) like `Button`, `Generic`, `List`, `Receipt`, `OpenGraph` and `Airline`. All of them are available through an expressive and easy API. 110 | 111 | > {callout-info} Facebook is still experimenting a lot with its Messenger features. This is why some of them behave differently on certain platforms. General it is easy to say that all of them work within the native Messenger on your phones. But e.g. the List Template cover image is not working inside the Facebook website chat and the online Messenger. 112 | 113 | ### Button Template 114 | 115 | Facebook Button Template Screenshot 116 | 117 | A [`Button Template`](https://developers.facebook.com/docs/messenger-platform/send-messages/template/button) is a text with several user input options. (buttons) The template uses `ElementButtons` which are different from the buttons you use for BotMan `Questions`. There are two types of ElementButtons. The default one is the `web_url` button which only needs an `url` next to the title. It links to an external website. Secondly we have `postback` buttons. They will trigger [Facebook postback actions](https://developers.facebook.com/docs/messenger-platform/webhook-reference/postback). They require the type `postback` and a `payload which is the text that Facebook will send to BotMan` when a user hits this button. If you use the ask method within a [Conversation](/__version__/conversations), you will be able to get the postback button's text with `$answer->getText()`. 118 | 119 | ```php 120 | $bot->reply(ButtonTemplate::create('Do you want to know more about BotMan?') 121 | ->addButton(ElementButton::create('Tell me more') 122 | ->type('postback') 123 | ->payload('tellmemore') 124 | ) 125 | ->addButton(ElementButton::create('Show me the docs') 126 | ->url('http://botman.io/') 127 | ) 128 | ); 129 | ``` 130 | 131 | ### Generic Template 132 | 133 | Facebook Generic Template Screenshot 134 | 135 | A [`Generic Template`](https://developers.facebook.com/docs/messenger-platform/send-messages/template/generic) is a horizontal scrollable carousel of elements. Every element requires at least a title which is provided through the static `create` method. Additionally it can have a `subtitle`, `image` and `buttons`. 136 | 137 | ```php 138 | $bot->reply(GenericTemplate::create() 139 | ->addImageAspectRatio(GenericTemplate::RATIO_SQUARE) 140 | ->addElements([ 141 | Element::create('BotMan Documentation') 142 | ->subtitle('All about BotMan') 143 | ->image('http://botman.io/img/botman-body.png') 144 | ->addButton(ElementButton::create('visit') 145 | ->url('http://botman.io') 146 | ) 147 | ->addButton(ElementButton::create('tell me more') 148 | ->payload('tellmemore') 149 | ->type('postback') 150 | ), 151 | Element::create('BotMan Laravel Starter') 152 | ->subtitle('This is the best way to start with Laravel and BotMan') 153 | ->image('http://botman.io/img/botman-body.png') 154 | ->addButton(ElementButton::create('visit') 155 | ->url('https://github.com/mpociot/botman-laravel-starter') 156 | ), 157 | ]) 158 | ); 159 | ``` 160 | 161 | ### List Template 162 | 163 | Facebook List Template Screenshot 164 | 165 | The [`List Template`](https://developers.facebook.com/docs/messenger-platform/send-messages/template/list) is a template that allows you to present a set of elements vertically. The default list will set the first element as a cover image. If you don't want a cover image call the `useCompactView()` method. Additionally to the elements your list can have one global button too. This is when you need the `addGlobalButton(...)` method. 166 | 167 | ```php 168 | $bot->reply(ListTemplate::create() 169 | ->useCompactView() 170 | ->addGlobalButton(ElementButton::create('view more') 171 | ->url('http://test.at') 172 | ) 173 | ->addElement(Element::create('BotMan Documentation') 174 | ->subtitle('All about BotMan') 175 | ->image('http://botman.io/img/botman-body.png') 176 | ->addButton(ElementButton::create('tell me more') 177 | ->payload('tellmemore') 178 | ->type('postback') 179 | ) 180 | ) 181 | ->addElement(Element::create('BotMan Laravel Starter') 182 | ->subtitle('This is the best way to start with Laravel and BotMan') 183 | ->image('http://botman.io/img/botman-body.png') 184 | ->addButton(ElementButton::create('visit') 185 | ->url('https://github.com/mpociot/botman-laravel-starter') 186 | ) 187 | ) 188 | ); 189 | ``` 190 | 191 | ### Receipt Template 192 | 193 | Facebook Receipt Template Screenshot 194 | 195 | Use the [`Receipt Template`](https://developers.facebook.com/docs/messenger-platform/send-messages/template/receipt) to send a order confirmation, with the transaction summary and description for each element. This template differs a lot from the others. This is why there are custom `ReceiptElements` and lots of other custom fields. Checkout the official [Facebook documentation](https://developers.facebook.com/docs/messenger-platform/send-api-reference/receipt-template) and the example below to see all the possibilities. In your Messenger you can click the template to see all of the information. 196 | 197 | ```php 198 | $bot->reply(ReceiptTemplate::create() 199 | ->recipientName('Christoph Rumpel') 200 | ->merchantName('BotMan GmbH') 201 | ->orderNumber('342343434343') 202 | ->timestamp('1428444852') 203 | ->orderUrl('http://test.at') 204 | ->currency('USD') 205 | ->paymentMethod('VISA') 206 | ->addElement(ReceiptElement::create('T-Shirt Small') 207 | ->price(15.99) 208 | ->image('http://botman.io/img/botman-body.png') 209 | ) 210 | ->addElement(ReceiptElement::create('Sticker') 211 | ->price(2.99) 212 | ->image('http://botman.io/img/botman-body.png') 213 | ) 214 | ->addAddress(ReceiptAddress::create() 215 | ->street1('Watsonstreet 12') 216 | ->city('Bot City') 217 | ->postalCode(100000) 218 | ->state('Washington AI') 219 | ->country('Botmanland') 220 | ) 221 | ->addSummary(ReceiptSummary::create() 222 | ->subtotal(18.98) 223 | ->shippingCost(10 ) 224 | ->totalTax(15) 225 | ->totalCost(23.98) 226 | ) 227 | ->addAdjustment(ReceiptAdjustment::create('Laravel Bonus') 228 | ->amount(5) 229 | ) 230 | ); 231 | ``` 232 | 233 | ### Media Template 234 | 235 | Facebook Media Template Screenshot 236 | 237 | You can use the [`Media Template`](https://developers.facebook.com/docs/messenger-platform/send-messages/template/media) to send images or videos with optional buttons. Here is an example on how to send an image with an attachment ID. 238 | 239 | ```php 240 | $bot->reply(MediaTemplate::create() 241 | ->element(MediaAttachmentElement::create('image') 242 | ->attachmentId('1543527005693234') 243 | ->addButton(ElementButton::create('Tell me more') 244 | ->type('postback') 245 | ->payload('Tell me more') 246 | ) 247 | ->addButton(ElementButton::create('Documentation') 248 | ->url('https://botman.io/') 249 | ) 250 | ) 251 | ); 252 | ``` 253 | And here is an example on how to send a video. 254 | 255 | ```php 256 | $bot->reply(MediaTemplate::create() 257 | ->element(MediaUrlElement::create('video') 258 | ->url('https://www.facebook.com/liechteneckers/videos/10155225087428922/') 259 | ->addButtons([ 260 | ElementButton::create('Web URL')->url('http://liechtenecker.at'), 261 | ElementButton::create('payload')->type('postback')->payload('test'), 262 | ]) 263 | ) 264 | ); 265 | ``` 266 | You probably have noticed that the main Template is the same for images or videos. (`MediaTemplate`) With the element you decide the attachment type. But you also decide if you send the attachment with the attachment ID or an Facebook URL. Checkout the official [Facebook documentation](https://developers.facebook.com/docs/messenger-platform/send-messages/template/media) for more information. 267 | 268 | ### OpenGraph Template 269 | 270 | You can use the [`OpenGraph Template`](https://developers.facebook.com/docs/messenger-platform/send-messages/template/open-graph) to send a structured message with an open graph url and a button (optional). 271 | 272 | ```php 273 | $bot->reply(OpenGraphTemplate::create() 274 | ->addElement(OpenGraphElement::create()->url('https://example.com')) 275 | ->addElements([ 276 | OpenGraphElement::create()->url('https://example.com'), 277 | OpenGraphElement::create()->url('https://example.com'), 278 | ]) 279 | ); 280 | ``` 281 | 282 | ### AirlineBoardingPass Template 283 | 284 | You can use the [`AirlineBoardingPass Template`](https://developers.facebook.com/docs/messenger-platform/send-messages/template/airline) to send boarding pass with travel's details (flight number, departure airport, arrival airport, flight schedule). 285 | 286 | ```php 287 | $bot->reply( 288 | AirlineBoardingPassTemplate::create( 289 | 'You are checked in.', 290 | 'en_US', 291 | [ 292 | AirlineBoardingPass::create( 293 | 'Jones Farbound', 294 | 'CG4X7U', 295 | 'https://www.example.com/en/logo.png', 296 | 'M1JONES FARBOUND CG4X7U nawouehgawgnapwi3jfa0wfh', 297 | 'https://www.example.com/en/PLAT.png', 298 | AirlineFlightInfo::create( 299 | 'c001', 300 | AirlineAirport::create('SFO', 'San Francisco'), 301 | AirlineAirport::create('SLC', 'Salt Lake City'), 302 | AirlineFlightSchedule::create('2016-01-02T19:45') 303 | ) 304 | ), 305 | ] 306 | ) 307 | ->themeColor('#FF0000') 308 | ); 309 | ``` 310 | 311 | ### AirlineCheckInTemplate Template 312 | 313 | You can use the [`AirlineCheckIn Template`](https://developers.facebook.com/docs/messenger-platform/send-messages/template/airline) to send check in informations (flight number, departure airport, arrival airport, flight schedule). 314 | 315 | ```php 316 | $bot->reply( 317 | AirlineCheckInTemplate::create( 318 | 'Check-in is available now.', 319 | 'en_US', 320 | 'ABCDEF', 321 | [ 322 | AirlineFlightInfo::create( 323 | 'c001', 324 | AirlineAirport::create('SFO', 'San Francisco'), 325 | AirlineAirport::create('SLC', 'Salt Lake City'), 326 | AirlineFlightSchedule::create('2016-01-02T19:45') 327 | ), 328 | ], 329 | 'https://www.airline.com/check-in' 330 | ) 331 | ->themeColor('#FF0000') 332 | ); 333 | ``` 334 | 335 | ### AirlineItinerary Template 336 | 337 | You can use the [`AirlineItinerary Template`](https://developers.facebook.com/docs/messenger-platform/send-messages/template/airline) to send flight itinerary's details (passengers information, flight details). 338 | 339 | ```php 340 | $bot->reply( 341 | AirlineItineraryTemplate::create( 342 | 'Here\'s your flight itinerary.', 343 | 'en_US', 344 | 'ABCDEF', 345 | [ 346 | AirlinePassengerInfo::create('p001', 'Farbound Smith Jr'), 347 | ], 348 | [ 349 | AirlineExtendedFlightInfo::create( 350 | 'c001', 351 | 's001', 352 | 'KL9123', 353 | AirlineAirport::create('SFO', 'San Francisco'), 354 | AirlineAirport::create('SLC', 'Salt Lake City'), 355 | AirlineFlightSchedule::create('2016-01-02T19:45'), 356 | Airline::TRAVEL_TYPE_FIRST_CLASS 357 | ), 358 | ], 359 | [ 360 | AirlinePassengerSegmentInfo::create('s001', 'p001', '12A', 'Business'), 361 | ], 362 | '14003', 363 | 'USD' 364 | ) 365 | ->themeColor('#FF0000') 366 | ->addPriceInfo('Fuel surcharge', '1597', 'USD') 367 | ->basePrice('12206') 368 | ->tax('200') 369 | ); 370 | ``` 371 | 372 | ### AirlineUpdate Template 373 | 374 | You can use the [`AirlineUpdate Template`](https://developers.facebook.com/docs/messenger-platform/send-messages/template/airline) to send an update regarding a flight (reason, updated flight informations). 375 | 376 | ```php 377 | $bot->reply( 378 | AirlineUpdateTemplate::create( 379 | Airline::UPDATE_TYPE_DELAY, 380 | 'en_US', 381 | 'CF23G2', 382 | AirlineFlightInfo::create( 383 | 'c001', 384 | AirlineAirport::create('SFO', 'San Francisco'), 385 | AirlineAirport::create('SLC', 'Salt Lake City'), 386 | AirlineFlightSchedule::create('2016-01-02T19:45') 387 | ) 388 | ) 389 | ->themeColor('#FF0000') 390 | ->introMessage('Your flight is delayed') 391 | ); 392 | ``` 393 | 394 | 395 | ## Supported Events 396 | 397 | The BotMan Facebook driver supports listening for the following events: 398 | ``` 399 | - messaging_checkout_updates 400 | - messaging_deliveries 401 | - messaging_optins 402 | - messaging_reads 403 | - messaging_referrals 404 | ``` 405 | 406 | 407 | ## Optin and Referral Events 408 | 409 | To react to Optin or Referral events, use the following event syntax: 410 | 411 | ```php 412 | $botman->on('messaging_referrals', function($payload, $bot) { 413 | 414 | }); 415 | 416 | $botman->on('messaging_optins', function($payload, $bot) { 417 | 418 | }); 419 | ``` 420 | 421 | You can find more details about M.me Links in the [official documentation](https://developers.facebook.com/docs/messenger-platform/discovery/m-me-links). 422 | 423 | 424 | ## Built-in Natural Language Processing 425 | 426 | Facebook Messenger comes with an integrated [Natural Language Processing](https://developers.facebook.com/docs/messenger-platform/built-in-nlp/) tool that you can enable for your Facebook page, if you want. 427 | Whenever a message contains one or more natural language processing entities that Facebook knows - such as greetings, datetimes or saying goodbye - the message will contain an extra array called "nlp". 428 | You may access this array using the `getExtras` method on the incoming message object like this: 429 | 430 | ```php 431 | $entities = $message->getExtras('nlp'); 432 | ``` 433 | 434 | If there are no NLP entities added to the message, this method will return `NULL`. You can take a look at the official [Facebook NLP documentation](https://developers.facebook.com/docs/messenger-platform/built-in-nlp/#handling_entities) to find out more about Facebook NLP entities and how they are structured. 435 | 436 | 437 | ## Studio Features 438 | 439 | 440 | ### Get Started Command 441 | 442 | Adding a [Get Started](https://developers.facebook.com/docs/messenger-platform/messenger-profile/get-started-button) button resolves the issue of users not knowing what to write to break the ice with your bot. It is displayed the first time the user interacts with a Facebook chatbot. When you click it, it will send a payload (text) to BotMan and you can react to it and send the first welcome message to the user and tell him how to use your bot. In order to define this payload you need to send a CURL with some data to Facebook. But BotMan Studio can do that for you too! 443 | 444 | First define the payload text in your `config/botman/facebook.php` file. 445 | 446 | ```php 447 | 'start_button_payload' => 'YOUR_PAYLOAD_TEXT' 448 | ``` 449 | 450 | Then run the artisan command: 451 | ```sh 452 | php artisan botman:facebook:AddStartButton 453 | ``` 454 | 455 | This will add the Get Started button to your page's chat. You are now able to listen to this button with the payload in your `hears` method. 456 | 457 | ```php 458 | $botman->hears('YOUR_PAYLOAD_TEXT', function (BotMan $bot) { 459 | ... 460 | }); 461 | ``` 462 | 463 | 464 | ### Greeting Text Command 465 | 466 | The [Facebook Greeting](https://developers.facebook.com/docs/messenger-platform/messenger-profile/greeting-text) text is shown on the welcome screen when a user interacts with your bot the first time. (like the Get Started Button) 467 | 468 | Define this text in your `config/botman/facebook.php` file. Then use the Artisan command to trigger the command: 469 | 470 | ```sh 471 | php artisan botman:facebook:AddGreetingText 472 | ``` 473 | 474 | 475 | ### Persistent Menu Command 476 | 477 | With BotMan Studio it now gets much easier to add a [Persistent Facebook Menu](https://developers.facebook.com/docs/messenger-platform/messenger-profile/persistent-menu) to your bot. First define the structure and types of your menu in your `config/botman/facebook.php` file. There you will find a `persistent_menu` demo menu payload. Just edit it to your needs. 478 | 479 | Then use the Artisan command to trigger the command: 480 | 481 | ```sh 482 | php artisan botman:facebook:AddMenu 483 | ``` 484 | 485 | 486 | ### Whitelist Domains Command 487 | 488 | Some features like Messenger Extensions and Checkbox Plugin require a bot to specify a [domain whitelist](https://developers.facebook.com/docs/messenger-platform/messenger-profile/domain-whitelisting). 489 | 490 | Define all domains in your `config/botman/facebook.php` file. Then use the Artisan command to trigger the command: 491 | 492 | ```sh 493 | php artisan botman:facebook:whitelistDomains 494 | ``` 495 | 496 | 497 | ### Configure Natural Language Processing 498 | 499 | Facebook Messenger comes with an integrated [Natural Language Processing](https://developers.facebook.com/docs/messenger-platform/built-in-nlp/) tool that you can enable or disable using the BotMan Studio command. 500 | 501 | ```sh 502 | php artisan botman:facebook:nlp 503 | ``` 504 | 505 | If you want to disable the NLP feature for your Facebook page, you may use the `--disable` option: 506 | 507 | ```sh 508 | php artisan botman:facebook:nlp --disable 509 | ``` 510 | --------------------------------------------------------------------------------