📜 ⬆️ ⬇️

Chat bot development for Bitrix24

My previous article on the development of a chat bot for Facebook Messenger showed that the topic is interesting to the inhabitants of Habr, so I continue.
Today we will have a bot development for the Bitrix24 messenger. The development language is the same - PHP.

general information


The platform for chat-bots Bitrkis24 appeared at the end of March of this year.
At the time of writing the bot, GitHub did not have a PHP library, so I wrote my own - github.com/pimax/bitrix24-bot-php

Write the code


The easiest option is to clone the repository github.com/pimax/bitrix24-bot-php-example

git clone https://github.com/pimax/bitrix24-bot-php-example.git . composer install cp config_example.php config.php 

Open the config.php for editing and fill in the information about your bot.
I will not dwell here in detail so as not to inflate the article, each parameter is supplied with a comment.
')
Let me explain in more detail the main part of the demo-bot.
In total, Bitrix24 transmits 4 types of events to the webhook:

ONAPPINSTALL - Installing the bot on the portal


 $bot->install(new Bot( $config['alias'], $config['type'], $config['url_message_add'], $config['url_welcome_message'], $config['url_bot_delete'], $config['data'] )); 

Everything here is elementary - we take the data from the config of our application and register the bot on the portal.
This code is unlikely to change with you.

ONIMBOTDELETE - Remove the bot


 $bot->uninstall(); 

Remove the bot from the portal.
Similar to the previous one, it is unlikely to change.

ONIMBOTJOINCHAT - Inviting a bot to chat


 $bot->send(new Message("Hello", $_REQUEST['data']['PARAMS']['DIALOG_ID'], [ new Message('[send=/command1]Command 1[/send]'), new Message('[send=/command2]Command 2[/send]'), new Message('[send=/command3]Command 3[/send]'), ])); 

Here options are already possible. A good tone is the behavior in which in the first message the bot will report its commands to the user. To prevent the user from entering commands manually, Bitrix24 provided the [send] code, which sends a message to the bot when clicking on a link.

This is how it looks like:



ONIMBOTMESSAGEADD - Receiving a message from a user


The main type for us.
In it, we must understand what the user wants from the bot, prepare an answer, and send a response to the user.

 switch ($_REQUEST['data']['PARAMS']['MESSAGE']) { case '/command1': $bot->send(new Message("Command 1 response", $_REQUEST['data']['PARAMS']['DIALOG_ID'])); break; case '/command2': $bot->send(new Message("Command 2 response", $_REQUEST['data']['PARAMS']['DIALOG_ID'])); break; case '/command3': $bot->send(new Message("Command 3 response", $_REQUEST['data']['PARAMS']['DIALOG_ID'])); break; default: $bot->send(new Message("Hello", $_REQUEST['data']['PARAMS']['DIALOG_ID'], [ new Message('[send=/command1]Command 1[/send]'), new Message('[send=/command2]Command 2[/send]'), new Message('[send=/command3]Command 3[/send]'), ])); } 

This code processes three commands, and in case the user has sent something else, it will again display a list of available commands.

Application Placement


Go to the section Applications> Add application of your portal.

Specify the name of the application, tick the "Application uses only API".
In the access rights, we note “Creating and managing chat bots”.
In the field Specify the link and specify the callback-link for the installation event indicate the link to our bot, for example: example.com/apps/bitrix24
Press the save button.

A real example of Bota for Job4Joy freelance exchange


For the purity of the experiment, we take the same task as in the article about Facebook Messenger and develop a chat bot for the Job4Joy freelance exchange.

So, our goal is to implement a bot, which, at our request, will issue new projects in the appropriate category.
Data will be received via RSS using picoFeed - github.com/fguillot/picoFeed
And github.com/SebastianM/GooglShortener for shortening links.

We perform

 git clone https://github.com/pimax/bitrix24-bot-php-example.git . composer install cp config_example.php config.php 

Next, edit config.php and add the list of feeds and the token for goo.gl:

 'google_token' => '', 'feeds' => [ '/all' => [ 'Title' => 'All jobs', 'Feed' => 'https://job4joy.com/marketplace/rss/' ], '/webdev' => [ 'Title' => 'Web Development', 'Feed' => 'https://job4joy.com/marketplace/rss/?id=3' ], '/software' => [ 'Title' => 'Software Development & IT', 'Feed' => 'https://job4joy.com/marketplace/rss/?id=5' ], '/design' => [ 'Title' => 'Design & Multimedia', 'Feed' => 'https://job4joy.com/marketplace/rss/?id=2' ], '/mobile' => [ 'Title' => 'Mobile Application', 'Feed' => 'https://job4joy.com/marketplace/rss/?id=7' ], '/server' => [ 'Title' => 'Host & Server Management', 'Feed' => 'https://job4joy.com/marketplace/rss/?id=6' ], '/writing' => [ 'Title' => 'Writing', 'Feed' => 'https://job4joy.com/marketplace/rss/?id=8' ], '/customer' => [ 'Title' => 'Customer Service', 'Feed' => 'https://job4joy.com/marketplace/rss/?id=10' ], '/marketing' => [ 'Title' => 'Marketing', 'Feed' => 'https://job4joy.com/marketplace/rss/?id=11' ], '/business' => [ 'Title' => 'Business Services', 'Feed' => 'https://job4joy.com/marketplace/rss/?id=12' ], '/translations' => [ 'Title' => 'Translation & Languages', 'Feed' => 'https://job4joy.com/marketplace/rss/?id=14' ] ] 

Create a file messages / ru.php, with the following contents:

 <?php return [ 'Hello! I can help you with IT projects.' => '!       .', 'find work & hire freelancers' => '   ', 'All jobs' => ' ', 'Web Development' => '-', 'Software Development & IT' => ' ', 'Design & Multimedia' => '  ', 'Mobile Application' => ' ', 'Host & Server Management' => '  ', 'Writing' => '', 'Customer Service' => ' ', 'Marketing' => '', 'Business Services' => ' ', 'Translation & Languages' => '', 'New projects not a found!' => '   !' ]; 

The basic language of our bot is English, but we will also support Russian.

Add the GoogleShortener library connection to index.php:

 require_once (dirname(__FILE__) .'/GooglShortener.php'); $googl = new GooglShortener($config['google_token']); 

Write the logging function immediately:

 /** * Log * * @param mixed $data Data * @param string $title Title * @return bool */ function writeToLog($data, $title = '') { $log = "\n------------------------\n"; $log .= date("Ymd G:i:s") . "\n"; $log .= (strlen($title) > 0 ? $title : 'DEBUG') . "\n"; $log .= print_r($data, 1); $log .= "\n------------------------\n"; file_put_contents(__DIR__ . '/imbot.log', $log, FILE_APPEND); return true; } 

Next, we write the function of the bot's welcome message:

 /** * Send Help Message * * @param $bot Bot instance * @return bool */ function sendHelpMessage($bot) { global $config; $attach = []; foreach ($config['feeds'] as $com => $feed) { $attach[] = new Message('[send='.$com.']'.$bot->t($feed['Title']).'[/send]'); } $bot->send(new Message($bot->t('Hello! I can help you with IT projects.'), $_REQUEST['data']['PARAMS']['DIALOG_ID'], $attach)); return true; } 

Next, write a function to get a list of projects for a specific feed and send messages to the user:

 /** * Get Feed Data * * @param $feed Feed data * @param $bot Bot instance * @return bool */ function getFeed($feed, $bot) { global $googl; try { $reader = new Reader; $resource = $reader->download($feed['Feed']); $parser = $reader->getParser( $resource->getUrl(), $resource->getContent(), $resource->getEncoding() ); $feed = $parser->execute(); $items = array_reverse($feed->getItems()); if (count($items)) { foreach ($items as $itm) { $url = $googl->shorten($itm->getUrl()); $message = substr(strip_tags($itm->getContent()), 0, 150); $bot->send(new Message("[B]".$itm->getTitle() . "[/B]\n" . $message . "\n", $_REQUEST['data']['PARAMS']['DIALOG_ID']), [ new Link($url->id, $url->id) ]); } } else { $bot->send(new Message($bot->t('New projects not a found!'), $_REQUEST['data']['PARAMS']['DIALOG_ID'])); } } catch (Exception $e) { writeToLog($e->getMessage(), 'Exception'); } return true; } 

That's all. The full code is posted on GitHub - github.com/pimax/job4joy_bitrix24bot

Publication in the directory for all


Now the application is available only to users of your portal.
In order to publish applications in the catalog for all, you need to become a 1C-Bitrix partner.
Detailed information on this process is available here - www.bitrix24.ru/apps/dev.php

Conclusion


In general, the platform makes a rather pleasant impression, despite its young age.
The biggest disadvantage for developers is quite a long moderation time. The bill can go for weeks without exaggeration. Perhaps this is due to the heavy load on the moderators and they do not have time. Today, the problem is typical for many messengers.

useful links


  1. An article on 1C-Bitrix about chatbots platform - dev.1c-bitrix.ru/community/blogs/marketplace_apps24/we-present-a-platform-for-chatbots-for-bitrix24.php
  2. Bitrix24 Bot PHP SDK - github.com/pimax/bitrix24-bot-php
  3. Bitrix24 Bot PHP SDK Example - github.com/pimax/bitrix24-bot-php-example
  4. Job4Joy Bot PHP Sources - github.com/pimax/job4joy_bitrix24bot

Source: https://habr.com/ru/post/282077/


All Articles