Table of Contents

What's New?

New Updates for Bitrix24 Bot Platform API.

August 2018

New methods in Chat API:


February 2018

  • The following fields: EVENT_MESSAGE_UPDATE and EVENT_MESSAGE_DELETE were added to the methods imbot.register and imbot.update to enable subscription to events that update and delete messages.
  • New chatbot type with with advanced privileges (supervisor) was added. It is the chatbot that has access to all messages in chats, where it is a participant (to all chats, if it was invited with the access to history, and to new chats, if the access to history is not available to it).

    To create a chatbot with advanced privileges, specify type S in the TYPE field in the imbot.register method.

    Please be advised, if not required by the logic of your app, it is recommended for the chatbot to respond to the user messages only if this chatbot is mentioned. It can be checked via the TO_USER_ID field, which will be passed into the event.

    Another addition were the handlers that trace message edits and deletions (available for the chatbot of this type).

  • The following new fields ENTITY_TYPE and ENTITY_ID were added to the method im.chat.add. These fields are used to perform quick search and identification of a chat in the following events: EVENT_MESSAGE_ADD, EVENT_MESSAGE_UPDATE, EVENT_MESSAGE_DELETE.
  • Method imbot.update no longer supports updates of the TYPE and OPENLINE fields.
  • New method is added: im.chat.get. It uses ENTITY_TYPE and ENTITY_ID to receive chat ID.
  • The following fields CHAT_ENTITY_TYPE and CHAT_ENTITY_ID were added to these events: EVENT_MESSAGE_ADD, EVENT_MESSAGE_UPDATE, EVENT_MESSAGE_DELETE to identify a chat (you can specify these fields at the moment of creation).

  • The field TO_USER_ID is added to the following events: EVENT_MESSAGE_ADD, EVENT_MESSAGE_UPDATE. This field will contain the ID of the mentioned user. Thanks to this addition, in case of the 'S' type bot you will be able to understand, whether to respond or not to respond.
  • Update for imbot.register and imbot.update: if all your event handlers will input the same address, instead of specifying EVENT_MESSAGE_ADD, EVENT_MESSAGE_UPDATE, EVENT_MESSAGE_DELETE, EVENT_WELCOME_MESSAGE, EVENT_BOT_DELETE - you can specify only EVENT_HANDLER - its value will be automatically written into all the event handlers.
  • Method im.chat.add was supplemented by a new OWNER_ID field, via which you can specify the chat owner.

  • The following methods were added to the Working with Chats (Bot API) section:

  • Parameter BOT_ID was added to all the Working with Chats (Bot API) methods.


December 2017

  • New error code MAX_COUNT_ERROR was added to the method imbot.register - it notifies that the maximum number of registered bots was reached for one application.
  • Now, maximum quantity of bots for single application is 5.


Where to begin?

This chapter provides general overview of what chatbots are, what purpose do they serve, how they operate and how to create your own chatbot application - with an example of completed chatbot for Bitrix24 platform.

What is Chatbot?


Chatbot - is a virtual chat-based bot, a software program that is created to imitate human behavior when conversing with several parties.

What is a chatbot, why it is required, and why develop it at all?

Although chatbots have become a trend only quite recently, today we can find a plethora of them, especially for Slack or Telegram. Chatbots can perform a variety of useful functions ranging from ticket booking to team management. Users don’t have to leave their favorite messenger to communicate with a chatbot.

What a chatbot can do?

  • Perform routine actions - they can do straightforward, tedious work without human intervention; the end result being usually better that, produced by a human, because chatbot cannot get tired;
  • Search and aggregate news and analytical data (Data-Driven Collaboration): data is available anywhere to all interested parties via their messengers;
  • E-commerce - for quick purchases without lengthy search; for communication with customers;
  • Act as a first customer support tier - client relations, assistants, consultants, frequently asked questions, telephony;
  • Just for Fun - just for the fun of it.

Bitrix24 Bot Platform

Bitrix24 chat (both private and group one) is a part of a complex ecosystem, being one of the multiple channels of communication that is fully integrated with other business tools. The use of chatbots in this context leads to a variety of possibilities for business users, since Bitrix24 (in browser, Desktop- and mobile- applications) already serves as the main workplace for many companies.

An example of a simplest chatbot is one that can post the essential information in chats about the parameters of identification system, integrated with Bitrix24. Another useful bot can help delivery couriers to process orders based on deals existing in the Bitrix24 CRM straight in the messenger of their mobile devices - no need to develop a separate mobile application for them.

Development of a chatbot for Bitrix24 - is a lucrative option for workflows automation in a fast and handy fashion. It is handy because getting information via a messenger is the user preference today. It is fast because the development process for a chatbot in Bitrix24 is quite straightforward.

Note: To learn more about Bitrix24 chatbots, view some of the standard, out-of-the-box Bitrix24 chatbots here.



Chatbot Features


Chatbot:

  • is a special kind of user in the system that can talk to anyone, but cannot log in to the system;
  • supports slash-commands processing;
  • can have a dedicated keyboard for responses, creating simple chat for a basic terminal.

Slash-commands

Slash-commands allow to quickly create requests for input or reception of information, or to format messages.

Note: Detailed information about commands can be found here


Keyboards

Keyboards have quite significant amount of capabilities.

  1. EchoBot
    Page navigation via "Help" button command

  2. Giphy
    Use the More button to get more images without entering the specified keyword twice:

Note: Get more information about keyboards here


Chats

If properly programmed, chatbot can communicate as effectively as a live person. It can post event reminders (about current tasks, meetings) or provide reference information. Chatbots can even go as far as create their own chats and invite human beings to those chats, to discuss a task, for example.

Note: Get more information about chats here


Notifications

Chatbot notifications can used to carry a lot of useful information. The notifications can include various data from multiple external systems.

Note: Get more information about notifications here



Chatbot Lifecycle

Chatbot submits posts to a chat using REST API, and receives replies and user commands via the REST API Events (POST requests).

The following figure shows a typical chatbot's lifecycle:



Creating an Application

The most important thing to remember about chatbots is their logic which is typically a reaction to an action performed by a user or system.

The chatbot API includes the six events that cover the required range of responses:

  • ONAPPINSTALL - event to install a chatbot application.
  • ONAPPUPDATE - updates the chatbot application.
  • ONIMJOINCHAT - event initiated when a chatbot is invited to conversation, either by a user's call in a private chat, or when the bot is connected to a group chat.
  • ONIMBOTMESSAGEADD - event initiated when a chatbot is invited to conversation, either by a user's call in a private chat, or when the bot is connected to a group chat.
  • ONIMCOMMANDADD - event initiated after a user sends a command to a bot in a private or group chat (chatbot cannot participate in the chat, if the command is global).
  • ONIMBOTDELETE - event initiated after the chatbot application is deleted. The event is initiated in parallel with OnAppUninstall.

All we have to do to implement the required chatbot logic is to add event handlers:

  1. Register the chatbot when installing it on the portal.
  2. Show a welcome message when the bot is invited to the chat.
  3. Analyze user requests and send something back in return. Where analysis means a simple "command line review", and not the lexical breakdown of natural language.

To fulfill the requirements, the chatbot REST API contains simple methods a developer can use. Only the two of those are needed to get started:

In the ONAPPINSTALL event handler, we are going to call the imbot.register method to add the chatbot to the current portal. When out chatbot receives an invitation via the ONIMJOINCHAT event, a call to the imbot.message.add method will show chatbot reference information. Finally, we will use the ONIMBOTMESSAGEADD method in the imbot.message.add event handler to reply to the user. It could not be easier, could it?

Another treat for a lazy developer: we don't have to implement OAuth 2.0 in our application because all the authentication parameters are passed to event handlers in the $_REQUEST array.

Note: for a full list of Chatbot API events and methods, please use this link.



Chatbot Example

To illustrate a fully functional, yet simple bot, we are going to create application that informs users of their overdue tasks. Our chatbot will recognize only one command: what's hot. The range of recognized commands can be extended anytime to get any kind of reports directly to the Bitrix24 chat.

Example of a simple chatbot:

<?php
/**
 * Simple and handy reporting chatbot for bitrix24
 */

$appsConfig     = array();
$configFileName = '/config_' . trim(str_replace('.', '_', $_REQUEST['auth']['domain'])) . '.php';
if (file_exists(__DIR__ . $configFileName)) {
   include_once __DIR__ . $configFileName;
}
// receive event "new message for bot"
if ($_REQUEST['event'] == 'ONIMBOTMESSAGEADD') {
   // check the event - register this application or not
   if (!isset($appsConfig[$_REQUEST['auth']['application_token']])) {
      return false;
   }
   // response time
   $arReport = getAnswer($_REQUEST['data']['PARAMS']['MESSAGE'], $_REQUEST['data']['PARAMS']['FROM_USER_ID']);
   $arReport['attach'][] = array("MESSAGE" => 'As soon as you're through with these tasks, just ask me [send=what's hot]What's hot?[/send] again – I'll give you more to have on your plate!');
   
   // send answer message
   $result = restCommand('imbot.message.add', 
      array(
         "DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
         "MESSAGE"   => $arReport['title'] . "\n" . $arReport['report'] . "\n",
         "ATTACH"    => array_merge(
            $arReport['attach']
         ),
      ), 
      $_REQUEST["auth"]);

} // receive event "open private dialog with bot" or "join bot to group chat"
else {
   if ($_REQUEST['event'] == 'ONIMBOTJOINCHAT') {
      // check the event - register this application or not
      if (!isset($appsConfig[$_REQUEST['auth']['application_token']])) {
         return false;
      }
      // send help message how to use chat-bot. For private chat and for group chat need send different instructions.
      $result = restCommand('imbot.message.add', array(
         'DIALOG_ID' => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
         'MESSAGE'   => Hello! I'm Reportoo, I can be a pain in the butt because I'm honest and candid.',
         "ATTACH"    => array(
            array('MESSAGE' => '[send=what's hot]What's hot?[/send]'),
         ),
      ), $_REQUEST["auth"]);

   } // receive event "delete chat-bot"
   else {
      if ($_REQUEST['event'] == 'ONIMBOTDELETE') {
         // check the event - register this application or not
         if (!isset($appsConfig[$_REQUEST['auth']['application_token']])) {
            return false;
         }
         // unset application variables
         unset($appsConfig[$_REQUEST['auth']['application_token']]);
         // save params
         saveParams($appsConfig);

      } // receive event "Application install"
      else {
         if ($_REQUEST['event'] == 'ONAPPINSTALL') {
            // handler for events
            $handlerBackUrl = ($_SERVER['SERVER_PORT'] == 443 ? 'https' : 'http') . '://' . $_SERVER['SERVER_NAME'] . (in_array($_SERVER['SERVER_PORT'],
               array(80, 443)) ? '' : ':' . $_SERVER['SERVER_PORT']) . $_SERVER['SCRIPT_NAME'];
            // If your application supports different localizations
            // use $_REQUEST['data']['LANGUAGE_ID'] to load correct localization
            // register new bot
            $result = restCommand('imbot.register', array(
               'CODE'                  => 'ReportBot',
               // app unique string bot ID (required)
               'TYPE'                  => 'B',
               // Bot type: B – robot with immediate response; H – human-like bot with a response delay from 2 to 10 seconds
               'EVENT_MESSAGE_ADD'     => $handlerBackUrl,
               // new message from user" event handler (required)
               'EVENT_WELCOME_MESSAGE' => $handlerBackUrl,
               // "bot invited" event handler (required)
               'EVENT_BOT_DELETE'      => $handlerBackUrl,
               // "user deleted bot" event handler (required)
               'PROPERTIES'            => array( // Chatbot personal data (required)
                  'NAME'              => 'Reportoo',
                  // Bot name (NAME either LAST_NAME is required)
                  'LAST_NAME'         => '',
                  // Bot name (NAME either LAST_NAME is required)
                  'COLOR'             => 'AQUA',
                  // Bot color for mobile app: RED, GREEN, MINT, LIGHT_BLUE, DARK_BLUE, PURPLE, AQUA, PINK, LIME, BROWN, AZURE, KHAKI, SAND, MARENGO, GRAY, GRAPHITE
                  'EMAIL'             => 'no@mail.com',
                  // bot e-mail
                  'PERSONAL_BIRTHDAY' => '2016-03-23',
                  // birthday, YYYY-mm-dd
                  'WORK_POSITION'     => 'I'm here to tell you about your tasks',
                  // Position – used as bot description
                  'PERSONAL_WWW'      => '',
                  // site link
                  'PERSONAL_GENDER'   => 'M',
                  // Bot gender, (M)ale or (F)emale or empty, if not required
                  'PERSONAL_PHOTO'    => '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',
                  // Bot avatar - base64
               ),
            ), $_REQUEST["auth"]);
            // save params
            $appsConfig[$_REQUEST['auth']['application_token']] = array(
               'BOT_ID'      => $result['result'],
               'LANGUAGE_ID' => $_REQUEST['data']['LANGUAGE_ID'],
            );
            saveParams($appsConfig);
            // write debug log
            // writeToLog($result, 'ReportBot register');
         }
      }
   }
}
/**
 * Save application configuration.
 *
 * @param $params
 *
 * @return bool
 */
function saveParams($params) {
   $config = "<?php\n";
   $config .= "\$appsConfig = " . var_export($params, true) . ";\n";
   $config .= "?>";
   $configFileName = '/config_' . trim(str_replace('.', '_', $_REQUEST['auth']['domain'])) . '.php';
   file_put_contents(__DIR__ . $configFileName, $config);
   return true;
}
/**
 * Send rest query to Bitrix24.
 *
 * @param       $method - Rest method, ex: methods
 * @param array $params - Method params, ex: array()
 * @param array $auth   - Authorize data, ex: array('domain' => 'https://test.bitrix24.com', 'access_token' => '7inpwszbuu8vnwr5jmabqa467rqur7u6')
 *
 * @return mixed
 */
function restCommand($method, array $params = array(), array $auth = array()) {
   $queryUrl  = 'https://' . $auth['domain'] . '/rest/' . $method;
   $queryData = http_build_query(array_merge($params, array('auth' => $auth['access_token'])));
   // writeToLog(array('URL' => $queryUrl, 'PARAMS' => array_merge($params, array("auth" => $auth["access_token"]))), 'ReportBot send data');
   $curl = curl_init();
   curl_setopt_array($curl, array(
      CURLOPT_POST           => 1,
      CURLOPT_HEADER         => 0,
      CURLOPT_RETURNTRANSFER => 1,
      CURLOPT_URL            => $queryUrl,
      CURLOPT_POSTFIELDS     => $queryData,
   ));
   $result = curl_exec($curl);
   curl_close($curl);
   $result = json_decode($result, 1);
   return $result;
}
/**
 * Write data to log file.
 *
 * @param mixed  $data
 * @param string $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;
}
/**
 * Command received, create report
 *
 * @param      string $text message sent by user
  * @param      int $user user ID
 *
 * @return     array
 */
function getAnswer($command = '', $user) {

   switch (strtolower($command)) {
       case 'what's hot':
           $arResult = b24BadTasks($user);
           break;
       default:
          $arResult = array(
            'title' => 'I'm stuck',
            'report'  => 'Sorry, what is it you wanted? I can't hear you!',
         );
   }

   return $arResult;
}

function b24BadTasks ($user) {
   $tasks = restCommand('task.item.list', 
      array(
         'ORDER' => array('DEADLINE' => 'desc'),
         'FILTER' => array('RESPONSIBLE_ID' => $user, '<DEADLINE' => '2016-03-23'),
         'PARAMS' => array(),
         'SELECT' => array()
      ), 
      $_REQUEST["auth"]);
   
   if (count($tasks['result']) > 0) {
      $arTasks = array();
      foreach ($tasks['result'] as $id => $arTask) {
         $arTasks[] = array(
            'LINK' => array(
               'NAME' => $arTask['TITLE'],
               'LINK' => 'https://'.$_REQUEST['auth']['domain'].'/company/personal/user/'.$arTask['RESPONSIBLE_ID'].'/tasks/task/view/'.$arTask['ID'].'/'
            )
         );
         $arTasks[] = array(
            'DELIMITER' => array(
               'SIZE' => 400,
               'COLOR' => '#c6c6c6'
            )
         );
      }
      $arReport = array(
         'title' => 'Oh yeah, we've got trouble. Tackle these ASAP:',
         'report'  => '',
         'attach' => $arTasks
      );
   }
   else {
      $arReport = array(
         'title' => 'You're awesome!',
         'report'  => 'You're no fun, no tasks overdue. Just joking, keep it up!',
      );
   }
   return $arReport;
}

At a first glance, you may find this code frightening. But do not fret. After you have finished this course, you will see that it's actually quite simple.

Users can create a chatbot for personal use, or publish it on Bitrix24 Marketplace.

Note: Chatbot does not require a HTTPS certificate explicitly. However, it is highly recommended due to potential transfer of personal or sensitive information. The application must be saved in UTF-8 encoding.

To get a feel of what a chatbot application is without publishing it on Applications24, take the example code, save it to your server and run the bot on your portal. Bitrix24 has a local application option and here's how to use it:

  • In the left menu, select Applications 1> Add Application 2 and select Add 3 button for My account only option:

    Click the image to expand <

  • Enter the bot name (Reportoo) and select Available as script only option and give the application the Create and manage chatbots permission (to enable the app to register the bot). Also, select the Tasks and Tasks (extended) permissions so that our bot could create a tasks report.

    Click on the image to expand <

  • Since we have all the event handlers in one file, specify the same app URL in both fields.
  • If the chatbot is created for Bitrix24 Self-Hosted (that is, via Available as script only option), then use the Upload a ZIP file containing your application required field to indicate path to installation file.

Actually, we are done: a message saying a new user (Reportoo) has joined the portal should now be visible in the public chat. We can now add it to the chat, then click the "What's hot" link and get a list of overdue tasks.



Creating an Open Channel Chatbot

Design of a chatbot intended for use with Open Channels is almost identical to the standard chatbot, discussed earlier, except for the following small details:

  1. An Open Channel chatbot must have O (zero) passed in the TYPE parameter when calling imbot.register to register a bot.
  2. If you want to extend an existing bot to support Open Channels, you have to add a new key OPENLINE => Y to enable hybrid mode.

    Attention! A hybrid mode enabled chatbot has to distinguish between private, group and Open Channel chats. To do so, simply check the CHAT_ENTITY_TYPE parameter when processing the ONIMBOTMESSAGEADD and ONIMBOTJOINCHAT events. It is set to CHAT_ENTITY_TYPE => LINES when the bot is used in an Open Channel chat.

Otherwise, the chatbot application is the same as the standard chatbot.

For deeper integration with Open Channels, an imopenlines scope access permission is required.

This permission enables the use of the commands:


Attention: The use of HTTPS certificate is not required for chatbots, but is highly recommended due to possible transmission of client's confidential data. The app itself shall have UTF-8 encoding.


Download chatbot example for Open Channels

We have prepared ITR Bot as the example used for Open Channels. It can be downloaded:

  • from Bitbucket service.
  • or found in «Bitrix24 Self-Hosted» here: \Bitrix\ImBot\Bot\OpenlinesMenuExample.

This chatbot as the first tier of customer support - initially, all messages will be going to it first, and only then to the employees in the queue after a period of time, that is specified in the Open Channel settings. Also, a class will be added to it for constructing a multilevel chat menu.


It means that even now you can use the code from the chatbot example on your server and launch a chatbot as a local application, without publishing it at Applications24:

  • Go to the left menu Applications > Add Application tab and select the Add button for My Account Only option:

  • Indicate the chatbot name, specifically, «ITR Bot», and enable Available as script only option and grant access permission rights for at least Creating and managing Chat bots (imbot) (the app won't be able to register the chatbot without these rights), as well as enable rights for Open Channels (imopenlines) (the app won't be able to work with Open Channels without these rights).

  • Due to specifics of how our code is written, it handles all events, so we will indicate the same URL in the both link windows of the app settings.
  • Please note, this chatbot does not publish messages about the fact it was invited to the account. After installation is complete, the chatbot will be accessible in the Open Channel settings, where it should be enabled. Also, specify the time period after which a conversation is switched form the chatbot to the queue:

    Note: Client can switch over from an operator earlier, by sending the message with zero digit or by selecting 0. Wait operator answer menu item. In any case, user can click 0 in any chatbot and he/she will be switched to an operator, without additional processing.

  • After the settings are saved, chatbot is ready for use. The example demonstrates the dialogue - first, ITR Bot responds, the client clicks on the menu items, then queue is switched to an operator (client has selected 0. Wait operator answer menu item):

  • Your own ITR Bot menu can be configured via itrRun method.
    /**
     * Run ITR menu
     *
     * @param $portalId
     * @param $dialogId
     * @param $userId
     * @param string $message
     * @return bool
     */
    function itrRun($portalId, $dialogId, $userId, $message = '')
    {
    	if ($userId <= 0)
    		return false;
    
    	$menu0 = new ItrMenu(0);
    	$menu0->setText('Main menu (#0)');
    	$menu0->addItem(1, 'Text', ItrItem::sendText('Text message (for #USER_NAME#)'));
    	$menu0->addItem(2, 'Text without menu', ItrItem::sendText('Text message without menu', true));
    	$menu0->addItem(3, 'Open menu #1', ItrItem::openMenu(1));
    	$menu0->addItem(0, 'Wait operator answer', ItrItem::sendText('Wait operator answer', true));
    
    	$menu1 = new ItrMenu(1);
    	$menu1->setText('Second menu (#1)');
    	$menu1->addItem(2, 'Transfer to queue', ItrItem::transferToQueue('Transfer to queue'));
    	$menu1->addItem(3, 'Transfer to user', ItrItem::transferToUser(1, false, 'Transfer to user #1'));
    	$menu1->addItem(4, 'Transfer to bot', ItrItem::transferToBot('marta', true, 'Transfer to bot Marta', 'Marta not found :('));
    	$menu1->addItem(5, 'Finish session', ItrItem::finishSession('Finish session'));
    	$menu1->addItem(6, 'Exec function', ItrItem::execFunction(function($context){
    		$result = restCommand('imbot.message.add', Array(
    			"DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
    			"MESSAGE" => 'Function executed (action)',
    		), $_REQUEST["auth"]);
    		writeToLog($result, 'Exec function');
    	}, 'Function executed (text)'));
    	$menu1->addItem(9, 'Back to main menu', ItrItem::openMenu(0));
    
    	$itr = new Itr($portalId, $dialogId, 0, $userId);
    	$itr->addMenu($menu0);
    	$itr->addMenu($menu1);
    	$itr->run(prepareText($message));
    
    	return true;
    }
    


Example: Creating a Support Channel

With the Open Channels module, you can set up a technical support line for any Bitrix24 application, including chatbots.

The following procedure is required:

  1. Open Manage Open Channels (account main menu Company > Open Channels item) and create a tech support Open Channel for your product:

  2. Then, connect a new Bitrix24.Network communication channel:

  3. Once connection is done, the Bitrix24.Network connection settings page becomes available:

    • Be sure to fill in the fields: Name, Short description and select an Avatar - to help your clients find you.
    • The Welcome Message will be shown to a user every time they open your Bitrix24.Network Open Channel:

    • Notice the Searchable option: uncheck it to create a private support channel. It is available only if a user specifies a unique ID in the search text.

      Checking the Searchable option makes your open channel searchable just like any Bitrix24.Network user.

Your open channel can be auto connected to the user's account using the imopenlines.network.join REST command:

$result = restCommand('imopenlines.network.join', Array(

    'CODE' => 'a588e1a88baaf301b9d0b0b33b1eefc2b' // search code as specified on the Connectors page

), $_REQUEST["auth"]);

After the Open Channel is configured, you can write a welcome message to a client via the imopenlines.network.message.add REST command:

Thank you for installation, we will be glad to help, if you have any questions - write to this chat. Have a good Day! :)

Note: The restCommand function is used here for illustration only. You can send a REST command with your own function, or use the Javascript-BX24.callMethod, or bitrix24-php-sdk methods. It is also possible to open such support channel via BX24.im.openMessenger JavaScript-method.



Possible Chatbot Usage Scenarios

Below you can find a brief description of ready-to-use Bitrix24 chatbots. These chatbot types are provisional: you can create a chatbot that can combine 2 or 3 types.

  • Personal Assistant

    Mia is your personal assistant. She can help you find answers to your questions, remind you of events, play tic-tac-toe or just do little chit-chat.

  • Specialist Purpose Bot

    Support Bot is designed for internal use for faster access to Bitrix24 helpdesk ticket system.

  • Open Channel Bots

    Open Channel Bot can get a user in contact with you and help along the way.

  • Entertainment Bots

    Giphy searches through a large library of animated GIF files so you can pick an image you find appropriate to your query and share it with your colleagues.

Note: A full list of Bitrix24 chatbots is available in the section with the same name Bitrix24 Marketplace.




Messages

In this chapter we will discuss messages and how to design, format and use them in Bitrix24 chats.

Formatting

Message text can be formatted by applying bold or strikethrough script or quote style. This lesson will show how to use user commands and REST API to format chat messages.

Note All highlighted methods use restCommand function. You can send a REST command with your own function, or use the BX24.callMethod javascript-method or bitrix24-php-sdk methods.


Formatting Tags

Consider the following example:

[B]bold[/B] text
[U]underline[/U] text
[I]oblique[/I] text
[S]strikethrough[/S] text

When posted to the chat, the message will be rendered like this:

Here's how we can use REST API to format the message:

restCommand('imbot.message.add', Array(
   "DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
   "MESSAGE" => "[B]bold[/B] text
[U]underline[/U] text
[I]oblique[/I] text
[S]strikethrough[/S] text",
), $_REQUEST["auth"]);

Line Break

To add a line break, add one of these sequences to the code:

[BR]
# BR # (no spaces)
\n

Any of these codes create a line break:

Using line breaks in a REST API call:

restCommand('imbot.message.add', Array(
   "DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
   "MESSAGE" => "First line[BR]Second line",
), $_REQUEST["auth"]);

Quotes

To format text as a quote, use a double closing angle bracket sequence or enclose text in two lines formed by the minus sign:

>>first quote line
>>second quote line

------------------------------------------------------
John Doe [08.04.2016 13:06:49]
Hello everyone!
------------------------------------------------------

The second method produces a result that looks a bit different because the first line contains the author name and time stamp:

Creating a quote using a REST API call:

restCommand('imbot.message.add', Array(
   "DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
   "MESSAGE" => ">>first quote line
>>second quote line

------------------------------------------------------
John Doe [08.04.2016 13:06:49]
Hello everyone!
------------------------------------------------------",
), $_REQUEST["auth"]);

Hyperlinks

Any text that conforms to the hyperlink pattern will be converted to a hyperlink. If the hyperlink URL resolves to a page containing rich formatting, it will be recognized by the system and will be added to the message:

Adding a hyperlink using a REST API call:

restCommand('imbot.message.add', Array(
   "DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
   "MESSAGE" => "http://bitrix24.com",
), $_REQUEST["auth"]);

Note: To disable rich formatting, use 'URL_PREVIEW' => 'N' key when adding a message:
restCommand('imbot.message.add', Array(
"DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
"MESSAGE" => "http://bitrix24.com",
'URL_PREVIEW' => 'N' 
), $_REQUEST["auth"]);


If the message contains a link to an image file http://shelenkov.com/bitrix/images/mantis.jpg (with a .png, .jpg or .gif extension), it will be posted as an image:


A BB code URL is also supported - [URL=http://bitrix24.com]Link to Bitrix24[/URL]:

This code uses REST API to add a BB URL code to the message:

restCommand('imbot.message.add', Array(
   "DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
   "MESSAGE" => "[URL=http://bitrix24.com]Link to Bitrix24[/URL]",
), $_REQUEST["auth"]);

IM supports special codes similar to the URL code.

  • [USER=5]Alexandra[/USER] - adds a link to a user.
  • [CALL=18012334455]call[/CALL] - adds a button to make a call using Bitrix24.
  • [CHAT=12]link[/CHAT] - adds a chat link.

These codes are also supported by REST API:

restCommand('imbot.message.add', Array(
   "DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
   "MESSAGE" => "[USER=5]Alexandra[/USER]
[CALL=18012334455]call[/CALL]
[CHAT=12]link[/CHAT]",
), $_REQUEST["auth"]);

Indents

Use the tab character to indent the text:

Using indents in a REST API call:

restCommand('imbot.message.add', Array(
   "DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
   "MESSAGE" => "
Indent
   Indent
      Indent",
), $_REQUEST["auth"]);

Active Links (commands)

To have a link send some text to the bot, use the SEND tag:

[send=text]button caption[/send] - sends text to the bot.

You can use this tag to force a user to send a hard-coded text to the bot. However, a preferable method is by using the Keyboards

Adding a command using REST API:

restCommand('imbot.message.add', Array(
   "DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
   "MESSAGE" => "[send=text]button caption[/send] - sends text to the bot",
), $_REQUEST["auth"]);

If additional user input is required by the command, use the PUT tag:

[put=/search]Enter search text[/put]

Use this tag to automatically add the command text to the input field. Once a user clicks the PUT link, the text that is specified after the equal sign will be added to the text input field. Now the user has to enter additional information and click the Send button. Again, a preferable method is by using the Keyboards)

Using REST API to prompt the user to enter text:

restCommand('imbot.message.add', Array(
   "DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
   "MESSAGE" => "[put=/search]Enter search text[/put]",
), $_REQUEST["auth"]);

Attachments

Use attachments to make a message more pronounced and comprehensive.

To embed an attachment to the message text, add a special BB code ATTACH to the message specified in the MESSAGE key. The [ATTACH=1] code will be replaced with the attachment when showing the message. If no ATTACH code is specified in the message text while the actual attachment exists, it will be shown at the end of the message.

restCommand('imbot.message.add', Array(
   "DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
   "MESSAGE" => "Message with middle attach [ATTACH=1] from bot",
   "ATTACH" => Array(
      "ID" => 1,
      "COLOR" => "#29619b",
      "BLOCKS" => Array(
         Array("LINK" => Array(
            "NAME" => "Ticket #12345: new IM module for API",
            "DESC" => "Need this done before the release!",
            "LINK" => "https://api.bitrix24.com/"
         )),
         Array("IMAGE" => Array(
            "NAME" => "Example",
            "LINK" => "https://training.bitrix24.com/bitrix/templates/b24_en_new/img/en/main/logo_rich.png",
         ))
      )
   )
), $_REQUEST["auth"]);

Note For detailed description of extended attachments, please refer to this lesson.



Attachments

Attachments can be used with any IM messages, irrespective of their origin (messages from a user or a chatbot).

Using Attachments

Before adding an attachment to a message you have to create it along with the message. While the message itself is defined by the MESSAGE key, attachments are created as an array of attachment objects and passed over to the REST command in the ATTACH key. There are two versions of the attachment object: full and short.


Full ATTACH version:

"ATTACH" => Array(
   "ID" => 1,
   "COLOR" => "#29619b",
   "BLOCKS" => Array(
      array(...),
      array(...),
   )
)

The full version includes the following keys:

  • ID - specifies the attachment ID for use in the ATTACH BB code. The attachment ID is required to place attachment in any part of a message, not only at the end of it.

    To add an attachment to the message text, add the [ATTACH=1] with the attachment ID, for example: [ATTACH=1]. Then, the message is displayed to the user, the code will be replaced with the attachment. Please note, BB-code is optional: if not specified, the attachment will be placed at the end of the message.

  • COLOR specifies the attachment background color. This key is optional; the default color is the color of the recipient's chat (or, if this is a notification - current user color). This key is optional, if not required.
  • BLOCKS specifies the attachment layout (see below).

restCommand('imbot.message.add', Array(
   "DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
   "MESSAGE" => "Message with middle attach [ATTACH=1] from bot",
   "ATTACH" => Array(
      "ID" => 1,
      "COLOR" => "#29619b",
      "BLOCKS" => Array(
         Array("LINK" => Array(
            "NAME" => "Ticket #12345: new IM module API",
            "DESC" => "Need this done before the release!",
            "LINK" => "https://api.bitrix24.com/"
         )),
         Array("IMAGE" => Array(
            "NAME" => "Implementation example",
            "LINK" => "https://training.bitrix24.com/bitrix/templates/b24_en_new/img/en/main/logo_rich.png",
         ))
      )
   )
), $_REQUEST["auth"]);


Short ATTACH version:

If all you want is an attachment below the message text, you can omit the ID and the COLOR keys:

"ATTACH" => Array(
   array(...),
   array(...),
)

Unlike the full version, layout goes in the short version without the BLOCKS keys.

restCommand('imbot.message.add', Array(
   "DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
   "MESSAGE" => "Message from bot",
   "ATTACH" => Array(
      Array("LINK" => Array(
         "NAME" => "Ticket  #12345: new IM module API",
         "DESC" => "Need this done before the release!",
         "LINK" => "https://api.bitrix24.com/"
      )),
      Array("IMAGE" => Array(
         "NAME" => "Implementation example",
         "LINK" => "https://training.bitrix24.com/bitrix/templates/b24_en_new/img/en/main/logo_rich.png",
      ))
   )
), $_REQUEST["auth"]);

Note:The examples use the restCommand function. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

Attention: Due to structural complexity, attachments are not added to XMPP, e-mail or push notifications.



Collections of Attachment Blocks


User Blocks

The USER block shows user name and optional avatar. The AVATAR and LINK keys are optional.

Example:

Array("USER" => Array(
   "NAME" => "John Smith",
   "AVATAR" => "http://shelenkov.com/bitrix/images/avatar.png",
   "LINK" => "http://shelenkov.com/",
)),

An entity ID can be used instead of the LINK key:

  • CHAT_ID => 1 specifies the chat link;
  • BOT_ID => 66 specifies the chatbot;
  • USER_ID => 1 specifies the user profile link.


Hyperlink Block

The LINK key displays a block with a hyperlink, description and image. This block is created automatically when a rich link is detected. The DESC and PREVIEW fields are optional.

Example:


Array("LINK" => Array(
   "NAME" => "Ticket #12345: new IM module API",
   "DESC" => "Need this done before the release!",
   "LINK" => "https://api.bitrix24.com/",
   "PREVIEW" => "https://training.bitrix24.com/bitrix/templates/b24_en_new/img/en/main/logo_rich.png"
)),

Entity ID can be used instead of the LINK key:

  • CHAT_ID => 1 - specifies chat link;
  • USER_ID => 1 - specifies user profile link.


Text Block

The MESSAGE key displays text with basic BB code defined formatting.

Example:

Array("MESSAGE" => "API will be accessible in the [B]im 16.0.0[/B] update"),

The following BB codes are possible: USER, CHAT, SEND, PUT, CALL, BR, B, U, I, S.



Delimiter

DELIMITER - The DELIMITER key prints a visual separator, a line. The COLOR and SIZE keys are optional.

Example:

Array("DELIMITER" => Array(
   'SIZE' => 200,
   'COLOR' => "#c6c6c6"
)),


Layout Block

The GRID key is used to format the enclosed arrays in blocks, rows or 2 columns.

  1. "DISPLAY" => "BLOCK" - Specifies that the enclosed arrays are to be shown one below the other.

    A WIDTH key is available to specify the block width in pixels.

    Example:

    Array("GRID" => Array(
        Array(
            "NAME" => "Description",
            "VALUE" => "Structured entity enclosures are required in IM messages and notifications.",
            "DISPLAY" => "BLOCK",
            "WIDTH" => "250"
        ),
        Array(
            "NAME" => "Category",
            "VALUE" => "Suggestions",
            "DISPLAY" => "BLOCK"
        ),
    )),
    
  2. "DISPLAY" => "LINE" This key value specifies that each block is rendered one after the other in sequence until there is no space left, thereafter wrapping to a new line.

    A WIDTH key is available to specify the block width in pixels.

    Example:

    Array("GRID" => Array(
       Array(
          "NAME" => "Priority",
          "VALUE" => "High",
          "COLOR" => "#ff0000",
          "DISPLAY" => "LINE",
           "WIDTH" => "250"
       ),
       Array(
          "NAME" => "Category",
          "VALUE" => "Suggestions",
          "DISPLAY" => "LINE"
       ),
    )), 
    
  3. "DISPLAY" => "COLUMN". This key value formats the blocks in two columns.

    A WIDTH key is available to specify the block width in pixels.

    Example:

    Array("GRID" => Array(
        Array(
            "NAME" => "Priority",
            "VALUE" => "High",
            "DISPLAY" => "COLUMN"
            "WIDTH" => "250"
        ),
        Array(
            "NAME" => "Category",
            "VALUE" => "Suggestions",
            "DISPLAY" => "COLUMN"
        ),
    )),
    

All layout types can use the additional keys:

  • COLOR - specifies the color to apply to the block (the VALUE key);
  • CHAT_ID - value is treated as the chat ID and will become chat link;
  • USER_ID - value is treated as the user ID and will become user profile link;
  • LINK - value will be shown as a link.
  • The VALUE key can also use these BB codes: USER, CHAT, SEND, PUT, CALL.


Image Block

The IMAGE key displays an image. It is recommended to provide a PREVIEW key value specifying a scaled down version of the image. If this key is missing, the LINK value is used instead. The NAME and PREVIEW keys are optional.

Example:

Array("IMAGE" => Array(
    Array(
        "NAME" => "Hello, I'm Mantis",
        "LINK" => "http://shelenkov.com/bitrix/images/mantis.jpg",
        "PREVIEW" => "http://shelenkov.com/bitrix/images/mantis.jpg"
    )
)),


File Block

The FILE key shows a formatted file download link. The NAME (filename) and SIZE (file size in bytes) keys are optional.

Example:

Array("FILE" => Array(
    Array(
        "NAME" => "mantis.jpg",
        "LINK" => "http://shelenkov.com/bitrix/images/mantis.jpg",
        "SIZE" => "1500000"
    )
)),


Examples and Suggested Usage

Treat the ATTACH object like it's a LEGO toy. Construct it according to your vision and requirements using available block types. The order in which you specify blocks is relevant.


Example «A Bug Tracker»

restCommand('imbot.message.add', Array(
   "DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
   "MESSAGE" => "You have a new notification",
   "ATTACH" => Array(
      Array("USER" => Array(
         "NAME" => "Mantis Notifications",
         "AVATAR" => "http://shelenkov.com/bitrix/images/mantis2.jpg",
         "LINK" => "http://shelenkov.com/",
      )),
      Array("LINK" => Array(
         "NAME" => "Open Mantis",
         "LINK" => "http://shelenkov.com/",
      )),
      Array("DELIMITER" => Array(
         'SIZE' => 200,
         'COLOR' => "#c6c6c6"
      )),
      Array("GRID" => Array(
         Array(
            "NAME" => "Project",
            "VALUE" => "BUGS",
            "DISPLAY" => "LINE",
            "WIDTH" => 100
         ),
         Array(
            "NAME" => "Category",
            "VALUE" => "im",
            "DISPLAY" => "LINE",
            "WIDTH" => 100
         ),
         Array(
            "NAME" => "Summary",
            "VALUE" => "Structured entity enclosures are required in IM messages and notifications.",
            "DISPLAY" => "BLOCK"
         ),
      )),
      Array("DELIMITER" => Array(
         'SIZE' => 200,
         'COLOR' => "#c6c6c6"
      )),
      Array("GRID" => Array(
         Array(
            "NAME" => "New ticket",
            "VALUE" => "",
            "DISPLAY" => "ROW",
            "WIDTH" => 100
         ),
         Array(
            "NAME" => "Assigned to",
            "VALUE" => "Evgeniy Shelenkov",
            "DISPLAY" => "ROW",
            "WIDTH" => 100
         ),
         Array(
            "NAME" => "Deadline",
            "VALUE" => "04.11.2015 17:50:43",
            "DISPLAY" => "ROW",
            "WIDTH" => 100
         ),
      )),
   )
), $_REQUEST["auth"]);


Example: Notification

restCommand('imbot.message.add', Array(
   "DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
   "MESSAGE" => "You have new notification",
   "ATTACH" => Array(
      Array("MESSAGE" => "Hey guys, update [b]im 16.0.0[/b] has been tested and is now ready for release.[BR] Add tags as required.[BR] No new commits are accepted."),
      Array("IMAGE" => Array(
         "LINK" => "http://shelenkov.com/bitrix/images/win.jpg",
      )),
   )
), $_REQUEST["auth"]);


Using Keyboards

Custom keyboards are essentially toolbars containing one or more user defined buttons. The keyboards provide alternative means of input, allowing a user to communicate with a chatbot by clicking the buttons.


Adding a Keyboard to a Chatbot

A keyboard is actually part of a chatbot message. To create a keyboard, you have to specify a KEYBOARD key with parameters defining the keyboard layout.

The following methods support the KEYBOARD key:

Consider the following example:

restCommand('imbot.command.answer', Array(
   "COMMAND_ID" => $command['COMMAND_ID'],
   "MESSAGE_ID" => $command['MESSAGE_ID'],
   "MESSAGE" => "Hello! My name is EchoBot :)[br] I am designed to answer your questions!",
   "KEYBOARD" => Array(
      Array(
        "TEXT" => "Bitrix24",
        "LINK" => "http://bitrix24.com",
        "BG_COLOR" => "#29619b",
        "TEXT_COLOR" => "#fff",
        "DISPLAY" => "LINE",
      ),
      Array(
        "TEXT" => "BitBucket",
        "LINK" => "https://bitbucket.org/Bitrix24com/rest-bot-echotest",
        "BG_COLOR" => "#2a4c7c",
        "TEXT_COLOR" => "#fff",
        "DISPLAY" => "LINE",
      ),
      Array("TYPE" => "NEWLINE"), // line break
      Array("TEXT" => "Echo", "COMMAND" => "echo", "COMMAND_PARAMS" => "test from keyboard", "DISPLAY" => "LINE"),
      Array("TEXT" => "List", "COMMAND" => "echoList", "DISPLAY" => "LINE"),
      Array("TEXT" => "Help", "COMMAND" => "help", "DISPLAY" => "LINE"),
   )
), $_REQUEST["auth"]);

Note: The example uses the restCommand function. It is used here for illustration only. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk methods.

Each button in the keyboard is defined by the following keys:

  • TEXT - specifies the button text;
  • LINK - specifies a hyperlink;
  • COMMAND - a command to send to the bot;
  • COMMAND_PARAMS - specifies command parameters;
  • BG_COLOR - specifies the button color;
  • BLOCK - if set to Y, the keyboard will be disabled after this button is clicked;
  • DISABLED - specify Y to disable the button;
  • TEXT_COLOR - specifies the button text color;
  • DISPLAY - specifies the button layout in the row. If set to BLOCK, only this button can occupy the row. If set to LINE, the buttons will be aligned one after the other;
  • WIDTH - button width in pixels. Try to avoid making buttons wider than 255 pixels, because it's the maximum width on mobile devices.
  • APP_ID - specifies the ID of an installed chat application.
  • APP_PARAMS - parameters that will be passed over to the chat application.

The TEXT key is required. To perform sensible action, one of the LINK and COMMAND keys are required as well.

If the LINK key is not empty, the button is treated as an external link. If COMMAND and COMMAND_PARAMS keys are specified, the button sends command to the bot.

If the APP_ID and APP_PARAMS keys are specified, the button will open a chat application window.

To start a new row of buttons, add a button containing only one key: "TYPE" => "NEWLINE".



Command Processing on the Chatbot Side

Chatbots use commands to process button clicks.

  1. To make a command recognizable, it has to be registered using the imbot.command.register (method in the ONAPPINSTALL event handler. To make the command available only from the keyboard, add the "HIDDEN" => "Y" key).

    Use these keys in the button description to fire a command:

    "COMMAND" => "page", // command to send to chatbot 
    "COMMAND_PARAMS" => "1", // command parameters
    
  2. Button click will generate ONIMCOMMANDADD event.

  3. 1. In the event handler, create a new message as a response or update an existing message (effectively creating page-by-page navigation feature).

  4. The [data][COMMAND] array passed to the event handler will contain the event information. This array now contains a new key, COMMAND_CONTEXT to describe calling context:
    • TEXTAREA for commands posted by user by typing in from the device keyboard;
    • KEYBOARD for commands originating from the chatbot keyboard or a context menu.


Application Launch Processing for Chatbot

Application for chat, launched from context menu, is working based on principles of Context Application.



Further Usage Examples

  1. EchoBot
    Page navigation; custom buttons are shown when user executes the Help command

  2. Giphy
    Use the More button to get more images for the specified keyword:







Using Context Menus

A context menu allows for chatbot-to-user interaction from the message context menu.


Adding Custom Items to the Context Menu

A context menu is part of a chatbot message. To add custom menu items, you have to specify MENU key.

The following methods support the Menu:

Consider the following example:

restCommand('im.message.add', Array(
   "DIALOG_ID" => 12,
   "MESSAGE" => "Hello! Message with context menu!",
   "MENU" => Array(
      Array(
        "TEXT" => "Bitrix24",
        "LINK" => "http://bitrix24.com",
      ),
      Array(
         "TEXT" => "Echo", 
         "COMMAND" => "echo", 
         "COMMAND_PARAMS" => "test from keyboard"
      ),
      Array(
         "TEXT" => "Open app", 
         "APP_ID" => "12", 
         "APP_PARAMS" => "TEST"
      ),
   )
), $_REQUEST["auth"]);

Note: The example uses the restCommand function. It is used here for illustration only. You can send a REST command with your own function, or use BX24.callMethod or bitrix24-php-sdk methods.

Each custom item in the context menu is defined by a set of keys:

  • TEXT - specifies text for a menu item;
  • LINK - specifies a hyperlink;
  • COMMAND - sends command to the bot;
  • COMMAND_PARAMS - specifies command parameters;
  • APP_ID - specifies ID of an installed chat application.
  • APP_PARAMS - parameters that will be passed over to the chat application.
  • DISABLED - specifies Y to disable the menu item.

TEXT, LINK or COMMAND are required.

If the LINK key is not empty, the menu item is treated as an external link. If the COMMAND and COMMAND_PARAMS keys are specified, the menu item sends a command to the bot, without posting it in the chat.

If the APP_ID and APP_PARAMS keys are specified, the menu item will open a chat application window.

If it is necessary to specify two lines with buttons in a row, then to separate them, create a button with the following content: "TYPE" => "NEWLINE".



Command Processing on the Chatbot side

Chatbots use commands to process menu items.

  1. To make a command recognizable, it has to be registered using imbot.command.register method in the ONAPPINSTALL event handler. (To make the command available only from the menu, add the "HIDDEN" => "Y" key).

    Use these keys in the menu item description to fire a command:

    "COMMAND" => "page", // command to send to chatbot 
    "COMMAND_PARAMS" => "1", // command parameters
    
  2. Menu item, when selected, generates ONIMCOMMANDADD event.

  3. Create a new message in the event handler as a response or update an existing message (effectively creating the page navigation feature).

  4. The [data][COMMAND] array passed to the event handler will contain the event information. This array now contains a new COMMAND_CONTEXT key to describe the calling context:
    • TEXTAREA for commands posted by user by typing in from the device keyboard;
    • KEYBOARD for commands originating from the chatbot keyboard or a context menu.

Application Launch Processing for Chat

Applications for chat, launched from context menu are working based on the Context Application principles.


Bot API

To work with Bot API, indicate scope: imbot (chatbot creation and management) when creating an application (or uploading a new version).


Working with Chatbots

Note: The restCommand function is used here for illustration only. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk JavaScript-method.


Attention! For chatbots to work properly, access to marta.bitrix.info shall be authorized from Bitrix24 account or site.

Attention! CLIENT_ID parameter shall be specified for all methods to work with chatbots via Webhooks. Such code shall be unique for each chatbot.


Chatbot registration

REST method: imbot.register

Method call:
$result = restCommand('imbot.register', Array(

    'CODE' => 'newbot', // String ID for bot, unique within your application framework (required)
    'TYPE' => 'H', // Bot type, B - chatbot, immediate responses, H - person, responses with 2-10 seconds delay, O - chatbot for Open Channels,  S - chatbot with extended privileges (supervisor)
    'EVENT_HANDLER' => 'http://www.hazz/chatApi/event.php', // Link to the handler of events, incoming from the server; see. Event Handlers section below (req.)  
    'OPENLINE' => 'Y', // Enable Open Channel support mode (optional, if TYPE = 'O').
    'CLIENT_ID' => '', // Chatbot string ID, used only in Webhooks mode
    'PROPERTIES' => Array( // Chatbot properties (req.)
        'NAME' => 'NewBot', // Chatbot name (one field NAME or LAST_NAME is required)
        'LAST_NAME' => '', // Chatbot last name (one field NAME or LAST_NAME is required)
        'COLOR' => 'GREEN', // Chatbot color for mobile application: RED, GREEN, MINT, LIGHT_BLUE, DARK_BLUE, PURPLE, AQUA, PINK, LIME, BROWN,  AZURE, KHAKI, SAND, MARENGO, GRAY, GRAPHITE
        'EMAIL' => 'test@test.com', // E-mail for communication
        'PERSONAL_BIRTHDAY' => '2016-03-11', // Birthday, yyyy-mm-dd
        'WORK_POSITION' => 'My First Bot', // Job title, used as description for chatbot
        'PERSONAL_WWW' => 'http://test.com', // Link to site
        'PERSONAL_GENDER' => 'F', // Chatbot gender, valid values M -  male, F - female, empty, if not required to be specified
        'PERSONAL_PHOTO' => '/* base64 image */', // Chatbot icon - base64
    )

), $_REQUEST["auth"]);
Required fields:
CODE - String ID for chatbot, unique within your application framework.
PROPERTIES - Array with chatbot properties.
EVENT_HANDLER - Link to the event handler for message sending to chatbot.
or
EVENT_MESSAGE_ADD - Link to event handler: send message to chatbot.
EVENT_WELCOME_MESSAGE - Link to event handler: open dialogue with chatbot or invite the chatbot to group chat.
EVENT_BOT_DELETE - Link to event handler: delete chat bot on the client side.
Returns: BOT_ID numerical ID for created bot or an error.

Event Handlers:
If you require to process events via different event handlers, then instead of EVENT_HANDLER you can specify each event handler individually:
 'EVENT_MESSAGE_ADD' => 'http://www.hazz/chatApi/event.php', // Link to event handler: send message to chatbot (required)
 'EVENT_WELCOME_MESSAGE' => 'http://www.hazz/chatApi/event.php', // Link to event handler: open dialogue with chatbot or invite the chatbot to group chat (required)
 'EVENT_BOT_DELETE' => 'http://www.hazz/chatApi/event.php', // Link to event handler: delete chat bot on the client side (required)
 'EVENT_MESSAGE_UPDATE' => 'http://www.hazz/chatApi/event.php', // Link to event handler: subscription to message update events 
 'EVENT_MESSAGE_DELETE' => 'http://www.hazz/chatApi/event.php', // Link to event handler: subscription to message deletion events 

Related links:

REST API - Installation and Update Events

Possible errors:

Error codeError description
EVENT_MESSAGE_ADD_ERROR Event handler link is invalid or not specified.
EVENT_WELCOME_MESSAGE_ERROR Event handler link is invalid or not specified.
EVENT_BOT_DELETE_ERROR Event handler link is invalid or not specified.
CODE_ERROR Chatbot string ID is not specified.
NAME_ERROR One of chatbot required fields NAME or LAST_NAME is not specified.
WRONG_REQUEST Something went wrong.
MAX_COUNT_ERROR Maximum quantity of registered bots for single application is reached.

Chatbot with extended privileges (supervisor) - it is the bot that has access to all messages in chats, where it is present (to all chats, if the bot was invited with history access rights, and to new chats, if the history access rights are unavailable to it).

To create chatbot with extended privileges, specify type S in the field TYPE in the method imbot.register.

Please note, if this action is not required by the logic of your application, it is recommended for the chatbot to respond to user messages only when this chatbot is mentioned. This can be checked via field TO_USER_ID, which will be passed to the event.


Attention! Bitrix24 REST restricts the work of event handlers, if more than one chatbot is to be installed within single application framework. Only one event handler per one application is permitted. That is why, upon registration of second chatbot, the following links to event handlers EVENT_MESSAGE_ADD, EVENT_WELCOME_MESSAGE and EVENT_BOT_DELETE shall be the same as for the first bot.

If within single application framework processing of several bots is required, then it shall be specified inside the event handler. So that during event execution, chatbot array is transmitted for proper processing of chatbots.



Maximum quantity of bots for single application is 5.



Chatbot selection from the system

Attention! All Person-to-person chats of this chatbot with users will be lost.

REST method: imbot.unregister

Method call:
$result = restCommand('imbot.unregister', Array(

    'BOT_ID' => 39 // Bot numerical ID 
    'CLIENT_ID' => '', // Chatbot string ID, used only in Webnooks mode

), $_REQUEST["auth"]);
Returns: true or error.

Related links:

REST API - Installation and Update Events

Possible errors:

Error codeError description
BOT_ID_ERROR Chatbot not found.
APP_ID_ERROR Chatbot is not part of this application: you can only work with chatbots, installed within application framework.


Bot data update

REST method: imbot.update

Method call:
$result = restCommand('imbot.update', Array(

    'BOT_ID' => 39, // Chatbot ID, shall be modified (required)
    'CLIENT_ID' => '', // Chatbot string ID, used only in Webhooks mode (required)
    'FIELDS' => Array( // Data for update (required)
        'CODE' => 'newbot', // String ID for bot, unique within your application framework 
        'EVENT_HANDLER' => 'http://www.hazz/chatApi/event.php', // Link to the handler of events, received from the server, see Event Handlers below (req.)  
        'PROPERTIES' => Array( // Required when bot data is updated
            'NAME' => 'UpdatedBot', // Chatbot name 
            'LAST_NAME' => '', // Chatbot last name 
            'COLOR' => 'MINT', // Chatbot color for mobile application: RED, GREEN, MINT, LIGHT_BLUE, DARK_BLUE, PURPLE, AQUA, PINK, LIME,  BROWN, AZURE, KHAKI, SAND, MARENGO, GRAY, GRAPHITE
            'EMAIL' => 'test2@test.com', // E-mail for communication
            'PERSONAL_BIRTHDAY' => '2016-03-12', // Birthday, yyyy-mm-dd
            'WORK_POSITION' => 'My second bot', // Job title, used as description for chatbot
            'PERSONAL_WWW' => 'http://test2.com', // Link to site
            'PERSONAL_GENDER' => 'M', // Chatbot gender, valid values M -  male, F - female, empty, if not required to be specified
            'PERSONAL_PHOTO' => '/* base64 image */', // Chatbot icon - base64
        )
    )

), $_REQUEST["auth"]);
Required fields:
BOT_ID - Chatbot ID, shall be modified.
FIELDS - Array with data to be updated.
PROPERTIES - Array with chatbot properties.
EVENT_HANDLER - link to the event handler for message sending to chatbot.
or
EVENT_MESSAGE_ADD - Link to event handler: send message to chatbot.
EVENT_WELCOME_MESSAGE - Link to event handler: open dialogue with chatbot or invite the chatbot to group chat.
EVENT_BOT_DELETE - Link to event handler: delete chat bot on the client side.
Returns: true or error.

Event Handlers:
If you require to process events via different event handlrs, then instead of EVENT_HANDLER you can specify each event handler individually:
 'EVENT_MESSAGE_ADD' => 'http://www.hazz/chatApi/event.php', // Link to event handler: send message to chatbot (required)
 'EVENT_WELCOME_MESSAGE' => 'http://www.hazz/chatApi/event.php', // Link to event handler: open dialogue with chatbot or invite the chatbot to group chat (required)
 'EVENT_BOT_DELETE' => 'http://www.hazz/chatApi/event.php', // Link to event handler: delete chat bot on the client side (required)
 'EVENT_MESSAGE_UPDATE' => 'http://www.hazz/chatApi/event.php', // Link to event handler: subscription to message update events 
 'EVENT_MESSAGE_DELETE' => 'http://www.hazz/chatApi/event.php', // Link to event handler: subscription to message deletion events 

Related links:

REST API - Installation and Update Events

Possible errors:

Error codeError description
BOT_ID_ERROR Chatbot not found.
APP_ID_ERROR Chatbot is not part of this application: you can only work with chatbots, installed within application framework.
EVENT_MESSAGE_ADD_ERROR Event handler link invalid or not specified
EVENT_WELCOME_MESSAGE_ERROR Event handler link invalid or not specified.
EVENT_BOT_DELETE_ERROR Event handler link invalid or not specified.
NAME_ERROR One of chatbot required fields NAME or LAST_NAME is not specified.
WRONG_REQUEST Something went wrong.

Attention! Method imbot.update no longer supports TYPE and OPENLINE field updates.



Access to available chatbots

REST-Method: imbot.bot.list

Method call:
$result = restCommand('imbot.bot.list', Array(
), $_REQUEST["auth"]);
Returns: array of arrays, containing chatbots data:
  • ID - chatbot ID.
  • NAME - chatbot name.
  • CODE - internal code.
  • OPENLINE - enable or disable Open Channel support.


Working with Chats

Note: The restCommand function is used here for illustration only. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk JavaScript-method.


Getting participants list

REST method: imbot.chat.user.list

Method call:
$result = restCommand('imbot.chat.user.list', Array(

   'CHAT_ID' => 13 // Chat ID
   'BOT_ID' => 39, // Chatbot ID from which the request is sent. May not be specified, if there is only one chatbot   

), $_REQUEST["auth"]);
Returns: participants' IDs array or an error.

Possible errors:

Error codeError description
CHAT_ID_EMPTY Chat ID is unavailable.


Participants invitation

REST method: imbot.chat.user.add

Method call:
$result = restCommand('imbot.chat.user.add', Array(

   'CHAT_ID' => 13 // Chat ID
   'USERS' => Array(3,4) // New users ID
   'BOT_ID' => 39, // Chatbot ID from which the request is sent. May not be specified, if there is only one chatbot   

), $_REQUEST["auth"]);
Returns: true or an error.

Possible errors:

Error codeError description
CHAT_ID_EMPTY Chat ID is unavailable.
WRONG_REQUEST Insufficient rights to add a participant to the chat or the participant is already in the chat.


Removal of participants

REST method: imbot.chat.user.delete

Method call:
$result = restCommand('imbot.chat.user.delete', Array(

   'CHAT_ID' => 13 // Chat ID
   'USER_ID' => 4 // Deleted user ID
   'BOT_ID' => 39, // Chatbot ID from which the request is sent. May not be specified, if there is only one chatbot   

), $_REQUEST["auth"]);
Returns: true or an error.

Possible errors:

Error codeError description
CHAT_ID_EMPTY Chat ID is unavailable.
USER_ID_EMPTY User ID is unavailable.
WRONG_REQUEST Insufficient rights to add a particiant to the chat, or the participant is already in the chat.


Chatbot exit from specified chat

REST method: imbot.chat.leave

Method call:
$result = restCommand('imbot.chat.leave', Array(

   'CHAT_ID' => 13 // Chat ID to exit
   'BOT_ID' => 39, // Chatbot ID from which the request is sent. May not be specified, if there is only one chatbot   

), $_REQUEST["auth"]);
Returns: true or an error.

Possible errors:

Error codeError description
CHAT_ID_EMPTY Chat ID is unavailable.
ACCESS_ERROR Insufficient rights for sending status to this chat.
BOT_ID_ERROR Chatbot not found.


Chat title update

REST method: imbot.chat.updateTitle

Method call:
$result = restCommand('imbot.chat.updateTitle', Array(

   'CHAT_ID' => 13 // Chat ID
   'TITLE' => 'New name for chat' // New title
   'BOT_ID' => 39, // Chatbot ID from which the request is sent. May not be specified, if there is only one chatbot   

), $_REQUEST["auth"]);
Returns: true or an error.

Possible errors:

Error codeError description
CHAT_ID_EMPTY Chat ID is unavailable.
TITLE_EMPTY Fail to send new chat title.
WRONG_REQUEST Title is already set or the specified chat already exist.


Chat color update

REST method: imbot.chat.updateColor

Method call:
$result = restCommand('imbot.chat.updateColor', Array(

   'CHAT_ID' => 13 // Chat ID
   'COLOR' => 'MINT' // Chat color for mobile application - RED, GREEN, MINT, LIGHT_BLUE, DARK_BLUE, PURPLE, AQUA, PINK, LIME, BROWN,  AZURE, KHAKI, SAND, MARENGO, GRAY, GRAPHITE
   'BOT_ID' => 39, // Chatbot ID from which the request is sent. May not be specified, if there is only one chatbot   

), $_REQUEST["auth"]);
Returns: true or an error.

Possible errors:

Error codeError description
CHAT_ID_EMPTY Chat ID is unavailable.
WRONG_COLOR Color is not included into available colors list.
WRONG_REQUEST Color is already defined or the existing chat does not exist.


Chat icon update

REST-method: imbot.chat.updateAvatar

Method call:
$result = restCommand('imbot.chat.updateAvatar', Array(

   'CHAT_ID' => 13 // Chat ID
   'AVATAR' => '/* base64 image */' // Image in base64 format
   'BOT_ID' => 39, // Chatbot ID from which the request is sent. May not be specified, if there is only one chatbot   

), $_REQUEST["auth"]);
Returns: true or an error.

Possible errors:

Error codeError description
CHAT_ID_EMPTY Chat ID is unavailable.
AVATAR_ERROR incorrect image format is defined.
WRONG_REQUEST Chat does not exist.




Create chat on behalf of chatbot

REST method: imbot.chat.add

Method call:
$result = restCommand('imbot.chat.add', Array(

  'TYPE' => 'CHAT' // OPEN - opened to join chat, CHAT - usual chat with invitations, CHAT by default 
   'TITLE' => 'My new private chat', // Chat title
   'DESCRIPTION' => 'Very important chat', // Chat description
   'COLOR' => 'PINK', // Chat color for mobile application - RED, GREEN, MINT, LIGHT_BLUE, DARK_BLUE, PURPLE, AQUA, PINK, LIME, BROWN, AZURE, KHAKI, SAND, MARENGO, GRAY, GRAPHITE
   'MESSAGE' => 'Welcome to the chat', // First greeting message in the chat
   'USERS' => Array(1,2), // Chat participants (req.)
   'AVATAR' => '/* base64 image */', // Chat icon in base64 format
   'ENTITY_TYPE' => 'CHAT', // Arbitrary entity ID (for example CHAT, CRM, OPENLINES, CALL and etc.), can be used for chat search and easy context definition in the following event handlers: ONIMBOTMESSAGEADD, ONIMBOTMESSAGEUPDATE, ONIMBOTMESSAGEDELETE
   'ENTITY_ID' => 13, // Entity numerical ID; it can be used for chat search and for easy context definition in the following event handlers: ONIMBOTMESSAGEADD, ONIMBOTMESSAGEUPDATE, ONIMBOTMESSAGEDELETE
   'OWNER_ID' => 39, // Chat owner ID. May not be specified, if your are creating chat under the necessary user.
   'BOT_ID' => 39, // Chatbot ID from which the request is sent. May not be specified, if there is only one chatbot

), $_REQUEST["auth"]);
Required fields: USERS (chat participants).

Returns: CHAT_ID chat numerical ID or an error.

Possible errors:

Error codeError description
USERS_EMPTY No chat participants.
WRONG_REQUEST Something went wrong.


Gets chat ID

REST method: imbot.chat.get

Method call:
$result = restCommand('imbot.chat.get', Array(


   'ENTITY_TYPE' => 'OPEN', // Arbitrary entity ID (for example CHAT, CRM, OPENLINES, CALL and etc.), can be used for chat search and easy context definition in the following event handlers: ONIMBOTMESSAGEADD, ONIMBOTMESSAGEUPDATE, ONIMBOTMESSAGEDELETE (req.)
   'ENTITY_ID' => 13, // Numerical entity ID; it can be used for chat search and easy context definition in the following events handlers: ONIMBOTMESSAGEADD, ONIMBOTMESSAGEUPDATE, ONIMBOTMESSAGEDELETE  (req.)
   'BOT_ID' => 39, // Chatbot ID from which the request is sent. May not be specified, if there is only one chatbot
   
), $_REQUEST["auth"]);
Required fields:
ENTITY_TYPE - arbitrary entity ID (for example CHAT, CRM, OPENLINES, CALL and etc); it can be used for chat search and for easy app context definition in the event handlers ONIMBOTMESSAGEADD, ONIMBOTMESSAGEUPDATE, ONIMBOTMESSAGEDELETE.
ENTITY_ID - numeric entity ID; it can be used for chat search and for easy app context definition in the event handlers ONIMBOTMESSAGEADD, ONIMBOTMESSAGEUPDATE, ONIMBOTMESSAGEDELETE.

Returns: returns chat ID CHAT_ID or null.
>

Change of chat owner

REST method: imbot.chat.setOwner

Method call:
$result = restCommand('imbot.chat.setOwner', Array(

   'CHAT_ID' => 13 // Chat ID
   'USER_ID' => '2' // New chat owner ID
   'BOT_ID' => 39, // Chatbot ID from which the request is sent. May not be specified, if there is only one chatbot   

), $_REQUEST["auth"]);
Return: true or an error.

Possible errors:

Error codeError description
CHAT_ID_EMPTY Chat ID was not transmitted.
USER_ID_EMPTY New chat owner ID was not transmitted.
WRONG_REQUEST Method is called by user without owner's rights or indicated user is not a chat participant.

Working with Messages

The restCommand function is used here for illustration only. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk JavaScript-method.


Attention! These methods of message processing are usually employed when the user is typing something, that is why the ONIMBOTMESSAGEADD event must be processed.


Sending message from chatbot

REST method: imbot.message.add

Method call:
$result = restCommand('imbot.message.add', Array(

    'BOT_ID' => 39, // ID of chatbot that sends request. Is optional, there is only one chatbot
    'DIALOG_ID' => 1, // Dialog ID: it can be either USER_ID, or chatXX - where XX is chat ID, transmitted in events ONIMBOTMESSAGEADD and ONIMJOINCHAT
    'MESSAGE' => 'answer text' // Message text
    'ATTACH' => '' // Attachment, optional field 
    'KEYBOARD' => '' // Keyboard, optional field 
    'MENU' => '' // Context menu, optional field
    'SYSTEM' => 'N' // Display messages as system messages, optional field, by default 'N'
    'URL_PREVIEW' => 'Y' // Convert links to rich-links, optional field, by default 'Y'

), $_REQUEST["auth"]);

You can post message on behalf of bot in private dialogues (they will be shown as system message). To do it, specify USER_FROM_ID and USER_TO_ID instead of DIALOG_ID.

Return: MESSAGE_ID message ID or an error.

Related Links:

Using Keyboards
Attachments
Formatting
Working with Events - ONIMBOTMESSAGEADD

Possible errors:

Error codeError description
BOT_ID_ERROR Chatbot not found.
APP_ID_ERROR Chatbot is not part of this application: you can only work with chatbots, installed within application framework.
DIALOG_ID_EMPTY Dialogue ID is not transmitted.
MESSAGE_EMPTY Message text is not transmitted.
ATTACH_ERROR Complete transmitted object was not validated.
ATTACH_OVERSIZE Maximum permissible attachment size was exceeded (30 Kb).
KEYBOARD_ERROR Complete transmitted keyboard object was not validated.
KEYBOARD_OVERSIZE Maximum permissible keyboard size was exceeded (30 Kb).
MENU_ERROR Complete transmitted menu object was not validated.
MENU_OVERSIZE Maximum permissible menu size was exceeded (30 Kb).
WRONG_REQUEST Something went wrong.


Updates (changes) the chatbot message

REST method: imbot.message.update

Method call:
$result = restCommand('imbot.message.update', Array(

    'BOT_ID' => 39, // ID of chatbot that sends request. Is optional, there is only one chatbot
    'MESSAGE_ID' => 1, // Message ID
    'MESSAGE' => 'answer text' // Message text, optional field, if null value is specified – message will be deleted
    'ATTACH' => '' // Attachment, optional field 
    'KEYBOARD' => '' // Keyboard, optional field 
    'MENU' => '' // Context menu, optional field
    'URL_PREVIEW' => 'Y' // Convert links to rich-links, optional field, by default 'Y'

), $_REQUEST["auth"]);
Return: true or error.

Related Links:

Using Keyboards
Attachments
Formatting
Working with Events - ONIMBOTMESSAGEADD message for chatbot

Possible errors:

Error codeError description
BOT_ID_ERROR Chatbot not found.
APP_ID_ERROR Chatbot is not part of this application: you can only work with chatbots, installed within application framework.
MESSAGE_EMPTY Message text is not transmitted.
CANT_EDIT_MESSAGE You do not have access to this message or time to modify it has expired (more than 3 days passed since publishing).
ATTACH_ERROR Complete transmitted attachment was not validated.
ATTACH_OVERSIZE Maximum permissible attachment size was exceeded (30 Kb).
KEYBOARD_ERROR Complete transmitted keyboard object was not validated.
KEYBOARD_OVERSIZE Maximum permissible keyboard size was exceeded (30 Kb).
MENU_ERROR Complete transmitted menu object was not validated.
MENU_OVERSIZE Maximum permissible menu size was exceeded (30 Kb).


Deletes chatbot message

REST method: imbot.message.delete

Method call:
$result = restCommand('imbot.message.delete', Array(

    'BOT_ID' => 39, // ID of chatbot that sends request. Is optional, there is only one chatbot
    'MESSAGE_ID' => 1, // Message ID
    'COMPLETE' => 'N', //  If message is required to be deleted completely, without a trace, then specify 'Y' (optional parameter)

), $_REQUEST["auth"]);
Return: true or error.

Possible errors:

Error codeError description
BOT_ID_ERROR Chatbot not found.
APP_ID_ERROR Chatbot is not part of this application: you can only work with chatbots, installed within application framework.
MESSAGE_ID_ERROR Message ID was not transmitted.
CANT_EDIT_MESSAGE You do not have access to this message or time to modify it has expired (more than 3 days passed since publishing).


Message «Like»

REST method: imbot.message.like

Method call:
$result = restCommand('imbot.message.like', Array(

    'BOT_ID' => 39, // ID of chatbot that sends request. Is optional, there is only one chatbot
    'MESSAGE_ID' => 1, // Message ID (any message, sent in personal dialogues or in group chats, where chatbot is located)
    'ACTION' => 'auto' // Action, connected with method: plus – click «Like»; minus – «Like» is removed; auto – automatic calculation, tick should/shouldn't be specified. If not specified, it will work in auto mode 

), $_REQUEST["auth"]);
Return: true or error.

Possible errors:

Error codeError description
BOT_ID_ERROR Chatbot not found.
APP_ID_ERROR Chatbot is not part of this application: you can only work with chatbots, installed within application framework.
MESSAGE_ID_ERROR Message ID was not transmitted.
WITHOUT_CHANGES After «Like» status call, it did not change.


Send "Chatbot is typing a message...»

REST method:imbot.chat.sendTyping

Method call:
$result = restCommand('imbot.chat.sendTyping', Array(

    'BOT_ID' => 39, // ID of chatbot that sends request. Is optional, there is only one chatbot
    'DIALOG_ID' => 1, // Dialogue ID, it is either USER_ID, or chatXX – where XX is chat ID, transmitted in events ONIMBOTMESSAGEADD and ONIMJOINCHAT

), $_REQUEST["auth"]);
Return: true or error.

Related Links:

Working with Events - ONIMBOTMESSAGEADD message for chatbot
Working with Events - ONIMJOINCHAT message for chatbot to join chat (or private chat)

Possible errors:

Error codeError description
BOT_ID_ERROR Chatbot not found.
DIALOG_ID_EMPTY Dialogue ID not transmitted.


Commands

Commands include general and local:
  • General commands work in any dialogue or chat. Example of such chat (COMMON = Y):
    /giphy picture
    

    Such command call in any chat formulates the response from chatbot, even if the chat doesn't have a chatbot.


  • Local commands work only in personal corresponding with the Chatbot and in group chats, where chatbot is a participant. The example of such command (COMMON = N):
    /help
    

    Call of this command in EchoBot example will return the list of accessible commands.


Example of «Commands and active hyperlinks»:



Working with Commands

Attention! The restCommand function is used here for illustration only. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk JavaScript-method.


Attention! To process a command, processing of add ONIMCOMMANDADD command event is required in the application.


Command registration for chatbot processing

REST method: imbot.command.register

Method call:
$result = restCommand('imbot.command.register', Array(

   'BOT_ID' => 62, // Command owner chatbot ID 
   'COMMAND' => 'echo', // Text of command, which user will enter in chats 
   'COMMON' => 'Y', // If 'Y’ is specified, then the command is accessible in all chats, if ‘N’ – then it is accessible only in chats with chatbot
    'HIDDEN' => 'N', // Hidden command or not – ‘N’ by default 
   'EXTRANET_SUPPORT' => 'N', // Extranet users access to command, ‘N’ by default
    'CLIENT_ID' => '', // chatbot string ID, used only in Webhooks mode 
   'LANG' => Array( // Array of translations, preferably to specify, as a minimum for ENG
      Array('LANGUAGE_ID' => 'en', 'TITLE' => 'Get echo message', 'PARAMS' => 'some text'), // Language, command description, which data to be required to be entered after the command.
   ),
   'EVENT_COMMAND_ADD' => 'http://www.hazz/chatApi/bot.php', // Link to command handler 

), $_REQUEST["auth"]);
Return: COMMAND_ID command ID or an error.

Related Links:

Working with Events - ONIMCOMMANDADD for chatbot

Possible errors:

Error codeError description
EVENT_COMMAND_ADD Link to event handler is invalid or not specified.
COMMAND_ERROR Command text is not specified, to which chatbot should respond.
BOT_ID_ERROR Chatbot not found.
APP_ID_ERROR Chatbot is not part of this application: you can only work with chatbots, installed within application framework.
LANG_ERROR Phrases are not transmitted for visible command.
WRONG_REQUEST Something went wrong.

Attention! Bitrix24 REST restricts the work of event handlers, if more than one chatbot is to be installed within single application framework. Only one event handler per one application is permitted. That is why, upon registration of second command, the following links to event handlers EVENT_COMMAND_ADD all be the same as for the first command.

If processing of several commands is required within single application framework, then it shall be specified inside the event handler. So that during event execution, chatbot array is transmitted for proper processing of chatbots.



Deleted command processing

REST method: imbot.command.unregister

Method call:
$result = restCommand('imbot.command.unregister', Array(

    'COMMAND_ID' => 13, // Deletion command ID 
    'CLIENT_ID' => '', // Chatbot string ID, used only in Webhooks mode
), $_REQUEST["auth"]);
Return: true or an error.

Possible errors:

Error codeError description
COMMAND_ID_ERROR Command not found.
APP_ID_ERROR Chatbot is not a part of this application: you can only work with chatbots, installed within application framework.
WRONG_REQUEST Something went wrong.


Command data update

REST method: imbot.command.update

Method call:
$result = restCommand('imbot.command.update', Array(

   'COMMAND_ID' => 13, // Chat ID
   'FIELDS' => Array(
      'EVENT_COMMAND_ADD' => 'http://www.hazz/chatApi/bot.php', // Link to command handler
      'HIDDEN' => 'N', // Command is hidden or not 
      'EXTRANET_SUPPORT' => 'N', // Extranet users command access
      'CLIENT_ID' => '', // Chatbot string ID, used only in Webhooks mode
      'LANG' => Array( // New translation phrases, all previous will be deleted  
         Array('LANGUAGE_ID' => 'en', 'TITLE' => 'Get echo message', 'PARAMS' => 'some text'),
      ),
   )

), $_REQUEST["auth"]);
Required fields: command ID and one of fields, needed for editing.

Return: true or an error.

Possible errors:

Error codeError description
COMMAND_ID_ERROR Command not found.
APP_ID_ERROR Chatbot is not a part of this application: you can only work with chatbots, installed within application framework.
EVENT_COMMAND_ADD Link to event handler invalid or not specified.
WRONG_REQUEST Something went wrong.


Posting an answer to command

REST method:imbot.command.answer

Method call:
$result = restCommand('imbot.command.answer', Array(

    'COMMAND_ID' => 13, // ID for command that prepared the report, (required to be specified or COMMAND)
    'COMMAND' => 'echo', // Name of command that prepared the answer (required to be specified or COMMAND_ID)
    'MESSAGE_ID' => 1122, // ID for message that requires an answer
    'MESSAGE' => 'answer text' // Answer text
    'ATTACH' => '' // Attachment, optional field
    'KEYBOARD' => '' // Keyboard, optional field
    'MENU' => '' // Context menu, optional field
    'SYSTEM' => 'N' // Display messages as system message, optional field, 'N' by default
    'URL_PREVIEW' => 'Y' // Convert links to rich-links, optional field, 'Y' by default
    'CLIENT_ID' => '', // Chatbot string ID, used only in Webhooks mode

), $_REQUEST["auth"]);
Return: MESSAGE_ID command ID or an error.

Related Links:

Using Keyboards
Attachments
Formatting


Possible errors:

Error codeError description
COMMAND_ID_ERROR Command not found.
APP_ID_ERROR Chatbot is not part of this application: you can only work with chatbots, installed within application frameworkприложения.
MESSAGE_EMPTY Message text is not transmitted.
ATTACH_ERROR Complete transmitted attachment object was not validated.
ATTACH_OVERSIZE Maximum permissible attachment size was exceeded (30 Kb).
KEYBOARD_ERROR Complete transmitted keyboard object was not validated.
KEYBOARD_OVERSIZE Maximum permissible keyboard size was exceeded (30 Kb).
MENU_ERROR Complete transmitted object menu was not validated.
MENU_OVERSIZE Maximum permissible menu size was exceeded (30 Kb).
WRONG_REQUEST Something went wrong.


Working with Events

When generating an event (adding a new message, opening of a dialogue with chatbot, chatbot invitation to a chat, deletion of chatbot from the client side) request for event handler is generated, indicated during bot registration. Find more details about this mechanism here.


ONAPPINSTALL event to install application

[data] => Array(
  [LANGUAGE_ID] = eng // Account's basic language 
  [VERSION] = 1 // Application version
)
[auth] => Array(
    [access_token] => lh8ze36o8ulgrljbyscr36c7ay5sinva // Key for sending requests to REST-service
    [scope] => imbot // Permitted access levels
    [domain] => b24.hazz // Bitrix24 account domain on which the application was installed
    [application_token] => c917d38f6bdb84e9d9e0bfe9d585be73 // Application token. It helps you to “beat back” redundant requests to event handler. All events have this field.

    [expires_in] => 3600 // Token expiration time, after which the new one shall be requested
    [member_id] => d41d8cd98f00b204e9800998ecf8427e // Unique account ID, required to extend authorization 
    [refresh_token] => 5f1ih5tsnsb11sc5heg3kp4ywqnjhd09 // Key to extend authorization
)

Attention! Basic variant of the work with chatbot, fields expires_in, member_id, refresh_token - are not required. If they are required for your application, you can read more about them here. Example of bot has an option for extension.



ONAPPUPDATE event to update application

[data] => Array(
  [LANGUAGE_ID] = eng // Basic language of account 
  [VERSION] = 2 // New version of account
  [PREVIOUS_VERSION] => 1 // Old version of application
)
[auth] => Array(
    [access_token] => lh8ze36o8ulgrljbyscr36c7ay5sinva // Key for requests to REST-service 
    [scope] => imbot // Permitted access levels
    [domain] => b24.hazz // Bitrix24 account domain, on which the application is installed  
    [application_token] => c917d38f6bdb84e9d9e0bfe9d585be73 // Application token. It helps you to “beat back” redundant requests to event handler. All events have this field.

    [expires_in] => 3600 // Token expiration time, after which the new one shall be requested
    [member_id] => d41d8cd98f00b204e9800998ecf8427e // Unique account ID, required to extend authorization 
    [refresh_token] => 5f1ih5tsnsb11sc5heg3kp4ywqnjhd09 // Key to extend authorization
)


Attention! All, that is described below – is the content of [data] field in the event. Authoriztion data in the [auth] key contain data of user-initiator of event. To receive bot authorization data, use [data][BOT][__BOT_CODE__].

ONIMBOTMESSAGEADD event initiated when chatbot receives a message

[BOT] => Array // Codes array for chatbots, to which the message is intended, 
(
    [39] => Array
    (
   [AUTH] => Array // Parameters for authorization as chatbot, to complete actions 
         (
            [domain] => b24.hazz
            [member_id] => d41d8cd98f00b204e9800998ecf8427e
            [application_token] => 8006ddd764e69deb28af0c768b10ed65
         )
        [BOT_ID] => 39    
        [BOT_CODE] => newbot
    )
)
[PARAMS] => Array // Message data array 
(
    [DIALOG_ID] => 1    // Dialogue ID
    [CHAT_TYPE] => P    // Type of message and chat, can be P (person-to-person), C (with limited number of participants), O (public chat), S (chatbot with extended privileges - supervisor)
    [CHAT_ENTITY_TYPE] => 'LINES'    // To identify chat (you can specify this field at the moment of creation); LINES will be specified in this field for Open Channel chats
    [CHAT_ENTITY_ID] => 13    // To identify a chat (you can specify this field at the moment of creation)
    [MESSAGE_ID] => 392 // Message ID
    [MESSAGE] => test3 // Message
    [MESSAGE_ORIGINAL] => [USER=39]NewBot[/USER] test3 // Original message with chatbot BB-code (parameter is accessible only in group chats)
    [FROM_USER_ID] => 1 // User ID who sent a message 
    [TO_USER_ID] => 1 // Chatbot ID or User ID: it will be Chatbot ID in person-to-person chat, and in group chat - User ID, who received a message. If '0' is specified - it is addressed to all chat participants
    [TO_CHAT_ID] => 6   // Chat ID (parameter is accessible only group chats)
    [LANGUAGE] => com    // Account default language ID
).  
[USER] => Array // Message owner data array, can be empty, if ID = 0
(
    [ID] => 1 // User ID
    [NAME] => Evgeniy Shelenkov // User name and last name 
    [FIRST_NAME] => Evgeniy // User name 
    [LAST_NAME] => Shelenkov // User last name 
    [WORK_POSITION] => // Work position 
    [GENDER] => M // Gender, can be either M (make), or F (female)
    [IS_BOT] => 'Y' // User - bot (Y), otherwise – ‘N’.
    [IS_CONNECTOR] => 'Y' // User - connector (participant OC-chat, client), otherwise – ‘N’.
    [IS_NETWORK] => 'Y' // It is network user (can be OC-chat participant, client or simply external user), otherwise – ‘N’.
    [IS_EXTRANET] => 'Y' // Extranet user (all non-intranet users), otherwise – ‘N’.
)


ONIMBOTMESSAGEUPDATE event for chatbot to update a message

[BOT] => Array // Codes array for chatbots, to which the message is intended
(
    [39] => Array
    (
   [AUTH] => Array // Parameters for authorization as chatbot, to perform actions
         (
            [domain] => b24.hazz
            [member_id] => d41d8cd98f00b204e9800998ecf8427e
            [application_token] => 8006ddd764e69deb28af0c768b10ed65
         )
        [BOT_ID] => 39    
        [BOT_CODE] => newbot
    )
)
[PARAMS] => Array // Message data array
(
    [DIALOG_ID] => 1    // Dialogue ID
    [CHAT_TYPE] => P    // Type of message and chat, can be P (person-to-person), C (with limited number of participants), O (public chat), S (chatbot with extended privileges - supervisor)
    [CHAT_ENTITY_TYPE] => 'LINES'    // To identify chat (you can specify this field at the moment of creation); LINES will be specified in this field for Open Channel chats
    [CHAT_ENTITY_ID] => 13    // To identify a chat (you can specify this field at the moment of creation)
    [MESSAGE_ID] => 392 // Message ID
    [MESSAGE] => test3 // Message
    [MESSAGE_ORIGINAL] => [USER=39]NewBot[/USER] test3 // Original message with chatbot BB-code (parameter is accessible only in group chats)
    [FROM_USER_ID] => 1 // User ID who sent a message 
    [TO_USER_ID] => 1 // Chatbot ID or User ID: it will be Chatbot ID in person-to-person chat, and in group chat - User ID, who received a message. If '0' is specified - it is addressed to all chat participants
    [TO_CHAT_ID] => 6   // Chat ID (parameter is accessible only group chats)
    [LANGUAGE] => com    // Account default language ID
)
[USER] => Array // Message owner data array, can be empty, if ID = 0
(
    [ID] => 1 // User ID
    [NAME] => Evgeniy Shelenkov // User name and last name 
    [FIRST_NAME] => Evgeniy // User name 
    [LAST_NAME] => Shelenkov // User last name 
    [WORK_POSITION] => // Work position 
    [GENDER] => M // Gender, can be either M (make), or F (female)
    [IS_BOT] => 'Y' // User - bot (Y), otherwise – ‘N’.
    [IS_CONNECTOR] => 'Y' // User - connector (participant OC-chat, client), otherwise – ‘N’.
    [IS_NETWORK] => 'Y' // It is network user (can be OC-chat participant, client or simply external user), otherwise – ‘N’.
    [IS_EXTRANET] => 'Y' // Extranet user (all non-intranet users), otherwise – ‘N’.
)


ONIMBOTMESSAGEDELETE event for chatbot to delete a message

[BOT] => Array // Codes array for chatbots, to which the message is intended
(
    [39] => Array
    (
   [AUTH] => Array // Parameters for authorization as chatbot, to perform actions
         (
            [domain] => b24.hazz
            [member_id] => d41d8cd98f00b204e9800998ecf8427e
            [application_token] => 8006ddd764e69deb28af0c768b10ed65
         )
        [BOT_ID] => 39    
        [BOT_CODE] => newbot
    )
)
[PARAMS] => Array // Message data array
(
    [DIALOG_ID] => 1    // Dialogue ID
    [CHAT_TYPE] => P    // Type of message and chat, can be P (person-to-person), C (with limited number of participants), O (public chat), S (chatbot with extended privileges - supervisor)
    [CHAT_ENTITY_TYPE] => 'LINES'    // To identify chat (you can specify this field at the moment of creation); LINES will be specified in this field for Open Channel chats
    [CHAT_ENTITY_ID] => 13    // To identify a chat (you can specify this field at the moment of creation)
    [MESSAGE_ID] => 392 // Message ID
    [MESSAGE] => test3 // Message
    [FROM_USER_ID] => 1 // User ID who sent a message 
    [TO_CHAT_ID] => 6   // Chat ID (parameter is accessible only group chats)
    [LANGUAGE] => com    // Account default language ID
)
[USER] => Array // Message owner data array, can be empty, if ID = 0
(
    [ID] => 1 // User ID
    [NAME] => Evgeniy Shelenkov // User name and last name 
    [FIRST_NAME] => Evgeniy // User name 
    [LAST_NAME] => Shelenkov // User last name 
    [WORK_POSITION] => // Work position 
    [GENDER] => M // Gender, can be either M (make), or F (female)
    [IS_BOT] => 'Y' // User - bot (Y), otherwise – ‘N’.
    [IS_CONNECTOR] => 'Y' // User - connector (participant OC-chat, client), otherwise – ‘N’.
    [IS_NETWORK] => 'Y' // It is network user (can be OC-chat participant, client or simply external user), otherwise – ‘N’.
    [IS_EXTRANET] => 'Y' // Extranet user (all non-intranet users), otherwise – ‘N’.
)


ONIMCOMMANDADD event for chatbot to receive command

[COMMAND] => Array // Commands array, which are called by the user
(
    [14] => Array 
    (
      [AUTH] => Array // Parameters to authorize as chatbot to perform actions
      (
         [domain] => b24.hazz
         [member_id] => d41d8cd98f00b204e9800998ecf8427e
         [application_token] => 8006ddd764e69deb28af0c768b10ed65
      )
      [BOT_ID] => 62 // Chatbot ID
      [BOT_CODE] => echobot // Chatbot code
      [COMMAND] => echo // Called command
      [COMMAND_ID] => 14 // Command ID
      [COMMAND_PARAMS] => test // Parameters, with which the command was called 
      [COMMAND_CONTEXT] => TEXTAREA // Command execution context. TEXTAREA - if the command is inputted manually, or KEYBOARD, if a keyboard key is pressed
      [MESSAGE_ID] => 1221 // Message ID, which needs a response
    )
)
[PARAMS] => Array // Message data array
(
    [DIALOG_ID] => 1    // Dialogue ID
    [CHAT_TYPE] => P    // Type of message and chat, can be P (person-to-person), C (with limited number of participants), O (public chat), S (chatbot with extended privileges - supervisor)
    [MESSAGE_ID] => 1221 // Message ID
    [MESSAGE] => /echo test // Message
    [MESSAGE_ORIGINAL] => [USER=39]NewBot[/USER] test3 // Original message with chatbot BB-code (parameter is accessible only in group chats)
    [FROM_USER_ID] => 1 // User ID who sent a message 
    [TO_USER_ID] => 2 // Other user ID (accessible only in person-to-person chats)
    [TO_CHAT_ID] => 6   // Chat ID (parameter is accessible only group chats)
    [LANGUAGE] => com    // Account default language ID

)
[USER] => Array // Message owner data array, can be empty, if ID = 0
(
    [ID] => 1 // User ID
    [NAME] => Evgeniy Shelenkov // User name and last name 
    [FIRST_NAME] => Evgeniy // User name 
    [LAST_NAME] => Shelenkov // User last name 
    [WORK_POSITION] => // Work position 
    [GENDER] => M // Gender, can be either M (make), or F (female)
)


ONIMBOTJOINCHAT event initiated then chatbot receives information that it has joined a chat (or private chat)

[BOT] => Array // Code array for chatbot, for which the event is intended 
(
    [39] => Array // Parameters for authorization as chatbot to perform actions 
    (
   [AUTH] => Array // Parameters for authorization as chatbot to perform actions
        (
            [domain] => b24.hazz 
            [member_id] => d41d8cd98f00b204e9800998ecf8427e
            [application_token] => 8006ddd764e69deb28af0c768b10ed65
        )
        [BOT_ID] => 39    
        [BOT_CODE] => newbot
    )
)
[PARAMS] => Array
(	
    [DIALOG_ID] => 1    // Dialogue ID
 [MESSAGE_ID] => 392 // Message ID
    [CHAT_TYPE] => P    // Type of message and chat, can be P (one-on-one chat), C (with limited number of participants), O (public chat)
    [CHAT_ENTITY_TYPE] => 'LINES'    // Chat subtype, can have LINES value (Open Channels) or empty 
    [USER_ID] => 1   // User ID (for person-to-person chats – user who opened chatbot, for group chats – user who invited chatbot)
    [LANGUAGE] => com    // Account default language ID
)
[USER] => Array // Message owner data array, can be empty, if ID = 0
 (



    [ID] => 1 // User ID
    [NAME] => Evgeniy Shelenkov // User name and last name 
    [FIRST_NAME] => Evgeniy // User name 
    [LAST_NAME] => Shelenkov // User last name 
    [WORK_POSITION] => // Work position 
    [GENDER] => M // Gender, can be either M (male), or F (female)
)


ONIMBOTDELETE event initiated when chatbot is deleted

[BOT_ID] => 39 // Chatbot ID
[BOT_CODE] => giphy // Chatbot code


Example of handler code to work with events

Example is fully functional, saves the configuration into a file: it will help you understand how chatbots generally are functioning.

File with commentaries and group icon are accessible in the repository at the following address: https://bitbucket.org/Bitrix24com/rest-bot-echotest/

Full List of Bot API Methods and Events

Working with chatbots:

MethodMethod Description
imbot.register Chatbot registration.
imbot.unregister Chatbot deletion.
imbot.update Chatbot data update.

Working with chats:

MethodMethod Description
imbot.chat.user.list Retrieving list of participants.
imbot.chat.user.add Participants invitation.
imbot.chat.user.delete Participants deletion.
imbot.chat.leave Chatbot exit from specified chat.
imbot.chat.updateTitle Chat title update.
imbot.chat.updateColor Chat color update.
imbot.chat.updateAvatar Chat icon update.

Working with messages:

MethodMethod Description
imbot.message.add Sending message from chatbot.
imbot.message.update Sending chatbot message update.
imbot.message.delete Chatbot message deletion.
imbot.message.like Message «Like».
imbot.chat.sendTyping Sending «Chatbot is typing a message...".

Working with commands:

MethodMethod Description
imbot.command.register Registration of command to be processed by chatbot.
imbot.command.unregister Command processing deletion.
imbot.command.update Command data update.
imbot.command.answer Posting command answer.

Working with events:

EventEvent description
ONAPPINSTALL Application installation event.
ONAPPUPDATE Application update event.
ONIMBOTMESSAGEADD Event for chatbot to receive message.
ONIMCOMMANDADD Event for chatbot to receive a command.
ONIMJOINCHAT Event for chatbot to receive information that it has joined a chat (or private chat).
ONIMBOTDELETE Event to delete chatbot.


Chat API

To work with Chat API when creating an application (or loading of new app version) the im (Chat and notifications) scope must be specified.


Platform version

im.revision.get

The method gets information about API revisions

Revision: 18

Parameters

None.

Call example

JavaScript

BX24.callMethod('im.revision.get', {}, function(result){
	if(result.error())
	{
		console.error(result.error().ex);
	}
	else
	{
		console.log(result.data());
	}
});

PHP

$result = restCommand('im.revision.get', Array(
), $_REQUEST["auth"]);

Example of response

{    
	"result": {
		"rest": 18,
		"web": 117,
		"mobile": 9,
	}
}

Description of keys:

  • rest – API revision for REST clients
  • web – API revision for web/desktop client
  • mobile – API revision for mobile client

Attention! The method is specified with using of the restCommand function. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.



Working with Chats

Attention! The restCommand function is used in all methods. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.


Create chat

REST method: im.chat.add

Method call:
$result = restCommand('im.chat.add', Array(

   'TYPE' => 'CHAT' // OPEN - opened to join chat, CHAT - usual chat with invitations, CHAT by default 
   'TITLE' => 'My new private chat', // Chat title
   'DESCRIPTION' => 'Very important chat', // Chat description
   'COLOR' => 'PINK', // Chat color for mobile application - RED, GREEN, MINT, LIGHT_BLUE, DARK_BLUE, PURPLE, AQUA, PINK, LIME, BROWN, AZURE, KHAKI, SAND, MARENGO, GRAY, GRAPHITE
   'MESSAGE' => 'Welcome to the chat', // First greeting message in the chat
   'USERS' => Array(1,2), // Chat participants (req.)
   'AVATAR' => '/* base64 image */', // Chat icon in base64 format
   'ENTITY_TYPE' => 'CHAT', // Arbitrary entity ID (for example CHAT, CRM, OPENLINES, CALL and etc.), can be used for chat search and easy context definition in the following event handlers: ONIMBOTMESSAGEADD, ONIMBOTMESSAGEUPDATE, ONIMBOTMESSAGEDELETE
   'ENTITY_ID' => 13, // Entity numerical ID; it can be used for chat search and for easy context definition in the following event handlers: ONIMBOTMESSAGEADD, ONIMBOTMESSAGEUPDATE, ONIMBOTMESSAGEDELETE
   'OWNER_ID' => 39, // Chat owner ID. May not be specified, if your are creating chat under the necessary user.

), $_REQUEST["auth"]);
Required fields: USERS (chat participants).

Returns: CHAT_ID chat numerical ID or an error.

Possible errors:

Error codeError description
USERS_EMPTY No chat participants.
WRONG_REQUEST Something went wrong.


Retrieve list of participants

REST method: im.chat.user.list

Method call:
$result = restCommand('im.chat.user.list', Array(

   'CHAT_ID' => 13 // Chat ID

), $_REQUEST["auth"]);
Return: array of participants IDs or an error.

Possible errors:

Error codeError description
CHAT_ID_EMPTY No Chat ID.


Invite participants

REST method: im.chat.user.add

Method call:
$result = restCommand('im.chat.user.add', Array(

   'CHAT_ID' => 13 // Chat ID
   'USERS' => Array(3,4) // New user IDs

), $_REQUEST["auth"]);
Return: true or an error.

Possible errors:

Error codeError description
CHAT_ID_EMPTY No Chat ID.
WRONG_REQUEST You have insufficient rights to add participant to chat or this participant is already joined the chat.


Delete chat participants

REST method: im.chat.user.delete

Method call:
$result = restCommand('im.chat.user.delete', Array(

   'CHAT_ID' => 13 // Chat ID
   'USER_ID' => 4 // Deleted user ID

), $_REQUEST["auth"]);
Return: true or an error.

Possible errors:

Error codeError description
CHAT_ID_EMPTY No Chat ID.
USER_ID_EMPTY No User ID.
WRONG_REQUEST You have insufficient rights to add participant to chat or this participant is already joined the chat.


Exit chat

REST method: im.chat.leave

Method call:
$result = restCommand('im.chat.leave', Array(

   'CHAT_ID' => 13 // Chat ID

), $_REQUEST["auth"]);
Return: true or an error.

Possible errors:

Error codeError description
CHAT_ID_EMPTY No Chat ID.
WRONG_REQUEST You are not a member of this chat.


Send «Writing to you...» status

REST method: im.chat.sendTyping

Method call:
$result = restCommand('im.chat.sendTyping', Array(

   'CHAT_ID' => 13 // Chat ID

), $_REQUEST["auth"]);
Return: true or an error.

Possible errors:

Error codeError description
CHAT_ID_EMPTY No Chat ID.
ACCESS_ERROR You have insufficient rights to send status to this chat.


Chat title update

REST method: im.chat.updateTitle

Method call:
$result = restCommand('im.chat.updateTitle', Array(

   'CHAT_ID' => 13 // Chat ID
   'TITLE' => 'New name for chat' // New title

), $_REQUEST["auth"]);
Return: true or an error.

Possible errors:

Error codeError description
CHAT_ID_EMPTY No Chat ID.
TITLE_EMPTY New chat title unavailable.
WRONG_REQUEST Title is not specified or indicated chat does not exist.


Chat color update

REST method: im.chat.updateColor

Method call:
$result = restCommand('im.chat.updateColor', Array(

   'CHAT_ID' => 13 // Chat ID
   'COLOR' => 'MINT' // Chat color for mobile application - RED, GREEN, MINT, LIGHT_BLUE, DARK_BLUE, PURPLE, AQUA, PINK, LIME, BROWN,  AZURE, KHAKI, SAND, MARENGO, GRAY, GRAPHITE

), $_REQUEST["auth"]);
Return: true or an error.

Possible errors:

Error codeError description
CHAT_ID_EMPTY No Chat ID.
WRONG_COLOR Color is not in available colors list.
WRONG_REQUEST Color is already specified or indicated chat does not exist.


Chat icon update

REST method: im.chat.updateAvatar

Method call:
$result = restCommand('im.chat.updateAvatar', Array(

   'CHAT_ID' => 13 // Chat ID
   'AVATAR' => '/* base64 image */' // Image in base64 format

), $_REQUEST["auth"]);
Return: true or an error.

Possible errors:

Error codeError description
CHAT_ID_EMPTY Chat ID was not transmitted.
AVATAR_ERROR Incorrect image format is transmitted.
WRONG_REQUEST Chat does not exist.


Change of chat owner

REST method: im.chat.setOwner

Method call:
$result = restCommand('im.chat.setOwner', Array(

   'CHAT_ID' => 13 // Chat ID
   'USER_ID' => '2' // New chat owner ID

), $_REQUEST["auth"]);
Return: true or an error.

Possible errors:

Error codeError description
CHAT_ID_EMPTY Chat ID was not transmitted.
USER_ID_EMPTY New chat owner ID was not transmitted.
WRONG_REQUEST Method is called by user without owner's rights or indicated user is not a chat participant.

Get chat ID

REST method: im.chat.get

Method call:
$result = restCommand('im.chat.get', Array(


   'ENTITY_TYPE' => 'OPEN', // Arbitrary entity ID (for example CHAT, CRM, OPENLINES, CALL and etc.), can be used for chat search and easy context definition in the following event handlers: ONIMBOTMESSAGEADD, ONIMBOTMESSAGEUPDATE, ONIMBOTMESSAGEDELETE (req.)
   'ENTITY_ID' => 13, // Numerical entity ID; it can be used for chat search and easy context definition in the following events handlers: ONIMBOTMESSAGEADD, ONIMBOTMESSAGEUPDATE, ONIMBOTMESSAGEDELETE  (req.)

), $_REQUEST["auth"]);
Required fields:
ENTITY_TYPE - arbitrary entity ID (for example CHAT, CRM, OPENLINES, CALL and etc); it can be used for chat search and for easy app context definition in the event handlers ONIMBOTMESSAGEADD, ONIMBOTMESSAGEUPDATE, ONIMBOTMESSAGEDELETE.
ENTITY_ID - numeric entity ID; it can be used for chat search and for easy app context definition in the event handlers ONIMBOTMESSAGEADD, ONIMBOTMESSAGEUPDATE, ONIMBOTMESSAGEDELETE.

Returns: returns chat ID CHAT_ID or null.


im.chat.mute

The method disables notifications in chat

Revision: 19
Get information on the current API revision (platform version) – im.revision.get.

Parameters

Parameter Example Req. Description Revision
CHAT_ID 17 Yes Chat ID 19
MUTE Y No Disable or enable notifications - Y|N 19
  • Variants of MUTE key: Y or N.

Method call

JavaScript

BX24.callMethod('im.chat.mute', {
	'CHAT_ID': 17,
	'MUTE': 'Y'
}, function(result){
	if(result.error())
	{
		console.error(result.error().ex);
	}
	else
	{
		console.log(result.data());
	}
});

PHP

$result = restCommand('im.chat.mute', Array(
	'CHAT_ID' => 17,
	'MUTE' => 'Y'
), $_REQUEST["auth"]);

Examples of result

{
	"result": true
}

Example of result when error occurs

{
    "error": "CHAT_ID_EMPTY",
    "error_description": "Chat ID can't be empty"
}

Description of keys:

  • error – error code
  • error_description – brief description of error

Possible error codes

Code Description
CHAT_ID_EMPTY Chat ID not passed

Attention! The method is specified with using of the restCommand function. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.



Working with Dialogs

Attention! The restCommand function is used in all methods. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.


MethodMethod description
im.dialog.messages.get Gets list of last messages in chat.


im.dialog.messages.get

The method gets the list of last messages in chat

Revision: 19
Get information on the current API revision (platform version) – im.revision.get.

Parameters

Parameter Example Req. Description Revision
DIALOG_ID chat29 Yes Dialog ID to load messages 19
LAST_ID 28561624 No ID of the last loaded message 19
FIRST_ID 454322 No ID of the first loaded message 19
LIMIT 20 No Limiting of number of selected messages in dialog 19
  • If the LAST_ID and FIRST_ID keys were not passed, the last 20 chat messages will be loaded.
  • To load next 20 messages you must pass LAST_ID with the minimal message ID, received from the last selection.
  • If you need to load next 20 messages, you must pass FIRST_ID with the maximum message ID, received from the last selection.
  • If you need to load first 20 messages, you must pass FIRST_ID with the ID equal to '0'. You will receive the result with the very first message, available to you in this chat.

Attention! Due to potential significant volume of data, this method does not support standard Bitrix24 REST API pagewise navigation.


Method call

JavaScript

BX24.callMethod('im.dialog.messages.get', {
	DIALOG_ID: 'chat29'
}, function(result){
	if(result.error())
	{
		console.error(result.error().ex);
	}
	else
	{
		console.log(result.data());
	}
});

PHP

$result = restCommand('im.dialog.messages.get', Array(
	'DIALOG_ID': 'chat29'
), $_REQUEST["auth"]);

Example of response

{
	"result": {
		"messages": [
		  {
			"id": 28561624,
			"chat_id": 29,
			"author_id": 1,
			"date": "2018-01-29T16:58:47+03:00",
			"text": "http://squirrel.com",
			"params": {
			  "URL_ID": [
				5
			  ],
			  "URL_ONLY": "Y",
			  "ATTACH": [
				{
				  "ID": "5",
				  "BLOCKS": [
					{
					  "RICH_LINK": [
						{
						  "NAME": "Squirrel",
						  "LINK": "http://squirrel.com",
						  "DESC": "Can find everything",
						  "PREVIEW": "https://yastatic.net/morda-logo/i/share-logo-ru.png"
						}
					  ]
					}
				  ],
				  "COLOR": "transparent"
				}
			  ]
			}
		  },
		  {
			"id": 28561623,
			"chat_id": 29,
			"author_id": 28,
			"date": "2018-01-29T16:43:38+03:00",
			"text": "",
			"params": {
			  "FILE_ID": [
				540
			  ]
			}
		  },
		  {
			"id": 28561622,
			"chat_id": 29,
			"author_id": 1,
			"date": "2018-01-29T16:43:12+03:00",
			"text": "Its operational :)",
			"params": {
			  "IS_EDITED": "Y"
			}
		  },
		  {
			"id": 28561618,
			"chat_id": 29,
			"author_id": 0,
			"date": "2018-01-25T15:15:22+03:00",
			"text": "John Harrington changed chat topic to \"The big chat\"",
			"params": null
		  },
		],
		"users": {
		  "1": {
			"id": 1,
			"name": "John Harrington",
			"first_name": "John",
			"last_name": "Harrington",
			"work_position": "",
			"color": "#df532d",
			"avatar": "http://192.168.2.232/upload/resize_cache/main/1d3/100_100_2/Harrington.png",
			"gender": "M",
			"birthday": "",
			"extranet": false,
			"network": false,
			"bot": false,
			"connector": false,
			"external_auth_id": "default",
			"status": "online",
			"idle": false,
			"last_activity_date": "2018-01-29T17:35:31+03:00",
			"mobile_last_date": false,
			"departments": [
			  50
			],
			"absent": false,
			"phones": {
			  "work_phone": "",
			  "personal_mobile": "",
			  "personal_phone": ""
			}
		  },
		  "28": {
			"id": 28,
			"name": "Chris Curtis",
			"first_name": "Chris",
			"last_name": "Curtis",
			"work_position": "manager",
			"color": "#728f7a",
			"avatar": "http://192.168.2.232/upload/resize_cache/main/8b8/100_100_2/26.jpg",
			"gender": "M",
			"birthday": "26-01",
			"extranet": false,
			"network": false,
			"bot": false,
			"connector": false,
			"external_auth_id": "default",
			"status": "online",
			"idle": false,
			"last_activity_date": false,
			"mobile_last_date": false,
			"departments": [
			  58
			],
			"absent": false,
			"phones": {
			  "work_phone": "8 (97643) 4590-563-2318",
			  "personal_mobile": "8 (33741) 1578-234-8853",
			  "personal_phone": ""
			}
		  },
		},
		"files": {
			"540": {
				"id": 540,
				"chatId": 29,
				"date": "2018-01-29T16:43:39+03:00",
				"type": "image",
				"preview": "",
				"name": "1176297_698081120237288_696773366_n.jpeg",
				"size": 55013,
				"image": {
					"width": 960,
					"height": 640
				},
				"status": "done",
				"progress": 100,
				"authorId": 1,
				"authorName": "John Harrington",
				"urlPreview": "http://192.168.2.232/bitrix/components/bitrix/im.messenger/show.file.php?fileId=540&preview=Y&fileName=1176297_698081120237288_696773366_n.jpeg",
				"urlShow": "http://192.168.2.232/bitrix/components/bitrix/im.messenger/show.file.php?fileId=540&fileName=1176297_698081120237288_696773366_n.jpeg",
				"urlDownload": "http://192.168.2.232/bitrix/components/bitrix/im.messenger/download.file.php?fileId=540"
			}
		},
		"chat_id": 29
	}
}    

Description of keys:

  • messages – array of messages:

    • id – message ID
    • chat_id – chat ID
    • author_id – author of messages (0 - for system message)
    • date – date of the message in ATOM format
    • text – message text
    • params – message parameters, parameter object, if parameters are not passed null (main types are described below)
  • users – user data description objects:

    • id – user ID
    • name – user first and last name
    • first_name – user name
    • last_name – user last name
    • work_position – position
    • color – user color in 'hex' format
    • avatar – avatar link (if empty, then avatar is not specified)
    • gender – user gender
    • birthday – user birthday in DD-MM format, if empty – not specified
    • extranet – extranet user attribute (true/false)
    • network – Bitrix24.Network user attribute (true/false)
    • bot – bot attribute (true/false)
    • connector – Open Channels user attribute (true/false)
    • external_auth_id – external authorization code
    • status – selected user status
    • idle – idle date when user is not using his/her PC, in ATOM format (if not specified, false)
    • last_activity_date – date of the last user action, in ATOM format
    • mobile_last_date – date of the last action inside mobile app, in ATOM format (if not specified, false)
    • absent – date, to which the user has a leave of absence, in ATOM format (if not specified, false)
  • files – object, describing files in selected messages:

    • id – file ID
    • chatId – chat ID
    • date – date when file is modified
    • type – file type: image – image, file – file
    • name – name of loaded file
    • size – actual size of image in bytes
    • image – actual image size in px
    • width – width in px
    • height – height in px
    • status – current status: done – loaded, upload – loading in progress
    • progress – loading progress percentage: 100 – loaded, -1 – current status unavailable
    • authorId – ID of the user who loaded an object
    • authorName – first and last name of user who loaded an object
    • urlPreview – link to image preview (available fro images)
    • urlShow – link to switch to object in "show" mode
    • urlDownload – link to start the download
  • chat_id – chat ID

Description of additional parameters:

  • ATTACH – object containing rich formatting
  • KEYBOARD – object containing keyboard description
  • IS_DELETED – flag that specifies message deleting
  • IS_EDITED – flag that specifies that message is edited
  • FILE_ID – array of file IDs
  • LIKE – array of user IDs. Those user 'liked' the message

Examples of response when error occurs

{
    "error": "DIALOG_ID_EMPTY",
    "error_description": "Dialog ID can't be empty"
}

Description of keys:

  • error – error code
  • error_description – brief description of error

Possible error codes

Code Description
DIALOG_ID_EMPTY Dialog ID not passed
ACCESS_ERROR Current user does not have appropriate permissions to access the dialog

Attention! The method is specified with using of the restCommand function. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.



Working with Files

Attention! The restCommand function is used in all methods. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.


MethodMethod description
im.disk.folder.get Get information on the folder storing files for chat.
im.disk.file.commit Publish uploaded file into chat.
im.disk.file.delete Delete files inside chat folder.


im.disk.folder.get

The method gets information on folder storing files for chat

Revision: 18
Get information on the current API revision (platform version) – im.revision.get.

Parameters

Parameter Example Req. Description Revision
CHAT_ID 17 Yes Chat ID 18

Method call

JavaScript

BX24.callMethod('im.disk.folder.get', {
	'CHAT_ID': 17,
}, function(result){
	if(result.error())
	{
		console.error(result.error().ex);
	}
	else
	{
		console.log(result.data());
	}
});

PHP

$result = restCommand('im.disk.folder.get', Array(
	'CHAT_ID' => 17,
), $_REQUEST["auth"]);

Example of response

{
	"result": {
		ID: 127
	}
}   

Example of response when error occurs

{
    "error": "CHAT_ID_EMPTY",
    "error_description": "Chat ID can't be empty"
}

Description of keys:

  • error – error code
  • error_description – brief description of error

Possible error codes

Code Description
CHAT_ID_EMPTY Chat ID not passed
ACCESS_ERROR Current user does not have appropriate permissions to access the dialog
INTERNAL_ERROR Server error, please contact technical support

Attention! The method is specified with using of the restCommand function. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.



im.disk.file.commit

The method publishes loaded file in the chat

Revision: 18
Get information on the current API revision (platform version) – im.revision.get.

Parameters

Parameter Example Req. Description Revision
CHAT_ID 17 Yes Chat ID 18
UPLOAD_ID 213 Yes* ID of the file, downloaded via DISK module methods 18
DISK_ID 112 Yes* ID of the file, available from the local drive 18
MESSAGE Important document No File description will be published in chat 18
SILENT_MODE N No Open Channel chat parameter that specifies if the file data was sent to a client or to another designation 18
  • To call the API successfully, specify CHAT_ID and one за two fields – UPLOAD_ID or DISK_ID.

Attention! File must be preliminarily downloaded via the disk.folder.uploadfile method.


Method call

JavaScript

BX24.callMethod('im.disk.file.commit', {
	'CHAT_ID': 17,
	'UPLOAD_ID': 112,
}, function(result){
	if(result.error())
	{
		console.error(result.error().ex);
	}
	else
	{
		console.log(result.data());
	}
});

PHP

$result = restCommand('im.disk.file.commit', Array(
	'CHAT_ID' => 17,
	'UPLOAD_ID' => 112,
), $_REQUEST["auth"]);

Example of response

{
	"result": true
} 

Example of response when error occurs

{
    "error": "CHAT_ID_EMPTY",
    "error_description": "Chat ID can't be empty"
}

Description of keys:

  • error – error code
  • error_description – brief description of error

Possible error codes

Code Description
CHAT_ID_EMPTY Chat ID not passed
ACCESS_ERROR Current user does not have permissions to access the dialog
FILES_ERROR File ID not passed

Attention! The method is specified with using of the restCommand function. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.



im.disk.file.delete

The method deletes files inside chat folder

Revision: 18
Get information on the current API revision (platform version) – im.revision.get.

Parameters

Parameter Example Req. Description Revision
CHAT_ID 17 Yes Chat ID 18
DISK_ID 112 Yes File ID 18

Method call

JavaScript

BX24.callMethod('im.disk.file.delete', {
	'CHAT_ID': 17,
	'DISK_ID': 112,
}, function(result){
	if(result.error())
	{
		console.error(result.error().ex);
	}
	else
	{
		console.log(result.data());
	}
});

PHP

$result = restCommand('im.disk.file.delete', Array(
	'CHAT_ID' => 17,
	'DISK_ID' => 112,
), $_REQUEST["auth"]);

Example of response

{
	"result": true
} 

Example of response when error occurs

{
    "error": "CHAT_ID_EMPTY",
    "error_description": "Chat ID can't be empty"
}

Description of keys:

  • error – error code
  • error_description – brief description of error

Possible error codes

Code Description
CHAT_ID_EMPTY Chat ID not passed
FILES_ERROR File ID not passed

Attention! The method is specified with using of the restCommand function. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.



Working with Users

Attention! The restCommand function is used in all methods. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.


MethodMethod description
im.user.get Get user data.
im.user.list.get Get multiple users data.
im.user.business.list Get list of users with Bitrix24 business tools access.
im.user.status.get Get information on specified user status.
im.user.status.set Specify user status.
im.user.status.idle.start Specify the automatic status «Away».
im.user.status.idle.end Disable the automatuc status «Away».


im.user.get

The method gets user data

Revision: 18
Get information on the current API revision (platform version) – im.revision.get.

Parameters

Parameter Example Req. Description Revision
ID 5 No User ID 18
AVATAR_HR N No Generate avatar in high resolution 18
  • If the ID key is not passed, current user data will be selected.

Method call

JavaScript

BX24.callMethod('im.user.get', {ID: 5}, function(result){
	if(result.error())
	{
		console.error(result.error().ex);
	}
	else
	{
		console.log(result.data());
	}
});

PHP

$result = restCommand('im.user.get', Array(
	'ID' => 5,
), $_REQUEST["auth"]);	

Example of response

{
	"result": {
		"id": 5,
		"name": "John Harrington",
		"first_name": "John",
		"last_name": "Harrington",
		"work_position": "",
		"color": "#df532d",
		"avatar": "http://192.168.2.232/upload/resize_cache/main/1d3/100_100_2/Harrington.png",
		"gender": "M",
		"birthday": "",
		"extranet": false,
		"network": false,
		"bot": false,
		"connector": false,
		"external_auth_id": "default",
		"status": "online",
		"idle": false,
		"last_activity_date": "2018-01-29T17:35:31+03:00",
		"desktop_last_date": false,
		"mobile_last_date": false,
		"departments": [
		  50
		],
		"absent": false,
		"phones": {
		  "work_phone": "",
		  "personal_mobile": "",
		  "personal_phone": ""
		}
	}
}   

Description of keys:

  • id – user ID
  • name – first and last user name
  • first_name – user first name
  • last_name – user last name
  • work_position – position
  • color – user color in 'hex' format
  • avatar – link to avatar (if empty, the avatar is not specified)
  • avatar_hr – link to avatar in high resolution (available only when a query with parameter AVATAR_HR = 'Y')
  • gender – user gender
  • birthday – user birthday in the DD-MM format, if empty – not specified
  • extranet – extranet user attribute (true/false)
  • network – Bitrix24.Network user attribute Bitrix24.Network (true/false)
  • bot – bot attribute (true/false)
  • connector – Open Channel user attribute (true/false)
  • external_auth_id – external authorization code
  • status – user selected status
  • idle – date, when user is not using his/her PC, in ATOM format (if not specified, false)
  • last_activity_date – date of the last user action, in ATOM format
  • mobile_last_date – date of the last action inside mobile app, in ATOM format (if not specified, false)
  • departments – department IDs
  • desktop_last_date – date of the action in the desktop app, in ATOM format (if not specified, false)
  • absent – date, to which the user has a leave of absence, in ATOM format (if not specified, false)
  • phones – array of phone numbers: work_phone – work phone, personal_mobile – mobile phone, personal_phone – personal phone number

Example of response when an error occurs

{
    "error": "ID_EMPTY",
    "error_description": "User ID can't be empty"
}

Description of keys:

  • error – error code
  • error_description – brief description of error

Possible error codes

Code Description
ID_EMPTY User ID not passed
USER_NOT_EXISTS User with indicated ID not found
ACCESS_DENIED Current user does not have permissions to access the data

Attention! The method is specified with using of the restCommand function. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.



im.user.list.get

The method gets multiple users data

Revision: 19
Get information on the current API revision (platform version) – im.revision.get.

Parameters

Parameter Example Req. Description Revision
ID [4,5] Yes User IDs 19
AVATAR_HR N No Generate avatar in high resolution 19
  • If the ID key is not passed, current user data will be selected.

Method call

JavaScript

BX24.callMethod('im.user.list.get', {ID: [4,5]}, function(result){
	if(result.error())
	{
		console.error(result.error().ex);
	}
	else
	{
		console.log(result.data());
	}
});

PHP

$result = restCommand('im.user.list.get', Array(
	'ID' => [4,5],
), $_REQUEST["auth"]);	

Example of response

{
	"result": {
		4: null,
		5: {
			"id": 5,
			"name": "John Harrington",
			"first_name": "John",
			"last_name": "Harrington",
			"work_position": "",
			"color": "#df532d",
			"avatar": "http://192.168.2.232/upload/resize_cache/main/1d3/100_100_2/Harrington.png",
			"gender": "M",
			"birthday": "",
			"extranet": false,
			"network": false,
			"bot": false,
			"connector": false,
			"external_auth_id": "default",
			"status": "online",
			"idle": false,
			"last_activity_date": "2018-01-29T17:35:31+03:00",
			"desktop_last_date": false,
			"mobile_last_date": false,
			"departments": [
			  50
			],
			"absent": false,
			"phones": {
			  "work_phone": "",
			  "personal_mobile": "",
			  "personal_phone": ""
			}
		}
	}
} 

Description of keys:

  • id – user ID
  • name – user first and last name
  • first_name – user name
  • last_name – user last name
  • work_position – position
  • color – user color in 'hex' format
  • avatar – link to avatar (if empty, avatar is not specified)
  • avatar_hr – link to avatar in high resolution (available only when a query with parameter AVATAR_HR = 'Y')
  • gender – user gender
  • birthday – user birthday in the DD-MM format, if empty – not specified
  • extranet – extranet user attribute (true/false)
  • network – Bitrix24.Network user attribute (true/false)
  • bot – bot attribute (true/false)
  • connector – Open Channel user attribute (true/false)
  • external_auth_id – external authorization code
  • status – selected user status
  • idle – date, when user is not using his/her PC, in ATOM format (if not specified, false)
  • last_activity_date – date of the last user action, in ATOM format
  • mobile_last_date – date of the last action inside mobile app, in ATOM format (if not specified, false)
  • departments – department IDs
  • desktop_last_date – date of the action in the desktop app, in ATOM format (if not specified, false)
  • absent – date, to which the user has a leave of absence, in ATOM format (if not specified, false)
  • phones – array of phone numbers: work_phone – work phone, personal_mobile – mobile phone, personal_phone – personal phone number

  • Example of response when an error occurs

    {
        "error": "INVALID_FORMAT",
        "error_description": "A wrong format for the ID field is passed"
    }
    

    Description of keys:

    • error – error code
    • error_description – brief description of error

    Possible error codes

    Code Description
    INVALID_FORMAT User ID not passed

    Attention! The method is specified with using of the restCommand function. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.



    im.user.business.list

    The method gets list of users with access to business tools

    Revision: 19
    Get information on the current API revision (platform version) – im.revision.get.

    Parameters

    Parameter Example Req. Description Revision
    USER_DATA N No Download user data 19
    OFFSET 0 No Offset user selection 19
    LIMIT 10 No Limit of user selection 19
    • If the parameter USER_DATA = Y is passed, the response will pass array of objects with user data instead of user IDs array.
    • If users cannot access business tools, false is returned in the response.
    • The method supports standard Bitrix24 REST API pagewise navigation. Additionally, there is a feature to build the navigation via OFFSET and LIMIT parameters.

    Method call

    JavaScript

    BX24.callMethod('im.user.business.list', {USER_DATA: 'Y'}, function(result){
    	if(result.error())
    	{
    		console.error(result.error().ex);
    	}
    	else
    	{
    		console.log('users', result.data());
    		console.log('total', result.total());
    	}
    });
    

    PHP

    $result = restCommand('im.user.business.list', Array(
    	'USER_DATA' => 'Y'
    ), $_REQUEST["auth"]);
    

    Example of response

    With the USER_DATA = N option:

    {
    	"result": [1],
    	"total": 1
    } 
    

    With the USER_DATA = Y option:

    {    
    	"result": [
    		{
    			"id": 1,
    			"name": "John Harrington",
    			"first_name": "John",
    			"last_name": "Harrington",
    			"work_position": "",
    			"color": "#df532d",
    			"avatar": "http://192.168.2.232/upload/resize_cache/main/1d3/100_100_2/Harrington.png",
    			"gender": "M",
    			"birthday": "",
    			"extranet": false,
    			"network": false,
    			"bot": false,
    			"connector": false,
    			"external_auth_id": "default",
    			"status": "online",
    			"idle": false,
    			"last_activity_date": "2018-01-29T17:35:31+03:00",
    			"desktop_last_date": false,
    			"mobile_last_date": false,
    			"departments": [
    			  50
    			],
    			"absent": false,
    			"phones": {
    			  "work_phone": "",
    			  "personal_mobile": "",
    			  "personal_phone": ""
    			}
    		}
    	],
    	"total": 1
    }  
    

    Description of keys:

    • id – user ID
    • name – user first and last name
    • first_name – user name
    • last_name – user last name
    • work_position – position
    • color – user color in 'hex' format
    • avatar – link to avatar (if empty, avatar is not specified)
    • avatar_hr – link to avatar in high resolution (available only when a query with parameter AVATAR_HR = 'Y')
    • gender – user gender
    • birthday – user birthday in the DD-MM format, if empty – not specified
    • extranet – extranet user attribute (true/false)
    • network – Bitrix24.Network user attribute (true/false)
    • bot – bot attribute (true/false)
    • connector – Open Channel user attribute (true/false)
    • external_auth_id – external authorization code
    • status – selected user status
    • idle – date, when user is not using his/her PC, in ATOM format (if not specified, false)
    • last_activity_date – date of the last user action, in ATOM format
    • mobile_last_date – date of the last action inside mobile app, in ATOM format (if not specified, false)
    • departments – department IDs
    • desktop_last_date – date of the action in the desktop app, in ATOM format (if not specified, false)
    • absent – date, to which the user has a leave of absence, in ATOM format (if not specified, false)
    • phones – array of phone numbers: work_phone – work phone, personal_mobile – mobile phone, personal_phone – personal phone number

    Attention! The method is specified with using of the restCommand function. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.



    im.user.status.get

    The method gets information on the specified user status

    Revision: 18
    Get information on the current API revision (platform version) – im.revision.get.

    Parameters

    None

    Method call

    JavaScript

    BX24.callMethod('im.user.status.get', {}, function(result){
    	if(result.error())
    	{
    		console.error(result.error().ex);
    	}
    	else
    	{
    		console.log(result.data());
    	}
    });
    

    PHP

    $result = restCommand('im.user.status.get', Array(
    ), $_REQUEST["auth"]);
    

    Example of response

    {
    	"result": "dnd"
    }
    

    Description of result:

    • online – Online
    • dnd – Do not disturb
    • away – Away

    Attention! The method is specified with using of the restCommand function. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.



    im.user.status.set

    The method specifies user status

    Revision: 18
    Get information on the current API revision (platform version) – im.revision.get.

    Parameters

    Parameter Example Req. Description Revision
    STATUS online Yes New user status 18

    The following statuses are available:

    • online – Online
    • dnd – Do not disturb
    • away – Away

    Method call

    JavaScript

    BX24.callMethod('im.user.status.set', {}, function(result){
    	if(result.error())
    	{
    		console.error(result.error().ex);
    	}
    	else
    	{
    		console.log(result.data());
    	}
    });
    

    PHP

    $result = restCommand('im.user.status.set', Array(
    ), $_REQUEST["auth"]);
    

    Example of response

    {
      "result": true
    }
    

    Attention! The method is specified with using of the restCommand function. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.



    im.user.status.idle.start

    The method specifies automatic status "Away"

    Revision: 18
    Get information on the current API revision (platform version) – im.revision.get.

    Parameters

    Parameter Example Req. Description Revision
    AGO 10 No Number of minutes away 18

    Method call

    JavaScript

    BX24.callMethod('im.user.status.idle.start', {
    	'AGO': 10
    }, function(result){
    	if(result.error())
    	{
    		console.error(result.error().ex);
    	}
    	else
    	{
    		console.log(result.data());
    	}
    });
    

    PHP

    $result = restCommand('im.user.status.idle.start', Array(
    	'AGO' => 10
    ), $_REQUEST["auth"]);
    

    Example of response

    {
      "result": true
    }
    

    Attention! The method is specified with using of the restCommand function. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.



    im.user.status.idle.end

    The method disables automatic status "Away"

    Revision: 18
    Get information on the current API revision (platform version) – im.revision.get.

    Parameters

    None

    Method call

    JavaScript

    BX24.callMethod('im.user.status.idle.end', {}, function(result){
    	if(result.error())
    	{
    		console.error(result.error().ex);
    	}
    	else
    	{
    		console.log(result.data());
    	}
    });
    

    PHP

    $result = restCommand('im.user.status.idle.start', Array(
    ), $_REQUEST["auth"]);	
    

    Example of response

    {
      "result": true
    }
    

    Attention! The method is specified with using of the restCommand function. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.



    Working with Messages

    Attention! The restCommand function is used in all methods. You can send a REST command with your own function, or use the BX24.callMethod or bitrix24-php-sdk JavaScript methods.


    Send message to chat

    REST method: im.message.add

    Method call:
    $result = restCommand('im.message.add', Array(
    
        'CHAT_ID' => 13, // Recipient chat ID, if message is for chat
        'USER_ID' => 2, // Recipient user ID, if message is for private chat 
        'MESSAGE' => 'Message text' // Message test
        'SYSTEM' => 'N' // To display message as system message or not, optional field, by default 'N'
        'ATTACH' => '' // Attachment, optional field
        'URL_PREVIEW' => 'Y' // Convert links to rich-links, optional field, by default 'Y'
        'KEYBOARD' => '' // Keyboard, optional field
        'MENU' => '' // Context menu, optional field
    ), $_REQUEST["auth"]);
    
    Return: MESSAGE_ID ID or an error.

    Related Links:

    Using Keyboards
    Attachments
    Formatting


    Possible errors:

    Error codeError description
    USER_ID_EMPTY Chat ID not specified, if message is sent in person-to-person chat.
    CHAT_ID_EMPTY Chat ID not specified if message is sent to chat.
    ACCESS_ERROR Insufficient rights to send message.
    MESSAGE_EMPTY No message text.
    ATTACH_ERROR Complete sent attachment object was not validated.
    ATTACH_OVERSIZE Maximum permissible attachment size was exceeded (30 Kb).
    KEYBOARD_ERROR Complete sent keyboard object was not validated.
    KEYBOARD_OVERSIZE Maximum permissible keyboard size was exceeded (30 Kb).
    MENU_ERROR Complete attachment object was not validated.
    MENU_OVERSIZE Maximum permissible menu size was exceeded (30 Kb).
    PARAMS_ERROR Something went wrong.


    Update chatbot message

    REST method: im.message.update

    Method call:
    $result = restCommand('im.message.update', Array(
    
        'MESSAGE_ID' => 1, // Message ID
        'MESSAGE' => 'answer text' // Message test, optional field, if empty value is specified - message will be deleted
        'ATTACH' => '' // Attachment, optional field
        'URL_PREVIEW' => 'Y' // Convert links to rich-links, optional field
        'KEYBOARD' => '' // Keyboard, optional field
        'MENU' => '' // Context menu, optional field
    ), $_REQUEST["auth"]);
    
    Return: true or an error.

    Related Links:

    Using Keyboards
    Attachments
    Formatting


    Possible errors:

    Error codeError description
    MESSAGE_ID_ERROR No message ID.
    CANT_EDIT_MESSAGE You do not have access to this message or time to modify it has expired (3 days passed since message posting).
    ATTACH_ERROR Complete sent attachment object not validated.
    ATTACH_OVERSIZE Maximum permissible attachment size was exceeded (30 Kb).
    KEYBOARD_ERROR Complete sent keyboard object not validated.
    KEYBOARD_OVERSIZE Maximum permissible keyboard size was exceeded (30 Kb).
    MENU_ERROR Complete sent menu object not validated.
    MENU_OVERSIZE Maximum permissible menu size was exceeded (30 Kb).


    Delete chatbot message

    REST method: im.message.delete

    Method call:
    $result = restCommand('im.message.delete', Array(
    
        'MESSAGE_ID' => 1, // Message ID
    
    ), $_REQUEST["auth"]);
    
    Return: true or an error.

    Possible errors:

    Error codeError description
    MESSAGE_ID_ERROR No message ID.
    CANT_EDIT_MESSAGE You don't have access to this message or time to modify it has expired (3 days passed since message posting).


    Message “Like”

    REST method: im.message.like

    Method call:
    $result = restCommand('im.message.like', Array(
    
        'MESSAGE_ID' => 1, // Message ID (any message, sent in private or group chats that have chatbot)
        'ACTION' => 'auto' // Action, connected with method: plus - select «Like»; minus – remove «Like»; auto – automatic calculation, whether specified or not. If 'Like' is not specified, auto mode operation
    
    ), $_REQUEST["auth"]);
    
    Return: true or an error.

    Possible errors:

    Error codeError description
    MESSAGE_ID_ERROR No message ID.
    WITHOUT_CHANGES «Like» status.


    Working with Departments

    Attention! The restCommand function is used in all methods. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.


    Methodmethod description
    im.department.get Get data department data.
    im.department.colleagues.list Get list of users included into your department.
    im.department.managers.get Get list of department managers.
    im.department.employees.get Get list of department employees.


    im.department.get

    The method gets department data

    Revision: 18
    To get information about the current API revision (platform version) – im.revision.get.

    Parameters

    Parameter Example Req. Description Revision
    ID [51] Yes Department ID 18
    USER_DATA N No Download user data 18
    • If the USER_DATA = Y parameter is passed, manager data will downloaded additionally with the result.

    Method call

    JavaScript

    BX24.callMethod('im.department.get', {ID: [51]}, function(result){
    	if(result.error())
    	{
    		console.error(result.error().ex);
    	}
    	else
    	{
    		console.log(result.data());
    	}
    });
    

    PHP

    $result = restCommand('im.department.get', Array(
    	'ID' => [51],
    ), $_REQUEST["auth"]);	
    

    Example of response

    {
    	"result": [
    		{
    			"id": 51,
    			"name": "New York branch",
    			"full_name": "New York branch / Bitrix24"
    			"manager_user_id": 11,
    		}
    	]
    }    
    

    Description of keys:

    • id – department ID
    • name – department abbreviated name
    • full_name – department full name
    • manager_user_data – manager data description object (unavailable, if USER_DATA != 'Y'):
      • id – user ID
      • name – user first and last name
      • first_name – user name
      • last_name – user last name
      • work_position – position
      • color – user color in 'hex' format
      • avatar – link to avatar (if empty, avatar is not specified)
      • gender – user gender
      • birthday – user birthday in the DD-MM format, if empty – not specified
      • extranet – extranet user attribute (true/false)
      • network – Bitrix24.Network user attribute (true/false)
      • bot – bot attribute (true/false)
      • connector – Open Channel user attribute (true/false)
      • external_auth_id – external authorization code
      • status – selected user status
      • idle – date, when user is not using his/her PC, in ATOM format (if not specified, false)
      • last_activity_date – date of the last user action, in ATOM format
      • mobile_last_date – date of the last action inside mobile app, in ATOM format (if not specified, false)
      • absent – date, to which the user has a leave of absence, in ATOM format (if not specified, false)

    Example of response when error occurs

    {
        "error": "INVALID_FORMAT",
        "error_description": "A wrong format for the ID field is passed"
    }
    

    Description of keys:

    • error – error code
    • error_description – brief description of error

    Possible error codes

    Code Description
    INVALID_FORMAT Invalid ID format is passed

    Attention! The method is specified with using of the restCommand function. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.



    im.department.colleagues.list

    The method gets list of users in your department

    Revision: 19
    Get information on the current API revision (platform version) – im.revision.get.

    Parameters

    Parameter Example Req. Description Revision
    USER_DATA N No Download user data 19
    OFFSET 0 No Offset selection of users 19
    LIMIT 10 No User selection limit 19
    • If the USER_DATA = Y parameter is passed, the array of objects with the specific user data is passed instead of IDs array.
    • The method supports standard Bitrix24 REST API pagewise navigation. Additionally it can build navigation via OFFSET and LIMIT parameters.

    Method call

    JavaScript

    BX24.callMethod('im.department.colleagues.list', {USER_DATA: 'Y'}, function(result){
    	if(result.error())
    	{
    		console.error(result.error().ex);
    	}
    	else
    	{
    		console.log('users', result.data());
    		console.log('total', result.total());
    	}
    });
    

    PHP

    $result = restCommand('im.department.colleagues.list', Array(
    	'USER_DATA' => 'Y'
    ), $_REQUEST["auth"]);	
    

    Example of response

    With the option USER_DATA = N:

    {
    	"result": [1],
    	"total": 1
    }    
    

    With the option USER_DATA = Y:

    {    
    	"result": [
    		{
    			"id": 1,
    			"name": "John Harrington",
    			"first_name": "John",
    			"last_name": "Harrington",
    			"work_position": "",
    			"color": "#df532d",
    			"avatar": "http://192.168.2.232/upload/resize_cache/main/1d3/100_100_2/Harrington.png",
    			"gender": "M",
    			"birthday": "",
    			"extranet": false,
    			"network": false,
    			"bot": false,
    			"connector": false,
    			"external_auth_id": "default",
    			"status": "online",
    			"idle": false,
    			"last_activity_date": "2018-01-29T17:35:31+03:00",
    			"desktop_last_date": false,
    			"mobile_last_date": false,
    			"departments": [
    			  50
    			],
    			"absent": false,
    			"phones": {
    			  "work_phone": "",
    			  "personal_mobile": "",
    			  "personal_phone": ""
    			}
    		}
    	],
    	"total": 1
    }     
    

    Description of keys:

    • id – user ID
    • name – user first and last name
    • first_name – user name
    • last_name – user last name
    • work_position – position
    • color – user color in 'hex' format
    • avatar – link to avatar (if empty, avatar is not specified)
    • gender – user gender
    • birthday – user birthday in the DD-MM format, if empty – not specified
    • extranet – extranet user attribute (true/false)
    • network – Bitrix24.Network user attribute (true/false)
    • bot – bot attribute (true/false)
    • connector – Open Channel user attribute (true/false)
    • external_auth_id – external authorization code
    • status – selected user status
    • idle – date, when user is not using his/her PC, in ATOM format (if not specified, false)
    • last_activity_date – date of the last user action, in ATOM format
    • mobile_last_date – date of the last action inside mobile app, in ATOM format (if not specified, false)
    • desktop_last_date – date of the action in the desktop app, in ATOM format (if not specified, false)
    • absent – date, to which the user has a leave of absence, in ATOM format (if not specified, false)
    • phones – array of phone numbers: work_phone – work phone, personal_mobile – mobile phone, personal_phone – personal phone number

    Attention! The method is specified with using of the restCommand function. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.



    im.department.managers.get

    The method gets list of department managers

    Revision: 19
    Get information on the current API revision (platform version) – im.revision.get.

    Parameters

    Parameter Example Req. Description Revision
    ID [105] Yes Department IDs 19
    USER_DATA N No Download user data 19
    • If the USER_DATA = Y parameter is passed, the array of objects with user data will be passed in the response instead of IDs array.

    Method call

    JavaScript

    BX24.callMethod('im.department.managers.get', {USER_DATA: 'Y'}, function(result){
    	if(result.error())
    	{
    		console.error(result.error().ex);
    	}
    	else
    	{
    		console.log('users', result.data());
    	}
    });
    

    PHP

    $result = restCommand('im.department.managers.get', Array(
    	'USER_DATA' => 'Y'
    ), $_REQUEST["auth"]);
    

    Example of response

    With the option USER_DATA = N:

    {
    	"result": {
    		105: [1]
    	},
    }    
    

    With the option USER_DATA = Y:

    {    
    	"result": {
    		105: {
    			"id": 1,
    			"name": "John Harrington",
    			"first_name": "John",
    			"last_name": "Harrington",
    			"work_position": "",
    			"color": "#df532d",
    			"avatar": "http://192.168.2.232/upload/resize_cache/main/1d3/100_100_2/Harrington.png",
    			"gender": "M",
    			"birthday": "",
    			"extranet": false,
    			"network": false,
    			"bot": false,
    			"connector": false,
    			"external_auth_id": "default",
    			"status": "online",
    			"idle": false,
    			"last_activity_date": "2018-01-29T17:35:31+03:00",
    			"desktop_last_date": false,
    			"mobile_last_date": false,
    			"departments": [
    			  50
    			],
    			"absent": false,
    			"phones": {
    			  "work_phone": "",
    			  "personal_mobile": "",
    			  "personal_phone": ""
    			}
    		}
    	}
    }       
    

    Description of keys:

    • id – user ID
    • name – user first and last name
    • first_name – user name
    • last_name – user last name
    • work_position – position
    • color – user color in 'hex' format
    • avatar – link to avatar (if empty, avatar is not specified)
    • gender – user gender
    • birthday – user birthday in the DD-MM format, if empty – not specified
    • extranet – extranet user attribute (true/false)
    • network – Bitrix24.Network user attribute (true/false)
    • bot – bot attribute (true/false)
    • connector – Open Channel user attribute (true/false)
    • external_auth_id – external authorization code
    • status – selected user status
    • idle – date, when user is not using his/her PC, in ATOM format (if not specified, false)
    • last_activity_date – date of the last user action, in ATOM format
    • mobile_last_date – date of the last action inside mobile app, in ATOM format (if not specified, false)
    • desktop_last_date – date of the action in the desktop app, in ATOM format (if not specified, false)
    • absent – date, to which the user has a leave of absence, in ATOM format (if not specified, false)
    • phones – array of phone numbers: work_phone – work phone, personal_mobile – mobile phone, personal_phone – personal phone number

    Example of response when error occurs

    {
        "error": "ID_EMPTY",
        "error_description": "Department ID can't be empty"
    }
    

    Description of keys:

    • error – error code
    • error_description – brief description of error

    Possible error codes

    Code Description
    ID_EMPTY

    Attention! The method is specified with using of the restCommand function. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.



    im.department.employees.get

    The method gets list of employees in a department

    Revision: 19
    Get information on the current API revision (platform version) – im.revision.get.

    Parameters

    Parameter Example Req. Description Revision
    ID [105] Yes Department IDs 19
    USER_DATA N No Download user data 19
    • If the parameterUSER_DATA = Y, the array of objects with user data is passed in the response instead of IDs array.

    Method call

    JavaScript

    BX24.callMethod('im.department.employees.get', {USER_DATA: 'Y'}, function(result){
    	if(result.error())
    	{
    		console.error(result.error().ex);
    	}
    	else
    	{
    		console.log('users', result.data());
    	}
    });
    

    PHP

    $result = restCommand('im.department.employees.get', Array(
    	'USER_DATA' => 'Y'
    ), $_REQUEST["auth"]);	
    

    Example of response

    With the option USER_DATA = N:

    {
    	"result": {
    		105: [1]
    	}
    }    
    

    With the option USER_DATA = Y:

    {    
    	"result": {
    		105: {
    			"id": 1,
    			"name": "John Harrington",
    			"first_name": "John",
    			"last_name": "Harrington",
    			"work_position": "",
    			"color": "#df532d",
    			"avatar": "http://192.168.2.232/upload/resize_cache/main/1d3/100_100_2/Harrington.png",
    			"gender": "M",
    			"birthday": "",
    			"extranet": false,
    			"network": false,
    			"bot": false,
    			"connector": false,
    			"external_auth_id": "default",
    			"status": "online",
    			"idle": false,
    			"last_activity_date": "2018-01-29T17:35:31+03:00",
    			"desktop_last_date": false,
    			"mobile_last_date": false,
    			"departments": [
    			  50
    			],
    			"absent": false,
    			"phones": {
    			  "work_phone": "",
    			  "personal_mobile": "",
    			  "personal_phone": ""
    			}
    		}
    	}
    }       
    

    Description of keys:

    • id – user ID
    • name – user first and last name
    • first_name – user name
    • last_name – user last name
    • work_position – position
    • color – user color in 'hex' format
    • avatar – link to avatar (if empty, avatar is not specified)
    • gender – user gender
    • birthday – user birthday in the DD-MM format, if empty – not specified
    • extranet – extranet user attribute (true/false)
    • network – Bitrix24.Network user attribute (true/false)
    • bot – bot attribute (true/false)
    • connector – Open Channel user attribute (true/false)
    • external_auth_id – external authorization code
    • status – selected user status
    • idle – date, when user is not using his/her PC, in ATOM format (if not specified, false)
    • last_activity_date – date of the last user action, in ATOM format
    • mobile_last_date – date of the last action inside mobile app, in ATOM format (if not specified, false)
    • desktop_last_date – date of the action in the desktop app, in ATOM format (if not specified, false)
    • absent – date, to which the user has a leave of absence, in ATOM format (if not specified, false)
    • phones – array of phone numbers: work_phone – work phone, personal_mobile – mobile phone, personal_phone – personal phone number

    Example of response when error occurs

    {
        "error": "ID_EMPTY",
        "error_description": "Department ID can't be empty"
    }
    

    Description of keys:

    • error – error code
    • error_description – brief description of error

    Possible error codes

    Code Description
    ID_EMPTY ID list not passed

    Attention! The method is specified with using of the restCommand function. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.



    Working with Search

    Attention! The restCommand function is used in all methods. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.


    MethodMethod description
    im.search.user.list User search.
    im.search.chat.list Chat search.
    im.search.department.list Department search.
    im.search.last.get Get an element list of the last search.
    im.search.last.add And a history element of the last search.
    im.search.last.delete Delete a history element of the last search.


    im.search.user.list

    The method searches for users

    Revision: 19
    Get information on the current API revision (platform version) – im.revision.get.

    Parameters

    Parameter Example Req. Description Revision
    FIND John Yes Search phrase 19
    BUSINESS N No Search among users with business tool access 19
    AVATAR_HR N No Generate avatar in high resolution 19
    OFFSET 0 No Offset of user selection 19
    LIMIT 10 No User selection limit 19
    • Search is performed by the following fields: Name, Last name, Position, Department.
    • The method supports standard Bitrix24 REST API pagewise naviagation. Additionally, it can build navigation via the OFFSET and LIMIT parameters.

    Method call

    JavaScript

    BX24.callMethod('im.search.user.list', {
    	FIND: 'John'
    }, function(result){
    	if(result.error())
    	{
    		console.error(result.error().ex);
    	}
    	else
    	{
    		console.log('users', result.data());
    		console.log('total', result.total());
    	}
    });
    

    PHP

    $result = restCommand('im.search.user.list', Array(
    	'FIND' => 'Евгений'
    ), $_REQUEST["auth"]);	
    

    Example of response

    {    
    	"result": {
    		1: {
    			"id": 1,
    			"name": "John Harrington",
    			"first_name": "John",
    			"last_name": "Harrington",
    			"work_position": "",
    			"color": "#df532d",
    			"avatar": "http://192.168.2.232/upload/resize_cache/main/1d3/100_100_2/Harrington.png",
    			"gender": "M",
    			"birthday": "",
    			"extranet": false,
    			"network": false,
    			"bot": false,
    			"connector": false,
    			"external_auth_id": "default",
    			"status": "online",
    			"idle": false,
    			"last_activity_date": "2018-01-29T17:35:31+03:00",
    			"desktop_last_date": false,
    			"mobile_last_date": false,
    			"departments": [
    			  50
    			],
    			"absent": false
    		}
    	},
    	"total": 1
    }      
    

    Description of keys:

    • id – user ID
    • name – user first and last name
    • first_name – user name
    • last_name – user last name
    • work_position – position
    • color – user color in 'hex' format
    • avatar – link to avatar (if empty, avatar is not specified)
    • gender – user gender
    • birthday – user birthday in the DD-MM format, if empty – not specified
    • extranet – extranet user attribute (true/false)
    • network – Bitrix24.Network user attribute (true/false)
    • bot – bot attribute (true/false)
    • connector – Open Channel user attribute (true/false)
    • external_auth_id – external authorization code
    • status – selected user status
    • idle – date, when user is not using his/her PC, in ATOM format (if not specified, false)
    • last_activity_date – date of the last user action, in ATOM format
    • mobile_last_date – date of the last action inside mobile app, in ATOM format (if not specified, false)
    • desktop_last_date – date of the action in the desktop app, in ATOM format (if not specified, false)
    • absent – date, to which the user has a leave of absence, in ATOM format (if not specified, false)

    Example of response when error occurs

    {
        "error": "FIND_SHORT",
        "error_description": "Too short a search phrase."
    }
    

    Description of keys:

    • error – error code
    • error_description – brief description of error

    Possible error codes

    Code Description
    FIND_SHORT Search phrase is top short, search is possible with three symbols minimum.

    Attention! The method is specified with using of the restCommand function. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.



    im.search.chat.list

    The method performs chat search

    Revision: 19
    Get information on the current API revision (platform version) – im.revision.get.

    Parameters

    Parameter Example Req. Description Revision
    FIND Mint Yes Search phrase 19
    OFFSET 0 No Offset of user selection 19
    LIMIT 10 No User selection limit 19
    • Search is performed by the following fields: chat participants Title, First name and Last name.
    • The method supports standard Bitrix24 REST API pagewise navigation. Additionally, it can build navigation via the OFFSET and LIMIT parameters.

    Method call

    JavaScript

    BX24.callMethod('im.search.chat.list', {
    	FIND: 'Mint'
    }, function(result){
    	if(result.error())
    	{
    		console.error(result.error().ex);
    	}
    	else
    	{
    		console.log('users', result.data());
    		console.log('total', result.total());
    	}
    });
    

    PHP

    $result = restCommand('im.search.chat.list', Array(
    	'FIND' => 'Mint'
    ), $_REQUEST["auth"]);
    

    Example of response

    {    
    	"result": {
    		21191:  {
    			"id": 21191,
    			"title": "Mint chat No.3",
    			"owner": 2,
    			"extranet": false,
    			"avatar": "",
    			"color": "#4ba984",
    			"type": "chat",
    			"entity_type": "",
    			"entity_data_1": "",
    			"entity_data_2": "",
    			"entity_data_3": "",
    			"date_create": "2017-10-14T12:15:32+02:00",
    			"message_type": "C"
    		}
    	},
    	"total": 1
    }    
    

    Description of keys:

    • id – chat ID
    • title – chat name
    • owner – chat owner user ID
    • color – chat color in 'hex' format
    • avatar – link to avatar (if empty, avatar is not specified)
    • type – chat type (group chat, call chat, open channel chat and etc.)
    • entity_type – chat external code – type
    • entity_id – chat external code – ID
    • entity_data_1 – external data for chat
    • entity_data_2 – external data for chat
    • entity_data_3 – external data for chat
    • date_create – date when chat is created in ATOM format
    • message_type – type of chat messages

    Example of response when error occurs

    {
        "error": "FIND_SHORT",
        "error_description": "Too short a search phrase."
    }
    

    Description of keys:

    • error – error code
    • error_description – brief description of error

    Possible error codes

    Code Description
    FIND_SHORT Search phrase is top short, search is performed with three symbols minimum.

    Attention! The method is specified with using of the restCommand function. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.



    im.search.department.list

    The method searches for departments

    Revision: 19
    Get information on the current API revision (platform version) – im.revision.get.

    Parameters

    Parameter Example Req. Description Revision
    FIND York Yes Search phase 19
    USER_DATA N No Download user data 19
    OFFSET 0 No Offset of user selection 19
    LIMIT 10 No User selection limit 19
    • If the parameter USER_DATA = Y, the manager data will be uploaded with the result.
    • Search is performed by the following fields: Department full name.
    • The method supports standard Bitrix24 REST API pagewise navigation. Additionally, it can build navigation via the OFFSET and LIMIT parameters.

    Method call

    JavaScript

    BX24.callMethod('im.search.department.list', {
    	FIND: 'York'
    }, function(result){
    	if(result.error())
    	{
    		console.error(result.error().ex);
    	}
    	else
    	{
    		console.log('users', result.data());
    		console.log('total', result.total());
    	}
    });
    

    PHP

    $result = restCommand('im.search.department.list', Array(
    	'FIND' => 'York'
    ), $_REQUEST["auth"]);	
    

    Example of response

    {    
    	"result": [
    		{
    			id: 51,
    			name: "New York branch",
    			full_name: "New York branch / Bitrix24",
    			manager_user_id: 11
    		}
    	],
    	"total": 1
    }             
    

    Description of keys:

    • id – department ID
    • name – department abbreviated name
    • full_name – department full name
    • manager_user_data – manager data description object (unavailable, if USER_DATA != 'Y')
      • id – user ID
      • name – user first and last name
      • first_name – user name
      • last_name – user last name
      • work_position – position
      • color – user color in 'hex' format
      • avatar – link to avatar (if empty, avatar is not specified)
      • gender – user gender
      • birthday – user birthday in the DD-MM format, if empty – not specified
      • extranet – extranet user attribute (true/false)
      • network – Bitrix24.Network user attribute (true/false)
      • bot – bot attribute (true/false)
      • connector – Open Channel user attribute (true/false)
      • external_auth_id – external authorization code
      • status – selected user status
      • idle – date, when user is not using his/her PC, in ATOM format (if not specified, false)
      • last_activity_date – date of the last user action, in ATOM format
      • mobile_last_date – date of the last action inside mobile app, in ATOM format (if not specified, false)
      • absent – date, to which the user has a leave of absence, in ATOM format (if not specified, false)

    Example of response when error occurs

    {
        "error": "FIND_SHORT",
        "error_description": "Too short a search phrase."
    }
    

    Description of keys:

    • error – error code
    • error_description – brief description of error

    Possible error codes

    Code Description
    FIND_SHORT Search phrase is top short, search is performed with three symbols minimum.

    Attention! The method is specified with using of the restCommand function. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.



    im.search.last.get

    The method gets list of elements of the last search

    Revision: 18
    Get information on the current API revision (platform version) – im.revision.get.

    Parameters

    Parameter Example Req. Description Revision
    SKIP_OPENLINES N No Skip open channel chats 18
    SKIP_CHAT N No Skip chats 18
    OFFSET N No Skip one-on-one dialogs 18

    Method call

    JavaScript

    BX24.callMethod('im.search.last.get', {}, function(result){
    	if(result.error())
    	{
    		console.error(result.error().ex);
    	}
    	else
    	{
    		console.log(result.data());
    	}
    });
    

    PHP

    $result = restCommand('im.user.business.list', Array(
    ), $_REQUEST["auth"]);	
    

    Example of response

    {    
    	"result": [
    		{
    			"id": 1,
    			"type": "user",
    			"title": "John Harrington",
    			"avatar": {
    				"url": "http://192.168.2.232/upload/resize_cache/main/1d3/100_100_2/Harrington.png",
    				"color": "#df532d"
    			}
    			"user": {
    				"id": 1,
    				"name": "John Harrington",
    				"first_name": "John",
    				"last_name": "Harrington",
    				"work_position": "",
    				"color": "#df532d",
    				"avatar": "http://192.168.2.232/upload/resize_cache/main/1d3/100_100_2/Harrington.png",
    				"gender": "M",
    				"birthday": "",
    				"extranet": false,
    				"network": false,
    				"bot": false,
    				"connector": false,
    				"external_auth_id": "default",
    				"status": "online",
    				"idle": false,
    				"last_activity_date": "2018-01-29T17:35:31+03:00",
    				"desktop_last_date": false,
    				"mobile_last_date": false,
    				"departments": [
    				  50
    				],
    				"absent": false,
    				"phones": {
    				  "work_phone": "",
    				  "personal_mobile": "",
    				  "personal_phone": ""
    				}
    			}
    		}
    	]
    }              
    

    Description of keys:

    • id – dialog ID (number if user, chatXXX if chat)
    • name – record type (user – if user, chat – if chat)
    • avatar – record avatar description object:
      • url – link to avatar (if empty, the avatar not specified)
      • color – dialog color in 'hex' format
    • title – record title
    • user – user data description object (unavailable, if record type – chat):
      • id – user ID
      • name – user first and last name
      • first_name – user name
      • last_name – user last name
      • work_position – position
      • color – user color in 'hex' format
      • avatar – link to avatar (if empty, avatar is not specified)
      • gender – user gender
      • birthday – user birthday in the DD-MM format, if empty – not specified
      • extranet – extranet user attribute (true/false)
      • network – Bitrix24.Network user attribute (true/false)
      • bot – bot attribute (true/false)
      • connector – Open Channel user attribute (true/false)
      • external_auth_id – external authorization code
      • status – selected user status
      • idle – date, when user is not using his/her PC, in ATOM format (if not specified, false)
      • last_activity_date – date of the last user action, in ATOM format
      • mobile_last_date – date of the last action inside mobile app, in ATOM format (if not specified, false)
      • absent – date, to which the user has a leave of absence, in ATOM format (if not specified, false)
    • chat – chat data description object (unavailable in this record type - user):
      • id – chat ID
      • title – chat name
      • owner – chat owner user name
      • extranet – attribute of extranet user chat participation (true/false)
      • color – chat color in 'hex' format
      • avatar – link to avatar (if empty, the avatar is not specified)
      • type – chat type (group chat, call chat, open line chat and etc.)
      • entity_type – external code for chat – type
      • entity_id – external code for chat – ID
      • entity_data_1 – external data for chat
      • entity_data_2 – external data for chat
      • entity_data_3 – external data for chat
      • date_create – date of chat creation in АТОМ format
      • message_type – type chat messages

    Attention! The method is specified with using of the restCommand function. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.



    im.search.last.add

    The method adds a history element of the last search

    Revision: 18
    Get information on the current API revision (platform version) – im.revision.get.

    Parameters

    Parameter Example Req. Description Revision
    DIALOG_ID chat17 Yes Dialog ID 18
    • DIALOG_ID – dialog ID (number – if user, chatXXX – if chat).

    Method call

    JavaScript

    BX24.callMethod('im.search.last.add', {
    	'DIALOG_ID': 'chat17'
    }, function(result){
    	if(result.error())
    	{
    		console.error(result.error().ex);
    	}
    	else
    	{
    		console.log(result.data());
    	}
    });
    

    PHP

    $result = restCommand('im.search.last.add', Array(
    	'DIALOG_ID' => 'chat17'
    ), $_REQUEST["auth"]);	
    

    Example of response

    {
    	"result": true
    }          
    

    Example of response when error occurs

    {
        "error": "DIALOG_ID_EMPTY",
        "error_description": "Dialog ID can't be empty"
    }
    

    Description of keys:

    • error – error code
    • error_description – brief description of error

    Possible error code

    Code Description
    DIALOG_ID_EMPTY Dialog ID not passed.

    Attention! The method is specified with using of the restCommand function. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.



    im.search.last.delete

    The method deletes a history element of the last search

    Revision: 18
    Get information on the current API revision (platform version) – im.revision.get.

    Parameters

    Parameter Example Req. Description Revision
    DIALOG_ID chat17 Yes Dialog ID 18
    • DIALOG_ID – dialog ID (number – if user, chatXXX – if chat).

    Method call

    JavaScript

    BX24.callMethod('im.search.last.delete', {
    	'DIALOG_ID': 'chat17'
    }, function(result){
    	if(result.error())
    	{
    		console.error(result.error().ex);
    	}
    	else
    	{
    		console.log(result.data());
    	}
    });
    

    PHP

    $result = restCommand('im.search.last.delete', Array(
    	'DIALOG_ID' => 'chat17'
    ), $_REQUEST["auth"]);
    

    Example of response

    {
    	"result": true
    }        
    

    Example of response when error occurs

    {
        "error": "DIALOG_ID_EMPTY",
        "error_description": "Dialog ID can't be empty"
    }
    

    Description of keys:

    • error – error code
    • error_description – brief description of error

    Possible error codes

    Code Description
    DIALOG_ID_EMPTY Dialog ID not passed.

    Attention! The method is specified with using of the restCommand function. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.



    Working with Recent Chat List

    Attention! The restCommand function is used in all methods. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.


    MethodMethod description
    im.recent.get List of recent user dialogs.
    im.recent.pin Pin dialog in favorites.
    im.recent.hide Delete dialog from the list of recent dialogs.


    im.recent.get

    The method gets the last user dialogs

    Revision: 18
    Get information on the current API revision (platform version) – im.revision.get.

    Parameters

    Parameter Example Req. Description Revision
    SKIP_OPENLINES N None Skip Open Channel chats 18
    SKIP_CHAT N None Skip chats 18
    SKIP_DIALOG N None Skip one-on-one dialogs 18

    Method call

    JavaScript

    BX24.callMethod('im.recent.get', {
    	'SKIP_OPENLINES': 'Y'
    }, function(result){
    	if(result.error())
    	{
    		console.error(result.error().ex);
    	}
    	else
    	{
    		console.log(result.data());
    	}
    });
    

    PHP

    $result = restCommand('im.user.status.idle.start', Array(
    	'SKIP_OPENLINES' => 'Y'
    ), $_REQUEST["auth"]);
    

    Example of response

    {
    	"result": [
    		{
    			"id": "1",
    		 	"type": "user",
    		 	"avatar": {
    				"url": "http://www.hazz/upload/resize_cache/main/1af/100_100_2/1464255149.png",
    				"color": "#df532d"
    		  	},
    			"title": "John Harrington",
    			"message": {
    				"id": "30468",
    				"text": "1",
    				"file": false,
    				"attach": false,
    				"author_id": "1"
    			},
    			"counter": "3",
    			"date": "2017-10-17T11:12:56+02:00",
    			"user": {
    				"id": "1",
    				"name": "John Harrington",
    				"first_name": "John",
    				"last_name": "Harrington",
    				"work_position": "IT specialist",
    				"color": "#df532d",
    				"avatar": "http://www.hazz/upload/resize_cache/main/1af/100_100_2/1464255149.png",
    				"gender": "M",
    				"birthday": false,
    				"extranet": false,
    				"network": false,
    				"bot": false,
    				"connector": false,
    				"external_auth_id": "default",
    				"status": "online",
    				"idle": false,
    				"last_activity_date": "2017-10-17T11:16:01+02:00",
    				"mobile_last_date": "2017-05-26T12:04:58+02:00",
    				"absent": "2017-11-01T00:00:00+02:00"
    			}
    		},
    		{
    			"id": "chat21191",
    			"type": "chat",
    			"avatar": {
    				"url": "",
    				"color": "#4ba984"
    			},
    			"title": "Mint Chat No.3",
    			"message": {
    				"id": "30467",
    				"text": "Permission for Bitrix24 update received from [Attachment]",
    				"file": false,
    				"attach": true,
    				"author_id": "2"
    			},
    			"counter": "0",
    			"date": "2017-10-17T10:38:20+02:00",
    			"chat": {
    				"id": "21191",
    				"title": "Mint chat No.3",
    				"owner": "2",
    				"extranet": false,
    				"avatar": "",
    				"color": "#4ba984",
    				"type": "chat",
    				"entity_type": "",
    				"entity_data_1": "",
    				"entity_data_2": "",
    				"entity_data_3": "",
    				"date_create": "2017-10-14T12:15:32+02:00",
    				"message_type": "C"
    			}
    		}
    	]
    }       
    

    Description of keys:

    • id – dialog ID (number if user, chatXXX if chat)
    • name – record type (user – if user, chat – if chat)
    • avatar – record avatar description object:
      • url – link to avatar (if empty, the avatar is not specified)
      • color – dialog color in 'hex' format
    • title – record title (First name, last name – for user, chat name - for chat)
    • messages – message description object:
      • id – message ID
      • text – message text (without BB-codes and string breaks)
      • file – file availability (true/false)
      • attach – attachment availability (true/false)
      • author_id – message author
      • date – message date in ATOM format
    • counter – counter for unread messages
    • user – user data description object (unavailable in this record type - chat):
      • id – user ID
      • name – user first and last name
      • first_name – user name
      • last_name – user last name
      • work_position – position
      • color – user color in 'hex' format
      • avatar – link to avatar (if empty, avatar is not specified)
      • gender – user gender
      • birthday – user birthday in the DD-MM format, if empty – not specified
      • extranet – extranet user attribute (true/false)
      • network – Bitrix24.Network user attribute (true/false)
      • bot – bot attribute (true/false)
      • connector – Open Channel user attribute (true/false)
      • external_auth_id – external authorization code
      • status – selected user status
      • idle – date, when user is not using his/her PC, in ATOM format (if not specified, false)
      • last_activity_date – date of the last user action, in ATOM format
      • mobile_last_date – date of the last action inside mobile app, in ATOM format (if not specified, false)
      • absent – date, to which the user has a leave of absence, in ATOM format (if not specified, false)
    • chat – chat data description object (unavailable if record type - user):
      • id – chat ID
      • title – chat name
      • owner – user-chat owner ID
      • extranet – attribute of extranet user participation in chat (true/false)
      • color – chat color in 'hex' format
      • avatar – link to avatar (if empty, avatar is not specified)
      • type – chat type (group chat, call chat, open channel chat and etc.)
      • entity_type – external code for chat – type
      • entity_id – external code for chat – identifier
      • entity_data_1 – external data for chat
      • entity_data_2 – external data for chat
      • entity_data_3 – external data for chat
      • date_create – date when chat is created in ATOM format
      • message_type – type of chat messages

    Attention! The method is specified with using of the restCommand function. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.



    im.recent.pin

    The method pin dialog in favorites

    Revision: 19
    Get information on the current API revision (platform version) – im.revision.get.

    Parameters

    Parameter Example Req. Description Revision
    DIALOG_ID chat17 Yes Dialog ID 19
    PIN Y No Pin or unpin a dialog 19
    • DIALOG_ID – dialog ID (number if user, chatXXX if chat).
    • If the PIN = N parameter is specified, the pinned dialog will be unpinned.

    Method call

    JavaScript

    BX24.callMethod('im.recent.pin', {
    	'DIALOG_ID': 'chat17'
    	'PIN': 'Y'
    }, function(result){
    	if(result.error())
    	{
    		console.error(result.error().ex);
    	}
    	else
    	{
    		console.log(result.data());
    	}
    });
    

    PHP

    $result = restCommand('im.recent.pin', Array(
    	'DIALOG_ID' => 'chat17',
    	'PIN' => 'Y'
    ), $_REQUEST["auth"]);	
    

    Example of response

    {
    	"result": true
    }      
    

    Example of response when error occurs

    {
        "error": "DIALOG_ID_EMPTY",
        "error_description": "Dialog ID can't be empty"
    }
    

    Description of keys:

    • error – error code
    • error_description – brief description of error

    Possible error codes

    Code Description
    DIALOG_ID_EMPTY Dialog ID not passed.

    Attention! The method is specified with using of the restCommand function. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.



    im.recent.hide

    The method deletes dialog from the list of recent chats

    Revision: 18
    Get information on the current API revision (platform version) – im.revision.get.

    Examples

    Parameter Example Req. Description Revision
    DIALOG_ID chat17 Yes Dialog ID 18
    • DIALOG_ID – dialog ID (number if user, chatXXX if chat).

    Method call

    JavaScript

    BX24.callMethod('im.recent.hide', {
    	'DIALOG_ID': 'chat17'
    }, function(result){
    	if(result.error())
    	{
    		console.error(result.error().ex);
    	}
    	else
    	{
    		console.log(result.data());
    	}
    });
    

    PHP

    $result = restCommand('im.recent.hide', Array(
    	'DIALOG_ID' => 'chat17'
    ), $_REQUEST["auth"]);	
    

    Example of response

    {
    	"result": true
    }  
    

    Example of response when error occurs

    {
        "error": "DIALOG_ID_EMPTY",
        "error_description": "Dialog ID can't be empty"
    }
    

    Description of keys:

    • error – error code
    • error_description – brief description of error

    Possible error codes

    Code Description
    DIALOG_ID_EMPTY Dialog ID not passed.

    Attention! The method is specified with using of the restCommand function. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.



    Working with Counters

    Attention! The restCommand function is used in all methods. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.


    im.counters.get

    The method gets counter data

    Revision: 18
    Get information on the current API revision (platform version) – im.revision.get.

    Parameters

    None

    Method call

    JavaScript

    BX24.callMethod('im.counters.get', {}, function(result){
    	if(result.error())
    	{
    		console.error(result.error().ex);
    	}
    	else
    	{
    		console.log(result.data());
    	}
    });
    

    PHP

    $result = restCommand('im.counters.get', Array(
    ), $_REQUEST["auth"]);	
    

    Example of response

    {    
    	"result": {
    		"CHAT": {18: 1},
    		"DIALOG": {1: 3, 5: 1},
    		"LINES": {},
    		"TYPE" {
    			"ALL": 5,
    			"CHAT": 1,
    			"DIALOG": 4,
    			"LINES": 0,
    			"NOTIFY": 0
    		}
    	}
    }   
    

    Description of keys:

    • CHAT – object, containing list of chats that have unread messages
    • DIALOG – object, containing list of dialogs that have unread messages
    • LINES – object, containing list of Open Channel chats that have unread messages
    • TYPE – object, containing cumulative counters
      • ALL – cumulative counter for all entities
      • CHAT – cumulative counter for chats
      • DIALOG – cumulative counter for dialogs
      • LINES – cumulative counter for Open Channels
      • NOTIFY – cumulative counter for notifications

    Attention! The method is specified with using of the restCommand function. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.



    Working with Notifications

    Attention! The restCommand function is used in all methods. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.


    Send personal notification

    REST method: im.notify.personal.add

    Method call:
    $result = restCommand('im.notify.personal.add', Array(
    
       'USER_ID' => 1, // ID of the user who will receive notification (required)
       'MESSAGE' => 'Personal notification', // notification text (required)
       'MESSAGE_OUT' => 'Personal notification text for mail', // notification text for mail, if not specified - MESSAGE field is used
       'TAG' => 'TEST', // notification tag, unique within the system. When adding notification with existing tag other notifications will be deleted
       'SUB_TAG' => 'SUB|TEST', // additional tag, without duplication check 
       'ATTACH' => '' // attachment
      
    ), $_REQUEST["auth"]);
    
    Required fields: USER_ID (ID of the user to will receive notification), MESSAGE (notification text).

    Result: notification text ID or error.

    Related links:

    How to work with attachments

    Possible errors:

    Error codeError description
    USER_ID_EMPTY Recipient ID not specified.
    MESSAGE_EMPTY Message text not passed.
    ATTACH_ERROR Complete attachment object not validated.
    ATTACH_OVERSIZE Maximum permissible attachemnt size is exceeded (30 Kb).


    Send system notification

    REST method: im.notify.system.add

    Method call:
    $result = restCommand('im.notify.system.add', Array(
    
       'USER_ID' => 1, // ID of the user, who will receive notification (required)
       'MESSAGE' => 'System notification', // notification text (required)
       'MESSAGE_OUT' => 'System notification text for mail', // notification text for mail, if not specified - MESSAGE field is used
       'TAG' => 'TEST', // notification tag, unique within the system. When adding notification with exiting tag, other notifications will be deleted
       'SUB_TAG' => 'SUB|TEST', // additional tag, without duplication check
       'ATTACH' => Array() // attachment
      
    ), $_REQUEST["auth"]);
    
    Required fields: USER_ID (ID of the user who will receive the notification), MESSAGE (notification text).

    Result: notification ID or error.

    Related links:

    How to work with attachments

    Possible errors:

    Error codeError description
    USER_ID_EMPTY Recipient ID not specified.
    MESSAGE_EMPTY Message text not passed.
    ATTACH_ERROR Complete attachment object not validated.
    ATTACH_OVERSIZE Maximum permitted attachment size exceeded (30 kb).


    Delete notification

    REST method: im.notify.delete

    Method call:
    $result = restCommand('im.notify.delete', Array(
    
        'ID' => 13, // notification ID (one of three parameters: ID, TAG or SUB_TAG is required)
        'TAG' => 'TEST' // notification tag (one of three parameters: ID, TAG or SUB_TAG is required)
        'SUB_TAG' => 'SUB|TEST' // additional tag (one of three parameters: ID, TAG or SUB_TAG is required)
    
    ), $_REQUEST["auth"]);
    
    Required fields: One of three parameter must be selected: ID (notification ID), TAG (notification tag) or SUB_TAG (additional tag).

    Result: true or error.

    Possible errors:

    Error codeError description
    PARAMS_ERROR Notification deletion error.


    im.notify.read

    The method cancels notification for read messages.

    Revision: 18
    Get information on the current API revision (platform version) – im.revision.get.

    Parameters

    Parameter Example Req. Description Revision
    ID 17 Yes Notification ID 18
    ONLY_CURRENT N No Read only the specified notification 18
    • If the ONLY_CURRENT parameter is passed with Y, check indicating that notification was read will be set only for the specified ID. Otherwise, the check is set for notification with equal or higher ID.

    Method call

    JavaScript

    BX24.callMethod('im.notify.read', {
    	'ID': 17,
    }, function(result){
    	if(result.error())
    	{
    		console.error(result.error().ex);
    	}
    	else
    	{
    		console.log(result.data());
    	}
    });
    

    PHP

    $result = restCommand('im.notify.read', Array(
    	'DIALOG_ID' => '17'
    ), $_REQUEST["auth"]);	
    

    Example of response

    {
    	"result": true
    }        
    

    Attention! The method is specified with using of the restCommand function. This method is used to send data in Bitrix24 and is available in the EchoBot example as well as in this article. You can use your own function or BX24.callMethod, or bitrix24-php-sdk JavaScript methods.



    Full List of Chat API Methods

    Platform version:

    MethodMethod description
    im.revision.get Gets information about API revisions.

    Working dialogs:

    MethodMethod description
    im.dialog.messages.get Gets the list of last messages in chat.

    Working with messages:

    MethodMethod description
    im.message.add Sends message to chat.
    im.message.update Updates chatbot message.
    im.message.delete Deletes chatbot message.
    im.message.like "Like" a message.

    Working with files:

    MethodMethod description
    im.disk.folder.get Gets information on folder storing files for chat
    im.disk.file.commit Publishes loaded file in the chat.
    im.disk.file.delete Deletes files inside chat folder.

    Working with users:

    MethodMethod description
    im.user.get Gets user data.
    im.user.list.get Gets multiple users data.
    im.user.business.list Gets list of users with access to business tools.
    im.user.status.get Gets information on the specified user status.
    im.user.status.set Specifies user status.
    im.user.status.idle.start Specifies automatic status "Away"
    im.user.status.idle.end Disables automatic status "Away"

    Working with departments:

    MethodMethod description
    im.department.get Gets department data.
    im.department.colleagues.list Gets list of users in your department.
    im.department.managers.get Gets list of department managers.
    im.department.employees.get Gets list of employees in a department.

    Working with search:

    MethodMethod description
    im.search.user.list Searches for users.
    im.search.chat.list Searches for chats.
    im.search.department.list Searches for departments.
    im.search.last.get Gets list of elements of the last search.
    im.search.last.add Adds a history element of the last search.
    im.search.last.delete Deletes a history element of the last search.

    Working with the list of recent chats:

    MethodMethod description
    im.recent.get Gets the last user dialogs.
    im.recent.pin Pins dialog in favorites.
    im.recent.hide Deletes dialog from the list of recent chats.

    Working with counters:

    MethodMethod description
    im.counters.get Gets counter data.

    Working with notifications:

    MethodMethod description
    im.notify.personal.add Sends personal notification.
    im.notify.system.add Sends sysytem notification.
    im.notify.delete Deletes notification.
    im.notify.read Cancels notification for read messages.


    Application for Chat

    What is it about?

    Applications for chat

    Developers now can integrate into Bitrix24 Messenger, by adding an icon to text input panel:

    If the app is not loading the image, service Application for chat icon will appear. After clicking on it, a text variant of the icon will appear.


    There are two types of chat application:

    1. JS command - when clicking on the icon, a chatbot command will be inserted into input field, a command will be sent to chat, telephone call will be initiated, or a support open channel will be opened.

      With the help of this format, developers can integrate a button in their chatbots to contact them.

      Example of such command for Martha chatbot - an icon for tick-tack-toe game:

    2. IFRAME application - it is an improved format. When clicking the button, IFRAME application will open, where the developer can do anything he/she desires.

      Application can cooperate with chat via JS-commands:

      • to insert message into input field
      • to send message on behalf of user
      • to close dialogue
      • to open technical support chat (OC consultant)
      • to make call

      Example of such implementation can be found in the example of Giphy chatbot:

      Tell the difference - previously you we're typing command in the form of a message and GIPHY returned you a random picture on the topic. Now you can see, what you are sending out.


      Attention: icons can understand context, and it means that the app can be displayed only in those chats that you require.

      For example, to communicate with technical support, it is better to deploy the app in your chatbot context. In other chats it will be excessive. Or you can develop a special application for Open Channels - it should be displayed only in the context of Open Channels.

      Accessible contexts: all, chat, bot, lines, user, call.

      Postfix can be added to each context -admin - then the icon will be displayed in the required context only to administrators.


    Context applications

    Context Applications are created to help user to interface with chatbot within the specific dialogue (message).

    For example, client writes in an open channel, open channel chatbot analyzes the message and prepares the variants of responses. To not disturb the work of operators and not to show the full flow of data to it, we are neatly creating a button, upon clicking on which, the IFRAME application will be initialized.


    Creating an Application

    There are two types of applications: JS-command and IFRAME-application.

    Please read how to work with applications via API-methods.



    Register application for chat

    REST method: imbot.app.register

    Method call for JS-command:
    $result = restCommand('imbot.app.register', Array(
    
       'BOT_ID' => 62, // Bot ID of chat application owner
       'CODE' => 'echo', // Application code for chat
       'JS_METHOD' => 'SEND', 
       'JS_PARAM' => '/help', 
       'ICON_FILE' => '/* base64 image */', // Your application icon - base64
       'CONTEXT' => 'BOT', // Application context
       'EXTRANET_SUPPORT' => 'N', // Extranet users command accessibility, by default ‘N’   'LIVECHAT_SUPPORT' => 'N', // Online chat support
       'IFRAME_POPUP' => 'N', // iframe will open and will be able to move inside the messenger, transition between dialogues will not close such window.
       'LANG' => Array( // translations array; it is preferably to indicate minimum for EN       Array('LANGUAGE_ID' => 'en', 'TITLE' => 'Chatbot BUTTON', 'DESCRIPTION' => 'Send help command'),
    
       )
    
    ), $_REQUEST["auth"]);
    

    Variants for JS_METHOD:

    • PUT - insert command for chatbot in text area, JS_PARAM can contain only command text and parameters for it (permitted symbols: a-z 0-9 - + _ / ).
    • SEND - send command to chatbot, JS_PARAM can contain only command text and parameters for it (permitted symbols a-z 0-9 - + _ / ).
    • CALL - call to a phone number.
    • SUPPORT - open technical support chatbot, operating via Open Channels. Open Channel JS_PARAM code must be indicated (32 symbols).

    ICON_FILE application icon format:

    • Base64 of your icon should returned to this field. Icon format is detailed in this documentation.
    • Please note, if this field is not specified, the application will be accessible in the system dialogue "Applications for chat".

    Application context CONTEXT:

    • ALL - application will be accessible in all chats.
    • USER - application will be accessible only in Person-to-person chats.
    • CHAT - application will be accessible only in Group chats.
    • BOT - application will be accessible only to chatbot that have installed the app.
    • LINES - application will be accessible only in Open Channels chats.
    • CALL - application will be accessible only in chats, created within Telephony framework.

    Postfix -admin can be added to each context, then the application will be accessible in the required context only to Bitrix24 administrators.


    Method call for IFRAME-application:
    $result = restCommand('imbot.app.register', Array(
    
       'BOT_ID' => 62, // Bot ID of chat application owner
       'CODE' => 'echo', // Application code for chat
       'IFRAME' => 'https://marta.bitrix.info/iframe/echo.php', 
       'IFRAME_WIDTH' => '350', // desired frame width. Minimum value - 250px  
       'IFRAME_HEIGHT' => '150', // desired frame height. Minimum value - 50px  
       'HASH' => 'd1ab17949a572b0979d8db0d5b349cd2', // token for access to your frame to check the signature, 32 symbols. 
       'ICON_FILE' => '/* base64 image */', // Your application icon - base64
       'CONTEXT' => 'BOT', // Application context
       'HIDDEN' => 'N', // application is hidden or not 
       'EXTRANET_SUPPORT' => 'N', // Extranet users command accessibility, by default ‘N’   'LIVECHAT_SUPPORT' => 'N', // Online chat support
       'IFRAME_POPUP' => 'N', // iframe will open and will be able to move inside the messenger, transition between dialogues will not close such window.
       'LANG' => Array( // translations array; it is preferably to indicate minimum for EN Array('LANGUAGE_ID' => 'en', 'TITLE' => 'Echobot IFRAME', 'DESCRIPTION' => 'Open Chatbot IFRAME app', 'COPYRIGHT' => 'Bitrix24'), 
       )
    
    ), $_REQUEST["auth"]);
    

    Attention:
    1. Although, when registering IFRAME-application you are specifying the window size, it can be reduced by the app to the actually available dimensions. Ideal variant - to create an app in such manner that it would fit into minimal dimensions and could freely adapt to an increase or a reduction of size; it will be very important for mobile devices.
    2. Link to IFRAME must lead to site with active HTTPS-certificate. You can find IFRAME-processor development rules and limitations in the following documentation.
    3. It is imperative to check HASH prior to completion of any operations.
    4. Applications are accessible only after page reloading or after service hit on server (refresh time differs for various installations, from 15 to 26 minutes). Application will immediately appear only when interfacing with context button.
    5. You shall specify the desired values of width and height of the app window in the IFRAME_WIDTH and IFRAME_HEIGHT values. If the messenger window will end up being smaller, than the app window - the app window will be reduced to the messenger window. Otherwise, if the message window ends up being larger than the app window - the desired dimensions for the app will be used.
    6. If the app is called from the context (keyboard or menu), the app will be called in the context mode, in this mode the IFRAME_POPUP values will be ignored.

    Return: APP_ID numerical ID of created application or an error.

    Possible errors:

    Error codeError description
    BOT_ID_ERROR Chatbot not found.
    APP_ID_ERROR Application for chat is not part to this REST-application, you can only work with applications for chat, installed within the framework of current REST-application.
    IFRAME_HTTPS Link to IFRAME must be specified to site with active HTTPS-certificate.
    HASH_ERROR You have not specified HASH for application. We recommend using unique HASH for each IFRAME and each installation.
    PARAMS_ERROR Error when specifying JS-command or IFRAME-parameters.
    LANG_ERROR Language phrases are not returned for visible command.
    WRONG_REQUEST Something went wrong.


    Delete application for chat

    REST-method: imbot.app.unregister

    Method call:
    $result = restCommand('imbot.app.unregister', Array(
    
        'APP_ID' => 13, // delete command ID
    
    ), $_REQUEST["auth"]);
    
    Return: true or an error.

    Possible errors:

    Error codeError description
    CHAT_APP_ID_ERROR Application not found.
    APP_ID_ERROR Application for chat is not part of this REST-application, you can work with application for chat, installed within current REST-application framework.
    WRONG_REQUEST Something went wrong.


    Update application data in chat

    Attention: required fields are application ID field and one of the fields, needed for editing. If JS and IFRAME methods are called in one command, only JS method will be used.

    REST-method: imbot.app.update

    Method call:
    $result = restCommand('imbot.app.update', Array(
    
       'APP_ID' => 13, // chat ID
       'FIELDS' => Array(
          'IFRAME' => 'https://marta.bitrix.info/iframe/echo.php',
           'IFRAME_WIDTH' => '350', // desired frame width. Minimum value - 250px  
           'IFRAME_HEIGHT' => '150', // desired frame height. Minimum value - 50px  
           'JS_METHOD' => 'SEND', 
           'JS_PARAM' => '/help', 
          'HASH' => 'register', // token for access to your frame, 32 symbols. 
           'ICON_FILE' => '/* base64 image */', // Your application icon - base64
           'CONTEXT' => 'BOT', // Application context
          'EXTRANET_SUPPORT' => 'N', // Extranet users command accessibility, by default ‘N’      
           'LIVECHAT_SUPPORT' => 'N', // Online chat support
          'IFRAME_POPUP' => 'N', // iframe will open and will be able to move inside the messenger, transition between dialogues will not close such window
          'LANG' => Array( // translations array; it is preferably to indicate minimum for EN          Array('LANGUAGE_ID' => 'en', 'TITLE' => 'Chatbot IFRAME', 'DESCRIPTION' => 'Open Chatbot IFRAME app', 'COPYRIGHT' => 'Bitrix24'), 
          )
       )
    ), $_REQUEST["auth"]);
    
    Return: true or an error.

    Possible errors:

    Error codeError description
    CHAT_APP_ID_ERROR Application not found.
    APP_ID_ERROR Application for chat is not part of this REST-application, you can work with application for chat, installed within current REST-application framework.
    IFRAME_HTTPS Link to IFRAME must be specified to site with active HTTPS-certificate.
    WRONG_REQUEST Something went wrong.


    Context Applications

    You find details about what is context application here.


    To work with context, you need to complete several actions:

    1. Creating an Application. You can register a hidden application, then it will not be displayed on the text input panel.
    2. Send (or update) any message with attached keyboard or from menu.
    3. You must input application identifier in the parameters of keyboard button or menu item.

    Method call:
    restCommand('imbot.message.add', Array(
       "DIALOG_ID" => 2,
       "BOT_ID" => 17,
       "MESSAGE" => "Hello! My name is ChatBot :)",
       "KEYBOARD" => [{"TEXT":"Open App","APP_ID":11}],
       "MENU" => [{"TEXT":"Open App","APP_ID":11}]
    
    ), $_REQUEST["auth"]);
    

    aside from APP_ID, you can input ant line into parameter APP_PARAMS; when your IFRAME will open, the data will be transferred to parameter BUTTON_PARAMS.

    You can find IFRAME-processor development rules and limitations in this documentation. When creating a message, you can use one of two options – KEYBOARD or MENU.



    Create Application Icon for Chat

    Then creating Application for chat icon, you need to follow several simple rules:

    1. Icon could be created with a transparent background, in .PNG format.

    2. Canvas size: 108x66 px, left part is used for inactive icon, second part - to show an active icon:

    3. Main part of the icon could not be larger than 45x32 px and shall be specifically aligned in the middle of each part:

    4. Main color of inactive icon - #b3b7bc, active - #2fc7f7:


      Below you can find several templates, for your convenience:

      textarea_icon.psd marta_icon.psd textarea_icon_f.psd
    5. To load an image, when registering or updating an application, you need to specify IMAGE_FILE key. The value of this key shall be your image base64:

      'ICON_FILE' => base64_encode(file_get_contents(__DIR__.'/icon_button.png')), 
      

      Attention: you may choose not to create an icon for the application. Then it will be folded into the service button:



    Create IFRAME-processor

    After application for chat is registered, you need to use IFRAME-processor.

    Attention: please note, that when registering an application, you are specifying window size, but it can be minimized by the app to its actual permitted dimensions. Ideal option - is to adapt the app to fit freely within sizing changes. It is essential for mobile devices.


    Your page will be open with the following data

    Array
    (
        [BOT_ID] => 17
        [BOT_CODE] => echoBot
        [APP_ID] => 11
        [APP_CODE] => echoFrame
        [DOMAIN] => https://test.bitrix24.com
        [DOMAIN_HASH] => 0e9c40cee01d6f182e9261b38b30b5c3
        [USER_ID] => 2
        [USER_HASH] => 7e23ac8b6f6c7044076301c7f81cd745
        [DIALOG_ID] => 950
        [CONTEXT] => textarea 
        [LANG] => com 
        [IS_CHROME] => Y 
        [MESSAGE_ID] => 12333 
        [BUTTON_PARAMS] => test
        [DIALOG_ENTITY_ID] => telegrambot|8|173633217|569
        [DIALOG_ENTITY_DATA_1] => Y|LEAD|56|N|N|1765
        [DIALOG_CONTEXT] => lines 
    
    )
    

    Parameter details:

    • BOT_ID and BOT_CODE - chatbot data, with which the application is launched.
    • APP_ID and APP_CODE - application data for launched application chat.
    • DOMAIN - account address, from which the app was launched.
    • DOMAIN_HASH - this HASH field, returned when icon is registered. It is used to cut off unauthorized requests.
    • USER_ID - user ID.
    • USER_HASH - HASH string to validate request at client's account.
    • DIALOG_ID - launched dialogue ID at user's account at the moment when the frame is opened.
    • CONTEXT - dialogue request, can be text area or button.
    • LANG - current client interface language.
    • IS_CHROME - the frame launch check in Google Chrome browser: was it launched or not.
    • DIALOG_CONTEXT - this parameter is not yet available. The request can be all, chat, bot, lines, user, request .
    • DIALOG_ENTITY_ID - additional chat data (this parameter is not yet available). Data is split for Open Channels|. Field values for Open Channels: 1 - channel, through which user writes, 2 – OC ID, 3 and 4 – service data (parameter is not yet available).
    • DIALOG_ENTITY_DATA_1 - chat additional data (this parameter is not yet available). Data is split for Open Channels|. Field values for Open Channels: 1 – saved in CRM, 2 – CRM entity type, 3 - CRM entity ID, 4 and 5 – service data, 6 – Open Channel session ID.

    If the frame is launched in the context mode:

    • MESSAGE_ID - message ID.
    • BUTTON_PARAMS - button parameter, set during sending.


    Interfacing with parent window (with messenger)

    You need to configure interfacing function with the main window, data initialization and forwarding.

    Initialization example:

    <script type="text/javascript">
       // initialize communication with main window function 
       function frameCommunicationInit()
       {
          if (!window.frameCommunication)
          {
             window.frameCommunication = {timeout: {}};
          }
          if(typeof window.postMessage === 'function')
          {
             window.addEventListener('message', function(event){
                var data = {};
                try { data = JSON.parse(event.data); } catch (err){}
       
                if (data.action == 'init')
                {
                   frameCommunication.uniqueLoadId = data.uniqueLoadId;
                   frameCommunication.postMessageSource = event.source;
                   frameCommunication.postMessageOrigin = event.origin;
                }
             });
          }
       }
    
       // send data to main window function
       function frameCommunicationSend(data)
       {
          data['uniqueLoadId'] = frameCommunication.uniqueLoadId;
          var encodedData = JSON.stringify(data);
          if (!frameCommunication.postMessageOrigin)
          {
             clearTimeout(frameCommunication.timeout[encodedData]);
             frameCommunication.timeout[encodedData] = setTimeout(function(){
                frameCommunicationSend(data);
             }, 10);
             return true;
          }
          
          if(typeof window.postMessage === 'function')
          {
             if(frameCommunication.postMessageSource)
             {
                frameCommunication.postMessageSource.postMessage(
                   encodedData,
                   frameCommunication.postMessageOrigin
                );
             }
          }
       }
       frameCommunicationInit();
    </script>
    

    The following function will be accessible to you:

    • Command to send text from user:
      frameCommunicationSend({'action': 'send', 'message': 'Send message'})

    • Command to send text to input field:
      frameCommunicationSend({'action': 'put', 'message': 'Put message'})

    • Command to start call:
      frameCommunicationSend({'action': 'call', 'number': '123456'})

    • Command to open dialogue with your open channel:
      frameCommunicationSend({'action': 'support', 'code': '6a4cdbcf753addac1a573ea64be826ca'})

    • Close frame command:
      frameCommunicationSend({'action': 'close'})



    Registration and security

    You can forgo checking the incoming requests, but we strongly recommend doing it.

    Based on the incoming data you can perform the required checks:

    1. We recommend checking REFERER for matching with specified domain.
    2. We recommend checking domain and its HASH.
    3. We recommend checking user and its HASH.
    4. Use unique HASH for each new registration.

    You can develop a sufficiently secure application if you combine all those factors.


    When registering a command, you must specify HASH-string. User and domain will use it to undersign:

    $hash = '0e9c40cee01d6f182e9261b38b30b5c3'; // HASH, specified during registration of the application.
    
    $check = parse_url($_GET['DOMAIN']);
    
    // check for validity of specified domain
    if ($_GET['DOMAIN_HASH'] == md5($check['host'].$hash))
    {
       echo 'OK';
    }
    
    // check for validity of specified user 
    if ($_GET['USER_HASH'] == md5($_GET['USER_ID'].$hash))
    {
       echo 'OK';
    }
    
    // check for REFERER
    if (strpos($_SERVER['HTTP_REFERER'], $_GET['DOMAIN'])!== 0)
    {
       echo 'OK';
    }
    

    The work in such mode is reviewed in detail in the preview example, which you can download here.

    New Desktop Clients

    To work with applications for chat, you will need a modern web browser and new desktop applications:

    • Windows: download
    • Mac OS: download
    • Unix: client is in development, alpha version with enabled frames will be published later. Brick does not yet support this function.


    REST API

    REST API Capabilities

    REST API is designed to create applications for Bitrix24 Cloud Service.

    REST API allows to receive access and to manage such Bitrix24 Cloud Service tool as:

    • CRM,
    • Workflows,
    • Drive,
    • Social Network,
    • Telephony,
    • Lists,
    • Notifications,
    • Tasks,
    • Working with users and multiple Company Divisions,
    • Activity Stream,
    • Calendars.

    To use REST API methods by third-party applications, the specific app should be registered in Bitrix24 Marketplace. In this case, the application has all the necessary data to receive the OAuth 2.0 key.

    The overview of how REST method is called is the following:

    https://domain_B24.bitrix24.{ru|en|de}/rest/name_method.transport?parameters_method&auth=key_authorization
    
    where transport - optional parameter, which can have values json or xml. By default - json.

    Request can be sent via both GET and POST methods.

    Parameter values are accepted in UTF-8 encoding.

    Attention! There is a limit for the number of requests. Two requests per second are permitted. If the limit is exceeded, then the limitation is triggered after 100 requests.

    Attention! Full and up-to-date version of REST API can be acquired here.



    Open Channels REST API

    Attention! To use methods IMOPENLINES REST, sufficient rights are required to imbot (Create and manage chatbots) available access to scope imopenlines (Open Channels).


    Connect Open Channel via code

    REST method: imopenlines.network.join

    Method call:
    $result = restCommand('imopenlines.network.join', Array(
    
        'CODE' => 'ab515f5d85a8b844d484f6ea75a2e494' // code for search from connector page
    
    ), $_REQUEST["auth"]);
    
    Return: true or error code.

    Possible errors:

    Error codeError description
    IMBOT_ERROR Bot management module is not installed.
    NOT_FOUND Open Channel not found.
    INACTIVE Open Channel is unavailable at the moment.

    Sent message from Open Channel to selected user

    REST method: imopenlines.network.message.add

    Method call:
    $result = restCommand('imopenlines.network.message.add', Array(
    
    	'CODE' => 'ab515f5d85a8b844d484f6ea75a2e494', // code of registered open channel
    	'USER_ID' => 2, // message recipient user code
    	'MESSAGE' => 'message text' // Message text
    	'ATTACH' => '' // Attachment, optional field
    	'KEYBOARD' => '' // Keyboard, optional field
    	'URL_PREVIEW' => 'Y' // Concert link to rich-link, optional field, by default 'Y'
    
    ), $_REQUEST["auth"]);
    
    Return: true or error code.

    Limitations:
    • You can send a message not more than once for each user during a week.
    • You can use keyboard only to configure the button-link to external site.

    Related links:

    Using Keyboards
    Attachments
    Formatting

    Possible errors:

    Error codeError description
    CODE_ERROR Incorrect code for Open Channel.
    USER_ID_EMPTY No ID for recipient user.
    MESSAGE_EMPTY No message text.
    ATTACH_ERROR Attachment object was not validated.
    ATTACH_OVERSIZE Maximum permissible attachment size was exceeded (30 Kb).
    KEYBOARD_ERROR Keyboard object was not validated.
    KEYBOARD_OVERSIZE Maximum permissible keyboard size was exceeded (30 Kb).
    USER_MESSAGE_LIMIT Message limit for specific user was exceeded.
    WRONG_REQUEST Something went wrong.


    Switch conversation to a free operator

    REST method: imopenlines.bot.session.operator

    Method call:
    $result = restCommand('imopenlines.bot.session.operator', Array(
    
        'CHAT_ID' => 12 // Chat ID
    
    ), $_REQUEST["auth"]);
    
    Return: true or Error code.

    Possible errors:

    Error codeError description
    CHAT_ID_EMPTY No chat ID.
    WRONG_CHAT Specified chat is not under bot control.
    BOT_ID_ERROR Incorrect chatbot ID.


    Switch conversation to a specific operator

    REST method: imopenlines.bot.session.transfer

    Method call:
    $result = restCommand('imopenlines.bot.session.transfer', Array(
    
        'CHAT_ID' => 12 // Chat ID
        'USER_ID' => 12 // User ID, to which forwarding is performed
        'LEAVE' => 'N' // Y/N. If 'N’ is specified – chatbot will not leave this chat after forwarding and will be available until user is confirmed	
    
    ), $_REQUEST["auth"]);
    

    Note: Instead of USER_ID, QUEUE_ID can be specified to switch to another open channel.

    Return: true or Error code.

    Possible errors:

    Error codeError description
    CHAT_ID_EMPTY No chat ID.
    USER_ID_EMPTY No user ID, to which conversation must be forwarded.
    WRONG_CHAT Incorrect user ID is specified, or this user is chatbot or extranet user.
    BOT_ID_ERROR Incorrect chatbot ID.


    Current session finish

    REST method: imopenlines.bot.session.finish

    Method call:
    $result = restCommand('imopenlines.bot.session.finish', Array(
    
        'CHAT_ID' => 12 // Chat ID	
    
    ), $_REQUEST["auth"]);
    
    Return: true or Error code.

    Possible errors:

    Error codeError description
    CHAT_ID_EMPTY No chat ID.
    BOT_ID_ERROR Incorrect chatbot ID.


    Note: Based on Open Channel REST API you can create technical support channel for your clients.



    Send Commands and Extend Authorization

    Within our course, we interface with Bitrix24 via PHP.

    All examples are provided with the use of restCommand functions:

    restCommand('imbot.message.add', Array(
       "DIALOG_ID" => $_REQUEST['data']['PARAMS']['DIALOG_ID'],
       "MESSAGE" => "[put=/search]Input search string[/put]",
    ), $_REQUEST["auth"]);
    
    where:
    First parameter - API name (imbot.message.add);
    Second parameter - API data return (Array(...))
    Third parameter - Data for request authorization ($_REQUEST["auth"]).

    Note: This function is used as an example. You can use your own function, based on interfacing protocol, or BX24.callMethod javascript-method, or a partner development bitrix24-php-sdk.

    RestCommand function

    /**
     * Send rest query to Bitrix24.
     *
     * @param $method - Rest method, ex: methods
     * @param array $params - Method params, ex: Array()
     * @param array $auth - Authorize data, ex: Array('domain' => 'https://test.bitrix24.com', 'access_token' => '7inpwszbuu8vnwr5jmabqa467rqur7u6')
     * @param boolean $authRefresh - If authorize is expired, refresh token
     * @return mixed
     */
    function restCommand($method, array $params = Array(), array $auth = Array(), $authRefresh = true)
    {
       $queryUrl = "https://".$auth["domain"]."/rest/".$method;
       $queryData = http_build_query(array_merge($params, array("auth" => $auth["access_token"])));
       
       $curl = curl_init();
    
       curl_setopt_array($curl, array(
          CURLOPT_POST => 1,
          CURLOPT_HEADER => 0,
          CURLOPT_RETURNTRANSFER => 1,
          CURLOPT_SSL_VERIFYPEER => 1,
          CURLOPT_URL => $queryUrl,
          CURLOPT_POSTFIELDS => $queryData,
       ));
    
       $result = curl_exec($curl);
       curl_close($curl);
    
       $result = json_decode($result, 1);
    
       if ($authRefresh && isset($result['error']) && in_array($result['error'], array('expired_token', 'invalid_token')))
       {
          $auth = restAuth($auth);
          if ($auth)
          {
             $result = restCommand($method, $params, $auth, false);
          }
       }
    
       return $result;
    }
    

    RestAuth function

    /**
     * Get new authorize data if you authorize is expire.
     *
     * @param array $auth - Authorize data, ex: Array('domain' => 'https://test.bitrix24.com', 'access_token' => '7inpwszbuu8vnwr5jmabqa467rqur7u6')
     * @return bool|mixed
     */
    function restAuth($auth)
    {
       if (!CLIENT_ID || !CLIENT_SECRET)
          return false;
    
       if(!isset($auth['refresh_token']) || !isset($auth['scope']) || !isset($auth['domain']))
          return false;
    
       $queryUrl = 'https://'.$auth['domain'].'/oauth/token/';
       $queryData = http_build_query($queryParams = array(
          'grant_type' => 'refresh_token',
          'client_id' => CLIENT_ID,
          'client_secret' => CLIENT_SECRET,
          'refresh_token' => $auth['refresh_token'],
          'scope' => $auth['scope'],
       ));
       
       $curl = curl_init();
    
       curl_setopt_array($curl, array(
          CURLOPT_HEADER => 0,
          CURLOPT_RETURNTRANSFER => 1,
          CURLOPT_URL => $queryUrl.'?'.$queryData,
       ));
    
       $result = curl_exec($curl);
       curl_close($curl);
    
       $result = json_decode($result, 1);
       
       return $result;
    }
    


    Event Subscription

    REST API interface allows to install your own server event handlers.

    An events handler is an URL to which the system sends a request after a user performs an action on the Bitrix24 account, hosting the application.

    The handler receives the following data on input:

    • event - specifies the event name.
    • data - an array containing the event data.
    • auth - contains the authentication information.

    The handler can be:

    • using received authentication information to send requests to REST API.
    • be installed only by a user with account administrative rights.

    Attention! If the event handler requires access to REST API to work with data, then it is strongly recommended to use the retrieved authentication data specifically, and not the data, saved on application side.

    When installing a handler, the application can specify a user whose credentials will be used by the event handler for authentication. By default, the event handler will be authenticated as a user whose actions triggered the event.

    An event handler is not called immediately after an event occurred. It will be activated after some time which depends on a current server load

    List of available event can be found via the REST method events.

    Event handler is installed as follows:

    • via REST method event.bind on the basis of restCommand:
      $handlerBackUrl  = 'http://www.my-domain.com/handler/';
      $result = restCommand('event.bind', Array(
         'EVENT' => 'OnAppUpdate',
         'HANDLER' => $handlerBackUrl
      ), $_REQUEST["auth"]);
      
    • or via BX24.callBind JS-library function:
      BX24.callBind('OnAppUpdate', 'http://www.my-domain.com/handler/');
      

      To get the list of registered event handlers, use REST method events.get.

      Removal of registered handler is done via REST method event.unbind or via JS-library function BX24.callUnbind.

      To grant application the access a specific event, a corresponding access permission has to be requested when registering an application version.

      Application can install any number of handlers of the same event, but all handlers shall be installed with authentication of different users. Furthermore, ability to call a handler depends on the access permission of a user, whose authorization is used to activate a handler.

      event names are case-independent.

      Attention! When uninstalling or installing a new version of an application, all event handlers, installed by this application, will be deleted.


      Installation and Update Events

      When installing and updating the application, 2 events are used: ONAPPINSTALL and ONAPPUPDATE. Both events has the same set of data, with only one different parameter - [PREVIOUS_VERSION] => 1, where old version of the app is specified.


      ONAPPINSTALL event for installation of the application

      [data] => Array(
        [LANGUAGE_ID] = com // Account basic language
        [VERSION] = 1 // Application version
      )
      [auth] => Array(
          [access_token] => lh8ze36o8ulgrljbyscr36c7ay5sinva // Key to send request to REST service
          [scope] => imbot // Permitted access levels 
          [domain] => b24.hazz // Bitrix24 domain account, on which the application is installed
          [application_token] => c917d38f6bdb84e9d9e0bfe9d585be73 // Application token will help you to "fend off" redundant requests to event handler; this field is available in all events
      
          [expires_in] => 3600 // Token expiration period, after which new token will have to be requested
          [member_id] => d41d8cd98f00b204e9800998ecf8427e // Unique account ID, required to extend authentication
          [refresh_token] => 5f1ih5tsnsb11sc5heg3kp4ywqnjhd09 // Key to extend authentication
      )
      

      ONAPPUPDATE event to update application

      [data] => Array(
        [LANGUAGE_ID] = com // Account basic language
        [VERSION] = 2 // Application new version
        [PREVIOUS_VERSION] => 1 // Application old version
      )
      [auth] => Array(
          [access_token] => lh8ze36o8ulgrljbyscr36c7ay5sinva // Key to send request to REST service
          [scope] => imbot // Permitted access levels 
          [domain] => b24.hazz // Bitrix24 domain account, on which the application is installed
          [application_token] => c917d38f6bdb84e9d9e0bfe9d585be73 // Application token will help you to "end off" redundant requests to event handler; this field is available in all events
      
          [expires_in] => 3600 // Token expiration period, after which new token will have to be requested
          [member_id] => d41d8cd98f00b204e9800998ecf8427e // Unique account ID, required to extend authentication
          [refresh_token] => 5f1ih5tsnsb11sc5heg3kp4ywqnjhd09 // Key to extend authentication
      )
      

      Attention! Fields expires_in, member_id, refresh_token - are not required in the basic chatbot operation. But, if it's required for your application, then you can read how to work with them here. Extension option is included into the bot example.



      JS methods for IFRAME applications

      Within IFRAME applications, you can use methods to open user dialogues or to manage window sizes. The following functions are provided to work with web-messenger:


      Open messenger window

      JavaScript method: BX24.im.openMessenger

      Method call:
      <script>>
          BX24.im.openMessenger('dialogId');
      </script>
      
      Parameters:

      dialogId - Dialogue ID:

      • userId or chatXXX - chat, where XXX - chat ID, it can be just a digit.
      • sgXXX - chat of group, where XXX – number of social media group (chat should be permitted in this group).
      • imol|XXXX - open channel, where XXX – code, returned via REST method imopenlines.network.join.

      If nothing is sent, chat interface will open with the last opened dialogue.



      Open history window

      JavaScript method: BX24.im.openHistory

      Method call:
      <script>>
          BX24.im.openHistory('dialogId');
      </script>
      
      Parameters:

      dialogId - Dialogue ID:

      • userId or chatXXX - chat, where XXX - chat ID, it can be just a digit.
      • imol|XXXX - open channel, wher XXX – number of open channel session.


      Call to internal number

      JavaScript method: BX24.im.callTo

      Method call:
      <script>>
          BX24.im.callTo('userId[, video=true]');
      </script>
      
      Parameters:

      dialogId - Account user ID.
      video - true - video call, false - audio call. Optional parameter.



      Call to telephone number

      JavaScript method: BX24.im.phoneTo

      Method call:
      <script>>
          BX24.im.phoneTo('number');
      </script>
      
      Parameters:

      number - Telephone number (string). Telephone number can have format: 6418736493 or (641) 873-6493.



      Additional Materials



      These Materials can be helpful during development of chatbots for Bitrix24: