Development of a chat bot for Bitrix24

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

general information


The platform for chat bots Bitrkis24 appeared at the end of March this year.
At the time of writing the bot, there was no PHP library in GitHub, so I wrote mine - github.com/pimax/bitrix24-bot-php

Writing a 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 config.php for editing and fill out information about your bot.
I will not dwell in detail here, so as not to inflate the article, each parameter is equipped with a comment.

I’ll explain in more detail the main part of the demo bot.
In total, Bitrix24 transmits 4 types of events to the webhook:

ONAPPINSTALL - Installing a 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 is elementary here - we take data from the config of our application and register the bot on the portal.
This code is unlikely to change with you.

ONIMBOTDELETE - Removing a bot


$bot->uninstall();

We remove the bot from the portal.
Like the previous one, it is unlikely to change.

ONIMBOTJOINCHAT - Invite 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 the options are already possible. A good tone is the behavior in which in the first message the bot will communicate its commands to the user. To prevent the user from entering commands manually, Bitrix24 provided a [send] code that sends a message to the bot when it clicks on the link.

This is how it looks:



ONIMBOTMESSAGEADD - Receive a message from a user


The main type for us.
In it, we must understand what the user wants from the bot, prepare a response, 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 if the user sends something else, it will again display a list of available commands.

Application Placement


Go to Applications> Add an application for your portal.

We indicate the name of the application, check the box "Application uses only API."
In access rights, we note "Creating and managing Chatbots."
In the Specify a link field and specify a callback link for the installation event, specify a link to our bot, for example: example.com/apps/bitrix24
Press the save button.

Real example of a Job4Joy freelance exchange bot


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

So, our goal is to implement a bot that, at our request, will issue new projects in the appropriate category.
We will receive the data via RSS using picoFeed - github.com/fguillot/picoFeed
and github.com/SebastianM/GooglShortener to shorten the links.

We carry out

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 a list of feeds and a 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 messages / ru.php file with the following contents:

 'Привет! Я помогу с проектами в сфере ИТ.',
    '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.

In index.php, add the GoogleShortener library connection:

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

Let's write immediately the logging function:

/**
 * Log
 *
 * @param mixed $data Data
 * @param string $title Title
 * @return bool
 */
function writeToLog($data, $title = '')
{
    $log = "\n------------------------\n";
    $log .= date("Y.m.d 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 bot's welcome message function:

/**
 * 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, we 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 catalog for all


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

Conclusion


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

useful links


  1. An article on 1C-Bitrix website about the platform for chat bots - 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

Also popular now: