imbot.v2.File.upload
Загрузить файл в чат
Описание
Метод imbot.v2.File.upload загружает файл в чат от имени бота. Объединяет три шага устаревшего API в один вызов: загрузку файла на диск, прикрепление к чату и отправку сообщения.
Параметры
botId
integer
обязательный
ID бота
botToken
string
необязательный
Уникальный токен авторизации бота. Обязателен при авторизации через вебхук, не нужен для OAuth.
Передавайте тот же botToken, который был указан при регистрации чат-бота
dialogId
string
обязательный
ID диалога. Для групповых чатов — chat{chatId}, для личных — {userId}
fields
object
обязательный
Данные файла и сообщения. Структура описана ниже
Параметр fields
name
string
обязательный
Имя файла с расширением
content
string
обязательный
Содержимое файла в кодировке Base64. Максимальный размер — 100 МБ
message
string
необязательный
Текст сообщения, отправляемого вместе с файлом
Примеры запроса
curl -X POST \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-d '{"botId":456,"botToken":"my_bot_token","dialogId":"chat5","fields":{"name":"report.pdf","content":"SGVsbG8gV29ybGQh","message":"Here is the report"}}' \
https://**put_your_bitrix24_address**/rest/**put_your_user_id_here**/**put_your_webhook_here**/imbot.v2.File.upload
curl -X POST \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-d '{"botId":456,"dialogId":"chat5","fields":{"name":"report.pdf","content":"SGVsbG8gV29ybGQh","message":"Here is the report"},"auth":"**put_access_token_here**"}' \
https://**put_your_bitrix24_address**/rest/imbot.v2.File.upload
try {
const response = await $b24.callMethod('imbot.v2.File.upload', {
botId: 456,
dialogId: 'chat5',
fields: { name: 'report.pdf', content: 'SGVsbG8gV29ybGQh', message: 'Here is the report' },
});
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.file.upload(
bot_id=456,
dialog_id="chat5",
fields={
"name": "report.pdf",
"content": "SGVsbG8gV29ybGQh",
"message": "Here is the report",
},
).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.File.upload',
[
'botId' => 456,
'dialogId' => 'chat5',
'fields' => [
'name' => 'report.pdf',
'content' => base64_encode(file_get_contents('/path/to/report.pdf')),
'message' => 'Here is the report',
],
]
);
$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.File.upload',
{
botId: 456,
dialogId: 'chat5',
fields: { name: 'report.pdf', content: btoa('...'), message: 'Here is the report' },
},
function(result) {
if (result.error()) {
console.error(result.error().ex);
} else {
console.log(result.data());
}
}
);
require_once('crest.php');
$result = CRest::call(
'imbot.v2.File.upload',
[
'botId' => 456,
'dialogId' => 'chat5',
'fields' => [
'name' => 'report.pdf',
'content' => base64_encode(file_get_contents('/path/to/report.pdf')),
'message' => 'Here is the report',
],
]
);
if (!empty($result['error'])) {
echo 'Error: '. $result['error_description'];
} else {
echo 'File ID: '. $result['result']['file']['id'];
}
// client и ctx уже созданы — см. раздел «SDK для Go»
res, err := client.Core().Call(ctx, "imbot.v2.File.upload", b24.Params{
"botId": 456,
"botToken": "my_bot_token",
"dialogId": "chat5",
"fields": b24.Params{
"name": "report.pdf",
"content": "SGVsbG8gV29ybGQh",
"message": "Here is the report",
},
})
if err != nil {
return fmt.Errorf("imbot.v2.File.upload: %w", err)
}
var item struct {
MessageID b24.ID `json:"messageId"`
ChatID b24.ID `json:"chatId"`
DialogID string `json:"dialogId"`
}
if err := json.Unmarshal(res.Result, &item); err != nil {
return fmt.Errorf("разбор ответа: %w", err)
}
fmt.Println(item.MessageID, item.ChatID)
Ответ
HTTP-статус: 200
{
"result": {
"file": {
"id": 138,
"chatId": 5,
"name": "report.pdf",
"extension": "pdf",
"size": 35341
},
"messageId": 123,
"chatId": 5,
"dialogId": "chat5"
},
"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": "FILE_TOO_LARGE",
"error_description": "File too large"
}
| Код | Описание | Значение |
|---|---|---|
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 | Бот зарегистрирован другим приложением |
FILE_EMPTY |
File name or content is empty | Не указано имя или содержимое файла |
FILE_INVALID_CONTENT |
Invalid base64 content | Невалидный Base64 |
FILE_FOLDER_ERROR |
Failed to get chat folder | Не удалось получить папку чата |
FILE_UPLOAD_FAILED |
File upload failed | Ошибка загрузки файла |
FILE_SEND_FAILED |
Failed to send message | Ошибка отправки сообщения |
FILE_TOO_LARGE |
File is too large | Размер файла превышает 100 МБ |

