Create simple chatbots with Laravel and BotMan under 5 minutes

Rahman Ardian
SkyshiDigital
Published in
4 min readApr 27, 2017
Chatbots will dominate social media (Source: TechCrunch)

Chatbots is so popular today, growing faster from year by year, many companies now have their own bots. Bots has two type, first type is virtual assistant and second is messaging apps. Virtual assistant is powered by machine learning, so they can keep your information and learn from your pattern, whereas messaging apps is only capable of interacting with users by following pre-programmed rules. In this tutorial, we will create simple chatbots messaging apps in telegram platform.

To create telegram bot we can register our bot by calling @BotFather account.

Click on /newbot command to create a new bot. For example, I create “Xchange Rate Bot” with username “XchangeRateBot”.

After successfully create bot, you will get your own token access. Save your token into your secret place.

Next step, we build backend system. I prefer to use Laravel framework. Then, we need additional package to create bot easily. So, I decide to choose BotMan. BotMan is a framework agnostic PHP library that is designed to simplify the task of developing innovative bots for multiple messaging platforms. BotMan has multiple support, such as telegram, messenger, slack, nexmo, hipchat, wechat, and microsoft bot framework. BotMan comes with boilerplate project in laravel. First thing, create project with this command.

$ composer create-project mpociot/botman-laravel-starter currencybot

To ensure botman is run, check your bot with this command.

$ php artisan botman:tinker

Then type test and you will see hello! response from your bot. Here’s the sample output of the program.

$ php artisan botman:tinker
You: test
BotMan: hello!

Yeah, you already build your own bot. The bot logic for botman tinker can be found in the routes/botman.php file. To make our bot more useful we need to find some public API. Thanks to Todd Motto who has created lists of public API, let’s go to https://github.com/toddmotto/public-apis. Because we create exchange rates bot, I choose fixer.io API. Go to http://fixer.io/ to see more example.

Next, setup your .env file, add your telegram token that you’ve created before.

TELEGRAM_TOKEN=YOUR_TELEGRAM_TOKEN

Open your BotManController.php file, to create new pattern add hears method and add your pattern, to make response of your pattern, add reply method. Let’s see the example below.

$botman->hears('Hello', function (BotMan $bot) {
$bot->reply('Hi there :)');
});

When you type hello to your bot, you will get response Hi there :) . If you type another word, you won’t see anything. BotMan comes with fallback method, this method will 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.

$botman->fallback(function($bot) {
$bot->reply('Sorry, I did not understand these commands.');
});

To make your bot feel and act more human, you can make it send “typing …” indicators by add types method before the reply method.

$botman->hears('Hello', function (BotMan $bot) {
$bot->types();
$bot->reply('Hi there :)');
});

Sometimes, we need to capture parameter from users input, in botman you can define command parameter like this.

$botman->hears('hello, I'm {name}', function ($bot, $name) {
$bot->reply('Hello '.$name.', nice to meet you!');
});

Fixer.io default rate is EURO based, but we can change base rate via query parameter http://api.fixer.io/latest?base={currency_name}. So, we can capture user currency rate with botman command parameter.

$botman->hears('Give me {currency} rates', function ($bot, $currency) {
$bot->types();
//Get Data From API
$bot->reply('Results');
});

To get data from API, we can handle API with Guzzle library that already exists in your laravel project. Create new method inside BotManController.php named getCurrency() with parameter currency code.

public function getCurrency($currency) {
$client = new Client();
$uri = 'http://api.fixer.io/latest?base='.$currency;
$response = $client->get($uri);
$results = json_decode($response->getBody()->getContents());

$date = date('d F Y', strtotime($results->date));
$data = "Here's the exchange rates based on ".$currency." currency\nDate: ".$date."\n";
foreach($results->rates as $k => $v) {
$data .= $k." - ".$v."\n";
}

return $data;
}

Call getCurrency method before reply method.

$botman->hears('Give me {currency} rates', function ($bot, $currency) {
$bot->types();
$results = $this->getCurrency($currency);
$bot->reply($results);
});

Here’s the complete source code for BotManController.php

Done! Now run your development server.

$ php artisan serve
Laravel development server started on http://127.0.0.1:8000/

Then, install ngrok to make your own server. Run your ngrok server on port 8000 (Laravel default development port).

$ ngrok http 8000

After ngrok run, connect your bot with telegram hook. Make sure you choose ngrok https, because telegram bot only run in https.

$ curl -X POST -F 'url=https://YOUR_NGROK_URL/botman' https://api.telegram.org/botYOUR_TELEGRAM_TOKEN/setWebhook

You will get response like this.

{"ok":true,"result":true,"description":"Webhook is already set"}

The hook successfully set. And then type “Give me {Currency Code} rates”, here’s the result:

It’s so easy right? You can deploy your project into heroku and enjoy your own bot.

--

--

Rahman Ardian
SkyshiDigital

Full time remote worker. Interest in technology and education. Loves cycling and archery. Ph.D Wannabe!