Get Message Context with imbot.v2.Chat.Message.getContext

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.

Scope: imbot

Who can execute the method: owner of the registered bot

The method imbot.v2.Chat.Message.getContext returns a window of messages surrounding the specified one. It is used for analyzing the dialogue history.

The method is available only for supervisor and personal type bots. For more details, see Bot Types.

Method Parameters

Required parameters are marked with *

Name
Type

Description

botId*
integer

Bot ID

botToken
string

Unique authorization token for the bot. Required for webhook authorization, not needed for OAuth.

Pass the same botToken that was specified during the chat bot registration.

messageId*
integer

ID of the central message

range
integer

Number of messages on each side of the central one (1–50). Default is 50

Code Examples

How to Use Examples in Documentation

curl -X POST \
          -H "Content-Type: application/json" \
          -H "Accept: application/json" \
          -d '{"botId":456,"botToken":"my_bot_token","messageId":789,"range":20}' \
          https://**put_your_bitrix24_address**/rest/**put_your_user_id_here**/**put_your_webhook_here**/imbot.v2.Chat.Message.getContext
        
curl -X POST \
          -H "Content-Type: application/json" \
          -H "Accept: application/json" \
          -d '{"botId":456,"messageId":789,"range":20,"auth":"**put_access_token_here**"}' \
          https://**put_your_bitrix24_address**/rest/imbot.v2.Chat.Message.getContext
        
try {
          const response = await $b24.callMethod('imbot.v2.Chat.Message.getContext', {
            botId: 456,
            messageId: 789,
            range: 20,
          });
        
          const { result } = response.getData();
          console.log('result:', result);
        } catch (error) {
          console.error('Error:', error);
        }
        
from b24pysdk.errors import BitrixAPIError, BitrixSDKException
        
        try:
            bitrix_response = client.imbot.v2.chat.message.get_context(
                bot_id=456,
                message_id=789,
                range=20,
            ).response
            result = bitrix_response.result
            print(result)
        except BitrixAPIError as error:
            print(
                "Bitrix API error",
                f"error: {error.error}",
                f"error_description: {error.error_description}",
                sep="\n",
            )
        except BitrixSDKException as error:
            print(f"Bitrix SDK error: {error.message}")
        except Exception as error:
            print(f"Unexpected error: {error}")
        
try {
            $response = $b24Service
                ->core
                ->call(
                    'imbot.v2.Chat.Message.getContext',
                    [
                        'botId' => 456,
                        'messageId' => 789,
                        'range' => 20,
                    ]
                );
        
            $result = $response
                ->getResponseData()
                ->getResult();
        
            echo 'result: '. print_r($result, true);
        } catch (Throwable $exception) {
            error_log($exception->getMessage());
            echo 'Error: '. $exception->getMessage();
        }
        
BX24.callMethod(
            'imbot.v2.Chat.Message.getContext',
            {
                botId: 456,
                messageId: 789,
                range: 20,
            },
            function(result) {
                if (result.error()) {
                    console.error(result.error().ex);
                } else {
                    console.log(result.data());
                }
            }
        );
        
require_once('crest.php');
        
        $result = CRest::call(
            'imbot.v2.Chat.Message.getContext',
            [
                'botId' => 456,
                'messageId' => 789,
                'range' => 20,
            ]
        );
        
        if (!empty($result['error'])) {
            echo 'Error: '. $result['error_description'];
        } else {
            foreach ($result['result']['messages'] as $message) {
                echo $message['id']. ': '. $message['text']. "\n";
            }
        }
        
// client and ctx are already created — see the Go SDK section
        res, err := client.Core().Call(ctx, "imbot.v2.Chat.Message.getContext", b24.Params{
        	"botId":     456,
        	"botToken":  "my_bot_token",
        	"messageId": 789,
        	"range":     20,
        })
        if err != nil {
        	return fmt.Errorf("imbot.v2.Chat.Message.getContext: %w", err)
        }
        
        var item struct {
        	HasPrevPage bool `json:"hasPrevPage"`
        	HasNextPage bool `json:"hasNextPage"`
        }
        if err := json.Unmarshal(res.Result, &item); err != nil {
        	return fmt.Errorf("parse response: %w", err)
        }
        fmt.Println(item.HasPrevPage, item.HasNextPage)
        

Response Handling

HTTP Status: 200

{
            "result": {
                "messages": [
                    {
                        "id": 785,
                        "chatId": 5,
                        "authorId": 1,
                        "date": "2026-03-19T14:25:00+02:00",
                        "text": "Good afternoon!",
                        "isSystem": false,
                        "uuid": "",
                        "forward": null,
                        "params": {},
                        "viewedByOthers": true
                    },
                    {
                        "id": 789,
                        "chatId": 5,
                        "authorId": 2,
                        "date": "2026-03-19T14:30:00+02:00",
                        "text": "Hi! How are you?",
                        "isSystem": false,
                        "uuid": "",
                        "forward": null,
                        "params": {},
                        "viewedByOthers": true
                    }
                ],
                "users": [
                    {
                        "id": 1,
                        "active": true,
                        "name": "John Smith",
                        "bot": false,
                        "type": "employee"
                    },
                    {
                        "id": 2,
                        "active": true,
                        "name": "Anna Davis",
                        "bot": false,
                        "type": "employee"
                    }
                ],
                "hasPrevPage": false,
                "hasNextPage": true
            },
            "time": {
                "start": 1728626400.123,
                "finish": 1728626400.234,
                "duration": 0.111,
                "processing": 0.045,
                "date_start": "2024-10-11T10:00:00+02:00",
                "date_finish": "2024-10-11T10:00:00+02:00"
            }
        }
        

Returned Data

Name
Type

Description

result
object

Result of the request

result.messages
Message[]

Array of messages from oldest to newest (detailed description)

result.users
User[]

Authors of messages (detailed description)

result.hasPrevPage
boolean

Are there earlier messages

result.hasNextPage
boolean

Are there later messages

time
time

Information about the request execution time

Fields of the Message Object

Field
Type

Description

id
integer

Identifier of the message

chatId
integer

Identifier of the chat

authorId
integer

Identifier of the message author

date
string

Date the message was sent

text
string

Text of the message

isSystem
boolean

System message

uuid
string

External identifier of the message

forward
object

Data about the forwarded message

params
object

Additional parameters of the message

viewedByOthers
boolean

Message viewed by other participants

Fields of the User Object

Field
Type

Description

id
integer

Identifier of the user

active
boolean

User is active

name
string

User's first and last name

bot
boolean

Indicates if the user is a bot

type
string

Type of user

Complete description of all object fields can be found on the Objects and Fields page.

Pagination

To load the next page, call the method again, passing the messageId of the last message from the current selection. For the previous page, use the ID of the first message.

Error Handling

HTTP Status: 400, 403

{
            "error": "BOT_TYPE_NOT_ALLOWED",
            "error_description": "Bot type not allowed"
        }
        

Name
type

Description

error
string

String error code. It consists of digits, Latin letters, and underscores. It may arrive empty — in that case only error_description shows the reason

error_description
string

Error message for the developer. Do not show it to the end user without processing

Possible Error Codes

Code

Description

Value

BOT_TOKEN_NOT_SPECIFIED

Bot token is not specified

botToken is not provided. Required for webhook authorization

BOT_ID_REQUIRED

Bot ID is required

botId is not provided

BOT_NOT_FOUND

Bot not found

Bot not found

BOT_OWNERSHIP_ERROR

Bot is registered by another application

Bot registered by another application

BOT_TYPE_NOT_ALLOWED

Bot type not allowed

Method available only for supervisor and personal type bots

MESSAGE_NOT_FOUND

Message not found

Message not found

MESSAGE_ACCESS_DENIED

Message access denied

Bot is not a participant in the chat with this message or does not have access to the history

Statuses and System Error Codes

HTTP Status: 4xx, 5xx

The errors described below are returned by the REST API itself, not by the logic of a specific method. They can arrive in response to any method.

Status

Code
Error Message

Description

500

INTERNAL_SERVER_ERROR
Internal server error

An internal server error has occurred. Retry the call, and if the error persists, contact the server administrator or Bitrix24 technical support

500

ERROR_UNEXPECTED_ANSWER
Server returned an unexpected response

The server returned an unexpected response. Retry the call, and if the error persists, contact the server administrator or Bitrix24 technical support

503

QUERY_LIMIT_EXCEEDED
Too many requests

The request intensity limit has been exceeded

429

OPERATION_TIME_LIMIT
Method is blocked due to operation time limit

The method is blocked because the request resource intensity limit has been exceeded. The block is lifted automatically once the accumulated execution time of the method no longer exceeds the limit

401

NO_AUTH_FOUND
Wrong authorization data

The request contains no authorization data: neither an access token nor a webhook code was passed

401

INVALID_REQUEST
Https required

Methods are called over the HTTPS protocol only

401

OVERLOAD_LIMIT
REST API is blocked due to overload

The REST API is blocked due to overload. This is a manual individual block. To have it lifted, contact Bitrix24 technical support

401

ACCESS_DENIED
REST is available only on commercial plans

The REST API is available only on commercial plans. A webhook receives a different error message — REST is available only by subscription

401

INVALID_CREDENTIALS
Invalid request credentials

No active webhook with the specified user identifier and secret code was found

404

ERROR_METHOD_NOT_FOUND
Method not found!

No method with this name was found. The name is misspelled, the method does not exist in the REST API, or it is unavailable without the required scope

401

insufficient_scope
The request requires higher privileges than provided by the webhook token

The request requires broader permissions than the token has: for a webhook these are the permissions granted to it, for an application it is the scope. For an application, the error message ends with provided by the access token

401

expired_token
The access token provided has expired

The access token has expired

401

user_access_error
The user does not have access to the application

The application is installed, but the Bitrix24 administrator has granted access to it only to specific users

403

PORTAL_DELETED
Portal was deleted

The public part of the site is closed. To open it on an on-premise installation, disable the "Temporary closure of the public part of the site" option. Path to the setting: Desktop > Settings > Product Settings > Module Settings > Main Module > Temporary closure of the public part of the site

Continue Learning