Find Message in Chat im.dialog.messages.search

Choose a tool for developing with an AI agent:

  • use Alaio Vibecode to build an app for Bitrix24 from a task description without knowing any programming language. The agent writes the code and deploys the app to a server, with no manual hosting setup
  • use the MCP server to develop a REST API integration in your own project. The agent refers to the official REST documentation

Scope: im

Who can execute the method: chat participant

The method im.dialog.messages.search performs a search for messages in the chat.

Method Parameters

Required parameters are marked with *

Name
type

Description

CHAT_ID*
integer

Identifier of the chat in which the search is performed

SEARCH_MESSAGE
string

Search string for the message text.

Search for this parameter is performed for strings longer than 2 characters

DATE_FROM
datetime

Start of the search period in ISO 8601 format (RFC3339)

DATE_TO
datetime

End of the search period in ISO 8601 format (RFC3339)

DATE
datetime

Search for messages on a specific date in ISO 8601 format (RFC3339).

If the parameter is provided, the search is performed within 24 hours from the specified date

ORDER
object

Sorting parameters.

Supported field:

  • ID — sort by message identifier, values ASC or DESC

Default: {"ID": "DESC"}

LIMIT
integer

Number of messages returned.

Default value: 50.
Maximum value: 200

LAST_ID
integer

Identifier of the last message from the previous selection for pagination

Code Examples

How to Use Examples in Documentation

curl -X POST \
        -H "Content-Type: application/json" \
        -H "Accept: application/json" \
        -d '{"CHAT_ID":3,"SEARCH_MESSAGE":"test","ORDER":{"ID":"DESC"},"LIMIT":20}' \
        https://**put_your_bitrix24_address**/rest/**put_your_user_id_here**/**put_your_webhook_here**/im.dialog.messages.search
        
curl -X POST \
        -H "Content-Type: application/json" \
        -H "Accept: application/json" \
        -d '{"CHAT_ID":3,"SEARCH_MESSAGE":"test","ORDER":{"ID":"DESC"},"LIMIT":20,"auth":"**put_access_token_here**"}' \
        https://**put_your_bitrix24_address**/rest/im.dialog.messages.search
        
// 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, ISODate } from '@bitrix24/b24jssdk'
        
        declare const $b24: B24Frame
        
        // Shape of the payload returned in result (match the "response handling" section of the page)
        type DialogMessagesSearchResult = {
          messages: Array<{
            id: number
            chat_id: number
            author_id: number
            date: ISODate
            text: string
            isSystem: boolean
            uuid: string | null
            forward: object | null
            params: unknown[]
            viewedByOthers: boolean
            unread: boolean
            viewed: boolean
          }>
          users: unknown[]
          files: unknown[]
          additionalMessages: unknown[]
          copilot: object | null
          stickers: unknown[]
          reactions: unknown[]
          tariffRestrictions: { isHistoryLimitExceeded: boolean }
          usersShort: unknown[]
        }
        
        try {
          const response = await $b24.actions.v2.call.make<DialogMessagesSearchResult>({
            method: 'im.dialog.messages.search',
            params: {
              CHAT_ID: 3,
              SEARCH_MESSAGE: 'test',
              ORDER: { ID: 'DESC' },
              LIMIT: 20,
            },
            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('Found messages:', result.messages.length, result.messages)
          }
        } catch (error) {
          // Thrown on transport or SDK failures (AjaxError, SdkError, etc.)
          console.error(error)
        }
        
<!-- 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 searchDialogMessages() {
            try {
              // Initialize the SDK inside a Bitrix24 frame
              const $b24 = await B24Js.initializeB24Frame()
        
              const response = await $b24.actions.v2.call.make({
                method: 'im.dialog.messages.search',
                params: {
                  CHAT_ID: 3,
                  SEARCH_MESSAGE: 'test',
                  ORDER: { ID: 'DESC' },
                  LIMIT: 20,
                },
                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('Found messages:', result.messages.length, result.messages)
            } catch (error) {
              // Thrown on transport or SDK failures (AjaxError, SdkError, etc.)
              console.error(error)
            }
          }
        
          document.addEventListener('DOMContentLoaded', searchDialogMessages)
        </script>
        
from b24pysdk.errors import BitrixAPIError, BitrixSDKException
        
        try:
            bitrix_response = client.im.dialog.messages.search(
                chat_id=3,
                search_message="test",
                order={
                    "ID": "DESC",
                },
                limit=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(
                    'im.dialog.messages.search',
                    [
                        'CHAT_ID' => 3,
                        'SEARCH_MESSAGE' => 'test',
                        'ORDER' => ['ID' => 'DESC'],
                        'LIMIT' => 20,
                    ]
                );
        
            $result = $response
                ->getResponseData()
                ->getResult();
        
            echo 'Success: ' . print_r($result, true);
        } catch (Throwable $e) {
            error_log($e->getMessage());
            echo 'Error: ' . $e->getMessage();
        }
        
BX24.callMethod(
            'im.dialog.messages.search',
            {
                CHAT_ID: 3,
                SEARCH_MESSAGE: 'test',
                ORDER: { ID: 'DESC' },
                LIMIT: 20
            },
            function(result)
            {
                if (result.error())
                {
                    console.error(result.error());
                }
                else
                {
                    console.log(result.data());
                }
            }
        );
        
require_once('crest.php');
        
        $result = CRest::call(
            'im.dialog.messages.search',
            [
                'CHAT_ID' => 3,
                'SEARCH_MESSAGE' => 'test',
                'ORDER' => ['ID' => 'DESC'],
                'LIMIT' => 20,
            ]
        );
        
        echo '<PRE>';
        print_r($result);
        echo '</PRE>';
        
// client and ctx are already created — see the Go SDK section
        res, err := client.Core().Call(ctx, "im.dialog.messages.search", b24.Params{
        	"CHAT_ID":        3,
        	"SEARCH_MESSAGE": "test",
        	"ORDER": b24.Params{
        		"ID": "DESC",
        	},
        	"LIMIT": 20,
        })
        if err != nil {
        	return fmt.Errorf("im.dialog.messages.search: %w", err)
        }
        
        // The response shape is shown below on this page.
        fmt.Printf("%s\n", res.Result)
        

Response Handling

HTTP status: 200

{
            "result": {
                "users": [
                    {
                        "id": 1,
                        "active": true,
                        "name": "Alex",
                        "firstName": "Alex",
                        "lastName": "",
                        "workPosition": "",
                        "color": "#df532d",
                        "avatar": "https://cdn-com.bitrix24.com/path/avatar.jpg",
                        "avatarHr": "https://cdn-com.bitrix24.com/path/avatar.jpg",
                        "gender": "F",
                        "birthday": "",
                        "extranet": false,
                        "network": false,
                        "bot": false,
                        "connector": false,
                        "externalAuthId": "socservices",
                        "status": "online",
                        "idle": false,
                        "lastActivityDate": "2026-02-13T14:27:33+01:00",
                        "mobileLastDate": false,
                        "desktopLastDate": false,
                        "absent": false,
                        "departments": [1, 107, 47, 3],
                        "phones": {
                            "personal_mobile": "19998887766",
                            "inner_phone": "111"
                        },
                        "botData": null,
                        "type": "user",
                        "website": "",
                        "email": "user@example.com"
                    }
                ],
                "files": [],
                "additionalMessages": [],
                "copilot": null,
                "stickers": [],
                "reactions": [],
                "tariffRestrictions": {
                    "isHistoryLimitExceeded": false
                },
                "usersShort": [],
                "messages": [
                    {
                        "id": 33653,
                        "chatId": 2421,
                        "chat_id": 2421,
                        "authorId": 1,
                        "author_id": 1,
                        "date": "2026-02-13T14:28:00+01:00",
                        "text": "test message",
                        "isSystem": false,
                        "uuid": "18533186-232b-4423-8438-64501da182f5",
                        "forward": null,
                        "params": [],
                        "viewedByOthers": false,
                        "block": null,
                        "unread": false,
                        "viewed": true,
                        "viewedCount": 0
                    }
                ]
            },
            "time": {
                "start": 1770982150,
                "finish": 1770982150.503861,
                "duration": 0.5038609504699707,
                "processing": 0,
                "date_start": "2026-02-13T14:29:10+01:00",
                "date_finish": "2026-02-13T14:29:10+01:00",
                "operating_reset_at": 1770982750,
                "operating": 0
            }
        }
        

Returned Data

Name
type

Description

result
object

Root element of the response

result.messages
array

Array of found messages (detailed description)

result.users
array

Users associated with the found messages (detailed description)

result.files
array

Files from the found messages

result.additionalMessages
array

Additional messages related to the found ones, such as forwarded or quoted (detailed description)

result.copilot
object

BitrixGPT data, if present in the response. Can be null

result.stickers
array

Stickers associated with the found messages

result.reactions
array

Reactions to the found messages (detailed description)

result.tariffRestrictions
object

Information about tariff restrictions on history.

Contains the flag isHistoryLimitExceeded — an indication of exceeding the message history limit by the plan

result.usersShort
array

Brief information about users who reacted.

Used as a supplementary reference to result.reactions.reactionUsers, contains id, name, avatar

time
time

Information about the request execution time

Message

Name
type

Description

id
integer

Identifier of the message

chatId
integer

Identifier of the chat

chat_id
integer

Identifier of the chat. A duplicate of the chatId field in the old spelling

authorId
integer

Identifier of the message author

author_id
integer

Identifier of the message author. A duplicate of the authorId field in the old spelling

date
datetime

Date and time of message creation

text
string

Text of the message

isSystem
boolean

Indicator of a system message

uuid
string

External UUID of the message. Can be null

forward
object

Information about forwarding. Can be null

params
array

Message parameters

viewedByOthers
boolean

Indicator that the message has been viewed by other participants

unread
boolean

Indicator of an unread message for the current user

viewed
boolean

Indicator that the message has been viewed by the current user

viewedCount
integer

Number of participants who have viewed the message

block
object

Service data of the message block. Can be null

User

Name
type

Description

id
integer

Identifier of the user

active
boolean

User is active

name
string

Full name

firstName
string

First name

lastName
string

Last name

workPosition
string

Position

color
string

Profile color in hex format

avatar
string

Avatar URL

avatarHr
string

High-resolution avatar URL

gender
string

Gender

birthday
string

Birthday

extranet
boolean

Indicator of an extranet user

network
boolean

Indicator of a Bitrix24 Network user

bot
boolean

Indicator of a bot

connector
boolean

Indicator of a connector user

externalAuthId
string

External authorization code

status
string

User status

idle
boolean

Indicator of inactivity

lastActivityDate
datetime

Date and time of last activity

mobileLastDate
datetime

Last activity in the mobile app. Can be false

desktopLastDate
datetime

Last activity in the desktop app. Can be false

absent
boolean

Indicator of absence

departments
array

Array of department identifiers

phones
object

User's phones

botData
object

Additional bot data. For a regular user null

type
string

User type

website
string

User's website

email
string

User's e-mail

Reactions

Name
type

Description

messageId
integer

Identifier of the message

reactionCounters
object

Count of reactions by each type

reactionUsers
object

Users by types of reactions

ownReactions
array

Reactions of the current user

Error Handling

HTTP status: 400, 403

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

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

CHAT_ID_EMPTY

CHAT_ID can't be empty

Required parameter CHAT_ID is not provided

ACCESS_ERROR

You do not have access to this chat

No access to the specified chat

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

REST API access is not active for this account. In Bitrix24 Cloud, check the current plan or trial status: Vibe+ plans include REST API access, while Essentials plans do not. 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