How to create a Viber bot using PHP
In November 2016, Viber introduced public accounts ( Viber public account , or simply PA). With their release, api has also become available, which allows you to:
- chat with user
- check the status of subscribers (online, offline)
- get information about a specific subscriber
- make entries (posts) on your page
All this allows you to create a pretty good bot, or integrate the bot into an existing project, which may well improve the quality of user interaction. If you have already created bots for telegram or slack, then creating a bot for Viber will not be difficult.
Introduction
Some time ago, I had a need to interact with users of vibe. I would like to introduce typical dialogs with users into my application, and also provide "button dialogs" (in cases where the user sees several buttons under the chat). But at that time there was no open (public) API for this, and had to either refuse or dodge with a rake.
With the release of public accounts (PA), the situation has changed, now we can create a more complete interaction with the "button dialogs" and the "conversions" we need. All this is great, if not one BUT - there is no SDK for PHP (for the sake of justice, there is sdk for nodejs and python ). I decided to fill this gap, and describe how you can create a simple bot in php, and create an SDK in one.
First steps
Before creating a bot, you need to access a special type of account. It may seem strange to you, but at the time of writing this post it is. To do this, go tohttps://www.viber.com/en/public-accounts and fill out the desired form:
In the form you indicate the phone to which access to public accounts will be granted, and after a while you will receive messages of the format "... You now have early access to Public Accounts! ...". After which you need to restart the Viber client and go through the following steps:
Open the "Public Accounts" section (icon in the upper right -
)
Click on "create account" (icon in the lower right -
)
- Fill in the data for your bot (you need a background image, the specified category, name, description, etc.)
At the last step, the choice of the method of working with messages will be available, select "api" and copy the key. (or you can simply look at it on the "edit information" PA screen):
For example, my key will be: 1111111111111111-2222222222222222-3333333333333333
Server side
To develop the bot and work with Viber-API, I use a small SDK: https://github.com/Bogdaan/viber-bot-php . It will allow to omit some details of the interaction with REST-api and build some logic of our bot. Install it:
composer require bogdaan/viber-bot-php
First, we need to register a webhook address - the address at which the Vibera backend will deliver us messages from users and some other events. The web server on which the bot will be located (and accordingly the webhook) must work on https with the correct SSL certificate. A self-signed certificate will not work here, if it is not there, try using letsencrypt.org .
For example, my vebhuk will: https://viber.hcbogdan.com/bot.php
. Create a file setup.php
:
$apiKey ]);
$result = $client->setWebhook($webhookUrl);
echo "Success!\n";
} catch (Exception $e) {
echo "Error: ". $e->getError() ."\n";
}
And register a webhook by executing the file:
$ php setup.php
Success!
Now, when the user sends a message, or enters the chat, requests will be sent to the webhook address. Create a file bot.php
:
';
// так будет выглядеть наш бот (имя и аватар - можно менять)
$botSender = new Sender([
'name' => 'Whois bot',
'avatar' => 'https://developers.viber.com/img/favicon.ico',
]);
try {
$bot = new Bot(['token' => $apiKey]);
$bot
->onConversation(function ($event) use ($bot, $botSender) {
// это событие будет вызвано, как только пользователь перейдет в чат
// вы можете отправить "привествие", но не можете посылать более сообщений
return (new \Viber\Api\Message\Text())
->setSender($botSender)
->setText("Can i help you?");
})
->onText('|whois .*|si', function ($event) use ($bot, $botSender) {
// это событие будет вызвано если пользователь пошлет сообщение
// которое совпадет с регулярным выражением
$bot->getClient()->sendMessage(
(new \Viber\Api\Message\Text())
->setSender($botSender)
->setReceiver($event->getSender()->getId())
->setText("I do not know )")
);
})
->run();
} catch (Exception $e) {
// todo - log exceptions
}
Then it remains to place the file bot.php
so that it is available on https://viber.hcbogdan.com/bot.php
, and go to chat with the bot from the vibe client. If you do not see the bot's answers, then it is worth checking your error_log and access_log for errors.
You can slightly improve the functionality of the bot and add logging. Let's do it with monolog:
composer require monolog/monolog
And add exception logging:
pushHandler(new \Monolog\Handler\StreamHandler('/tmp/bot.log'));
$log->warning('Exception: '. $e->getMessage());
}
All exceptions will come in /tmp/bot.log
.
The basic version of your bot is ready, you can add your own logic, add buttons to the chat, use deep links and html markup - all this is available in the SDK. I created several demos that you can see in the viber chat : // pa? ChatURI = viber-bot-php & context = habrahabr . If you do not have a viber client yet, you can find the chat at this link: viber-bot-php .