imbot.v2.Chat.Message.getContext
Получить контекст сообщения
Описание
Метод imbot.v2.Chat.Message.getContext возвращает окно сообщений вокруг указанного. Используется для анализа истории диалога.
Метод доступен только для ботов типа supervisor и personal. Подробнее — Типы ботов.
Параметры
botId
integer
обязательный
ID бота
botToken
string
необязательный
Уникальный токен авторизации бота. Обязателен при авторизации через вебхук, не нужен для OAuth.
Передавайте тот же botToken, который был указан при регистрации чат-бота
messageId
integer
обязательный
ID центрального сообщения
range
integer
необязательный
Количество сообщений в каждую сторону от центрального (1–50). По умолчанию 50
Примеры запроса
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",
f"error: {error.error}",
f"error_description: {error.error_description}",
sep="\n",
)
except BitrixSDKException as error:
print(f"Ошибка Bitrix SDK: {error.message}")
except Exception as error:
print(f"Непредвиденная ошибка: {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 и ctx уже созданы — см. раздел «SDK для Go»
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("разбор ответа: %w", err)
}
fmt.Println(item.HasPrevPage, item.HasNextPage)
Ответ
HTTP-статус: 200
{
"result": {
"messages": [
{
"id": 785,
"chatId": 5,
"authorId": 1,
"date": "2026-03-19T14:25:00+03:00",
"text": "Добрый день!",
"isSystem": false,
"uuid": "",
"forward": null,
"params": {},
"viewedByOthers": true
},
{
"id": 789,
"chatId": 5,
"authorId": 2,
"date": "2026-03-19T14:30:00+03:00",
"text": "Привет! Как дела?",
"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+03:00",
"date_finish": "2024-10-11T10:00:00+03:00"
}
}
Обработка ошибок
HTTP-статус: 400
{
"error": "BOT_TYPE_NOT_ALLOWED",
"error_description": "Bot type not allowed"
}
| Код | Описание | Значение |
|---|---|---|
BOT_TOKEN_NOT_SPECIFIED |
Bot token is not specified | Не указан botToken. Обязателен при авторизации через вебхук |
BOT_ID_REQUIRED |
Bot ID is required | Не указан botId |
BOT_NOT_FOUND |
Bot not found | Бот не найден |
BOT_OWNERSHIP_ERROR |
Bot is registered by another application | Бот зарегистрирован другим приложением |
BOT_TYPE_NOT_ALLOWED |
Bot type not allowed | Метод доступен только для ботов типа supervisor и personal |
MESSAGE_NOT_FOUND |
Message not found | Сообщение не найдено |
MESSAGE_ACCESS_DENIED |
Message access denied | Бот не является участником чата с этим сообщением или не имеет доступа к истории |

