Skip to content

Latest commit

 

History

History
428 lines (349 loc) · 12.9 KB

File metadata and controls

428 lines (349 loc) · 12.9 KB

Working with Context Menu

{% note tip "" %}

If you are developing integrations for Bitrix24 using AI tools (Codex, Claude Code, Cursor), connect to the MCP server so that the assistant can utilize the official REST documentation.

{% endnote %}

The context menu is a set of actions within a message. You can add your own items to the context menu to open links or send commands to the bot.

Methods that support context menu functionality:

How to Add an Item to the Context Menu

To add an item to the context menu, pass the MENU parameter when creating or updating a message.

MENU can be passed as:

  • a JSON string
  • an object with the root key ITEMS
  • an array of items without wrapping

If the MENU does not contain the key ITEMS, the server will automatically assume that a shortened format has been provided and will wrap the array in ITEMS.

{% list tabs %}

  • Full format with the key ITEMS

    {
        "MENU": {
            "ITEMS": [
                { "TEXT": "Open Website", "LINK": "https://example.com" }
            ]
        }
    }
  • Shortened format

    {
        "MENU": [
            { "TEXT": "Open Website", "LINK": "https://example.com" }
        ]
    }

{% endlist %}

Menu Item Fields

#| || Name type | Description || || TEXT string | The text of the menu item.

For menu items, it is mandatory to specify TEXT and one action field — LINK, COMMAND, ACTION + ACTION_VALUE, or APP_ID || || LINK string | The link for the menu item. http/https and relative paths /... are allowed. || || COMMAND string | The command for the bot.

For more details on command processing by the chat bot, see below || || COMMAND_PARAMS string | Command parameters. Pass together with COMMAND || || APP_ID integer | The application identifier for the chat.

Deprecated scenario. To open an application from chat, use widgets. || || APP_PARAMS string | Parameters for launching the application in chat. Pass together with APP_ID.

Deprecated scenario. To open an application from chat, use widgets.

{% note info "" %}

Currently, the option with parameters APP_ID and APP_PARAMS is used in chats Open Channels

{% endnote %} || || ACTION string | Action:

  • PUT — insert text into the input field
  • SEND — send text
  • COPY — copy text to clipboard
  • CALL — make a call
  • DIALOG — open chat

Available starting from REST API IM revision 28 || || ACTION_VALUE string | Value for ACTION:

  • PUT — text to be inserted into the input field
  • SEND — text to be sent
  • COPY — text to be copied to clipboard
  • CALL — phone number in international format
  • DIALOG — chat identifier in the format chatXXX for group chat and ID of the user for personal chat

Available starting from REST API IM revision 28 || || CONTEXT string | Display context.

Allowed values:

  • MOBILE — show only on mobile devices
  • DESKTOP — show only in desktop version
  • ALL — show everywhere

Default is ALL || || DISABLED string | Activity of the menu item.

Allowed values:

  • Y — menu item is inactive
  • N — menu item is active

Default is N || |#

Example of Sending a Message with a Context Menu

{% include Example Notes %}

{% list tabs %}

  • cURL (Webhook)

    curl -X POST \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -d '{"DIALOG_ID":"chat2725","MESSAGE":"Select an action from the menu","URL_PREVIEW":"Y","MENU":{"ITEMS":[{"TEXT":"Open Website","LINK":"https://www.example.com/"},{"TEXT":"Send Text","ACTION":"SEND","ACTION_VALUE":"Done"}]}}' \
    https://**put_your_bitrix24_address**/rest/**put_your_user_id_here**/**put_your_webhook_here**/im.message.add
  • cURL (OAuth)

    curl -X POST \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -d '{"DIALOG_ID":"chat2725","MESSAGE":"Select an action from the menu","URL_PREVIEW":"Y","MENU":{"ITEMS":[{"TEXT":"Open Website","LINK":"https://www.example.com/"},{"TEXT":"Send Text","ACTION":"SEND","ACTION_VALUE":"Done"}]}},"auth":"**put_access_token_here**"}' \
    https://**put_your_bitrix24_address**/rest/im.message.add
  • JS (TS)

    // This snippet is an ES module: top-level await requires type="module" or a bundler.
    // $b24 is an already-initialized SDK instance (see the SDK "Get started" guide).
    import { Text } from '@bitrix24/b24jssdk'
    import type { B24Frame } from '@bitrix24/b24jssdk'
    
    declare const $b24: B24Frame
    
    try {
      const response = await $b24.actions.v2.call.make<number>({
        method: 'im.message.add',
        params: {
          DIALOG_ID: 'chat2725',
          MESSAGE: 'Select an action from the menu',
          URL_PREVIEW: 'Y',
          MENU: {
            ITEMS: [
              {
                TEXT: 'Open website',
                LINK: 'https://www.example.com/',
              },
              {
                TEXT: 'Send text',
                ACTION: 'SEND',
                ACTION_VALUE: 'Done',
              },
            ],
          },
        },
        requestId: Text.getUuidRfc4122()
      })
    
      // The payload is available only on a successful response
      if (!response.isSuccess) {
        console.error(response.getErrorMessages().join('; '))
      } else {
        const result = response.getData()!.result
        console.info('Created message with ID:', result)
      }
    } catch (error) {
      // Thrown on transport or SDK failures (AjaxError, SdkError, etc.)
      console.error(error)
    }
  • JS (UMD)

    <!-- Load the SDK (UMD build); it is exposed as the global B24Js -->
    <script src="https://unpkg.com/@bitrix24/b24jssdk@1/dist/umd/index.min.js"></script>
    <script>
      async function addMessageWithMenu() {
        try {
          // Initialize the SDK inside a Bitrix24 frame
          const $b24 = await B24Js.initializeB24Frame()
    
          const response = await $b24.actions.v2.call.make({
            method: 'im.message.add',
            params: {
              DIALOG_ID: 'chat2725',
              MESSAGE: 'Select an action from the menu',
              URL_PREVIEW: 'Y',
              MENU: {
                ITEMS: [
                  {
                    TEXT: 'Open website',
                    LINK: 'https://www.example.com/',
                  },
                  {
                    TEXT: 'Send text',
                    ACTION: 'SEND',
                    ACTION_VALUE: 'Done',
                  },
                ],
              },
            },
            requestId: B24Js.Text.getUuidRfc4122()
          })
    
          // The payload is available only on a successful response
          if (!response.isSuccess) {
            console.error(response.getErrorMessages().join('; '))
            return
          }
    
          const result = response.getData().result
          console.info('Created message with ID:', result)
        } catch (error) {
          // Thrown on transport or SDK failures (AjaxError, SdkError, etc.)
          console.error(error)
        }
      }
    
      document.addEventListener('DOMContentLoaded', addMessageWithMenu)
    </script>
  • PHP

    try {
        $response = $b24Service
            ->core
            ->call(
                'im.message.add',
                [
                    'DIALOG_ID' => 'chat2725',
                    'MESSAGE' => 'Select an action from the menu',
                    'URL_PREVIEW' => 'Y',
                    'MENU' => [
                        'ITEMS' => [
                            [
                                'TEXT' => 'Open Website',
                                'LINK' => 'https://www.example.com/'
                            ],
                            [
                                'TEXT' => 'Send Text',
                                'ACTION' => 'SEND',
                                'ACTION_VALUE' => 'Done'
                            ]
                        ]
                    ]
                ]
            );
    
        $result = $response
            ->getResponseData()
            ->getResult();
    
        echo 'Success: ' . print_r($result, true);
        processData($result);
    
    } catch (Throwable $e) {
        error_log($e->getMessage());
        echo 'Error adding message: ' . $e->getMessage();
    }
  • BX24.js

    BX24.callMethod(
        'im.message.add',
        {
            DIALOG_ID: 'chat2725',
            MESSAGE: 'Select an action from the menu',
            URL_PREVIEW: 'Y',
            MENU: {
                ITEMS: [
                    {
                        TEXT: 'Open Website',
                        LINK: 'https://www.example.com/'
                    },
                    {
                        TEXT: 'Send Text',
                        ACTION: 'SEND',
                        ACTION_VALUE: 'Done',
                    }
                ]
            }
        },
        function(result) {
            if (result.error()) {
                console.error(result.error().ex);
            } else {
                console.log(result.data());
            }
        }
    );
  • PHP CRest

    require_once('crest.php');
    
    $result = CRest::call(
        'im.message.add',
        [
            'DIALOG_ID' => 'chat2725',
            'MESSAGE' => 'Select an action from the menu',
            'URL_PREVIEW' => 'Y',
            'MENU' => [
                'ITEMS' => [
                    [
                        'TEXT' => 'Open Website',
                        'LINK' => 'https://www.example.com/'
                    ],
                    [
                        'TEXT' => 'Send Text',
                        'ACTION' => 'SEND',
                        'ACTION_VALUE' => 'Done'
                    ]
                ]
            ]
        ]
    );
    
    echo '<PRE>';
    print_r($result);
    echo '</PRE>';
  • Go

    // client and ctx are already created — see the Go SDK section
    res, err := client.Core().Call(ctx, "im.message.add", b24.Params{
    	"DIALOG_ID":   "chat2725",
    	"MESSAGE":     "Select an action from the menu",
    	"URL_PREVIEW": "Y",
    	"MENU": b24.Params{
    		"ITEMS": []b24.Params{
    			{
    				"TEXT": "Open Website",
    				"LINK": "https://www.example.com/",
    			},
    			{
    				"TEXT":         "Send Text",
    				"ACTION":       "SEND",
    				"ACTION_VALUE": "Done",
    			},
    		},
    	},
    })
    if err != nil {
    	return fmt.Errorf("im.message.add: %w", err)
    }
    
    // The response arrives as json.RawMessage — unmarshal it
    // into a struct matching the response shape shown below on this page.
    fmt.Printf("%s\n", res.Result)

{% endlist %}

How to Update or Remove the Context Menu

To update menu items, use the methods:

To disable the display of additional menu items, pass:

  • MENU: 'N'
  • an empty value for MENU

Command Processing by the Chat Bot {#command-processing}

  1. To ensure the command works in the menu, register it using the method imbot.command.register.

    In the menu item, specify the following keys:

    "COMMAND" => "example", // command that will be sent to the chat bot
    "COMMAND_PARAMS" => "example", // parameters for the command
  2. Clicking on the menu item will generate the event ONIMCOMMANDADD.

  3. Inside the event, the array data[COMMAND] will contain data about the invoked event. The value COMMAND_CONTEXT will indicate the context in which the command was invoked:

    • TEXTAREA — command entered manually
    • KEYBOARD — command invoked by button
    • MENU — command invoked from the context menu

Continue Learning