From 4332f97c3fd352ce4714d23a32acaeb4f828a23b Mon Sep 17 00:00:00 2001 From: aanshisingh-cometchat Date: Tue, 17 Feb 2026 17:34:26 +0530 Subject: [PATCH 01/43] refactor: improve sdk doc --- .../additional-message-filtering.mdx | 54 +++++++++++ sdk/javascript/advanced-overview.mdx | 40 ++++++++ sdk/javascript/ai-agents.mdx | 56 +++++++++++- sdk/javascript/ai-moderation.mdx | 49 +++++++++- sdk/javascript/all-real-time-listeners.mdx | 56 ++++++++++++ sdk/javascript/authentication-overview.mdx | 91 +++++++++++++++++++ sdk/javascript/block-users.mdx | 74 ++++++++++++++- sdk/javascript/call-logs.mdx | 44 +++++++++ sdk/javascript/calling-overview.mdx | 32 +++++++ sdk/javascript/calling-setup.mdx | 45 +++++++++ sdk/javascript/connection-status.mdx | 43 +++++++++ sdk/javascript/create-group.mdx | 85 ++++++++++++++++- sdk/javascript/custom-css.mdx | 38 ++++++++ sdk/javascript/default-call.mdx | 55 +++++++++++ sdk/javascript/delete-conversation.mdx | 42 +++++++++ sdk/javascript/delete-group.mdx | 55 ++++++++++- sdk/javascript/delete-message.mdx | 67 +++++++++++++- sdk/javascript/delivery-read-receipts.mdx | 59 ++++++++++++ sdk/javascript/direct-call.mdx | 55 +++++++++++ sdk/javascript/edit-message.mdx | 67 ++++++++++++++ sdk/javascript/flag-message.mdx | 40 ++++++++ sdk/javascript/group-add-members.mdx | 50 ++++++++++ sdk/javascript/group-change-member-scope.mdx | 47 ++++++++++ sdk/javascript/group-kick-ban-members.mdx | 50 ++++++++++ sdk/javascript/groups-overview.mdx | 34 +++++++ sdk/javascript/interactive-messages.mdx | 49 ++++++++++ sdk/javascript/join-group.mdx | 50 ++++++++++ sdk/javascript/key-concepts.mdx | 34 +++++++ sdk/javascript/leave-group.mdx | 47 ++++++++++ sdk/javascript/login-listener.mdx | 42 ++++++++- ...aging-web-sockets-connections-manually.mdx | 36 ++++++++ sdk/javascript/mentions.mdx | 44 +++++++++ .../message-structure-and-hierarchy.mdx | 30 ++++++ sdk/javascript/messaging-overview.mdx | 29 ++++++ sdk/javascript/overview.mdx | 45 +++++++++ sdk/javascript/presenter-mode.mdx | 45 +++++++++ sdk/javascript/rate-limits.mdx | 22 +++++ sdk/javascript/reactions.mdx | 44 +++++++++ sdk/javascript/receive-message.mdx | 48 ++++++++++ sdk/javascript/recording.mdx | 41 +++++++++ sdk/javascript/resources-overview.mdx | 21 +++++ sdk/javascript/retrieve-conversations.mdx | 37 ++++++++ sdk/javascript/retrieve-group-members.mdx | 35 +++++++ sdk/javascript/retrieve-groups.mdx | 37 ++++++++ sdk/javascript/retrieve-users.mdx | 36 ++++++++ sdk/javascript/send-message.mdx | 39 ++++++++ sdk/javascript/session-timeout.mdx | 23 +++++ sdk/javascript/setup-sdk.mdx | 43 +++++++++ sdk/javascript/standalone-calling.mdx | 38 ++++++++ sdk/javascript/threaded-messages.mdx | 41 +++++++++ sdk/javascript/transfer-group-ownership.mdx | 28 ++++++ sdk/javascript/transient-messages.mdx | 36 ++++++++ sdk/javascript/typing-indicators.mdx | 39 ++++++++ sdk/javascript/update-group.mdx | 26 ++++++ sdk/javascript/upgrading-from-v3.mdx | 24 ++++- sdk/javascript/user-management.mdx | 42 +++++++++ sdk/javascript/user-presence.mdx | 50 ++++++++++ sdk/javascript/users-overview.mdx | 22 +++++ sdk/javascript/video-view-customisation.mdx | 34 +++++++ sdk/javascript/virtual-background.mdx | 33 +++++++ 60 files changed, 2609 insertions(+), 9 deletions(-) diff --git a/sdk/javascript/additional-message-filtering.mdx b/sdk/javascript/additional-message-filtering.mdx index 6648ba35e..8b97c9307 100644 --- a/sdk/javascript/additional-message-filtering.mdx +++ b/sdk/javascript/additional-message-filtering.mdx @@ -1,8 +1,42 @@ --- title: "Additional Message Filtering" +description: "Advanced filtering options for fetching messages using MessagesRequestBuilder in the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Filter by category and type +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setUID("UID") + .setCategories(["message"]) + .setTypes(["image", "video", "audio", "file"]) + .setLimit(50) + .build(); + +// Unread messages only +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setUID("UID") + .setUnread(true) + .setLimit(50) + .build(); + +// Threaded messages +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setUID("UID") + .setParentMessageId(parentId) + .setLimit(50) + .build(); + +// Fetch with pagination +messagesRequest.fetchPrevious().then(messages => { }); +messagesRequest.fetchNext().then(messages => { }); +``` + +**Key methods:** `setUID()`, `setGUID()`, `setLimit()`, `setCategories()`, `setTypes()`, `setTags()`, `setUnread()`, `setParentMessageId()`, `setMessageId()`, `setTimestamp()`, `hideReplies()`, `hideDeletedMessages()` + The `MessagesRequest` class as you must be familiar with helps you to fetch messages based on the various parameters provided to it. This document will help you understand better the various options that are available using the `MessagesRequest` class. @@ -1474,3 +1508,23 @@ let GUID: string = "GUID", + + +--- + +## Next Steps + + + + Send text, media, and custom messages + + + Listen for incoming messages in real-time + + + Understand message categories, types, and hierarchy + + + Work with threaded conversations + + diff --git a/sdk/javascript/advanced-overview.mdx b/sdk/javascript/advanced-overview.mdx index 7a8e791f6..87376691e 100644 --- a/sdk/javascript/advanced-overview.mdx +++ b/sdk/javascript/advanced-overview.mdx @@ -1,8 +1,48 @@ --- title: "Advanced" sidebarTitle: "Overview" +description: "Advanced SDK features including connection management, real-time listeners, login listeners, and WebSocket configuration." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Check connection status +CometChat.getConnectionStatus(); // "connected" | "connecting" | "disconnected" + +// Listen for connection changes +CometChat.addConnectionListener("LISTENER_ID", new CometChat.ConnectionListener({ + onConnected: () => console.log("Connected"), + onDisconnected: () => console.log("Disconnected") +})); + +// Listen for login events +CometChat.addLoginListener("LISTENER_ID", new CometChat.LoginListener({ + onLoginSuccess: (user) => console.log("Logged in:", user), + onLogoutSuccess: () => console.log("Logged out") +})); +``` + This section helps you to know about the Connection Listeners. + +--- + +## Next Steps + + + + Monitor and respond to connection state changes + + + Manually manage WebSocket connections + + + Listen for login and logout events + + + Complete reference for all SDK listeners + + diff --git a/sdk/javascript/ai-agents.mdx b/sdk/javascript/ai-agents.mdx index f4b88d96a..2df8401c2 100644 --- a/sdk/javascript/ai-agents.mdx +++ b/sdk/javascript/ai-agents.mdx @@ -1,7 +1,37 @@ --- title: "AI Agents" +description: "Integrate AI Agents into your app to enable intelligent, automated conversations with real-time streaming events and tool invocations." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```javascript +// Listen for real-time AI Agent events (streaming) +CometChat.addAIAssistantListener("LISTENER_ID", { + onAIAssistantEventReceived: (event) => console.log("Event:", event) +}); + +// Listen for persisted agentic messages +CometChat.addMessageListener("LISTENER_ID", { + onAIAssistantMessageReceived: (msg) => console.log("Assistant reply:", msg), + onAIToolResultReceived: (msg) => console.log("Tool result:", msg), + onAIToolArgumentsReceived: (msg) => console.log("Tool args:", msg) +}); + +// Cleanup +CometChat.removeAIAssistantListener("LISTENER_ID"); +CometChat.removeMessageListener("LISTENER_ID"); +``` + +**Event flow:** Run Start → Tool Call(s) → Text Message Stream → Run Finished + + + +**Available via:** SDK | [UI Kits](/ui-kit/react/overview) | [Dashboard](https://app.cometchat.com) + + # AI Agents Overview AI Agents enable intelligent, automated interactions within your application. They can process user messages, trigger tools, and respond with contextually relevant information. For a broader introduction, see the [AI Agents section](/ai-agents). @@ -131,4 +161,28 @@ These events are received via the **`MessageListener`** after the run completes. CometChat.removeMessageListener(listnerId); ``` - \ No newline at end of file + + + + +Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + + +--- + +## Next Steps + + + + Set up AI-powered chatbots for automated conversations + + + Automatically moderate messages with AI + + + AI-powered features like smart replies and conversation summaries + + + Send text messages that trigger AI Agent responses + + diff --git a/sdk/javascript/ai-moderation.mdx b/sdk/javascript/ai-moderation.mdx index 768de5403..0bedaeab8 100644 --- a/sdk/javascript/ai-moderation.mdx +++ b/sdk/javascript/ai-moderation.mdx @@ -1,7 +1,36 @@ --- title: "AI Moderation" +description: "Automatically moderate chat messages using AI to detect and block inappropriate content in real-time." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```javascript +// Send message — check moderation status +CometChat.sendMessage(textMessage).then(message => { + const status = message.getModerationStatus(); + // CometChat.ModerationStatus.PENDING | APPROVED | DISAPPROVED +}); + +// Listen for moderation results +CometChat.addMessageListener("MOD_LISTENER", new CometChat.MessageListener({ + onMessageModerated: (message) => { + const status = message.getModerationStatus(); + // Handle APPROVED or DISAPPROVED + } +})); +``` + +**Supported types:** Text, Image, Video messages only +**Statuses:** `PENDING` → `APPROVED` or `DISAPPROVED` + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) | [Dashboard](https://app.cometchat.com) + + ## Overview AI Moderation in the CometChat SDK helps ensure that your chat application remains safe and compliant by automatically reviewing messages for inappropriate content. This feature leverages AI to moderate messages in real-time, reducing manual intervention and improving user experience. @@ -300,5 +329,23 @@ Here's a complete implementation showing the full moderation flow: + +Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + + ## Next Steps -After implementing AI Moderation, consider adding a reporting feature to allow users to flag messages they find inappropriate. For more details, see the [Flag Message](/sdk/javascript/flag-message) documentation. + + + + Allow users to report inappropriate messages manually + + + Build intelligent automated conversations with AI Agents + + + Smart replies, conversation summaries, and more + + + Send text, media, and custom messages + + diff --git a/sdk/javascript/all-real-time-listeners.mdx b/sdk/javascript/all-real-time-listeners.mdx index a70adfb54..f4293a5d6 100644 --- a/sdk/javascript/all-real-time-listeners.mdx +++ b/sdk/javascript/all-real-time-listeners.mdx @@ -1,8 +1,44 @@ --- title: "All Real Time Listeners" +description: "Complete reference for all CometChat real-time listeners including User, Group, Message, and Call listeners." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```javascript +// User Listener — online/offline presence +CometChat.addUserListener("ID", new CometChat.UserListener({ + onUserOnline: (user) => { }, + onUserOffline: (user) => { } +})); + +// Message Listener — messages, typing, receipts, reactions +CometChat.addMessageListener("ID", new CometChat.MessageListener({ + onTextMessageReceived: (msg) => { }, + onMediaMessageReceived: (msg) => { }, + onTypingStarted: (indicator) => { }, + onMessagesRead: (receipt) => { } +})); + +// Group Listener — member join/leave/kick/ban/scope changes +CometChat.addGroupListener("ID", new CometChat.GroupListener({ ... })); + +// Call Listener — incoming/outgoing call events +CometChat.addCallListener("ID", new CometChat.CallListener({ ... })); + +// Always clean up +CometChat.removeUserListener("ID"); +CometChat.removeMessageListener("ID"); +CometChat.removeGroupListener("ID"); +CometChat.removeCallListener("ID"); +``` + + +Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + CometChat provides 4 listeners viz. @@ -530,3 +566,23 @@ CometChat.removeCallListener(listenerID); + + +--- + +## Next Steps + + + + Handle incoming messages in real-time + + + Show when users are typing + + + Track online/offline status of users + + + Monitor SDK connection state changes + + diff --git a/sdk/javascript/authentication-overview.mdx b/sdk/javascript/authentication-overview.mdx index 1df057175..39fdb8c65 100644 --- a/sdk/javascript/authentication-overview.mdx +++ b/sdk/javascript/authentication-overview.mdx @@ -1,9 +1,30 @@ --- title: "Authentication" sidebarTitle: "Overview" +description: "Create users, log in with Auth Key or Auth Token, check login status, and log out using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Check existing session +const user = await CometChat.getLoggedinUser(); + +// Login with Auth Key (development only) +CometChat.login("UID", "AUTH_KEY").then(user => console.log("Logged in:", user)); + +// Login with Auth Token (production) +CometChat.login("AUTH_TOKEN").then(user => console.log("Logged in:", user)); + +// Logout +CometChat.logout().then(() => console.log("Logged out")); +``` + +**Create users via:** [Dashboard](https://app.cometchat.com) (testing) | [REST API](https://api-explorer.cometchat.com/reference/creates-user) (production) +**Test UIDs:** `cometchat-uid-1` through `cometchat-uid-5` + ## Create User @@ -32,6 +53,10 @@ The CometChat SDK maintains the session of the logged-in user within the SDK. Th This straightforward authentication method is ideal for proof-of-concept (POC) development or during the early stages of application development. For production environments, however, we strongly recommend using an [AuthToken](#login-using-auth-token) instead of an Auth Key to ensure enhanced security. + +**Auth Key** is for development/testing only. In production, generate **Auth Tokens** on your server using the REST API and pass them to the client. Never expose Auth Keys in production client code. + + ```js @@ -85,6 +110,24 @@ CometChat.getLoggedinUser().then( + +```javascript +var UID = "UID"; +var authKey = "AUTH_KEY"; + +try { + const loggedInUser = await CometChat.getLoggedinUser(); + if (!loggedInUser) { + const user = await CometChat.login(UID, authKey); + console.log("Login Successful:", { user }); + } +} catch (error) { + console.log("Login failed with exception:", { error }); +} +``` + + + | Parameters | Description | @@ -153,6 +196,23 @@ CometChat.getLoggedinUser().then( + +```javascript +var authToken = "AUTH_TOKEN"; + +try { + const loggedInUser = await CometChat.getLoggedinUser(); + if (!loggedInUser) { + const user = await CometChat.login(authToken); + console.log("Login Successful:", { user }); + } +} catch (error) { + console.log("Login failed with exception:", { error }); +} +``` + + + | Parameter | Description | @@ -194,4 +254,35 @@ CometChat.logout().then( + +```javascript +try { + await CometChat.logout(); + console.log("Logout completed successfully"); +} catch (error) { + console.log("Logout failed with exception:", { error }); +} +``` + + + + +--- + +## Next Steps + + + + Send your first text, media, or custom message + + + Install and initialize the CometChat SDK + + + Create, update, and delete users programmatically + + + Listen for login and logout events in real-time + + diff --git a/sdk/javascript/block-users.mdx b/sdk/javascript/block-users.mdx index 738e07ab1..ba7c72bca 100644 --- a/sdk/javascript/block-users.mdx +++ b/sdk/javascript/block-users.mdx @@ -1,8 +1,30 @@ --- title: "Block Users" +description: "Block and unblock users, and retrieve the list of blocked users using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Block users +await CometChat.blockUsers(["UID1", "UID2"]); + +// Unblock users +await CometChat.unblockUsers(["UID1", "UID2"]); + +// Get blocked users list +let request = new CometChat.BlockedUsersRequestBuilder().setLimit(30).build(); +let blockedUsers = await request.fetchNext(); +``` + +**Directions:** `BLOCKED_BY_ME` | `HAS_BLOCKED_ME` | `BOTH` (default) + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + ## Block Users @@ -11,7 +33,7 @@ title: "Block Users" You can block users using the `blockUsers()` method. Once any user is blocked, all the communication to and from the respective user will be completely blocked. You can block multiple users in a single operation. The `blockUsers()` method takes a `Array` as a parameter which holds the list of `UID's` to be blocked. - + ```javascript var usersList = ["UID1", "UID2", "UID3"]; @@ -41,6 +63,20 @@ CometChat.blockUsers(usersList).then( + +```javascript +var usersList = ["UID1", "UID2", "UID3"]; + +try { + const list = await CometChat.blockUsers(usersList); + console.log("users list blocked", { list }); +} catch (error) { + console.log("Blocking user fails with error", error); +} +``` + + + It returns a Array which contains `UID's` as the keys and "success" or "fail" as the value based on if the block operation for the `UID` was successful or not. @@ -52,7 +88,7 @@ It returns a Array which contains `UID's` as the keys and "success" or "fail" as You can unblock the already blocked users using the `unblockUsers()` method. You can unblock multiple users in a single operation. The `unblockUsers()` method takes a `Array` as a parameter which holds the list of `UID's` to be unblocked. - + ```javascript var usersList = ["UID1", "UID2", "UID3"]; @@ -82,6 +118,20 @@ CometChat.unblockUsers(usersList).then( + +```javascript +var usersList = ["UID1", "UID2", "UID3"]; + +try { + const list = await CometChat.unblockUsers(usersList); + console.log("users list unblocked", { list }); +} catch (error) { + console.log("unblocking user fails with error", error); +} +``` + + + It returns a Array which contains `UID's` as the keys and `success` or `fail` as the value based on if the unblock operation for the `UID` was successful or not. @@ -224,3 +274,23 @@ blockedUsersRequest.fetchNext().then( + + +--- + +## Next Steps + + + + Fetch and filter user lists + + + Track online/offline status of users + + + Create, update, and delete users + + + Report inappropriate messages from users + + diff --git a/sdk/javascript/call-logs.mdx b/sdk/javascript/call-logs.mdx index 74f2b87af..9a46620f0 100644 --- a/sdk/javascript/call-logs.mdx +++ b/sdk/javascript/call-logs.mdx @@ -1,8 +1,32 @@ --- title: "Call Logs" +description: "Fetch, filter, and retrieve call history including duration, participants, and recording status using the CometChat Calls SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Fetch call logs +let request = new CometChatCalls.CallLogRequestBuilder() + .setLimit(30) + .setAuthToken(loggedInUser.getAuthToken()) + .setCallCategory("call") + .build(); + +let logs = await request.fetchNext(); + +// Get details for a specific call session +let details = await CometChatCalls.getCallDetails("SESSION_ID", authToken); +``` + +**Filters:** `setCallType()`, `setCallStatus()`, `setCallCategory()`, `setCallDirection()`, `setHasRecording()`, `setUid()`, `setGuid()` + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [Dashboard](https://app.cometchat.com) + ## Overview @@ -94,3 +118,23 @@ CometChatCalls.getCallDetails(sessionID, authToken) ``` Note: Replace**`"SESSION_ID"`**with the ID of the session you are interested in. + + +--- + +## Next Steps + + + + Implement the complete ringing call flow + + + Record audio and video calls + + + Start call sessions without the ringing flow + + + Install and initialize the Calls SDK + + diff --git a/sdk/javascript/calling-overview.mdx b/sdk/javascript/calling-overview.mdx index 18bc0ea62..863414550 100644 --- a/sdk/javascript/calling-overview.mdx +++ b/sdk/javascript/calling-overview.mdx @@ -1,8 +1,26 @@ --- title: "Calling" sidebarTitle: "Overview" +description: "Overview of CometChat voice and video calling capabilities including ringing, direct call sessions, and standalone calling." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +Choose your calling approach: +- **Ringing** → [Default Call](/sdk/javascript/default-call) — Full call flow with notifications, accept/reject +- **Call Session** → [Direct Call](/sdk/javascript/direct-call) — Session-based calling with custom UI +- **Standalone** → [Standalone Calling](/sdk/javascript/standalone-calling) — Calls SDK only, no Chat SDK needed + +```bash +# Install Calls SDK +npm install @cometchat/calls-sdk-javascript +``` + +**Features:** Recording, Virtual Background, Screen Sharing, Custom CSS, Call Logs, Session Timeout + + ## Overview CometChat provides voice and video calling capabilities for your web application. This guide helps you choose the right implementation approach based on your use case. @@ -96,3 +114,17 @@ Use this when you want: Configure automatic call termination when participants are inactive. + + +--- + +## Next Steps + + + + Install and initialize the Calls SDK + + + Implement the complete ringing call flow + + diff --git a/sdk/javascript/calling-setup.mdx b/sdk/javascript/calling-setup.mdx index 7cd07247e..0c61d682d 100644 --- a/sdk/javascript/calling-setup.mdx +++ b/sdk/javascript/calling-setup.mdx @@ -1,8 +1,33 @@ --- title: "Setup" +description: "Install and initialize the CometChat Calls SDK for JavaScript to enable voice and video calling in your application." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Setup Reference** +```bash +npm install @cometchat/calls-sdk-javascript +``` + +```javascript +import { CometChatCalls } from "@cometchat/calls-sdk-javascript"; + +const callAppSetting = new CometChatCalls.CallAppSettingsBuilder() + .setAppId("APP_ID") + .setRegion("REGION") + .build(); + +CometChatCalls.init(callAppSetting).then(() => console.log("Calls SDK ready")); +``` + +**Required:** App ID, Region from [CometChat Dashboard](https://app.cometchat.com) + + + +`CometChatCalls.init()` must be called before any other Calls SDK method. Make sure the Chat SDK is also initialized via `CometChat.init()` first (unless using [Standalone Calling](/sdk/javascript/standalone-calling)). + ## Get your Application Keys @@ -115,3 +140,23 @@ Make sure you replace the `APP_ID` with your CometChat **App ID** and `REGION` w | Parameter | Description | | ----------------- | ---------------------------------------- | | `callAppSettings` | An object of the `CallAppSettings` class | + + +--- + +## Next Steps + + + + Implement the complete ringing call flow + + + Start call sessions without the ringing flow + + + Use Calls SDK without the Chat SDK + + + Compare calling approaches and features + + diff --git a/sdk/javascript/connection-status.mdx b/sdk/javascript/connection-status.mdx index 7c67128bb..85070d9ff 100644 --- a/sdk/javascript/connection-status.mdx +++ b/sdk/javascript/connection-status.mdx @@ -1,8 +1,27 @@ --- title: "Connection Status" +description: "Monitor real-time WebSocket connection status and respond to connectivity changes using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Get current status: "connecting" | "connected" | "disconnected" +var status = CometChat.getConnectionStatus(); + +// Listen for connection changes +CometChat.addConnectionListener("LISTENER_ID", new CometChat.ConnectionListener({ + onConnected: () => console.log("Connected"), + inConnecting: () => console.log("Connecting..."), + onDisconnected: () => console.log("Disconnected") +})); + +// Cleanup +CometChat.removeConnectionListener("LISTENER_ID"); +``` + CometChat SDK provides you with a mechanism to get real-time status of the connection to CometChat web-socket servers. @@ -93,3 +112,27 @@ The `CometChat.getConnectionStatus` method will return either of the below 3 val 1. connecting 2. connected 3. disconnected + + + +Always remove connection listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + + +--- + +## Next Steps + + + + Manually manage WebSocket connections + + + Listen for login and logout events + + + Complete reference for all SDK listeners + + + Install and initialize the CometChat SDK + + diff --git a/sdk/javascript/create-group.mdx b/sdk/javascript/create-group.mdx index 29eed3de5..057256d0d 100644 --- a/sdk/javascript/create-group.mdx +++ b/sdk/javascript/create-group.mdx @@ -1,8 +1,29 @@ --- title: "Create A Group" +description: "Create public, private, or password-protected groups and optionally add members during creation using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Create a group +let group = new CometChat.Group("GUID", "Group Name", CometChat.GROUP_TYPE.PUBLIC, ""); +let createdGroup = await CometChat.createGroup(group); + +// Create group with members +let members = [new CometChat.GroupMember("UID", CometChat.GROUP_MEMBER_SCOPE.PARTICIPANT)]; +let result = await CometChat.createGroupWithMembers(group, members, []); +``` + +**Group types:** `PUBLIC` | `PASSWORD` | `PRIVATE` +**Member scopes:** `ADMIN` | `MODERATOR` | `PARTICIPANT` + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + ## Create a Group @@ -24,7 +45,7 @@ The `groupType` needs to be either of the below 3 values: 3.`CometChat.GROUP_TYPE.PRIVATE` - + ```javascript var GUID = "GUID"; var groupName = "Hello Group!"; @@ -64,6 +85,25 @@ CometChat.createGroup(group).then( + +```javascript +var GUID = "GUID"; +var groupName = "Hello Group!"; +var groupType = CometChat.GROUP_TYPE.PUBLIC; +var password = ""; + +var group = new CometChat.Group(GUID, groupName, groupType, password); + +try { + const createdGroup = await CometChat.createGroup(group); + console.log("Group created successfully:", createdGroup); +} catch (error) { + console.log("Group creation failed with exception:", error); +} +``` + + + The createGroup() method takes the following parameters: @@ -148,6 +188,29 @@ CometChat.createGroupWithMembers(group, members, banMembers).then( + +```javascript +let GUID = "cometchat-guid-11"; +let UID = "cometchat-uid-1"; +let groupName = "Hello Group!"; +let groupType = CometChat.GROUP_TYPE.PUBLIC; + +let group = new CometChat.Group(GUID, groupName, groupType); +let members = [ + new CometChat.GroupMember(UID, CometChat.GROUP_MEMBER_SCOPE.PARTICIPANT) +]; +let banMembers = ["cometchat-uid-2"]; + +try { + const response = await CometChat.createGroupWithMembers(group, members, banMembers); + console.log("Group created successfully", response); +} catch (error) { + console.log("Some error occured while creating group", error); +} +``` + + + This method returns an Object which has two keys: `group` & `members` . The group key has the Group Object which contains all the information of the group which is created. The members key has the `UID` of the users and the value will either be `success` or an `error` message describing why the operation to add/ban the user failed. @@ -171,3 +234,23 @@ This method returns an Object which has two keys: `group` & `members` . The grou | scope | Yes | Scope of the logged in user. Can be: 1. Admin 2. Moderator 3. Participant | | membersCount | No | The number of members in the groups | | tags | Yes | A list of tags to identify specific groups. | + + +--- + +## Next Steps + + + + Join public, private, or password-protected groups + + + Add users to an existing group + + + Fetch and filter group lists + + + Overview of all group management features + + diff --git a/sdk/javascript/custom-css.mdx b/sdk/javascript/custom-css.mdx index 56698ccf3..99bd9f5ff 100644 --- a/sdk/javascript/custom-css.mdx +++ b/sdk/javascript/custom-css.mdx @@ -1,8 +1,26 @@ --- title: "Custom CSS" +description: "Customize the CometChat calling UI with custom CSS classes for buttons, video containers, name labels, and grid layouts." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```css +/* Key CSS classes for call UI customization */ +.cc-main-container { } /* Outermost call container */ +.cc-bottom-buttons-container { } /* Bottom action buttons bar */ +.cc-name-label { } /* User name text */ +.cc-video-container { } /* Video feed container */ +.cc-end-call-icon-container { } /* End call button */ +.cc-audio-icon-container { } /* Audio toggle button */ +.cc-video-icon-container { } /* Video toggle button */ +.cc-screen-share-icon-container { } /* Screen share button */ +``` + +**Modes:** `DEFAULT` | `TILE` | `SPOTLIGHT` + Passing custom CSS allows you to personalize and enhance the user interface of the call screen. @@ -170,3 +188,23 @@ The above example results in the below output:- * Avoid resizing the grid container. Altering the grid container’s dimensions can negatively impact the grid layout, leading to undesirable visual distortions. By following these recommendations, you can maintain a stable and visually consistent grid layout. + + +--- + +## Next Steps + + + + Customize video call layout and participant tiles + + + Apply blur or custom image backgrounds during calls + + + Enable screen sharing and presentation mode + + + Overview of all calling features and approaches + + diff --git a/sdk/javascript/default-call.mdx b/sdk/javascript/default-call.mdx index 180de4d73..2705fe7b4 100644 --- a/sdk/javascript/default-call.mdx +++ b/sdk/javascript/default-call.mdx @@ -1,7 +1,38 @@ --- title: "Ringing" +description: "Implement a complete calling workflow with ringing, incoming/outgoing call UI, accept/reject/cancel functionality, and call session management." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```javascript +// Initiate a call +const call = new CometChat.Call("UID", CometChat.CALL_TYPE.VIDEO, CometChat.RECEIVER_TYPE.USER); +await CometChat.initiateCall(call); + +// Listen for call events +CometChat.addCallListener("ID", new CometChat.CallListener({ + onIncomingCallReceived: (call) => { /* show incoming UI */ }, + onOutgoingCallAccepted: (call) => { /* start session */ }, + onOutgoingCallRejected: (call) => { /* dismiss UI */ }, + onIncomingCallCancelled: (call) => { /* dismiss UI */ } +})); + +// Accept / Reject / Cancel +await CometChat.acceptCall(sessionId); +await CometChat.rejectCall(sessionId, CometChat.CALL_STATUS.REJECTED); +await CometChat.rejectCall(sessionId, CometChat.CALL_STATUS.CANCELLED); +``` + +**Flow:** Initiate → Receiver notified → Accept/Reject → Start session + + + +**Available via:** SDK | [UI Kits](/ui-kit/react/overview) + + ## Overview This section explains how to implement a complete calling workflow with ringing functionality, including incoming/outgoing call UI, call acceptance, rejection, and cancellation. Previously known as **Default Calling**. @@ -518,3 +549,27 @@ CometChat.rejectCall(sessionId, status).then( ``` + + + +Always remove call listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + + +--- + +## Next Steps + + + + Manage call sessions, tokens, and settings + + + Retrieve and display call history + + + Record audio and video calls + + + Install and initialize the Calls SDK + + diff --git a/sdk/javascript/delete-conversation.mdx b/sdk/javascript/delete-conversation.mdx index b91669f6a..045d2f33e 100644 --- a/sdk/javascript/delete-conversation.mdx +++ b/sdk/javascript/delete-conversation.mdx @@ -1,8 +1,30 @@ --- title: "Delete A Conversation" +description: "Delete user or group conversations for the logged-in user using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Delete user conversation +await CometChat.deleteConversation("UID", "user"); + +// Delete group conversation +await CometChat.deleteConversation("GUID", "group"); +``` + +**Note:** Deletes only for the logged-in user. Use [REST API](https://api-explorer.cometchat.com/reference/resets-user-conversation) to delete for all participants. + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + + +This operation is irreversible. Deleted conversations cannot be recovered for the logged-in user. + In case you want to delete a conversation, you can use the `deleteConversation()` method. @@ -79,3 +101,23 @@ The `deleteConversation()` method takes the following parameters: | ---------------- | --------------------------------------------------------------------------------- | -------- | | conversationWith | `UID` of the user or `GUID` of the group whose conversation you want to delete. | YES | | conversationType | The type of conversation you want to delete . It can be either `user` or `group`. | YES | + + +--- + +## Next Steps + + + + Fetch and filter conversation lists + + + Delete individual messages from conversations + + + Show when users are typing in conversations + + + Track message delivery and read status + + diff --git a/sdk/javascript/delete-group.mdx b/sdk/javascript/delete-group.mdx index 54bcf4137..1e79e443d 100644 --- a/sdk/javascript/delete-group.mdx +++ b/sdk/javascript/delete-group.mdx @@ -1,15 +1,34 @@ --- title: "Delete A Group" +description: "Delete a group permanently using the CometChat JavaScript SDK. Only group admins can perform this operation." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Delete a group (admin only) +await CometChat.deleteGroup("GUID"); +``` + +**Requirement:** Logged-in user must be an Admin of the group. + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + + +This operation is irreversible. Deleted groups and their messages cannot be recovered. + ## Delete a Group To delete a group you need to use the `deleteGroup()` method. The user must be an `Admin` of the group they are trying to delete. - + ```javascript var GUID = "GUID"; @@ -39,6 +58,20 @@ CometChat.deleteGroup(GUID).then( + +```javascript +var GUID = "GUID"; + +try { + const response = await CometChat.deleteGroup(GUID); + console.log("Group deleted successfully:", response); +} catch (error) { + console.log("Group delete failed with exception:", error); +} +``` + + + The `deleteGroup()` method takes the following parameters: @@ -46,3 +79,23 @@ The `deleteGroup()` method takes the following parameters: | Parameter | Description | | --------- | ---------------------------------------------- | | `GUID` | The GUID of the group you would like to delete | + + +--- + +## Next Steps + + + + Update group name, icon, description, and metadata + + + Leave a group you are a member of + + + Create public, private, or password-protected groups + + + Overview of all group management features + + diff --git a/sdk/javascript/delete-message.mdx b/sdk/javascript/delete-message.mdx index d84b07614..400c3916e 100644 --- a/sdk/javascript/delete-message.mdx +++ b/sdk/javascript/delete-message.mdx @@ -1,8 +1,35 @@ --- title: "Delete A Message" +description: "Delete messages, receive real-time deletion events, and handle missed deletion events using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Delete a message +await CometChat.deleteMessage(messageId); + +// Listen for real-time deletions +CometChat.addMessageListener("ID", new CometChat.MessageListener({ + onMessageDeleted: (message) => { + console.log("Deleted:", message.getId(), message.getDeletedAt()); + } +})); +``` + +**Who can delete:** Message sender, Group admin, Group moderator +**Deleted fields:** `deletedAt` (timestamp), `deletedBy` (user who deleted) + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + + +This operation is irreversible. Deleted messages cannot be recovered. + While [deleting a message](/sdk/javascript/delete-message#delete-a-message) is straightforward, receiving events for deleted messages with CometChat has two parts: @@ -16,7 +43,7 @@ While [deleting a message](/sdk/javascript/delete-message#delete-a-message) is s In case you have to delete a message, you can use the `deleteMessage()` method. This method takes the message ID of the message to be deleted. - + ```javascript let messageId = "ID_OF_THE_MESSAGE_YOU_WANT_TO_DELETE"; @@ -46,6 +73,20 @@ CometChat.deleteMessage(messageId).then( + +```javascript +let messageId = "ID_OF_THE_MESSAGE_YOU_WANT_TO_DELETE"; + +try { + const message = await CometChat.deleteMessage(messageId); + console.log("Message deleted", message); +} catch (error) { + console.log("Message delete failed with error:", error); +} +``` + + + Once the message is deleted, In the `onSuccess()` callback, you get an object of the `BaseMessage` class, with the `deletedAt` field set with the timestamp of the time the message was deleted. Also, the `deletedBy` field is set. These two fields can be used to identify if the message is deleted while iterating through a list of messages. @@ -118,3 +159,27 @@ For the message deleted event, in the `Action` object received, the following fi In order to edit or delete a message you need to be either the sender of the message or the admin/moderator of the group in which the message was sent. + + + +Always remove message listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + + +--- + +## Next Steps + + + + Edit sent messages in conversations + + + Send text, media, and custom messages + + + Listen for incoming messages in real-time + + + Report inappropriate messages + + diff --git a/sdk/javascript/delivery-read-receipts.mdx b/sdk/javascript/delivery-read-receipts.mdx index 464e319fd..779976167 100644 --- a/sdk/javascript/delivery-read-receipts.mdx +++ b/sdk/javascript/delivery-read-receipts.mdx @@ -1,8 +1,40 @@ --- title: "Delivery & Read Receipts" +description: "Learn how to mark messages as delivered, read, or unread and receive real-time receipt events using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```javascript +// Mark message as delivered (pass message object) +await CometChat.markAsDelivered(message); + +// Mark message as read (pass message object) +await CometChat.markAsRead(message); + +// Mark entire conversation as read +await CometChat.markConversationAsRead("USER_UID", "user"); +// Mark message as unread +await CometChat.markMessageAsUnread(message); + +// Listen for receipt events +CometChat.addMessageListener("receipts", new CometChat.MessageListener({ + onMessagesDelivered: (receipt) => { }, + onMessagesRead: (receipt) => { }, + onMessagesDeliveredToAll: (receipt) => { }, // Group only + onMessagesReadByAll: (receipt) => { } // Group only +})); +``` + + +Delivery and read receipts let you track whether messages have been delivered to and read by recipients. This page covers marking messages as delivered, read, or unread, and receiving real-time receipt events. + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + ## Mark Messages as Delivered @@ -791,3 +823,30 @@ The following features will be available only if the **Enhanced Messaging Status * `markMessageAsUnread` method. + + +Always remove message listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + +```javascript +CometChat.removeMessageListener("UNIQUE_LISTENER_ID"); +``` + + +--- + +## Next Steps + + + + Show real-time typing status to users in conversations + + + Listen for incoming messages in real time + + + Fetch conversation list with unread counts + + + Complete reference for all SDK event listeners + + diff --git a/sdk/javascript/direct-call.mdx b/sdk/javascript/direct-call.mdx index 0bedb0234..c7e5c3f46 100644 --- a/sdk/javascript/direct-call.mdx +++ b/sdk/javascript/direct-call.mdx @@ -1,13 +1,41 @@ --- title: "Call Session" +description: "Learn how to generate call tokens, start and manage call sessions, configure call settings, and handle call events using the CometChat JavaScript Calls SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```javascript +// Generate call token +const callToken = await CometChatCalls.generateToken(sessionId, authToken); + +// Build call settings +const callSettings = new CometChatCalls.CallSettingsBuilder() + .enableDefaultLayout(true) + .setIsAudioOnlyCall(false) + .setCallListener(callListener) + .build(); + +// Start call session +CometChatCalls.startSession(callToken.token, callSettings, htmlElement); + +// End call session +CometChatCalls.endSession(); +``` + + ## Overview This section demonstrates how to start a call session in a web application. Previously known as **Direct Calling**. Before you begin, we strongly recommend you read the [calling setup guide](/sdk/javascript/calling-setup). + +**Available via:** SDK | [UI Kits](/ui-kit/react/overview) + + If you want to implement a complete calling experience with ringing functionality (incoming/outgoing call UI), follow the [Ringing](/sdk/javascript/default-call) guide first. Once the call is accepted, return here to start the call session. @@ -706,3 +734,30 @@ CometChatCalls.endSession(); ``` + + +Always remove call event listeners when they're no longer needed (e.g., on component unmount or when the call screen is closed). Failing to remove listeners can cause memory leaks and duplicate event handling. + +```javascript +CometChatCalls.removeCallEventListener("UNIQUE_LISTENER_ID"); +``` + + +--- + +## Next Steps + + + + Implement calls with incoming/outgoing ringing UI + + + Record call sessions for playback + + + Customize the video layout and main video container + + + Retrieve and display call history + + diff --git a/sdk/javascript/edit-message.mdx b/sdk/javascript/edit-message.mdx index 8b91b4aea..6949d2812 100644 --- a/sdk/javascript/edit-message.mdx +++ b/sdk/javascript/edit-message.mdx @@ -1,14 +1,34 @@ --- title: "Edit A Message" +description: "Learn how to edit text and custom messages, receive real-time edit events, and handle missed edit events using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Edit a text message +const textMessage = new CometChat.TextMessage(receiverID, "Updated text", receiverType); +textMessage.setId(messageId); +await CometChat.editMessage(textMessage); + +// Listen for real-time edits +CometChat.addMessageListener("edits", new CometChat.MessageListener({ + onMessageEdited: (message) => console.log("Edited:", message) +})); +``` + While [editing a message](/sdk/javascript/edit-message#edit-a-message) is straightforward, receiving events for edited messages with CometChat has two parts: 1. Adding a listener to receive [real-time message edits](/sdk/javascript/edit-message#real-time-message-edit-events) when your app is running 2. Calling a method to retrieve [missed message edits](/sdk/javascript/edit-message#missed-message-edit-events) when your app was not running + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + ## Edit a Message *In other words, as a sender, how do I edit a message?* @@ -103,6 +123,26 @@ CometChat.editMessage(textMessage).then( + +```javascript +try { + let receiverID = "RECEIVER_UID"; + let messageText = "Hello world!"; + let receiverType = CometChat.RECEIVER_TYPE.USER; + let messageId = "MESSAGE_ID_OF_THE_MESSAGE_TO_BE_EDITED"; + let textMessage = new CometChat.TextMessage(receiverID, messageText, receiverType); + + textMessage.setId(messageId); + + const message = await CometChat.editMessage(textMessage); + console.log("Message Edited", message); +} catch (error) { + console.log("Message editing failed with error:", error); +} +``` + + + The object of the edited message will be returned in the `onSuccess()` callback method of the listener. The message object will contain the `editedAt` field set with the timestamp of the time the message was edited. This will help you identify if the message was edited while iterating through the list of messages. The `editedBy` field is also set to the UID of the user who edited the message. @@ -157,6 +197,14 @@ new CometChat.MessageListener({ + +Always remove message listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + +```javascript +CometChat.removeMessageListener("UNIQUE_LISTENER_ID"); +``` + + ## Missed Message Edit Events *In other words, as a recipient, how do I know when someone edited their message when my app was not running?* @@ -175,3 +223,22 @@ For the message edited event, in the `Action` object received, the following fie In order to edit a message, you need to be either the sender of the message or the admin/moderator of the group in which the message was sent. + +--- + +## Next Steps + + + + Remove messages from conversations + + + Send text, media, and custom messages + + + Organize conversations with message threads + + + Listen for incoming messages in real time + + diff --git a/sdk/javascript/flag-message.mdx b/sdk/javascript/flag-message.mdx index 350149f5d..486ed70fc 100644 --- a/sdk/javascript/flag-message.mdx +++ b/sdk/javascript/flag-message.mdx @@ -1,11 +1,32 @@ --- title: "Flag Message" +description: "Learn how to flag inappropriate messages for moderation review using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```javascript +// Get available flag reasons +const reasons = await CometChat.getFlagReasons(); + +// Flag a message +await CometChat.flagMessage("MESSAGE_ID", { + reasonId: "spam", + remark: "Promotional content" +}); +``` + + ## Overview Flagging messages allows users to report inappropriate content to moderators or administrators. When a message is flagged, it appears in the [CometChat Dashboard](https://app.cometchat.com) under **Moderation > Flagged Messages** for review. + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | Dashboard + + For a complete understanding of how flagged messages are reviewed and managed, see the [Flagged Messages](/moderation/flagged-messages) documentation. @@ -218,3 +239,22 @@ if (result.success) { showToast("Message reported successfully"); } ``` + +--- + +## Next Steps + + + + Automate content moderation with AI + + + Remove messages from conversations + + + Listen for incoming messages in real time + + + Send text, media, and custom messages + + diff --git a/sdk/javascript/group-add-members.mdx b/sdk/javascript/group-add-members.mdx index 98170bf0b..9b12c24c3 100644 --- a/sdk/javascript/group-add-members.mdx +++ b/sdk/javascript/group-add-members.mdx @@ -1,8 +1,31 @@ --- title: "Add Members To A Group" +description: "Learn how to add members to a group, receive real-time member added events, and handle missed events using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Add members to a group +const members = [ + new CometChat.GroupMember("UID", CometChat.GROUP_MEMBER_SCOPE.PARTICIPANT) +]; +await CometChat.addMembersToGroup("GUID", members, []); + +// Listen for member added events +CometChat.addGroupListener("listener", new CometChat.GroupListener({ + onMemberAddedToGroup: (message, userAdded, userAddedBy, userAddedIn) => { } +})); +``` + + +You can add members to a group programmatically and listen for real-time events when members are added. + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + ## Add Members to Group @@ -121,6 +144,14 @@ CometChat.addGroupListener( + +Always remove group listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + +```javascript +CometChat.removeGroupListener("UNIQUE_LISTENER_ID"); +``` + + ## Member Added to Group event in Message History *In other words, as a member of a group, how do I know when someone is added to the group when my app is not running?* @@ -133,3 +164,22 @@ For the group member added event, in the `Action` object received, the following 2. `actionOn` - User object containing the details of the user who was added to the group 3. `actionBy` - User object containing the details of the user who added the member to the group 4. `actionFor` - Group object containing the details of the group to which the member was added + +--- + +## Next Steps + + + + Remove or ban members from a group + + + Promote or demote group members + + + Fetch the list of members in a group + + + Allow users to join public or password-protected groups + + diff --git a/sdk/javascript/group-change-member-scope.mdx b/sdk/javascript/group-change-member-scope.mdx index 422ae34b8..f3aac9a4b 100644 --- a/sdk/javascript/group-change-member-scope.mdx +++ b/sdk/javascript/group-change-member-scope.mdx @@ -1,8 +1,28 @@ --- title: "Change Member Scope" +description: "Learn how to change group member roles (admin, moderator, participant) and receive real-time scope change events using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Change member scope to admin +await CometChat.updateGroupMemberScope("GUID", "UID", CometChat.GROUP_MEMBER_SCOPE.ADMIN); + +// Listen for scope change events +CometChat.addGroupListener("listener", new CometChat.GroupListener({ + onGroupMemberScopeChanged: (message, changedUser, newScope, oldScope, changedGroup) => { } +})); +``` + + +You can change the role of a group member between admin, moderator, and participant. + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + ## Change Scope of a Group Member @@ -96,6 +116,14 @@ CometChat.addGroupListener( + +Always remove group listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + +```javascript +CometChat.removeGroupListener("UNIQUE_LISTENER_ID"); +``` + + ## Missed Group Member Scope Changed Events *In other words, as a member of a group, how do I know when someone's scope is changed when my app is not running?* @@ -110,3 +138,22 @@ For the group member scope changed event, in the `Action` object received, the f 4. `actionFor` - Group object containing the details of the group in which the member scope was changed 5. `oldScope` - The original scope of the member 6. `newScope` - The updated scope of the member + +--- + +## Next Steps + + + + Transfer ownership of a group to another member + + + Remove or ban members from a group + + + Add new members to a group + + + Fetch the list of members in a group + + diff --git a/sdk/javascript/group-kick-ban-members.mdx b/sdk/javascript/group-kick-ban-members.mdx index 7433686cd..237d8421f 100644 --- a/sdk/javascript/group-kick-ban-members.mdx +++ b/sdk/javascript/group-kick-ban-members.mdx @@ -1,8 +1,27 @@ --- title: "Ban Or Kick Member From A Group" +description: "Learn how to kick, ban, and unban group members, fetch banned member lists, and receive real-time events using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Kick a member +await CometChat.kickGroupMember("GUID", "UID"); + +// Ban a member +await CometChat.banGroupMember("GUID", "UID"); + +// Unban a member +await CometChat.unbanGroupMember("GUID", "UID"); + +// Fetch banned members +const request = new CometChat.BannedMembersRequestBuilder("GUID").setLimit(30).build(); +const bannedMembers = await request.fetchNext(); +``` + There are certain actions that can be performed on the group members: @@ -13,6 +32,10 @@ There are certain actions that can be performed on the group members: All the above actions can only be performed by the **Admin** or the **Moderator** of the group. + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + ## Kick a Group Member The Admin or Moderator of a group can kick a member out of the group using the `kickGroupMember()` method. @@ -329,6 +352,14 @@ CometChat.addGroupListener( + +Always remove group listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + +```javascript +CometChat.removeGroupListener("UNIQUE_LISTENER_ID"); +``` + + ## Missed Group Member Kicked/Banned Events *In other words, as a member of a group, how do I know when someone is banned/kicked when my app is not running?* @@ -355,3 +386,22 @@ For group member unbanned event, the details can be obtained using the below fie 2. `actionBy` - User object containing the details of the user who has unbanned the member 3. `actionOn` - User object containing the details of the member that has been unbanned 4. `actionFor` - Group object containing the details of the Group from which the member was unbanned + +--- + +## Next Steps + + + + Add new members to a group + + + Promote or demote group members + + + Fetch the list of members in a group + + + Allow members to leave a group + + diff --git a/sdk/javascript/groups-overview.mdx b/sdk/javascript/groups-overview.mdx index 4f3d1c363..077147425 100644 --- a/sdk/javascript/groups-overview.mdx +++ b/sdk/javascript/groups-overview.mdx @@ -1,10 +1,44 @@ --- title: "Groups" sidebarTitle: "Overview" +description: "Overview of group management in the CometChat JavaScript SDK including group types, member roles, and available operations." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +Choose your path: +- **Create a Group** → [Create Group](/sdk/javascript/create-group) +- **Join a Group** → [Join Group](/sdk/javascript/join-group) +- **Retrieve Groups** → [Retrieve Groups](/sdk/javascript/retrieve-groups) +- **Manage Members** → [Add](/sdk/javascript/group-add-members) | [Kick/Ban](/sdk/javascript/group-kick-ban-members) | [Change Scope](/sdk/javascript/group-change-member-scope) +- **Update/Delete** → [Update Group](/sdk/javascript/update-group) | [Delete Group](/sdk/javascript/delete-group) + Groups help your users to converse together in a single space. You can have three types of groups- private, public and password protected. Each group includes three kinds of users- owner, moderator, member. + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + +--- + +## Next Steps + + + + Create public, private, or password-protected groups + + + Join existing groups as a participant + + + Fetch and filter the list of groups + + + Get the member list for a group + + diff --git a/sdk/javascript/interactive-messages.mdx b/sdk/javascript/interactive-messages.mdx index 2f083f734..99fefb199 100644 --- a/sdk/javascript/interactive-messages.mdx +++ b/sdk/javascript/interactive-messages.mdx @@ -1,11 +1,33 @@ --- title: "Interactive Messages" +description: "Learn how to send and receive interactive messages with embedded forms, buttons, and other UI elements using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Send an interactive message +const interactiveMessage = new CometChat.InteractiveMessage( + receiverId, receiverType, "form", interactiveData +); +await CometChat.sendInteractiveMessage(interactiveMessage); + +// Listen for interactive messages +CometChat.addMessageListener("interactive", new CometChat.MessageListener({ + onInteractiveMessageReceived: (message) => { }, + onInteractionGoalCompleted: (receipt) => { } +})); +``` + An InteractiveMessage is a specialised object that encapsulates an interactive unit within a chat message, such as an embedded form that users can fill out directly within the chat interface. This enhances user engagement by making the chat experience more interactive and responsive to user input. + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + ## InteractiveMessage `InteractiveMessage` is a chat message with embedded interactive content. It can contain various properties: @@ -198,6 +220,33 @@ CometChat.addMessageListener( These event listeners offer your application a way to provide real-time updates in response to incoming interactive messages and goal completions, contributing to a more dynamic and responsive user chat experience. + +Always remove message listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + +```javascript +CometChat.removeMessageListener("UNIQUE_ID"); +``` + + ## Usage An InteractiveMessage is constructed with the receiver's UID, the receiver type, the interactive type, and interactive data as a JSONObject. Once created, the InteractiveMessage can be sent using CometChat's sendInteractiveMessage() method. Incoming InteractiveMessages can be received and processed via CometChat's message listener framework. + +--- + +## Next Steps + + + + Send text, media, and custom messages + + + Listen for incoming messages in real time + + + Send ephemeral messages that aren't stored + + + Understand message types and hierarchy + + diff --git a/sdk/javascript/join-group.mdx b/sdk/javascript/join-group.mdx index 744f9e723..6dda9a744 100644 --- a/sdk/javascript/join-group.mdx +++ b/sdk/javascript/join-group.mdx @@ -1,8 +1,31 @@ --- title: "Join A Group" +description: "Learn how to join public, password-protected, and private groups, and receive real-time join events using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Join a public group +await CometChat.joinGroup("GUID", CometChat.GROUP_TYPE.PUBLIC, ""); + +// Join a password-protected group +await CometChat.joinGroup("GUID", CometChat.GROUP_TYPE.PASSWORD, "password123"); + +// Listen for member joined events +CometChat.addGroupListener("listener", new CometChat.GroupListener({ + onGroupMemberJoined: (message, joinedUser, joinedGroup) => { } +})); +``` + + +You can join groups to start participating in group conversations and receive real-time events when other members join. + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + ## Join a Group @@ -94,6 +117,14 @@ CometChat.addGroupListener( + +Always remove group listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + +```javascript +CometChat.removeGroupListener("UNIQUE_LISTNER_ID"); +``` + + ## Missed Group Member Joined Events *In other words, as a member of a group, how do I know if someone joins the group when my app is not running?* @@ -105,3 +136,22 @@ For the group member joined event, in the `Action` object received, the followin 1. `action` - `joined` 2. `actionBy` - User object containing the details of the user who joined the group 3. `actionFor`- Group object containing the details of the group the user has joined + +--- + +## Next Steps + + + + Allow members to leave a group + + + Fetch the list of members in a group + + + Send messages to group conversations + + + Programmatically add members to a group + + diff --git a/sdk/javascript/key-concepts.mdx b/sdk/javascript/key-concepts.mdx index 37e5885f1..4c1bd1475 100644 --- a/sdk/javascript/key-concepts.mdx +++ b/sdk/javascript/key-concepts.mdx @@ -1,8 +1,23 @@ --- title: "Key Concepts" +description: "Understand the core concepts of CometChat including users, groups, messaging categories, authentication, and member roles." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +Key identifiers: +- **UID** — Unique User Identifier (alphanumeric, underscore, hyphen) +- **GUID** — Group Unique Identifier (alphanumeric, underscore, hyphen) +- **Auth Key** — Development-only credential for quick testing +- **Auth Token** — Secure per-user token for production use +- **REST API Key** — Server-side credential, never expose in client code + +Group types: `Public` | `Password` | `Private` +Member scopes: `Admin` | `Moderator` | `Participant` +Message categories: `message` | `custom` | `action` | `call` + ### CometChat Dashboard @@ -125,3 +140,22 @@ Any message in CometChat can belong to either one of the below categories | call | These are call-related messages. These can belong to either one of the two types: 1. audio 2. video | For more information, you can refer to the [Message structure and hierarchy guide](/sdk/javascript/message-structure-and-hierarchy). + +--- + +## Next Steps + + + + Install and initialize the CometChat SDK + + + Log users in and manage auth tokens + + + Send your first text or media message + + + Create and manage group conversations + + diff --git a/sdk/javascript/leave-group.mdx b/sdk/javascript/leave-group.mdx index a9534b8aa..cc5f56435 100644 --- a/sdk/javascript/leave-group.mdx +++ b/sdk/javascript/leave-group.mdx @@ -1,8 +1,28 @@ --- title: "Leave A Group" +description: "Learn how to leave a group and receive real-time events when members leave using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Leave a group +await CometChat.leaveGroup("GUID"); + +// Listen for member left events +CometChat.addGroupListener("listener", new CometChat.GroupListener({ + onGroupMemberLeft: (message, leavingUser, group) => { } +})); +``` + + +You can leave a group to stop receiving updates and messages from that group conversation. + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + ## Leave a Group @@ -84,6 +104,14 @@ CometChat.addGroupListener( + +Always remove group listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + +```javascript +CometChat.removeGroupListener("UNIQUE_LISTENER_ID"); +``` + + ## Missed Group Member Left Events *In other words, as a member of a group, how do I know if someone has left it when my app is not running?* @@ -95,3 +123,22 @@ For the group member left event, in the `Action` object received, the following 1. `action` - `left` 2. `actionBy` - User object containing the details of the user who left the group 3. `actionFor` - Group object containing the details of the group the user has left + +--- + +## Next Steps + + + + Join public or password-protected groups + + + Permanently delete a group + + + Remove or ban members from a group + + + Fetch and filter the list of groups + + diff --git a/sdk/javascript/login-listener.mdx b/sdk/javascript/login-listener.mdx index 4c98ff4c4..a48019199 100644 --- a/sdk/javascript/login-listener.mdx +++ b/sdk/javascript/login-listener.mdx @@ -1,8 +1,25 @@ --- title: "Login Listener" +description: "Listen for real-time login and logout events using the CometChat JavaScript SDK LoginListener class." --- - +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```javascript +// Add login listener +CometChat.addLoginListener("LISTENER_ID", new CometChat.LoginListener({ + loginSuccess: (user) => { }, + loginFailure: (error) => { }, + logoutSuccess: () => { }, + logoutFailure: (error) => { } +})); + +// Remove login listener +CometChat.removeLoginListener("LISTENER_ID"); +``` + The CometChat SDK provides you with real-time updates for the `login` and `logout` events. This can be achieved using the `LoginListener` class provided. LoginListener consists of 4 events that can be triggered. These are as follows: @@ -86,3 +103,26 @@ In order to stop receiving events related to login and logout you need to use th + + +Always remove login listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + + +--- + +## Next Steps + + + + Learn about login methods and auth tokens + + + Monitor the SDK connection state in real time + + + Complete reference for all SDK event listeners + + + Manually manage WebSocket connections + + diff --git a/sdk/javascript/managing-web-sockets-connections-manually.mdx b/sdk/javascript/managing-web-sockets-connections-manually.mdx index 90cf107b5..f5b671f63 100644 --- a/sdk/javascript/managing-web-sockets-connections-manually.mdx +++ b/sdk/javascript/managing-web-sockets-connections-manually.mdx @@ -1,8 +1,25 @@ --- title: "Managing Web Sockets Connections Manually" +description: "Learn how to manually manage WebSocket connections for real-time messaging using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Disable auto WebSocket connection during init +const appSettings = new CometChat.AppSettingsBuilder() + .setRegion("REGION") + .autoEstablishSocketConnection(false) + .build(); +await CometChat.init("APP_ID", appSettings); + +// Manually connect/disconnect +CometChat.connect(); +CometChat.disconnect(); +``` + ## Default SDK behaviour on login @@ -98,3 +115,22 @@ CometChat.disconnect(); + +--- + +## Next Steps + + + + Monitor the SDK connection state in real time + + + Listen for login and logout events + + + Complete reference for all SDK event listeners + + + SDK installation and initialization guide + + diff --git a/sdk/javascript/mentions.mdx b/sdk/javascript/mentions.mdx index c3ce4742a..19b21bcb7 100644 --- a/sdk/javascript/mentions.mdx +++ b/sdk/javascript/mentions.mdx @@ -1,13 +1,38 @@ --- title: "Mentions" +description: "Learn how to send messages with user mentions, retrieve mentioned users, and filter messages by mention metadata using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```javascript +// Send a message with a mention (use <@uid:UID> format) +const msg = new CometChat.TextMessage("receiverUID", "Hello <@uid:cometchat-uid-1>", CometChat.RECEIVER_TYPE.USER); +await CometChat.sendMessage(msg); + +// Get mentioned users from a message +const mentionedUsers = message.getMentionedUsers(); + +// Fetch messages with mention tag info +const request = new CometChat.MessagesRequestBuilder() + .setUID("UID").setLimit(30).mentionsWithTagInfo(true).build(); +const messages = await request.fetchPrevious(); +``` + + + Mentions in messages enable users to refer to specific individual within a conversation. This is done by using the `<@uid:UID>` format, where `UID` represents the user’s unique identification. Mentions are a powerful tool for enhancing communication in messaging platforms. They streamline interaction by allowing users to easily engage and collaborate with particular individuals, especially in group conversations. + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + ## Send Mentioned Messages To send a message with a mentioned user, you must follow a specific format: `<@uid:UID>`. For example, to mention the user with UID `cometchat-uid-1` with the message "`Hello`," your text would be `"Hello, <@uid:cometchat-uid-1>"` @@ -366,3 +391,22 @@ To retrieve the list of users mentioned in the particular message, you can use t ```javascript message.getMentionedUsers() ``` + +--- + +## Next Steps + + + + Send text, media, and custom messages + + + Listen for incoming messages in real time + + + Add emoji reactions to messages + + + Organize conversations with message threads + + diff --git a/sdk/javascript/message-structure-and-hierarchy.mdx b/sdk/javascript/message-structure-and-hierarchy.mdx index 797cb91df..dc01985ab 100644 --- a/sdk/javascript/message-structure-and-hierarchy.mdx +++ b/sdk/javascript/message-structure-and-hierarchy.mdx @@ -1,9 +1,20 @@ --- title: "Message" sidebarTitle: "Message Structure And Hierarchy" +description: "Understand the message categories, types, and hierarchy in the CometChat JavaScript SDK including text, media, custom, action, interactive, and call messages." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +Message categories and types: +- **message** → `text`, `image`, `video`, `audio`, `file` +- **custom** → Developer-defined types (e.g., `location`, `poll`) +- **interactive** → `form`, `card`, `customInteractive` +- **action** → `groupMember` (joined/left/kicked/banned), `message` (edited/deleted) +- **call** → `audio`, `video` + The below diagram helps you better understand the various message categories and types that a CometChat message can belong to. @@ -84,3 +95,22 @@ The call messages have a property called status that helps you figure out the st 5. unanswered - when the call was not answered by the receiver. 6. busy - when the receiver of the call was busy on another call. 7. ended - when the call was successfully completed and ended by either the initiator or receiver. + +--- + +## Next Steps + + + + Send text, media, and custom messages + + + Listen for incoming messages in real time + + + Send messages with embedded forms and buttons + + + Advanced message filtering with RequestBuilder + + diff --git a/sdk/javascript/messaging-overview.mdx b/sdk/javascript/messaging-overview.mdx index 5a8902b43..bb3a05a95 100644 --- a/sdk/javascript/messaging-overview.mdx +++ b/sdk/javascript/messaging-overview.mdx @@ -1,12 +1,41 @@ --- title: "Messaging" sidebarTitle: "Overview" +description: "Overview of messaging capabilities in the CometChat JavaScript SDK including sending, receiving, editing, deleting messages, and advanced features." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +Choose your path: +- **Send Messages** → [Send Message](/sdk/javascript/send-message) - Text, media, custom +- **Receive Messages** → [Receive Message](/sdk/javascript/receive-message) - Real-time listeners +- **Edit/Delete** → [Edit](/sdk/javascript/edit-message) | [Delete](/sdk/javascript/delete-message) +- **Advanced** → [Threads](/sdk/javascript/threaded-messages) | [Reactions](/sdk/javascript/reactions) | [Mentions](/sdk/javascript/mentions) + Messaging is one of the core features of CometChat. We've thoughtfully created methods to help you send, receive and fetch message history. At the minimum, you must add code for [sending messages](/sdk/javascript/send-message) and [receiving messages](/sdk/javascript/receive-message). Once you've implemented that, you can proceed to more advanced features like [typing indicators](/sdk/javascript/typing-indicators) and [delivery & read receipts](/sdk/javascript/delivery-read-receipts). + +--- + +## Next Steps + + + + Send text, media, and custom messages + + + Listen for incoming messages in real time + + + Understand message categories and types + + + Show real-time typing status in conversations + + diff --git a/sdk/javascript/overview.mdx b/sdk/javascript/overview.mdx index f7edcaaa2..430c58008 100644 --- a/sdk/javascript/overview.mdx +++ b/sdk/javascript/overview.mdx @@ -1,8 +1,30 @@ --- title: "Overview" +description: "Get started with the CometChat JavaScript SDK — install, initialize, create users, log in, and integrate UI Kits or Chat Widget." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Setup Reference** +```bash +# Install +npm install @cometchat/chat-sdk-javascript +``` + +```javascript +// Initialize (run once at app start) +const appSettings = new CometChat.AppSettingsBuilder().setRegion("REGION").subscribePresenceForAllUsers().build(); +await CometChat.init("APP_ID", appSettings); + +// Login +await CometChat.login("UID", "AUTH_KEY"); // Dev only +await CometChat.login(AUTH_TOKEN); // Production +``` + +**Required Credentials:** App ID, Region, Auth Key (dev) or Auth Token (prod) +**Get from:** [CometChat Dashboard](https://app.cometchat.com) → Your App → API & Auth Keys + This guide demonstrates how to add chat to a JavaScript application using CometChat. Before you begin, we strongly recommend you read the [Key Concepts](/sdk/javascript/key-concepts) guide. @@ -356,6 +378,10 @@ CometChat.init(appID, appSetting).then( Make sure you replace the `APP_ID` with your CometChat **App ID** and `APP_REGION` with your **App Region** in the above code. + +`CometChat.init()` must be called before any other SDK method. Calling `login()`, `sendMessage()`, or registering listeners before `init()` will fail. + + ## Register and Login your user Once initialization is successful, you will need to create a user. To create users on the fly, you can use the `createUser()` method. This method takes a `User` object and the `Auth Key` as input parameters and returns the created `User` object if the request is successful. @@ -500,3 +526,22 @@ UID can be alphanumeric with an underscore and hyphen. Spaces, punctuation and o ## Integrate our Chat Widget * Please refer to the section to integrate [Chat Widget](/widget/html-bootstrap-jquery) into your Website. + +--- + +## Next Steps + + + + Understand UIDs, GUIDs, auth tokens, and more + + + Learn about login methods and auth token generation + + + Send your first text or media message + + + Listen for incoming messages in real time + + diff --git a/sdk/javascript/presenter-mode.mdx b/sdk/javascript/presenter-mode.mdx index 42b2bdc2a..83e5c091c 100644 --- a/sdk/javascript/presenter-mode.mdx +++ b/sdk/javascript/presenter-mode.mdx @@ -1,8 +1,26 @@ --- title: "Presenter Mode" +description: "Learn how to implement Presenter Mode for webinars, keynotes, and online classes using the CometChat JavaScript Calls SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Start a presentation session +const settings = new CometChatCalls.PresenterSettingsBuilder() + .setIsPresenter(true) + .enableDefaultLayout(true) + .setCallEventListener(callListener) + .build(); + +CometChatCalls.joinPresentation(callToken, settings, htmlElement); +``` + +- **Presenter** (max 5): Can share video, audio, and screen +- **Viewer** (up to 100 total): Passive consumers, no outgoing streams + ## Overview @@ -145,3 +163,30 @@ The options available for customization of calls are: In case you wish to achieve a completely customised UI for the Calling experience, you can do so by embedding default android buttons to the screen as per your requirement and then use the below methods to achieve different functionalities for the embedded buttons. For the use case where you wish to align your own custom buttons and not use the default layout provided by CometChat you can embed the buttons in your layout and use the below methods to perform the corresponding operations: + + +Always remove call event listeners when they're no longer needed (e.g., on component unmount or when the presentation screen is closed). Failing to remove listeners can cause memory leaks and duplicate event handling. + +```javascript +CometChatCalls.removeCallEventListener("UNIQUE_ID"); +``` + + +--- + +## Next Steps + + + + Start standard call sessions without presenter mode + + + Record call and presentation sessions + + + Add virtual backgrounds to video calls + + + Customize the video layout and containers + + diff --git a/sdk/javascript/rate-limits.mdx b/sdk/javascript/rate-limits.mdx index 17581b144..12d15d83e 100644 --- a/sdk/javascript/rate-limits.mdx +++ b/sdk/javascript/rate-limits.mdx @@ -1,8 +1,17 @@ --- title: "Rate Limits" +description: "Understand CometChat REST API rate limits, response headers, and how to handle rate-limited requests in your JavaScript application." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +- Core Operations (login, create/delete user, create/join group): `10,000` requests/min cumulative +- Standard Operations (all other): `20,000` requests/min cumulative +- Rate-limited responses return HTTP `429` with `Retry-After` and `X-Rate-Limit-Reset` headers +- Monitor usage via `X-Rate-Limit` and `X-Rate-Limit-Remaining` response headers + ### CometChat REST API Rate Limits @@ -32,3 +41,16 @@ However, we do provide the following response headers that you can use to confir `X-Rate-Limit: 700` `X-Rate-Limit-Remaining: 699` + +--- + +## Next Steps + + + + Install and configure the CometChat JavaScript SDK + + + Learn the core concepts behind CometChat + + diff --git a/sdk/javascript/reactions.mdx b/sdk/javascript/reactions.mdx index 8ac8f43fd..671283901 100644 --- a/sdk/javascript/reactions.mdx +++ b/sdk/javascript/reactions.mdx @@ -1,11 +1,38 @@ --- title: "Reactions" +description: "Add, remove, and fetch message reactions in real-time using the CometChat JavaScript SDK. Includes listener events and helper methods for updating UI." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Add a reaction +await CometChat.addReaction(messageId, "😊"); + +// Remove a reaction +await CometChat.removeReaction(messageId, "😊"); + +// Fetch reactions for a message +const request = new CometChat.ReactionRequestBuilder() + .setMessageId(messageId).setLimit(10).build(); +const reactions = await request.fetchNext(); + +// Listen for reaction events +CometChat.addMessageListener("LISTENER_ID", { + onMessageReactionAdded: (reaction) => {}, + onMessageReactionRemoved: (reaction) => {} +}); +``` + Enhance user engagement in your chat application with message reactions. Users can express their emotions using reactions to messages. This feature allows users to add or remove reactions, and to fetch all reactions on a message. You can also listen to reaction events in real-time. Let's see how to work with reactions in CometChat's SDK. + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + ## Add a Reaction Users can add a reaction to a message by calling `addReaction` with the message ID and the reaction emoji. @@ -201,6 +228,10 @@ reactionRequest.fetchPrevious().then( Keep the chat interactive with real-time updates for reactions. Register a listener for these events and make your UI responsive. + +Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + + ```js @@ -361,3 +392,16 @@ action After calling this method, the message instance's reactions are updated. You can then use message.getReactions() to get the latest reactions and refresh your UI accordingly. + +--- + +## Next Steps + + + + Send text, media, and custom messages to users and groups + + + Listen for incoming messages in real-time and fetch missed messages + + diff --git a/sdk/javascript/receive-message.mdx b/sdk/javascript/receive-message.mdx index a6f9a8925..78400ed03 100644 --- a/sdk/javascript/receive-message.mdx +++ b/sdk/javascript/receive-message.mdx @@ -1,20 +1,55 @@ --- title: "Receive A Message" +description: "Receive real-time messages, fetch missed and unread messages, retrieve message history, search messages, and get unread counts using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Listen for real-time messages +CometChat.addMessageListener("LISTENER_ID", new CometChat.MessageListener({ + onTextMessageReceived: (msg) => {}, + onMediaMessageReceived: (msg) => {}, + onCustomMessageReceived: (msg) => {} +})); + +// Fetch missed messages (while app was offline) +const latestId = await CometChat.getLastDeliveredMessageId(); +const request = new CometChat.MessagesRequestBuilder() + .setUID("UID").setMessageId(latestId).setLimit(30).build(); +const messages = await request.fetchNext(); + +// Fetch message history +const request = new CometChat.MessagesRequestBuilder() + .setUID("UID").setLimit(30).build(); +const messages = await request.fetchPrevious(); + +// Get unread message count +const counts = await CometChat.getUnreadMessageCount(); +``` + Receiving messages with CometChat has two parts: 1. Adding a listener to receive [real-time messages](/sdk/javascript/receive-message#real-time-messages) when your app is running 2. Calling a method to retrieve [missed messages](/sdk/javascript/receive-message#missed-messages) when your app was not running + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + ## Real-Time Messages *In other words, as a recipient, how do I receive messages when my app is running?* To receive real-time incoming messages, you need to register the `MessageListener` wherever you wish to receive the incoming messages. You can use the `addMessageListener()` method to do so. + +Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + + ```javascript @@ -956,3 +991,16 @@ CometChat.getUnreadMessageCountForAllGroups().then( It returns an object which will contain the GUID as the key and the unread message count as the value. + +--- + +## Next Steps + + + + Track when messages are delivered and read by recipients + + + Show real-time typing status in conversations + + diff --git a/sdk/javascript/recording.mdx b/sdk/javascript/recording.mdx index 214d56bcd..ef184040d 100644 --- a/sdk/javascript/recording.mdx +++ b/sdk/javascript/recording.mdx @@ -1,11 +1,35 @@ --- title: "Recording (Beta)" +description: "Implement call recording for voice and video calls using the CometChat JavaScript SDK, including start/stop controls, listeners, and accessing recordings from the Dashboard." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Start recording +CometChatCalls.startRecording(); + +// Stop recording +CometChatCalls.stopRecording(); + +// Listen for recording events (in CallSettings) +const callListener = new CometChatCalls.OngoingCallListener({ + onRecordingStarted: (event) => console.log("Recording started", event.user), + onRecordingStopped: (event) => console.log("Recording stopped", event.user), +}); +``` + +**Recordings are available on the [CometChat Dashboard](https://app.cometchat.com) → Calls section.** + This section will guide you to implement call recording feature for the voice and video calls. + +**Available via:** SDK | Dashboard + + ## Implementation Once you have decided to implement [Default Calling](/sdk/javascript/default-call) or [Direct Calling](/sdk/javascript/direct-call) calling and followed the steps to implement them. Just few additional listeners and methods will help you quickly implement call recording in your app. @@ -14,6 +38,10 @@ You need to make changes in the CometChat.startCall method and add the required A basic example of how to make changes to implement recording for a direct call/ a default call: + +Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + + ```js @@ -137,3 +165,16 @@ Currently, the call recordings are available on the [CometChat Dashboard](https: + +--- + +## Next Steps + + + + Implement ringing call flows with accept/reject functionality + + + Retrieve and display call history for users and groups + + diff --git a/sdk/javascript/resources-overview.mdx b/sdk/javascript/resources-overview.mdx index ea0d211bf..fce2b674a 100644 --- a/sdk/javascript/resources-overview.mdx +++ b/sdk/javascript/resources-overview.mdx @@ -1,12 +1,33 @@ --- title: "Resources" sidebarTitle: "Overview" +description: "Access CometChat JavaScript SDK resources including real-time listeners reference, migration guides, and rate limits." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +- [All Real-Time Listeners](/sdk/javascript/all-real-time-listeners) — Complete listener reference +- [Upgrading from v3](/sdk/javascript/upgrading-from-v3) — Migration guide +- [Rate Limits](/sdk/javascript/rate-limits) — API rate limit details + We have a number of resources that will help you while integrating CometChat in your app. You can begin with the [all real-time listeners](/sdk/javascript/all-real-time-listeners) guide. If you're upgrading from v2, we recommend reading our [Upgrading from v3](/sdk/javascript/upgrading-from-v3) guide. + +--- + +## Next Steps + + + + Complete reference for all CometChat event listeners + + + Step-by-step migration guide from SDK v3 to v4 + + \ No newline at end of file diff --git a/sdk/javascript/retrieve-conversations.mdx b/sdk/javascript/retrieve-conversations.mdx index a58ef59d1..c31330ef3 100644 --- a/sdk/javascript/retrieve-conversations.mdx +++ b/sdk/javascript/retrieve-conversations.mdx @@ -1,11 +1,35 @@ --- title: "Retrieve Conversations" +description: "Fetch, filter, tag, and search conversations using the CometChat JavaScript SDK. Includes pagination, tag-based filtering, agentic conversation filters, and message-to-conversation conversion." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Fetch conversations list +const request = new CometChat.ConversationsRequestBuilder() + .setLimit(30).build(); +const conversations = await request.fetchNext(); + +// Get a specific conversation +const conversation = await CometChat.getConversation("UID", "user"); + +// Tag a conversation +await CometChat.tagConversation("UID", "user", ["archived"]); + +// Convert message to conversation +const conversation = await CometChat.CometChatHelper.getConversationFromMessage(message); +``` + Conversations provide the last messages for every one-on-one and group conversation the logged-in user is a part of. This makes it easy for you to build a **Recent Chat** list. + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + ## Retrieve List of Conversations *In other words, as a logged-in user, how do I retrieve the latest conversations that I've been a part of?* @@ -622,3 +646,16 @@ CometChat.CometChatHelper.getConversationFromMessage(message).then( While converting the `Message` object to the `Conversation` object, the `unreadMessageCount` & `tags` will not be available in the `Conversation` object. The unread message count needs to be managed in your client-side code. + +--- + +## Next Steps + + + + Remove conversations from the logged-in user's list + + + Show real-time typing status in conversations + + diff --git a/sdk/javascript/retrieve-group-members.mdx b/sdk/javascript/retrieve-group-members.mdx index 3e21b909d..8b506e3c5 100644 --- a/sdk/javascript/retrieve-group-members.mdx +++ b/sdk/javascript/retrieve-group-members.mdx @@ -1,9 +1,31 @@ --- title: "Retrieve Group Members" +description: "Fetch and filter group members by scope, status, and search keyword using the CometChat JavaScript SDK with pagination support." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Fetch group members +const request = new CometChat.GroupMembersRequestBuilder("GUID") + .setLimit(30).build(); +const members = await request.fetchNext(); + +// Filter by scope +const request = new CometChat.GroupMembersRequestBuilder("GUID") + .setLimit(30).setScopes(["admin", "moderator"]).build(); + +// Search members +const request = new CometChat.GroupMembersRequestBuilder("GUID") + .setLimit(30).setSearchKeyword("john").build(); +``` + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + ## Retrieve the List of Group Members In order to fetch the list of groups members for a group, you can use the `GroupMembersRequest` class. To use this class i.e to create an object of the GroupMembersRequest class, you need to use the `GroupMembersRequestBuilder` class. The `GroupMembersRequestBuilder` class allows you to set the parameters based on which the groups are to be fetched. @@ -187,3 +209,16 @@ groupMembersRequest.fetchNext().then( + +--- + +## Next Steps + + + + Add users to a group programmatically + + + Remove or ban members from a group + + diff --git a/sdk/javascript/retrieve-groups.mdx b/sdk/javascript/retrieve-groups.mdx index 92a074c0d..a60efe03b 100644 --- a/sdk/javascript/retrieve-groups.mdx +++ b/sdk/javascript/retrieve-groups.mdx @@ -1,9 +1,33 @@ --- title: "Retrieve Groups" +description: "Fetch, filter, and search groups using the CometChat JavaScript SDK. Includes pagination, tag-based filtering, joined-only groups, and online member counts." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Fetch groups list +const request = new CometChat.GroupsRequestBuilder() + .setLimit(30).build(); +const groups = await request.fetchNext(); + +// Get specific group details +const group = await CometChat.getGroup("GUID"); + +// Fetch only joined groups +const request = new CometChat.GroupsRequestBuilder() + .setLimit(30).joinedOnly(true).build(); + +// Get online member count +const count = await CometChat.getOnlineGroupMemberCount(["GUID"]); +``` + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + ## Retrieve List of Groups *In other words, as a logged-in user, how do I retrieve the list of groups I've joined and groups that are available?* @@ -283,3 +307,16 @@ CometChat.getOnlineGroupMemberCount(guids).then( This method returns a JSON Object with the GUID as the key and the online member count for that group as the value. + +--- + +## Next Steps + + + + Create public, private, or password-protected groups + + + Fetch and filter members of a specific group + + diff --git a/sdk/javascript/retrieve-users.mdx b/sdk/javascript/retrieve-users.mdx index 943df6404..87160c09e 100644 --- a/sdk/javascript/retrieve-users.mdx +++ b/sdk/javascript/retrieve-users.mdx @@ -1,9 +1,32 @@ --- title: "Retrieve Users" +description: "Fetch, filter, search, and sort users using the CometChat JavaScript SDK. Includes pagination, role-based filtering, tag support, and online user counts." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Fetch users list +const request = new CometChat.UsersRequestBuilder() + .setLimit(30).build(); +const users = await request.fetchNext(); + +// Get specific user details +const user = await CometChat.getUser("UID"); + +// Get logged-in user +const me = await CometChat.getLoggedinUser(); + +// Get online user count +const count = await CometChat.getOnlineUserCount(); +``` + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + ## Retrieve Logged In User Details You can get the details of the logged-in user using the `getLoggedInUser()` method. This method can also be used to check if the user is logged in or not. If the method returns `Promise` with reject callback, it indicates that the user is not logged in and you need to log the user into CometChat SDK. @@ -535,3 +558,16 @@ CometChat.getOnlineUserCount().then( This method returns the total online user count for your app. + +--- + +## Next Steps + + + + Track and subscribe to user online/offline status + + + Block and unblock users from your application + + diff --git a/sdk/javascript/send-message.mdx b/sdk/javascript/send-message.mdx index ae9f8e125..cd5ebf4fc 100644 --- a/sdk/javascript/send-message.mdx +++ b/sdk/javascript/send-message.mdx @@ -1,11 +1,37 @@ --- title: "Send A Message" +description: "Send text, media, and custom messages to users and groups using the CometChat JavaScript SDK. Includes metadata, tags, quoted messages, and multiple attachments." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Send text message to user +const msg = new CometChat.TextMessage("UID", "Hello!", CometChat.RECEIVER_TYPE.USER); +await CometChat.sendMessage(msg); + +// Send text message to group +const msg = new CometChat.TextMessage("GUID", "Hello!", CometChat.RECEIVER_TYPE.GROUP); +await CometChat.sendMessage(msg); + +// Send media message +const msg = new CometChat.MediaMessage("UID", file, CometChat.MESSAGE_TYPE.IMAGE, CometChat.RECEIVER_TYPE.USER); +await CometChat.sendMediaMessage(msg); + +// Send custom message +const msg = new CometChat.CustomMessage("UID", CometChat.RECEIVER_TYPE.USER, "customType", { key: "value" }); +await CometChat.sendCustomMessage(msg); +``` + Using CometChat, you can send three types of messages: + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + 1. [Text Message](/sdk/javascript/send-message#text-message) is the most common and standard message type. 2. [Media Message](/sdk/javascript/send-message#media-message) for sending photos, videos and files. 3. [Custom Message](/sdk/javascript/send-message#custom-message), for sending completely custom data using JSON structures. @@ -1725,3 +1751,16 @@ CometChat.sendCustomMessage(customMessage).then( It is also possible to send interactive messages from CometChat, to know more [click here](/sdk/javascript/interactive-messages) + +--- + +## Next Steps + + + + Listen for incoming messages in real-time and fetch missed messages + + + Edit previously sent text and custom messages + + diff --git a/sdk/javascript/session-timeout.mdx b/sdk/javascript/session-timeout.mdx index 23470881f..541c17ebe 100644 --- a/sdk/javascript/session-timeout.mdx +++ b/sdk/javascript/session-timeout.mdx @@ -1,8 +1,18 @@ --- title: "Session Timeout Flow" +description: "Handle idle session timeouts in CometChat calls, including automatic termination, user prompts, and the onSessionTimeout event." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +- Default idle timeout: 180 seconds (3 minutes) alone in a session +- Warning dialog appears at 120 seconds with stay/leave options +- Auto-terminates after 60 more seconds if no action taken +- Listen for `onSessionTimeout` event to handle auto-termination +- Customize timeout with `setIdleTimeoutPeriod(seconds)` in CallSettings (v4.1.0+) + Available since v4.1.0 @@ -32,3 +42,16 @@ This feature helps manage inactive call sessions and prevents unnecessary resour The `onSessionTimeout` event is triggered when the call automatically terminates due to session timeout, as illustrated in the diagram above. + +--- + +## Next Steps + + + + Implement ringing call flows with accept/reject functionality + + + Implement calling without the Chat SDK + + diff --git a/sdk/javascript/setup-sdk.mdx b/sdk/javascript/setup-sdk.mdx index e9bdce872..23f3a1201 100644 --- a/sdk/javascript/setup-sdk.mdx +++ b/sdk/javascript/setup-sdk.mdx @@ -1,10 +1,32 @@ --- title: "Setup" sidebarTitle: "Overview" +description: "Install, configure, and initialize the CometChat JavaScript SDK in your application using npm or CDN." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Setup Reference** +```bash +# Install +npm install @cometchat/chat-sdk-javascript +``` + +```javascript +import { CometChat } from "@cometchat/chat-sdk-javascript"; +// Initialize (run once at app start) +const appSettings = new CometChat.AppSettingsBuilder() + .subscribePresenceForAllUsers() + .setRegion("REGION") + .autoEstablishSocketConnection(true) + .build(); +await CometChat.init("APP_ID", appSettings); +``` + +**Required:** App ID, Region from [CometChat Dashboard](https://app.cometchat.com) → API & Auth Keys + Migrating app version from v3 to v4 ? @@ -128,7 +150,28 @@ CometChat.init(appID, appSetting).then( Make sure you replace the `APP_ID` with your CometChat **App ID** and `APP_REGION` with your **App Region** in the above code. + +`CometChat.init()` must be called before any other SDK method. Calling `login()`, `sendMessage()`, or registering listeners before `init()` will fail. + + + +**Auth Key** is for development/testing only. In production, generate **Auth Tokens** on your server using the REST API and pass them to the client. Never expose Auth Keys in production client code. + + | Parameter | Description | | ---------- | ----------------------------------- | | appID | CometChat App ID | | appSetting | An object of the AppSettings class. | + +--- + +## Next Steps + + + + Log in users with Auth Key or Auth Token + + + Send your first text, media, or custom message + + diff --git a/sdk/javascript/standalone-calling.mdx b/sdk/javascript/standalone-calling.mdx index 09df82d0e..3f48a1202 100644 --- a/sdk/javascript/standalone-calling.mdx +++ b/sdk/javascript/standalone-calling.mdx @@ -1,7 +1,28 @@ --- title: "Standalone Calling" +description: "Implement video and audio calling using only the CometChat Calls SDK without the Chat SDK. Covers authentication, token generation, session management, and call controls." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```javascript +// Generate call token (requires user auth token from REST API) +const callToken = await CometChatCalls.generateToken(sessionId, userAuthToken); + +// Start call session +const callSettings = new CometChatCalls.CallSettingsBuilder() + .enableDefaultLayout(true) + .setIsAudioOnlyCall(false) + .setCallListener(callListener) + .build(); +CometChatCalls.startSession(callToken.token, callSettings, htmlElement); + +// End session +CometChatCalls.endSession(); +``` + ## Overview This section demonstrates how to implement calling functionality using only the CometChat Calls SDK, without requiring the Chat SDK. This is ideal for applications that need video/audio calling capabilities without the full chat infrastructure. @@ -228,6 +249,10 @@ Configure the call experience using the following `CallSettingsBuilder` methods: The `OngoingCallListener` provides real-time callbacks for call session events, including participant changes, call state updates, and error conditions. + +Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + + You can register listeners in two ways: 1. **Via CallSettingsBuilder:** Use `.setCallListener(listener)` when building call settings @@ -647,3 +672,16 @@ CometChatCalls.endSession(); ``` + +--- + +## Next Steps + + + + Implement ringing call flows using the Chat SDK + + + Add call recording to your voice and video calls + + diff --git a/sdk/javascript/threaded-messages.mdx b/sdk/javascript/threaded-messages.mdx index e2d29a55a..542882774 100644 --- a/sdk/javascript/threaded-messages.mdx +++ b/sdk/javascript/threaded-messages.mdx @@ -1,11 +1,35 @@ --- title: "Threaded Messages" +description: "Send, receive, and fetch threaded messages using the CometChat JavaScript SDK. Includes real-time listeners, thread message history, and filtering thread replies." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Send message in a thread +const msg = new CometChat.TextMessage("UID", "Reply", CometChat.RECEIVER_TYPE.USER); +msg.setParentMessageId(100); +await CometChat.sendMessage(msg); + +// Fetch thread messages +const request = new CometChat.MessagesRequestBuilder() + .setParentMessageId(100).setLimit(30).build(); +const messages = await request.fetchPrevious(); + +// Exclude thread replies from main conversation +const request = new CometChat.MessagesRequestBuilder() + .setUID("UID").setLimit(30).hideReplies(true).build(); +``` + Messages that are started from a particular message are called Threaded messages or simply threads. Each Thread is attached to a message which is the Parent message for that thread. + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + ## Send Message in a Thread As mentioned in the [Send a Message](/sdk/javascript/send-message) section. You can either send a message to a User or a Group based on the `receiverType` and the UID/GUID specified for the message. A message can belong to either of the below types: @@ -67,6 +91,10 @@ Similarly, using the `setParentMessageId()` method, Media and Custom Messages ca The procedure to receive real-time messages is exactly the same as mentioned in the [Receive Messages](/sdk/javascript/receive-message). This can be achieved using the `MessageListener` class provided by the SDK. + +Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + + To add a MessageListener, you can use the `addMessageListener()` method of the SDK. The only thing that needs to be checked is if the received message belongs to the active thread. This can be done using the `parentMessageId` field of the message object. @@ -271,3 +299,16 @@ messagesRequest.fetchPrevious().then( The above snippet will return messages between the logged in user and `cometchat-uid-1` excluding all the threaded messages belonging to the same conversation. + +--- + +## Next Steps + + + + Send text, media, and custom messages to users and groups + + + Listen for incoming messages in real-time and fetch missed messages + + diff --git a/sdk/javascript/transfer-group-ownership.mdx b/sdk/javascript/transfer-group-ownership.mdx index 1de52a892..f3e6311c0 100644 --- a/sdk/javascript/transfer-group-ownership.mdx +++ b/sdk/javascript/transfer-group-ownership.mdx @@ -1,11 +1,26 @@ --- title: "Transfer Group Ownership" +description: "Transfer ownership of a CometChat group to another member using the JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Transfer group ownership +await CometChat.transferGroupOwnership("GUID", "NEW_OWNER_UID"); +``` + +**Note:** Only the current group owner can transfer ownership. The owner must transfer ownership before leaving the group. + *In other words, as a logged-in user, how do I transfer the ownership of any group if I am the owner of the group?* + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + In order to transfer the ownership of any group, the first condition is that you must be the owner of the group. In case you are the owner of the group, you can use the `transferGroupOwnership()` method provided by the `CometChat` class. This will be helpful as the owner is not allowed to leave the group. In case, you as the owner would like to leave the group, you will have to use this method and transfer your ownership first to any other member of the group and only then you will be allowed to leave the group. @@ -42,3 +57,16 @@ CometChat.transferGroupOwnership(GUID, UID).then( + +--- + +## Next Steps + + + + Leave a group after transferring ownership + + + Promote or demote group members + + diff --git a/sdk/javascript/transient-messages.mdx b/sdk/javascript/transient-messages.mdx index 9f44b2267..d6bda9cb3 100644 --- a/sdk/javascript/transient-messages.mdx +++ b/sdk/javascript/transient-messages.mdx @@ -1,11 +1,30 @@ --- title: "Transient Messages" +description: "Send and receive ephemeral real-time messages that are not stored on the server using the CometChat JavaScript SDK. Ideal for live reactions and temporary indicators." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Send transient message to user +const msg = new CometChat.TransientMessage("UID", CometChat.RECEIVER_TYPE.USER, { LIVE_REACTION: "heart" }); +CometChat.sendTransientMessage(msg); + +// Listen for transient messages +CometChat.addMessageListener("LISTENER_ID", new CometChat.MessageListener({ + onTransientMessageReceived: (msg) => console.log("Transient:", msg) +})); +``` + Transient messages are messages that are sent in real-time only and are not saved or tracked anywhere. The receiver of the message will only receive the message if he is online and these messages cannot be retrieved later. + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + ## Send a Transient Message You can use the `sendTransientMessage()` method to send a transient message to a user or in a group. The receiver will receive this information in the `onTransientMessageReceived()` method of the `MessageListener` class. In order to send the transient message, you need to use the `TransientMessage` class. @@ -65,6 +84,10 @@ CometChat.sendTransientMessage(transientMessage); *In other words, as a recipient, how do I know when someone sends a transient message?* + +Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + + You will receive the transient message in the `onTransientMessageReceived()` method of the registered `MessageListener` class. @@ -110,3 +133,16 @@ The `TransientMessage` class consists of the below parameters: | **receiverId** | Unique Id of the receiver. This can be the Id of the group or the user the transient message is sent to. | | **receiverType** | The type of the receiver - `CometChat.RECEIVER_TYPE.USER` or `CometChat.RECEIVER_TYPE.GROUP` | | **data** | A JSONObject to provide data. | + +--- + +## Next Steps + + + + Show real-time typing status in conversations + + + Send text, media, and custom messages + + diff --git a/sdk/javascript/typing-indicators.mdx b/sdk/javascript/typing-indicators.mdx index 0174f5727..027ba3e0b 100644 --- a/sdk/javascript/typing-indicators.mdx +++ b/sdk/javascript/typing-indicators.mdx @@ -1,9 +1,31 @@ --- title: "Typing Indicators" +description: "Send and receive real-time typing indicators for users and groups using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Start typing indicator +const typing = new CometChat.TypingIndicator("UID", CometChat.RECEIVER_TYPE.USER); +CometChat.startTyping(typing); + +// Stop typing indicator +CometChat.endTyping(typing); + +// Listen for typing events +CometChat.addMessageListener("LISTENER_ID", new CometChat.MessageListener({ + onTypingStarted: (indicator) => console.log("Typing started:", indicator), + onTypingEnded: (indicator) => console.log("Typing ended:", indicator) +})); +``` + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + ## Send a Typing Indicator *In other words, as a sender, how do I let the recipient(s) know that I'm typing?* @@ -121,6 +143,10 @@ You can use the `metadata` field of the `TypingIndicator` class to pass addition *In other words, as a recipient, how do I know when someone is typing?* + +Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + + You will receive the typing indicators in the `onTypingStarted()` and the `onTypingEnded()` method of the registered `MessageListener` class. @@ -172,3 +198,16 @@ The `TypingIndicator` class consists of the below parameters: | **receiverId** | Unique Id of the receiver. This can be the Id of the group or the user the typing indicator is sent to. | | **receiverType** | This parameter indicates if the typing indicator is to be sent to a user or a group. The possible values are: 1. `CometChat.RECEIVER_TYPE.USER` 2. `CometChat.RECEIVER_TYPE.GROUP` | | **metadata** | A JSONObject to provider additional data. | + +--- + +## Next Steps + + + + Track when messages are delivered and read + + + Send ephemeral real-time messages like live reactions + + diff --git a/sdk/javascript/update-group.mdx b/sdk/javascript/update-group.mdx index c8717d61c..8d90ab334 100644 --- a/sdk/javascript/update-group.mdx +++ b/sdk/javascript/update-group.mdx @@ -1,9 +1,22 @@ --- title: "Update A Group" +description: "Update group details such as name, type, icon, and description using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Update group details +const group = new CometChat.Group("GUID", "New Name", CometChat.GROUP_TYPE.PUBLIC); +const updated = await CometChat.updateGroup(group); +``` + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + ## Update Group *In other words, as a group owner, how can I update the group details?* @@ -59,3 +72,16 @@ This method takes an instance of the `Group` class as a parameter which should c After a successful update of the group, you will receive an instance of `Group` class containing update information of the group. For more information on the `Group` class, please check [here](/sdk/javascript/create-group#create-a-group). + +--- + +## Next Steps + + + + Permanently delete a group + + + Fetch and filter groups with pagination + + diff --git a/sdk/javascript/upgrading-from-v3.mdx b/sdk/javascript/upgrading-from-v3.mdx index 00cf6868a..633bb9c2c 100644 --- a/sdk/javascript/upgrading-from-v3.mdx +++ b/sdk/javascript/upgrading-from-v3.mdx @@ -1,9 +1,18 @@ --- title: "Upgrading From V3" +description: "Migrate your CometChat JavaScript SDK integration from v3 to v4 with updated dependencies and import statements." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** - +Key changes from v3 to v4: +- Chat SDK: `npm i @cometchat/chat-sdk-javascript` +- Calls SDK: `npm i @cometchat/calls-sdk-javascript` +- Import: `import { CometChat } from '@cometchat/chat-sdk-javascript'` +- Import Calls: `import { CometChatCalls } from '@cometchat/calls-sdk-javascript'` + ## Upgrading From v3 Upgrading from v3.x to v4 is fairly simple. Below are the major changes that are released as a part of CometChat v4: @@ -63,3 +72,16 @@ import {CometChatCalls} from '@cometchat/calls-sdk-javascript'; + +--- + +## Next Steps + + + + Install and configure the CometChat JavaScript SDK + + + Learn the core concepts behind CometChat v4 + + diff --git a/sdk/javascript/user-management.mdx b/sdk/javascript/user-management.mdx index 76ac2b585..bc4e9deee 100644 --- a/sdk/javascript/user-management.mdx +++ b/sdk/javascript/user-management.mdx @@ -1,11 +1,35 @@ --- title: "User Management" +description: "Create, update, and manage CometChat users programmatically using the JavaScript SDK. Includes user creation, profile updates, and the User class reference." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Create a user +const user = new CometChat.User("user1"); +user.setName("Kevin"); +await CometChat.createUser(user, "AUTH_KEY"); + +// Update a user +user.setName("Kevin Fernandez"); +await CometChat.updateUser(user, "AUTH_KEY"); + +// Update logged-in user (no auth key needed) +await CometChat.updateCurrentUserDetails(user); +``` + +**Note:** User creation/deletion should ideally happen on your backend via the [REST API](https://api-explorer.cometchat.com). + When a user logs into your app, you need to programmatically login the user into CometChat. But before you log in the user to CometChat, you need to create the user. + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + Summing up- **When a user registers in your app** @@ -195,3 +219,21 @@ Deleting a user can only be achieved via the Restful APIs. For more information | hasBlockedMe | No | A boolean that determines if the user has blocked the logged in user | | blockedByMe | No | A boolean that determines if the logged in user has blocked the user | | tags | Yes | A list of tags to identify specific users | + +## Next Steps + + + + Fetch user lists with filters and pagination + + + Track real-time online/offline status + + + Block and unblock users programmatically + + + Log in and manage user sessions + + + diff --git a/sdk/javascript/user-presence.mdx b/sdk/javascript/user-presence.mdx index 503bc0d6f..676bbe774 100644 --- a/sdk/javascript/user-presence.mdx +++ b/sdk/javascript/user-presence.mdx @@ -1,12 +1,36 @@ --- title: "User Presence" sidebarTitle: "Overview" +description: "Track real-time user online/offline status and configure presence subscriptions using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Subscribe to presence during init +const appSettings = new CometChat.AppSettingsBuilder() + .subscribePresenceForAllUsers() // or .subscribePresenceForRoles([]) / .subscribePresenceForFriends() + .setRegion("REGION").build(); + +// Listen for presence changes +CometChat.addUserListener("LISTENER_ID", new CometChat.UserListener({ + onUserOnline: (user) => console.log("Online:", user), + onUserOffline: (user) => console.log("Offline:", user) +})); + +// Remove listener +CometChat.removeUserListener("LISTENER_ID"); +``` + User Presence helps us understand if a user is available to chat or not. + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + ## Real-time Presence *In other words, as a logged-in user, how do I know if a user is online or offline?* @@ -95,6 +119,14 @@ CometChat.removeUserListener(listenerID); + +Always remove your `UserListener` when the component or view unmounts to prevent memory leaks and duplicate event handling. + +```javascript +CometChat.removeUserListener("LISTENER_ID"); +``` + + ## User List Presence *In other words, as a logged-in user, when I retrieve the user list, how do I know if a user is online/offline?* @@ -107,3 +139,21 @@ When you fetch the list of users, in the [User](/sdk/javascript/user-management# * offline - This indicates that the user is currently offline and is not available to chat. 2. `lastActiveAt` - in case the user is offline, this field holds the timestamp of the time when the user was last online. This can be used to display the Last seen of the user if need be. + +## Next Steps + + + + Create, update, and manage users + + + Fetch user lists with filters and pagination + + + Monitor SDK connection state changes + + + Complete reference for all event listeners + + + diff --git a/sdk/javascript/users-overview.mdx b/sdk/javascript/users-overview.mdx index 2193624f4..6b16f4307 100644 --- a/sdk/javascript/users-overview.mdx +++ b/sdk/javascript/users-overview.mdx @@ -1,10 +1,32 @@ --- title: "Users" sidebarTitle: "Overview" +description: "Overview of CometChat user functionality including user management, retrieval, and presence tracking in the JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +- [User Management](/sdk/javascript/user-management) — Create and update users +- [Retrieve Users](/sdk/javascript/retrieve-users) — Fetch and filter user lists +- [User Presence](/sdk/javascript/user-presence) — Track online/offline status +- [Block Users](/sdk/javascript/block-users) — Block and unblock users + The primary aim for our Users functionality is to allow you to quickly retrieve and add users to CometChat. You can begin with [user management](/sdk/javascript/user-management) to sync your users to CometChat. Once that is done, you can [retrieve users](/sdk/javascript/retrieve-users) and display them in your app. + +--- + +## Next Steps + + + + Create and update users in CometChat + + + Fetch and filter user lists with pagination + + \ No newline at end of file diff --git a/sdk/javascript/video-view-customisation.mdx b/sdk/javascript/video-view-customisation.mdx index 2fd632577..57611379e 100644 --- a/sdk/javascript/video-view-customisation.mdx +++ b/sdk/javascript/video-view-customisation.mdx @@ -1,9 +1,25 @@ --- title: "Video View Customisation" +description: "Customize the main video container in CometChat calls including aspect ratio, full screen button, name labels, and network labels." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Customize main video container +const videoSettings = new CometChat.MainVideoContainerSetting(); +videoSettings.setMainVideoAspectRatio(CometChat.CallSettings.ASPECT_RATIO_CONTAIN); +videoSettings.setFullScreenButtonParams(CometChat.CallSettings.POSITION_BOTTOM_RIGHT, true); +videoSettings.setNameLabelParams(CometChat.CallSettings.POSITION_BOTTOM_LEFT, true, "rgba(27,27,27,0.4)"); +// Apply to call settings +const callSettings = new CometChatCalls.CallSettingsBuilder() + .setMainVideoContainerSetting(videoSettings) + .build(); +``` + This section will guide you to customise the main video container. ## Implementation @@ -39,3 +55,21 @@ videoSettings.setNetworkLabelParams(CometChat.CallSettings.POSITION_BOTTOM_RIGHT + +## Next Steps + + + + Implement standard audio and video calls + + + Start calls without a prior message + + + Add background blur and custom images to calls + + + Record audio and video calls + + + diff --git a/sdk/javascript/virtual-background.mdx b/sdk/javascript/virtual-background.mdx index 63edd0a83..5e6f0a9b7 100644 --- a/sdk/javascript/virtual-background.mdx +++ b/sdk/javascript/virtual-background.mdx @@ -1,9 +1,24 @@ --- title: "Virtual Background" +description: "Implement virtual background features in CometChat video calls including background blur, custom images, and user-configurable settings." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Apply background blur +const callController = CometChat.CallController.getInstance(); +callController.setBackgroundBlur(1); // blur level 1-99 +// Set background image +callController.setBackgroundImage("https://example.com/bg.jpg"); + +// Open virtual background settings UI +callController.openVirtualBackground(); +``` + This section will guide you to implement virtual background feature in video calls. ## Implementation @@ -114,3 +129,21 @@ The `VirtualBackground` Class is the required in case you want to change how the | `setImages(images: Array)` | This method allows developer to add their custom background image which the end user can choose. | | `enforceBackgroundBlur(enforceBackgroundBlur: number)` | This method starts the call with background blurred. To blur the background you need to pass an integer value between 1-99 which decides the blur level. **Default = 0** | | `enforceBackgroundImage(enforceBackgroundImage: string)` | This methods starts the call with the provided background image. | + +## Next Steps + + + + Customize the main video container layout + + + Implement standard audio and video calls + + + Start calls without a prior message + + + Enable screen sharing and presenter features + + + From 50e60be8a73c7ed1b4cd3cfba79db5b288a45927 Mon Sep 17 00:00:00 2001 From: aanshisingh-cometchat Date: Tue, 17 Feb 2026 18:01:34 +0530 Subject: [PATCH 02/43] refactor: update the sdk doc --- sdk/javascript/user-management.mdx | 90 +++++++++++++++------------ sdk/javascript/user-presence.mdx | 98 ++++++++++++++++++------------ sdk/javascript/users-overview.mdx | 16 +++-- 3 files changed, 120 insertions(+), 84 deletions(-) diff --git a/sdk/javascript/user-management.mdx b/sdk/javascript/user-management.mdx index bc4e9deee..080f5ebc3 100644 --- a/sdk/javascript/user-management.mdx +++ b/sdk/javascript/user-management.mdx @@ -46,11 +46,15 @@ Summing up- Ideally, user creation should take place at your backend. You can refer our Rest API to learn more about [creating a user](https://api-explorer.cometchat.com/reference/creates-user) and use the appropriate code sample based on your backend language. + +**Security:** Never expose your `Auth Key` in client-side production code. User creation and updates using `Auth Key` should ideally happen on your backend server. Use client-side creation only for prototyping or development. + + However, if you wish to create users on the fly, you can use the `createUser()` method. This method takes a `User` object and the `Auth Key` as input parameters and returns the created `User` object if the request is successful. -```js +```javascript let authKey = "AUTH_KEY"; var uid = "user1"; var name = "Kevin"; @@ -61,15 +65,13 @@ user.setName(name); CometChat.createUser(user, authKey).then( user => { - console.log("user created", user); + console.log("user created", user); }, error => { - console.log("error", error); + console.log("error", error); } ) ``` - - ```typescript let authKey: string = "AUTH_KEY"; @@ -82,15 +84,13 @@ user.setName(name); CometChat.createUser(user, authKey).then( (user: CometChat.User) => { - console.log("user created", user); + console.log("user created", user); }, (error: CometChat.CometChatException) => { - console.log("error", error); + console.log("error", error); } ); ``` - - @@ -105,7 +105,7 @@ Updating a user similar to creating a user should ideally be achieved at your ba -```js +```javascript let authKey = "AUTH_KEY"; let uid = "user1"; let name = "Kevin Fernandez"; @@ -116,15 +116,13 @@ user.setName(name); CometChat.updateUser(user, authKey).then( user => { - console.log("user updated", user); + console.log("user updated", user); }, error => { - console.log("error", error); + console.log("error", error); } -) +) ``` - - ```typescript let authKey: string = "AUTH_KEY"; @@ -137,15 +135,13 @@ user.setName(name); CometChat.updateUser(user, authKey).then( (user: CometChat.User) => { - console.log("user updated", user); + console.log("user updated", user); }, (error: CometChat.CometChatException) => { - console.log("error", error); + console.log("error", error); } -) +) ``` - - Please make sure the `User` object provided to the `updateUser()` method has the `UID` of the user to be updated set. @@ -156,7 +152,7 @@ Updating a logged-in user is similar to updating a user. The only difference bei -```js +```javascript let uid = "user1"; let name = "Kevin Fernandez"; @@ -166,15 +162,13 @@ user.setName(name); CometChat.updateCurrentUserDetails(user).then( user => { - console.log("user updated", user); + console.log("user updated", user); }, error => { - console.log("error", error); + console.log("error", error); } ) ``` - - ```typescript var uid: string = "user1"; @@ -186,15 +180,13 @@ user.setName(name); CometChat.updateCurrentUserDetails(user).then( (user: CometChat.User) => { - console.log("user updated", user); + console.log("user updated", user); }, (error: CometChat.CometChatException) => { - console.log("error", error); + console.log("error", error); } ); ``` - - By using the `updateCurrentUserDetails()` method one can only update the logged-in user irrespective of the UID passed. Also, it is not possible to update the role of a logged-in user. @@ -220,20 +212,42 @@ Deleting a user can only be achieved via the Restful APIs. For more information | blockedByMe | No | A boolean that determines if the logged in user has blocked the user | | tags | Yes | A list of tags to identify specific users | + + + +| Practice | Details | +| --- | --- | +| Backend user creation | Always create and update users from your backend server using the REST API to keep your `Auth Key` secure | +| UID format | Use alphanumeric characters, underscores, and hyphens only. Avoid spaces and special characters | +| Metadata usage | Store additional user info (e.g., department, preferences) in the `metadata` JSON field rather than creating custom fields | +| Sync on registration | Create the CometChat user immediately when a user registers in your app to avoid login failures | + + + + +| Symptom | Cause | Fix | +| --- | --- | --- | +| `createUser()` fails with "Auth Key not found" | Invalid or missing Auth Key | Verify the Auth Key from your [CometChat Dashboard](https://app.cometchat.com) | +| `createUser()` fails with "UID already exists" | A user with that UID was already created | Use `updateUser()` instead, or choose a different UID | +| `updateCurrentUserDetails()` doesn't update role | Role cannot be changed for the logged-in user | Use `updateUser()` with Auth Key from your backend to change roles | +| User not appearing in user list | User was created but not yet indexed | Wait a moment and retry. Ensure `createUser()` resolved successfully | + + + + ## Next Steps - - Fetch user lists with filters and pagination + + Fetch and filter user lists with pagination. - - Track real-time online/offline status + + Monitor real-time online/offline status. - - Block and unblock users programmatically + + Block and unblock users. - - Log in and manage user sessions + + Log users into CometChat. - diff --git a/sdk/javascript/user-presence.mdx b/sdk/javascript/user-presence.mdx index 676bbe774..0652ff3de 100644 --- a/sdk/javascript/user-presence.mdx +++ b/sdk/javascript/user-presence.mdx @@ -47,28 +47,30 @@ For presence subscription, the AppSettingsBuilder provides 3 methods : If none of the above methods are used, no presence will be sent to the logged-in user. + +You must configure presence subscription in `AppSettings` during `CometChat.init()` before any presence events will be delivered. See [Setup SDK](/sdk/javascript/setup-sdk) for details. + + You need to register the `UserListener` using the `addUserListener()` method where ever you wish to receive these events in. - -``` + +```javascript let listenerID = "UNIQUE_LISTENER_ID"; CometChat.addUserListener( -listenerID, -new CometChat.UserListener({ - onUserOnline: onlineUser => { - console.log("On User Online:", { onlineUser }); - }, - onUserOffline: offlineUser => { - console.log("On User Offline:", { offlineUser }); - } -}) -); + listenerID, + new CometChat.UserListener({ + onUserOnline: onlineUser => { + console.log("On User Online:", { onlineUser }); + }, + onUserOffline: offlineUser => { + console.log("On User Offline:", { offlineUser }); + } + }) +); ``` - - ```typescript let listenerID: string = "UNIQUE_LISTENER_ID"; @@ -76,18 +78,16 @@ let listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addUserListener( listenerID, new CometChat.UserListener({ - onUserOnline: (onlineUser: CometChat.User) => { - console.log("On User Online:", { onlineUser }); - }, - onUserOffline: (offlineUser: CometChat.User) => { - console.log("On User Offline:", { offlineUser }); - } + onUserOnline: (onlineUser: CometChat.User) => { + console.log("On User Online:", { onlineUser }); + }, + onUserOffline: (offlineUser: CometChat.User) => { + console.log("On User Offline:", { offlineUser }); + } }) ); ``` - - | Parameter | Description | @@ -96,27 +96,23 @@ CometChat.addUserListener( You will receive an object of the `User` class in the listener methods. -We recommend you remove the listener once the activity or view is not in use. - -We suggest adding this method when not in use. + +**Listener Cleanup:** Always remove the listener when the component or view is unmounted/destroyed to prevent memory leaks and duplicate callbacks. Use `CometChat.removeUserListener(listenerID)` in your cleanup logic. + - -``` + +```javascript let listenerID = "UNIQUE_LISTENER_ID"; CometChat.removeUserListener(listenerID); ``` - - ```typescript let listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.removeUserListener(listenerID); ``` - - @@ -140,20 +136,42 @@ When you fetch the list of users, in the [User](/sdk/javascript/user-management# 2. `lastActiveAt` - in case the user is offline, this field holds the timestamp of the time when the user was last online. This can be used to display the Last seen of the user if need be. + + + +| Practice | Details | +| --- | --- | +| Choose the right subscription | Use `subscribePresenceForFriends()` or `subscribePresenceForRoles()` instead of `subscribePresenceForAllUsers()` in apps with many users to reduce unnecessary events | +| Unique listener IDs | Use unique, descriptive listener IDs (e.g., `"chat-screen-presence"`) to avoid accidentally overwriting other listeners | +| Cleanup on unmount | Always call `removeUserListener()` when the component/view is destroyed | +| Combine with user list | Use the `status` field from `UsersRequest` results for initial state, then update via `UserListener` for real-time changes | + + + + +| Symptom | Cause | Fix | +| --- | --- | --- | +| No presence events received | Presence subscription not configured in `AppSettings` | Add `subscribePresenceForAllUsers()`, `subscribePresenceForRoles()`, or `subscribePresenceForFriends()` to your `AppSettingsBuilder` | +| Presence events stop after navigation | Listener was removed or component unmounted | Re-register the listener when the component mounts again | +| Duplicate presence events | Multiple listeners registered with the same or different IDs | Ensure you remove old listeners before adding new ones | +| `lastActiveAt` is `0` or `null` | User has never been online or data not yet available | Handle this case in your UI with a fallback like "Never active" | + + + + ## Next Steps - - Create, update, and manage users + + Fetch user lists with filtering and pagination. - - Fetch user lists with filters and pagination + + Create and update users programmatically. - - Monitor SDK connection state changes + + Monitor SDK connection to CometChat servers. - - Complete reference for all event listeners + + Overview of all available real-time listeners. - diff --git a/sdk/javascript/users-overview.mdx b/sdk/javascript/users-overview.mdx index 6b16f4307..98246d430 100644 --- a/sdk/javascript/users-overview.mdx +++ b/sdk/javascript/users-overview.mdx @@ -18,15 +18,19 @@ The primary aim for our Users functionality is to allow you to quickly retrieve You can begin with [user management](/sdk/javascript/user-management) to sync your users to CometChat. Once that is done, you can [retrieve users](/sdk/javascript/retrieve-users) and display them in your app. ---- - ## Next Steps - - Create and update users in CometChat + + Create, update, and delete users in CometChat. - Fetch and filter user lists with pagination + Fetch user lists with filtering, sorting, and pagination. + + + Monitor real-time online/offline status of users. + + + Block and unblock users to control communication. - \ No newline at end of file + From 2c1d7887ce66abcd8a405941547a6b7d9468a446 Mon Sep 17 00:00:00 2001 From: PrajwalDhuleCC Date: Wed, 18 Feb 2026 15:52:36 +0530 Subject: [PATCH 03/43] docs(javascript-sdk): enhance authentication and key concepts documentation - Add authentication flow sequence diagram to clarify user login process - Convert var declarations to const in code examples for modern JavaScript practices - Add Best Practices section with accordions covering session checks, auth tokens, token expiry, and logout - Add Troubleshooting section addressing common login errors and session persistence issues - Add Glossary Quick Lookup table in key-concepts for quick reference of SDK terminology - Improve code consistency across JavaScript, TypeScript, and Async/Await examples - Enhance developer experience with clearer guidance on production-ready authentication patterns --- sdk/javascript/authentication-overview.mdx | 72 ++++++++++++-- sdk/javascript/key-concepts.mdx | 20 ++++ sdk/javascript/login-listener.mdx | 94 ++++++++++++++++++- .../message-structure-and-hierarchy.mdx | 72 ++++++++++++++ sdk/javascript/overview.mdx | 84 +++++++++++++++-- sdk/javascript/rate-limits.mdx | 70 ++++++++++++++ sdk/javascript/setup-sdk.mdx | 71 +++++++++++++- 7 files changed, 459 insertions(+), 24 deletions(-) diff --git a/sdk/javascript/authentication-overview.mdx b/sdk/javascript/authentication-overview.mdx index 39fdb8c65..2a4f6499e 100644 --- a/sdk/javascript/authentication-overview.mdx +++ b/sdk/javascript/authentication-overview.mdx @@ -33,6 +33,26 @@ Before you log in a user, you must add the user to CometChat. 1. **For proof of concept/MVPs**: Create the user using the [CometChat Dashboard](https://app.cometchat.com). 2. **For production apps**: Use the CometChat [Create User API](https://api-explorer.cometchat.com/reference/creates-user) to create the user when your user signs up in your app. +### Authentication Flow + +```mermaid +sequenceDiagram + participant User + participant YourApp as Your App + participant YourServer as Your Server + participant CometChat as CometChat + + User->>YourApp: Signs up / Logs in + YourApp->>YourServer: Authenticate user + YourServer->>CometChat: Create user (REST API, first time only) + CometChat-->>YourServer: User created + YourServer->>CometChat: Create Auth Token (REST API) + CometChat-->>YourServer: Auth Token + YourServer-->>YourApp: Return Auth Token + YourApp->>CometChat: CometChat.login(authToken) + CometChat-->>YourApp: User object (logged in) +``` + We have setup 5 users for testing having UIDs: `cometchat-uid-1`, `cometchat-uid-2`, `cometchat-uid-3`, `cometchat-uid-4` and `cometchat-uid-5`. @@ -60,8 +80,8 @@ This straightforward authentication method is ideal for proof-of-concept (POC) d ```js -var UID = "UID"; -var authKey = "AUTH_KEY"; +const UID = "UID"; +const authKey = "AUTH_KEY"; CometChat.getLoggedinUser().then( (user) => { @@ -86,8 +106,8 @@ CometChat.getLoggedinUser().then( ```typescript -var UID: string = "cometchat-uid-1", - authKey: string = "AUTH_KEY"; +const UID: string = "cometchat-uid-1"; +const authKey: string = "AUTH_KEY"; CometChat.getLoggedinUser().then( (user: CometChat.User) => { @@ -112,8 +132,8 @@ CometChat.getLoggedinUser().then( ```javascript -var UID = "UID"; -var authKey = "AUTH_KEY"; +const UID = "UID"; +const authKey = "AUTH_KEY"; try { const loggedInUser = await CometChat.getLoggedinUser(); @@ -148,7 +168,7 @@ This advanced authentication procedure does not use the Auth Key directly in you ```js -var authToken = "AUTH_TOKEN"; +const authToken = "AUTH_TOKEN"; CometChat.getLoggedinUser().then( (user) => { @@ -173,7 +193,7 @@ CometChat.getLoggedinUser().then( ```typescript -var authToken: string = "AUTH_TOKEN"; +const authToken: string = "AUTH_TOKEN"; CometChat.getLoggedinUser().then( (user: CometChat.User) => { @@ -198,7 +218,7 @@ CometChat.getLoggedinUser().then( ```javascript -var authToken = "AUTH_TOKEN"; +const authToken = "AUTH_TOKEN"; try { const loggedInUser = await CometChat.getLoggedinUser(); @@ -268,6 +288,40 @@ try { +## Best Practices + + + + Before calling `login()`, use `CometChat.getLoggedinUser()` to check if a session already exists. This avoids unnecessary login calls and prevents session conflicts. + + + Auth Keys are convenient for development but expose your app to security risks in production. Always generate Auth Tokens server-side using the [REST API](https://api-explorer.cometchat.com/reference/create-authtoken) and pass them to the client. + + + Auth Tokens can expire. Implement a mechanism to detect login failures due to expired tokens and re-generate them from your server. Use the [Login Listener](/sdk/javascript/login-listener) to detect session changes. + + + Always call `CometChat.logout()` when your user signs out of your app. This clears the SDK session and stops real-time event delivery, preventing stale data and memory leaks. + + + +## Troubleshooting + + + + The user must be created in CometChat before they can log in. Create the user via the [Dashboard](https://app.cometchat.com) (testing) or [REST API](https://api-explorer.cometchat.com/reference/creates-user) (production) first. + + + Verify your Auth Key matches the one in your [CometChat Dashboard](https://app.cometchat.com) → API & Auth Keys. Ensure you haven't accidentally used the REST API Key instead. + + + Ensure `CometChat.init()` has been called and completed successfully before calling `login()`. Verify your App ID and Region are correct. + + + This can happen if the SDK session was not persisted. Ensure `init()` is called on every app load before checking `getLoggedinUser()`. The SDK stores session data in the browser — clearing browser storage will clear the session. + + + --- ## Next Steps diff --git a/sdk/javascript/key-concepts.mdx b/sdk/javascript/key-concepts.mdx index 4c1bd1475..dcb2b1c3c 100644 --- a/sdk/javascript/key-concepts.mdx +++ b/sdk/javascript/key-concepts.mdx @@ -141,6 +141,26 @@ Any message in CometChat can belong to either one of the below categories For more information, you can refer to the [Message structure and hierarchy guide](/sdk/javascript/message-structure-and-hierarchy). +### Glossary Quick Lookup + +| Term | Definition | Learn More | +| --- | --- | --- | +| UID | Unique User Identifier — alphanumeric string you assign to each user | [Users Overview](/sdk/javascript/users-overview) | +| GUID | Group Unique Identifier — alphanumeric string you assign to each group | [Groups Overview](/sdk/javascript/groups-overview) | +| Auth Key | Development-only credential for quick testing. Never use in production | [Authentication](/sdk/javascript/authentication-overview) | +| Auth Token | Secure, per-user token generated via REST API. Use in production | [Authentication](/sdk/javascript/authentication-overview#login-using-auth-token) | +| REST API Key | Server-side credential for REST API calls. Never expose in client code | [CometChat Dashboard](https://app.cometchat.com) | +| Receiver Type | Specifies if a message target is a `user` or `group` | [Send Message](/sdk/javascript/send-message) | +| Scope | Group member scope: `admin`, `moderator`, or `participant` | [Change Member Scope](/sdk/javascript/group-change-member-scope) | +| Listener | Callback handler for real-time events (messages, presence, calls, groups) | [All Real-Time Listeners](/sdk/javascript/all-real-time-listeners) | +| Conversation | A chat thread between two users or within a group | [Retrieve Conversations](/sdk/javascript/retrieve-conversations) | +| Metadata | Custom JSON data attached to users, groups, or messages | [Send Message](/sdk/javascript/send-message) | +| Tags | String labels for categorizing users, groups, conversations, or messages | [Additional Filtering](/sdk/javascript/additional-message-filtering) | +| RequestBuilder | Builder pattern class for constructing filtered/paginated queries | [Additional Filtering](/sdk/javascript/additional-message-filtering) | +| AppSettings | Configuration object for initializing the SDK (App ID, Region, presence) | [Setup SDK](/sdk/javascript/setup-sdk) | +| Transient Message | Ephemeral message not stored on server (typing indicators, live reactions) | [Transient Messages](/sdk/javascript/transient-messages) | +| Interactive Message | Message with actionable UI elements (forms, cards, buttons) | [Interactive Messages](/sdk/javascript/interactive-messages) | + --- ## Next Steps diff --git a/sdk/javascript/login-listener.mdx b/sdk/javascript/login-listener.mdx index a48019199..b58b9dd97 100644 --- a/sdk/javascript/login-listener.mdx +++ b/sdk/javascript/login-listener.mdx @@ -59,7 +59,7 @@ To add the `LoginListener`, you need to use the `addLoginListener()` method prov ```typescript - var listenerID: string = "UNIQUE_LISTENER_ID"; + const listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addLoginListener( listenerID, new CometChat.LoginListener({ @@ -83,12 +83,86 @@ To add the `LoginListener`, you need to use the `addLoginListener()` method prov +### React Example + +If you're using React, register the listener inside a `useEffect` hook and clean it up on unmount: + + + +```javascript +import { useEffect } from "react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; + +function useLoginListener() { + useEffect(() => { + const listenerID = "LOGIN_LISTENER"; + CometChat.addLoginListener( + listenerID, + new CometChat.LoginListener({ + loginSuccess: (user) => { + console.log("User logged in:", user); + }, + loginFailure: (error) => { + console.log("Login failed:", error); + }, + logoutSuccess: () => { + console.log("User logged out"); + // Redirect to login page, clear app state, etc. + }, + logoutFailure: (error) => { + console.log("Logout failed:", error); + }, + }) + ); + + return () => { + CometChat.removeLoginListener(listenerID); + }; + }, []); +} +``` + + +```typescript +import { useEffect } from "react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; + +function useLoginListener(): void { + useEffect(() => { + const listenerID: string = "LOGIN_LISTENER"; + CometChat.addLoginListener( + listenerID, + new CometChat.LoginListener({ + loginSuccess: (user: CometChat.User) => { + console.log("User logged in:", user); + }, + loginFailure: (error: CometChat.CometChatException) => { + console.log("Login failed:", error); + }, + logoutSuccess: () => { + console.log("User logged out"); + }, + logoutFailure: (error: CometChat.CometChatException) => { + console.log("Logout failed:", error); + }, + }) + ); + + return () => { + CometChat.removeLoginListener(listenerID); + }; + }, []); +} +``` + + + In order to stop receiving events related to login and logout you need to use the removeLoginListener() method provided by the SDK and pass the ID of the listener that needs to be removed. ```js - var listenerID = "UNIQUE_LISTENER_ID"; + const listenerID = "UNIQUE_LISTENER_ID"; CometChat.removeLoginListener(listenerID); ``` @@ -96,7 +170,7 @@ In order to stop receiving events related to login and logout you need to use th ```typescript - var listenerID: string = "UNIQUE_LISTENER_ID"; + const listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.removeLoginListener(listenerID); ``` @@ -108,6 +182,20 @@ In order to stop receiving events related to login and logout you need to use th Always remove login listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. +## Best Practices + + + + Each listener must have a unique ID string. If you register a new listener with the same ID, it will replace the previous one. Use descriptive IDs like `"LOGIN_LISTENER_MAIN"` or `"LOGIN_LISTENER_AUTH_SCREEN"` to avoid accidental overwrites. + + + Use the `logoutSuccess` callback to clear your app's local state, redirect to the login screen, and clean up any other SDK listeners. This ensures a clean state when the user logs out. + + + Register login listeners as early as possible in your app lifecycle (e.g., right after `init()`). Remove them only when the component or page that registered them is destroyed. + + + --- ## Next Steps diff --git a/sdk/javascript/message-structure-and-hierarchy.mdx b/sdk/javascript/message-structure-and-hierarchy.mdx index dc01985ab..389707975 100644 --- a/sdk/javascript/message-structure-and-hierarchy.mdx +++ b/sdk/javascript/message-structure-and-hierarchy.mdx @@ -22,6 +22,74 @@ The below diagram helps you better understand the various message categories and +### Checking Message Category and Type + +You can determine the category and type of any received message using the following methods: + + + +```javascript +// Check message category +const category = message.getCategory(); // "message", "custom", "action", "call", "interactive" + +// Check message type +const type = message.getType(); // "text", "image", "video", "audio", "file", etc. + +// Example: Handle different message categories +switch (category) { + case CometChat.CATEGORY_MESSAGE: + if (type === CometChat.MESSAGE_TYPE.TEXT) { + console.log("Text message:", message.getText()); + } else if (type === CometChat.MESSAGE_TYPE.IMAGE) { + console.log("Image URL:", message.getData().url); + } + break; + case CometChat.CATEGORY_CUSTOM: + console.log("Custom message type:", type, "data:", message.getData()); + break; + case CometChat.CATEGORY_ACTION: + console.log("Action:", message.getAction()); + break; + case CometChat.CATEGORY_CALL: + console.log("Call status:", message.getStatus()); + break; +} +``` + + +```typescript +// Check message category +const category: string = message.getCategory(); +const type: string = message.getType(); + +// Example: Handle different message categories +switch (category) { + case CometChat.CATEGORY_MESSAGE: + if (type === CometChat.MESSAGE_TYPE.TEXT) { + const textMsg = message as CometChat.TextMessage; + console.log("Text message:", textMsg.getText()); + } else if (type === CometChat.MESSAGE_TYPE.IMAGE) { + const mediaMsg = message as CometChat.MediaMessage; + console.log("Image URL:", mediaMsg.getData().url); + } + break; + case CometChat.CATEGORY_CUSTOM: + const customMsg = message as CometChat.CustomMessage; + console.log("Custom message type:", type, "data:", customMsg.getData()); + break; + case CometChat.CATEGORY_ACTION: + const actionMsg = message as CometChat.Action; + console.log("Action:", actionMsg.getAction()); + break; + case CometChat.CATEGORY_CALL: + const callMsg = message as CometChat.Call; + console.log("Call status:", callMsg.getStatus()); + break; +} +``` + + + As you can see in the above diagram, every message belongs to a particular category. A message can belong to either one of the 4 categories 1. Message @@ -43,6 +111,8 @@ A message belonging to the category `message` can be classified into either 1 of In the case of messages that belong to the `custom` category, there are no predefined types. Custom messages can be used by developers to send messages that do not fit in the default category and types provided by CometChat. For messages with the category `custom`, the developers can set their own type to uniquely identify the custom message. A very good example of a custom message would be the sharing of location co-ordinates. In this case, the developer can decide to use the custom message with type set to `location`. +For sending custom messages, see [Send Message → Custom Messages](/sdk/javascript/send-message#custom-message). + ## Interactive An InteractiveMessage is a specialized object that encapsulates an interactive unit within a chat message, such as an embedded form that users can fill out directly within the chat interface. Messages belonging to the interactive category can further be classified into one of the below types: @@ -86,6 +156,8 @@ Messages with the category `call` are Calling related messages. These can belong 1. audio 2. video +For implementing calling, see [Default Calling](/sdk/javascript/default-call) or [Direct Calling](/sdk/javascript/direct-call). + The call messages have a property called status that helps you figure out the status of the call. The status can be either one of the below values: 1. initiated - when a is initiated to a user/group diff --git a/sdk/javascript/overview.mdx b/sdk/javascript/overview.mdx index 430c58008..2c025e641 100644 --- a/sdk/javascript/overview.mdx +++ b/sdk/javascript/overview.mdx @@ -99,6 +99,10 @@ Include the CometChat JavaScript library in your HTML code ### Server Side Rendering (SSR) Compatibility + +**Server-Side Rendering (SSR):** CometChat SDK requires browser APIs (`window`, `WebSocket`). For Next.js, Nuxt, or other SSR frameworks, initialize the SDK only on the client side using dynamic imports or `useEffect`. See the examples below. + + You can use CometChat with SSR frameworks such as [Next.js](https://nextjs.org/) or [NuxtJS](https://nuxtjs.org/) by importing it dynamically on the client side. #### Next.js @@ -374,6 +378,27 @@ CometChat.init(appID, appSetting).then( + +```javascript +let appID = "APP_ID"; +let region = "APP_REGION"; +let appSetting = new CometChat.AppSettingsBuilder() + .subscribePresenceForAllUsers() + .setRegion(region) + .autoEstablishSocketConnection(true) + .setStorageMode(CometChat.StorageMode.SESSION) + .build(); + +try { + await CometChat.init(appID, appSetting); + console.log("Initialization completed successfully"); +} catch (error) { + console.log("Initialization failed with error:", error); +} +``` + + + Make sure you replace the `APP_ID` with your CometChat **App ID** and `APP_REGION` with your **App Region** in the above code. @@ -382,6 +407,10 @@ Make sure you replace the `APP_ID` with your CometChat **App ID** and `APP_REGIO `CometChat.init()` must be called before any other SDK method. Calling `login()`, `sendMessage()`, or registering listeners before `init()` will fail. + +**Auth Key** is for development/testing only. In production, generate **Auth Tokens** on your server using the REST API and pass them to the client. Never expose Auth Keys in production client code. + + ## Register and Login your user Once initialization is successful, you will need to create a user. To create users on the fly, you can use the `createUser()` method. This method takes a `User` object and the `Auth Key` as input parameters and returns the created `User` object if the request is successful. @@ -389,11 +418,11 @@ Once initialization is successful, you will need to create a user. To create use ```js -let authKey = "AUTH_KEY"; -var UID = "user1"; -var name = "Kevin"; +const authKey = "AUTH_KEY"; +const UID = "user1"; +const name = "Kevin"; -var user = new CometChat.User(UID); +const user = new CometChat.User(UID); user.setName(name); @@ -415,7 +444,7 @@ let authKey: string = "AUTH_KEY", UID: string = "user1", name: string = "Kevin"; -var user = new CometChat.User(UID); +const user = new CometChat.User(UID); user.setName(name); @@ -431,6 +460,25 @@ CometChat.createUser(user, authKey).then( + +```javascript +const authKey = "AUTH_KEY"; +const UID = "user1"; +const name = "Kevin"; + +const user = new CometChat.User(UID); +user.setName(name); + +try { + const createdUser = await CometChat.createUser(user, authKey); + console.log("user created", createdUser); +} catch (error) { + console.log("error", error); +} +``` + + + Make sure that `UID` and `name` are specified as these are mandatory fields to create a user. @@ -448,8 +496,8 @@ This straightforward authentication method is ideal for proof-of-concept (POC) d ```js -var UID = "cometchat-uid-1"; -var authKey = "AUTH_KEY"; +const UID = "cometchat-uid-1"; +const authKey = "AUTH_KEY"; CometChat.getLoggedinUser().then( (user) => { @@ -474,8 +522,8 @@ CometChat.getLoggedinUser().then( ```typescript -var UID: string = "cometchat-uid-1", - authKey: string = "AUTH_KEY"; +const UID: string = "cometchat-uid-1"; +const authKey: string = "AUTH_KEY"; CometChat.getLoggedinUser().then( (user: CometChat.User) => { @@ -498,6 +546,24 @@ CometChat.getLoggedinUser().then( + +```javascript +const UID = "cometchat-uid-1"; +const authKey = "AUTH_KEY"; + +try { + const loggedInUser = await CometChat.getLoggedinUser(); + if (!loggedInUser) { + const user = await CometChat.login(UID, authKey); + console.log("Login Successful:", { user }); + } +} catch (error) { + console.log("Login failed with exception:", { error }); +} +``` + + + Make sure you replace the `AUTH_KEY` with your CometChat **AuthKey** in the above code. diff --git a/sdk/javascript/rate-limits.mdx b/sdk/javascript/rate-limits.mdx index 12d15d83e..9c970fd4c 100644 --- a/sdk/javascript/rate-limits.mdx +++ b/sdk/javascript/rate-limits.mdx @@ -42,6 +42,76 @@ However, we do provide the following response headers that you can use to confir `X-Rate-Limit-Remaining: 699` +## Handling Rate-Limited Responses + +When your application receives a `429` response, you should wait before retrying. Here's a recommended approach using exponential backoff: + + + +```javascript +async function callWithRetry(apiCall, maxRetries = 3) { + for (let attempt = 0; attempt < maxRetries; attempt++) { + try { + return await apiCall(); + } catch (error) { + if (error.code === "ERR_TOO_MANY_REQUESTS" && attempt < maxRetries - 1) { + const waitTime = Math.pow(2, attempt) * 1000; // 1s, 2s, 4s + console.log(`Rate limited. Retrying in ${waitTime / 1000}s...`); + await new Promise((resolve) => setTimeout(resolve, waitTime)); + } else { + throw error; + } + } + } +} + +// Usage +const users = await callWithRetry(() => + new CometChat.UsersRequestBuilder().setLimit(30).build().fetchNext() +); +``` + + +```typescript +async function callWithRetry(apiCall: () => Promise, maxRetries: number = 3): Promise { + for (let attempt = 0; attempt < maxRetries; attempt++) { + try { + return await apiCall(); + } catch (error: any) { + if (error.code === "ERR_TOO_MANY_REQUESTS" && attempt < maxRetries - 1) { + const waitTime = Math.pow(2, attempt) * 1000; + console.log(`Rate limited. Retrying in ${waitTime / 1000}s...`); + await new Promise((resolve) => setTimeout(resolve, waitTime)); + } else { + throw error; + } + } + } + throw new Error("Max retries exceeded"); +} + +// Usage +const users: CometChat.User[] = await callWithRetry(() => + new CometChat.UsersRequestBuilder().setLimit(30).build().fetchNext() +); +``` + + + +## Best Practices + + + + If you need to perform many operations (e.g., sending messages to multiple users), space them out over time rather than firing them all at once. Use a queue or throttle mechanism to stay within the per-minute limits. + + + Check the `X-Rate-Limit-Remaining` header in REST API responses to proactively slow down before hitting the limit. This is more efficient than waiting for `429` errors. + + + Core operations (login, create/delete user, create/join group) share a lower cumulative limit of 10,000/min. Standard operations have a higher 20,000/min limit. Plan your architecture accordingly — avoid frequent login/logout cycles. + + + --- ## Next Steps diff --git a/sdk/javascript/setup-sdk.mdx b/sdk/javascript/setup-sdk.mdx index 23f3a1201..c6a0a5943 100644 --- a/sdk/javascript/setup-sdk.mdx +++ b/sdk/javascript/setup-sdk.mdx @@ -45,11 +45,11 @@ Follow steps mentioned in **Add the CometChat dependency** section below to upgr ## Add the CometChat Dependency -### NPM +### Package Manager - -```js + +```bash npm install @cometchat/chat-sdk-javascript ``` @@ -146,6 +146,26 @@ CometChat.init(appID, appSetting).then( + +```javascript +let appID = "APP_ID"; +let region = "APP_REGION"; +let appSetting = new CometChat.AppSettingsBuilder() + .subscribePresenceForAllUsers() + .setRegion(region) + .autoEstablishSocketConnection(true) + .build(); + +try { + await CometChat.init(appID, appSetting); + console.log("Initialization completed successfully"); +} catch (error) { + console.log("Initialization failed with error:", error); +} +``` + + + Make sure you replace the `APP_ID` with your CometChat **App ID** and `APP_REGION` with your **App Region** in the above code. @@ -163,6 +183,51 @@ Make sure you replace the `APP_ID` with your CometChat **App ID** and `APP_REGIO | appID | CometChat App ID | | appSetting | An object of the AppSettings class. | +### AppSettings Configuration Options + +| Method | Description | Default | +| --- | --- | --- | +| `setRegion(region)` | The region where your app was created (`us`, `eu`, `in`, `in-private`) | Required | +| `subscribePresenceForAllUsers()` | Subscribe to presence events for all users | — | +| `subscribePresenceForRoles(roles)` | Subscribe to presence events for specific roles | — | +| `subscribePresenceForFriends()` | Subscribe to presence events for friends only | — | +| `autoEstablishSocketConnection(bool)` | Let the SDK manage WebSocket connections internally | `true` | +| `overrideAdminHost(adminHost)` | Use a custom admin URL (dedicated deployment) | — | +| `overrideClientHost(clientHost)` | Use a custom client URL (dedicated deployment) | — | +| `setStorageMode(storageMode)` | Configure local storage mode (`CometChat.StorageMode.SESSION` for session storage) | — | + + +**Server-Side Rendering (SSR):** CometChat SDK requires browser APIs (`window`, `WebSocket`). For Next.js, Nuxt, or other SSR frameworks, initialize the SDK only on the client side using dynamic imports or `useEffect`. See the [Overview page](/sdk/javascript/overview#server-side-rendering-ssr-compatibility) for framework-specific examples. + + +## Best Practices + + + + Call `CometChat.init()` as early as possible in your application lifecycle — typically in your entry file (`index.js`, `main.js`, or `App.js`). It only needs to be called once per app session. + + + Use `CometChat.getLoggedinUser()` to check if a user session already exists before calling `login()`. This avoids unnecessary login calls and improves app startup time. + + + Store your App ID, Region, and Auth Key in environment variables rather than hardcoding them. This makes it easier to switch between development and production environments. + + + +## Troubleshooting + + + + Verify your App ID is correct and matches the one in your [CometChat Dashboard](https://app.cometchat.com). Ensure you're using the right region (`us`, `eu`, `in`, or `in-private`). + + + This means `init()` was not called or hasn't completed before other SDK methods were invoked. Ensure `init()` resolves successfully before calling `login()`, `sendMessage()`, or registering listeners. + + + If you're behind a corporate firewall or proxy, WebSocket connections may be blocked. Check your network configuration. You can also manage WebSocket connections manually — see [Managing WebSocket Connections](/sdk/javascript/managing-web-sockets-connections-manually). + + + --- ## Next Steps From 2cdcb8242f3e0481134c456d0f76dd956f0189e4 Mon Sep 17 00:00:00 2001 From: PrajwalDhuleCC Date: Wed, 18 Feb 2026 16:55:30 +0530 Subject: [PATCH 04/43] docs(javascript-sdk): enhance message handling documentation with best practices and troubleshooting - Add best practices accordion to additional-message-filtering.mdx with filter combination strategies and performance tips - Add troubleshooting accordion to additional-message-filtering.mdx with common filtering issues and solutions - Add best practices accordion to receive-message.mdx covering listener management and message fetching patterns - Add troubleshooting accordion to receive-message.mdx addressing listener, pagination, and message count issues - Add async/await tab example to send-message.mdx for modern JavaScript syntax - Replace var declarations with const/let throughout send-message.mdx code examples for consistency - Add best practices accordion to send-message.mdx with message type selection and error handling guidance - Add troubleshooting accordion to send-message.mdx for common sending and media upload issues - Improve code quality and developer experience across all JavaScript SDK documentation --- .../additional-message-filtering.mdx | 18 +++++ sdk/javascript/receive-message.mdx | 23 +++++- sdk/javascript/send-message.mdx | 70 +++++++++++++++---- sdk/javascript/threaded-messages.mdx | 25 +++++-- 4 files changed, 115 insertions(+), 21 deletions(-) diff --git a/sdk/javascript/additional-message-filtering.mdx b/sdk/javascript/additional-message-filtering.mdx index 8b97c9307..d37795d7b 100644 --- a/sdk/javascript/additional-message-filtering.mdx +++ b/sdk/javascript/additional-message-filtering.mdx @@ -1509,6 +1509,24 @@ let GUID: string = "GUID", + +- **Combine filters strategically**: Use `setCategories()` with `setTypes()` for precise filtering +- **Set reasonable limits**: Use 30-50 messages per fetch for optimal performance +- **Use timestamps for sync**: `setUpdatedAfter()` helps sync local cache with server +- **Hide deleted messages in UI**: Use `hideDeletedMessages(true)` for cleaner message lists +- **Filter blocked users**: Use `hideMessagesFromBlockedUsers(true)` to respect user preferences +- **Reuse MessagesRequest**: Call `fetchPrevious()`/`fetchNext()` on the same object for pagination + + + +| Issue | Cause | Solution | +|-------|-------|----------| +| No messages returned | Conflicting filters | Simplify filters and add them one at a time | +| Missing message types | Category not included | Ensure category matches type (e.g., "message" for "text") | +| Pagination not working | New request object | Reuse the same MessagesRequest object for pagination | +| Thread replies included | `hideReplies` not set | Add `.hideReplies(true)` to exclude thread messages | +| Deleted messages showing | Default behavior | Add `.hideDeletedMessages(true)` to filter them out | + --- diff --git a/sdk/javascript/receive-message.mdx b/sdk/javascript/receive-message.mdx index 78400ed03..ed1cd686d 100644 --- a/sdk/javascript/receive-message.mdx +++ b/sdk/javascript/receive-message.mdx @@ -151,7 +151,7 @@ let UID = "UID"; let limit = 30; let latestId = await CometChat.getLastDeliveredMessageId(); -var messagesRequest = new CometChat.MessagesRequestBuilder() +let messagesRequest = new CometChat.MessagesRequestBuilder() .setUID(UID) .setMessageId(latestId) .setLimit(limit) @@ -204,7 +204,7 @@ let GUID = "GUID"; let limit = 30; let latestId = await CometChat.getLastDeliveredMessageId(); -var messagesRequest = new CometChat.MessagesRequestBuilder() +let messagesRequest = new CometChat.MessagesRequestBuilder() .setGUID(GUID) .setMessageId(latestId) .setLimit(limit) @@ -992,6 +992,25 @@ CometChat.getUnreadMessageCountForAllGroups().then( It returns an object which will contain the GUID as the key and the unread message count as the value. + +- **Remove listeners on cleanup**: Always call `removeMessageListener()` when components unmount to prevent memory leaks +- **Use unique listener IDs**: Generate unique IDs per component/screen to avoid conflicts +- **Handle all message types**: Implement handlers for text, media, and custom messages +- **Fetch missed messages on app resume**: Call `getLastDeliveredMessageId()` and fetch messages since that ID +- **Paginate message history**: Use `setLimit()` with reasonable values (30-50) and call `fetchPrevious()` for more +- **Filter by category/type**: Use `setCategories()` and `setTypes()` to fetch only relevant messages + + + +| Issue | Cause | Solution | +|-------|-------|----------| +| Not receiving messages | Listener not added | Verify `addMessageListener()` was called with correct ID | +| Duplicate messages | Multiple listeners | Ensure only one listener per ID; remove on unmount | +| Missing messages | App was offline | Use `getLastDeliveredMessageId()` + `fetchNext()` for missed messages | +| Wrong message count | Blocked users included | Use `hideMessagesFromBlockedUsers` parameter | +| History not loading | Wrong method | Use `fetchPrevious()` for history, `fetchNext()` for missed messages | + + --- ## Next Steps diff --git a/sdk/javascript/send-message.mdx b/sdk/javascript/send-message.mdx index cd5ebf4fc..60aa359e5 100644 --- a/sdk/javascript/send-message.mdx +++ b/sdk/javascript/send-message.mdx @@ -196,6 +196,27 @@ CometChat.sendMessage(textMessage).then( + +```javascript +try { + const receiverID = "UID"; + const messageText = "Hello world!"; + const receiverType = CometChat.RECEIVER_TYPE.USER; + const textMessage = new CometChat.TextMessage( + receiverID, + messageText, + receiverType + ); + + const message = await CometChat.sendMessage(textMessage); + console.log("Message sent successfully:", message); +} catch (error) { + console.log("Message sending failed with error:", error); +} +``` + + + ### Set Quoted Message Id @@ -426,11 +447,11 @@ Getting file Object: @@ -573,11 +594,11 @@ Getting file Object: @@ -857,11 +878,11 @@ Getting files: @@ -1752,6 +1773,25 @@ It is also possible to send interactive messages from CometChat, to know more [c + +- **Use appropriate message types**: Choose text, media, or custom messages based on your content +- **Add metadata for context**: Use `setMetadata()` to attach location, device info, or other contextual data +- **Tag important messages**: Use `setTags()` to mark messages for easy filtering (e.g., "starred", "important") +- **Handle errors gracefully**: Always implement error callbacks to handle network issues or invalid parameters +- **Use async/await for cleaner code**: Modern JavaScript syntax makes message sending code more readable +- **Validate file types**: Before sending media messages, verify the file type matches the message type (IMAGE, VIDEO, AUDIO, FILE) + + + +| Issue | Cause | Solution | +|-------|-------|----------| +| Message not sent | User not logged in | Ensure `CometChat.login()` succeeded before sending | +| Media upload fails | File too large | Check file size limits in your CometChat plan | +| Custom message not received | Missing listener | Ensure receiver has `onCustomMessageReceived` handler | +| Metadata not appearing | Wrong method | Use `setMetadata()` before calling send method | +| Quoted message fails | Invalid message ID | Verify the quoted message ID exists | + + --- ## Next Steps diff --git a/sdk/javascript/threaded-messages.mdx b/sdk/javascript/threaded-messages.mdx index 542882774..90704dd18 100644 --- a/sdk/javascript/threaded-messages.mdx +++ b/sdk/javascript/threaded-messages.mdx @@ -100,8 +100,8 @@ To add a MessageListener, you can use the `addMessageListener()` method of the S ```javascript -var listenerID = "UNIQUE_LISTENER_ID"; -var activeThreadId = 100; +const listenerID = "UNIQUE_LISTENER_ID"; +const activeThreadId = 100; CometChat.addMessageListener( listenerID, @@ -129,8 +129,8 @@ new CometChat.MessageListener({ ```typescript -var listenerID: string = "UNIQUE_LISTENER_ID", - activeThreadId: number = 100; +const listenerID: string = "UNIQUE_LISTENER_ID"; +const activeThreadId: number = 100; CometChat.addMessageListener( listenerID, @@ -300,6 +300,23 @@ messagesRequest.fetchPrevious().then( The above snippet will return messages between the logged in user and `cometchat-uid-1` excluding all the threaded messages belonging to the same conversation. + +- **Track active thread ID**: Store the current thread's `parentMessageId` to filter incoming messages +- **Use `hideReplies(true)`**: Exclude thread replies from main conversation to avoid clutter +- **Paginate thread messages**: Use `setLimit()` and `fetchPrevious()` for large threads +- **Remove listeners on thread close**: Clean up message listeners when user exits a thread view +- **Show reply count**: Display the number of replies on parent messages to indicate thread activity + + + +| Issue | Cause | Solution | +|-------|-------|----------| +| Thread replies in main chat | `hideReplies` not set | Add `.hideReplies(true)` to MessagesRequestBuilder | +| Missing thread messages | Wrong parent ID | Verify `setParentMessageId()` uses correct message ID | +| Real-time messages not filtered | Not checking parent ID | Compare `getParentMessageId()` with active thread ID | +| Empty thread | Parent message deleted | Handle case where parent message no longer exists | + + --- ## Next Steps From c14b74b8bb32a4a774f3ecc76b58f4af84448800 Mon Sep 17 00:00:00 2001 From: PrajwalDhuleCC Date: Fri, 20 Feb 2026 17:29:46 +0530 Subject: [PATCH 05/43] docs(javascript-sdk): enhance calling and messaging documentation with best practices and troubleshooting - Convert troubleshooting tables to formatted lists with detailed explanations in additional-message-filtering.mdx - Fix formatting inconsistencies (bold markdown) across call-logs.mdx, calling-overview.mdx, and calling-setup.mdx - Add comprehensive best practices and troubleshooting sections to call-logs.mdx with AccordionGroup - Expand calling-overview.mdx with best practices and troubleshooting guidance for different calling approaches - Restructure code examples in call-logs.mdx with Tabs component for JavaScript, TypeScript, and Async/Await variants - Add best practices and troubleshooting sections to calling-setup.mdx, default-call.mdx, and direct-call.mdx - Enhance delete-conversation.mdx, delivery-read-receipts.mdx, and other messaging docs with structured guidance - Improve documentation clarity and consistency across 19 JavaScript SDK documentation files - Provide users with actionable troubleshooting steps and implementation best practices for common issues --- .../additional-message-filtering.mdx | 12 +- sdk/javascript/call-logs.mdx | 71 +++++++-- sdk/javascript/calling-overview.mdx | 18 +++ sdk/javascript/calling-setup.mdx | 18 +++ sdk/javascript/default-call.mdx | 19 +++ sdk/javascript/delete-conversation.mdx | 13 ++ sdk/javascript/delivery-read-receipts.mdx | 141 ++++++++++-------- sdk/javascript/direct-call.mdx | 27 +++- sdk/javascript/mentions.mdx | 23 ++- sdk/javascript/reactions.mdx | 15 ++ sdk/javascript/receive-message.mdx | 12 +- sdk/javascript/recording.mdx | 19 +++ sdk/javascript/send-message.mdx | 12 +- sdk/javascript/session-timeout.mdx | 17 +++ sdk/javascript/standalone-calling.mdx | 19 +++ sdk/javascript/threaded-messages.mdx | 10 +- sdk/javascript/typing-indicators.mdx | 15 ++ sdk/javascript/user-management.mdx | 24 +-- sdk/javascript/user-presence.mdx | 24 +-- 19 files changed, 365 insertions(+), 144 deletions(-) diff --git a/sdk/javascript/additional-message-filtering.mdx b/sdk/javascript/additional-message-filtering.mdx index d37795d7b..aa8916377 100644 --- a/sdk/javascript/additional-message-filtering.mdx +++ b/sdk/javascript/additional-message-filtering.mdx @@ -1519,13 +1519,11 @@ let GUID: string = "GUID", -| Issue | Cause | Solution | -|-------|-------|----------| -| No messages returned | Conflicting filters | Simplify filters and add them one at a time | -| Missing message types | Category not included | Ensure category matches type (e.g., "message" for "text") | -| Pagination not working | New request object | Reuse the same MessagesRequest object for pagination | -| Thread replies included | `hideReplies` not set | Add `.hideReplies(true)` to exclude thread messages | -| Deleted messages showing | Default behavior | Add `.hideDeletedMessages(true)` to filter them out | +- **No messages returned** — Conflicting filters may cancel each other out. Simplify filters and add them one at a time to isolate the issue. +- **Missing message types** — Ensure the category matches the type (e.g., category `"message"` for type `"text"`). +- **Pagination not working** — Reuse the same `MessagesRequest` object for `fetchPrevious()` / `fetchNext()` calls. Creating a new object resets pagination. +- **Thread replies included** — Add `.hideReplies(true)` to exclude thread messages from the main conversation. +- **Deleted messages showing** — Add `.hideDeletedMessages(true)` to filter them out. This is not enabled by default. --- diff --git a/sdk/javascript/call-logs.mdx b/sdk/javascript/call-logs.mdx index 9a46620f0..9fb4addad 100644 --- a/sdk/javascript/call-logs.mdx +++ b/sdk/javascript/call-logs.mdx @@ -64,7 +64,7 @@ let callLogRequestBuilder = new CometChatCalls.CallLogRequestBuilder() ### Fetch Next -The**`fetchNext()`**method retrieves the next set of call logs. +The `fetchNext()` method retrieves the next set of call logs. ```javascript let callLogRequestBuilder = new CometChatCalls.CallLogRequestBuilder() @@ -84,7 +84,7 @@ callLogRequestBuilder.fetchNext() ### Fetch Previous -The**`fetchPrevious()`**method retrieves the previous set of call logs. +The `fetchPrevious()` method retrieves the previous set of call logs. ```javascript let callLogRequestBuilder = new CometChatCalls.CallLogRequestBuilder() @@ -104,21 +104,68 @@ callLogRequestBuilder.fetchPrevious() ## Get Call Details -To retrieve the specific details of a call, use the**`getCallDetails()`**method. This method requires the Auth token of the logged-in user and the session ID along with a callback listener. +To retrieve the specific details of a call, use the `getCallDetails()` method. This method requires the Auth token of the logged-in user and the session ID along with a callback listener. + + ```javascript -var sessionID = "SESSION_ID"; -CometChatCalls.getCallDetails(sessionID, authToken) -.then((callLogs: Array) => { - console.log(callLogs); - }) - .catch(err => { - console.log(err); - }); +const sessionID = "SESSION_ID"; +CometChatCalls.getCallDetails(sessionID, authToken).then( + (callLogs) => { + console.log("Call details:", callLogs); + }, + (error) => { + console.log("Error fetching call details:", error); + } +); +``` + + +```typescript +const sessionID: string = "SESSION_ID"; +CometChatCalls.getCallDetails(sessionID, authToken).then( + (callLogs: Array) => { + console.log("Call details:", callLogs); + }, + (error: any) => { + console.log("Error fetching call details:", error); + } +); ``` + + +```javascript +const sessionID = "SESSION_ID"; +try { + const callLogs = await CometChatCalls.getCallDetails(sessionID, authToken); + console.log("Call details:", callLogs); +} catch (error) { + console.log("Error fetching call details:", error); +} +``` + + -Note: Replace**`"SESSION_ID"`**with the ID of the session you are interested in. +Note: Replace `"SESSION_ID"` with the ID of the session you are interested in. + +--- + + + - **Paginate results** — Use `setLimit()` with reasonable values (30-50) and implement pagination with `fetchNext()` / `fetchPrevious()` for large call histories. + - **Filter by category** — Use `setCallCategory("call")` or `setCallCategory("meet")` to separate regular calls from meetings. + - **Cache auth tokens** — Store the user's auth token rather than fetching it repeatedly for each call log request. + - **Handle empty results** — Always check if the returned array is empty before processing call logs. + - **Use appropriate filters** — Combine filters like `setCallDirection()`, `setCallStatus()`, and `setHasRecording()` to narrow down results efficiently. + + + - **Empty call logs returned** — Verify the auth token is valid and belongs to a user who has participated in calls. Check that filters aren't too restrictive. + - **Auth token errors** — Ensure you're using `loggedInUser.getAuthToken()` and that the user is logged in before fetching call logs. + - **Missing recordings** — Use `setHasRecording(true)` to filter only calls with recordings. Recordings may take time to process after a call ends. + - **Pagination not working** — Make sure you're reusing the same `CallLogRequestBuilder` instance for `fetchNext()` / `fetchPrevious()` calls. + - **Session ID not found** — The session ID must match an existing call session. Verify the session ID is correct and the call has completed. + + --- diff --git a/sdk/javascript/calling-overview.mdx b/sdk/javascript/calling-overview.mdx index 863414550..ce140dedf 100644 --- a/sdk/javascript/calling-overview.mdx +++ b/sdk/javascript/calling-overview.mdx @@ -115,6 +115,24 @@ Use this when you want: +--- + + + + - **Choose the right approach** — Use Ringing for full call experience with notifications, Call Session for custom UI, and Standalone for minimal SDK footprint. + - **Initialize both SDKs** — For Ringing and Call Session flows, ensure both Chat SDK and Calls SDK are initialized before starting calls. + - **Handle all call states** — Implement handlers for accepted, rejected, cancelled, busy, and ended states to provide a complete user experience. + - **Clean up resources** — Always call `CometChatCalls.endSession()` when leaving a call to release camera, microphone, and network resources. + - **Test on multiple devices** — Voice and video calling behavior can vary across browsers and devices. Test thoroughly on your target platforms. + + + - **No audio/video** — Check browser permissions for camera and microphone. Ensure the user granted access when prompted. + - **Call not connecting** — Verify both participants have initialized the Calls SDK and are using the same session ID. + - **One-way audio** — This often indicates a firewall or NAT issue. CometChat uses TURN servers, but corporate networks may block WebRTC traffic. + - **Poor call quality** — Check network bandwidth. Video calls require stable connections. Consider offering audio-only fallback for poor connections. + - **Calls SDK not found** — Ensure `@cometchat/calls-sdk-javascript` is installed and imported correctly. + + --- diff --git a/sdk/javascript/calling-setup.mdx b/sdk/javascript/calling-setup.mdx index 0c61d682d..2ca0ea53f 100644 --- a/sdk/javascript/calling-setup.mdx +++ b/sdk/javascript/calling-setup.mdx @@ -141,6 +141,24 @@ Make sure you replace the `APP_ID` with your CometChat **App ID** and `REGION` w | ----------------- | ---------------------------------------- | | `callAppSettings` | An object of the `CallAppSettings` class | +--- + + + + - **Initialize once** — Call `CometChatCalls.init()` only once at app startup, typically in your main entry file (index.js, App.js). + - **Initialize Chat SDK first** — Unless using [Standalone Calling](/sdk/javascript/standalone-calling), always initialize the Chat SDK (`CometChat.init()`) before the Calls SDK. + - **Handle initialization errors** — Always implement error handling for the init promise to catch configuration issues early. + - **Use environment variables** — Store App ID and Region in environment variables rather than hardcoding them. + - **Verify initialization** — Before making any Calls SDK method calls, ensure initialization completed successfully. + + + - **"CometChatCalls is not initialized"** — Ensure `CometChatCalls.init()` completed successfully before calling other methods. Check that the promise resolved without errors. + - **Invalid App ID or Region** — Verify your App ID and Region match exactly what's shown in the [CometChat Dashboard](https://app.cometchat.com). Region is case-sensitive (e.g., "us", "eu"). + - **CORS errors** — If using a custom host, ensure your domain is whitelisted in the CometChat Dashboard under App Settings. + - **Module not found** — Verify the package is installed correctly with `npm list @cometchat/calls-sdk-javascript`. Try removing node_modules and reinstalling. + - **Chat SDK not initialized** — If you see errors about missing user context, ensure `CometChat.init()` and `CometChat.login()` completed before initializing the Calls SDK. + + --- diff --git a/sdk/javascript/default-call.mdx b/sdk/javascript/default-call.mdx index 2705fe7b4..2ed0138a6 100644 --- a/sdk/javascript/default-call.mdx +++ b/sdk/javascript/default-call.mdx @@ -557,6 +557,25 @@ Always remove call listeners when they're no longer needed (e.g., on component u --- + + + - **Store session ID** — Save the session ID from `initiateCall()` response immediately. You'll need it for accept, reject, cancel, and starting the session. + - **Handle all call states** — Implement handlers for all listener events (accepted, rejected, cancelled, busy, ended) to provide a complete user experience. + - **Show appropriate UI** — Display outgoing call UI after `initiateCall()`, incoming call UI in `onIncomingCallReceived()`, and dismiss UI in rejection/cancellation callbacks. + - **Clean up on unmount** — Remove call listeners when the component unmounts or when navigating away from the call screen. + - **Handle busy state** — Check if the user is already on a call before accepting a new one. Use `CALL_STATUS.BUSY` to inform the caller. + + + - **Call not received** — Verify the receiver is logged in and has registered the call listener. Check that the receiver UID/GUID is correct. + - **Duplicate call events** — Ensure you're using unique listener IDs and removing listeners when no longer needed. Multiple registrations with the same ID replace the previous listener. + - **Session not starting after accept** — After `acceptCall()` succeeds, you must generate a call token and call `startSession()`. The accept only signals intent, it doesn't start the media session. + - **Call stuck in ringing state** — Implement timeout logic to auto-cancel calls that aren't answered within a reasonable time (e.g., 30-60 seconds). + - **"Call already in progress" error** — Use `CometChat.getActiveCall()` to check for existing calls before initiating a new one. + + + +--- + ## Next Steps diff --git a/sdk/javascript/delete-conversation.mdx b/sdk/javascript/delete-conversation.mdx index 045d2f33e..edfe350d3 100644 --- a/sdk/javascript/delete-conversation.mdx +++ b/sdk/javascript/delete-conversation.mdx @@ -102,6 +102,19 @@ The `deleteConversation()` method takes the following parameters: | conversationWith | `UID` of the user or `GUID` of the group whose conversation you want to delete. | YES | | conversationType | The type of conversation you want to delete . It can be either `user` or `group`. | YES | + +- **Confirm before deleting**: Always show a confirmation dialog before deleting conversations +- **Update UI immediately**: Remove the conversation from the list optimistically, then handle errors +- **Handle errors gracefully**: If deletion fails, restore the conversation in the UI +- **Clear local cache**: If you cache conversations locally, remove them after successful deletion + + + +- **Conversation still visible after deletion** — Refresh the conversation list after deletion. Update your UI immediately on success. +- **Delete fails** — Verify the UID or GUID exists and is correct. +- **Other user still sees messages** — The SDK deletes for the logged-in user only. Use the REST API to delete for all participants. +- **"Conversation not found" error** — The conversation may already be deleted, or the `conversationType` doesn't match. Ensure it's `user` or `group` as appropriate. + --- diff --git a/sdk/javascript/delivery-read-receipts.mdx b/sdk/javascript/delivery-read-receipts.mdx index 779976167..446e577fc 100644 --- a/sdk/javascript/delivery-read-receipts.mdx +++ b/sdk/javascript/delivery-read-receipts.mdx @@ -59,10 +59,10 @@ Ideally, you would like to mark all the messages as delivered for any conversati ```javascript -var messageId = "MESSAGE_ID"; -var receiverId = "MESSAGE_RECEIVER_UID"; -var receiverType = "user"; -var senderId = "MESSAGE_SENDER_UID"; +const messageId = "MESSAGE_ID"; +const receiverId = "MESSAGE_RECEIVER_UID"; +const receiverType = "user"; +const senderId = "MESSAGE_SENDER_UID"; CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId); ``` @@ -70,10 +70,10 @@ CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId); ```javascript -var messageId = "MESSAGE_ID"; -var receiverId = "MESSAGE_RECEIVER_GUID"; -var receiverType = "group"; -var senderId = "MESSAGE_SENDER_UID"; +const messageId = "MESSAGE_ID"; +const receiverId = "MESSAGE_RECEIVER_GUID"; +const receiverType = "group"; +const senderId = "MESSAGE_SENDER_UID"; CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId); ``` @@ -81,10 +81,10 @@ CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId); ```typescript -var messageId: string = "MESSAGE_ID"; -var receiverId: string = "MESSAGE_RECEIVER_UID"; -var receiverType: string = "user"; -var senderId: string = "MESSAGE_SENDER_UID"; +const messageId: string = "MESSAGE_ID"; +const receiverId: string = "MESSAGE_RECEIVER_UID"; +const receiverType: string = "user"; +const senderId: string = "MESSAGE_SENDER_UID"; CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId); ``` @@ -92,10 +92,10 @@ CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId); ```typescript -var messageId: string = "MESSAGE_ID"; -var receiverId: string = "MESSAGE_RECEIVER_GUID"; -var receiverType: string = "group"; -var senderId: string = "MESSAGE_SENDER_UID"; +const messageId: string = "MESSAGE_ID"; +const receiverId: string = "MESSAGE_RECEIVER_GUID"; +const receiverType: string = "group"; +const senderId: string = "MESSAGE_SENDER_UID"; CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId); ``` @@ -154,10 +154,10 @@ CometChat.markAsDelivered( ```typescript -var messageId: string = "MESSAGE_ID"; -var receiverId: string = "MESSAGE_SENDER_UID"; -var receiverType: string = "user"; -var senderId: string = "MESSAGE_SENDER_UID"; +const messageId: string = "MESSAGE_ID"; +const receiverId: string = "MESSAGE_SENDER_UID"; +const receiverType: string = "user"; +const senderId: string = "MESSAGE_SENDER_UID"; CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId).then( () => { console.log("mark as delivered success."); @@ -175,10 +175,10 @@ CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId).then( ```typescript -var messageId: string = "MESSAGE_ID"; -var receiverId: string = "MESSAGE_RECEIVER_GUID"; -var receiverType: string = "group"; -var senderId: string = "MESSAGE_SENDER_UID"; +const messageId: string = "MESSAGE_ID"; +const receiverId: string = "MESSAGE_RECEIVER_GUID"; +const receiverType: string = "group"; +const senderId: string = "MESSAGE_SENDER_UID"; CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId).then( () => { console.log("mark as delivered success."); @@ -270,8 +270,8 @@ This method will mark all messages in the conversation as delivered. ```javascript -var conversationWith = "USER_UID"; -var conversationType = "user"; +const conversationWith = "USER_UID"; +const conversationType = "user"; CometChat.markConversationAsDelivered(conversationWith, conversationType).then( (response) => { @@ -286,8 +286,8 @@ CometChat.markConversationAsDelivered(conversationWith, conversationType).then( ```javascript -var conversationWith = "GROUP_GUID"; -var conversationType = "group"; +const conversationWith = "GROUP_GUID"; +const conversationType = "group"; CometChat.markConversationAsDelivered(conversationWith, conversationType).then( (response) => { @@ -302,8 +302,8 @@ CometChat.markConversationAsDelivered(conversationWith, conversationType).then( ```typescript -var conversationWith: string = "USER_UID"; -var conversationType: string = "user"; +const conversationWith: string = "USER_UID"; +const conversationType: string = "user"; CometChat.markConversationAsDelivered(conversationWith, conversationType).then( (response: string) => { @@ -318,8 +318,8 @@ CometChat.markConversationAsDelivered(conversationWith, conversationType).then( ```typescript -var conversationWith: string = "GROUP_GUID"; -var conversationType: string = "group"; +const conversationWith: string = "GROUP_GUID"; +const conversationType: string = "group"; CometChat.markConversationAsDelivered(conversationWith, conversationType).then( (response: string) => { @@ -356,10 +356,10 @@ Ideally, you would like to mark all the messages as read for any conversation wh ```javascript -var messageId = "MESSAGE_ID"; -var receiverId = "MESSAGE_SENDER_UID"; -var receiverType = "user"; -var senderId = "MESSAGE_SENDER_UID"; +const messageId = "MESSAGE_ID"; +const receiverId = "MESSAGE_SENDER_UID"; +const receiverType = "user"; +const senderId = "MESSAGE_SENDER_UID"; CometChat.markAsRead(messageId, receiverId, receiverType, senderId); ``` @@ -367,9 +367,9 @@ CometChat.markAsRead(messageId, receiverId, receiverType, senderId); ```javascript -var receiverId = "MESSAGE_RECEIVER_GUID"; -var receiverType = "group"; -var senderId = "MESSAGE_SENDER_UID"; +const receiverId = "MESSAGE_RECEIVER_GUID"; +const receiverType = "group"; +const senderId = "MESSAGE_SENDER_UID"; CometChat.markAsRead(messageId, receiverId, receiverType, senderId); ``` @@ -377,10 +377,10 @@ CometChat.markAsRead(messageId, receiverId, receiverType, senderId); ```typescript -var messageId: string = "MESSAGE_ID"; -var receiverId: string = "MESSAGE_SENDER_UID"; -var receiverType: string = "user"; -var senderId: string = "MESSAGE_SENDER_UID"; +const messageId: string = "MESSAGE_ID"; +const receiverId: string = "MESSAGE_SENDER_UID"; +const receiverType: string = "user"; +const senderId: string = "MESSAGE_SENDER_UID"; CometChat.markAsRead(messageId, receiverId, receiverType, senderId); ``` @@ -388,10 +388,10 @@ CometChat.markAsRead(messageId, receiverId, receiverType, senderId); ```typescript -var messageId: string = "MESSAGE_ID"; -var receiverId: string = "MESSAGE_RECEIVER_GUID"; -var receiverType: string = "group"; -var senderId: string = "MESSAGE_SENDER_UID"; +const messageId: string = "MESSAGE_ID"; +const receiverId: string = "MESSAGE_RECEIVER_GUID"; +const receiverType: string = "group"; +const senderId: string = "MESSAGE_SENDER_UID"; CometChat.markAsRead(messageId, receiverId, receiverType, senderId); ``` @@ -444,10 +444,10 @@ CometChat.markAsRead( ```typescript -var messageId: string = "MESSAGE_ID"; -var receiverId: string = "MESSAGE_SENDER_UID"; -var receiverType: string = "user"; -var senderId: string = "MESSAGE_SENDER_UID"; +const messageId: string = "MESSAGE_ID"; +const receiverId: string = "MESSAGE_SENDER_UID"; +const receiverType: string = "user"; +const senderId: string = "MESSAGE_SENDER_UID"; CometChat.markAsRead(messageId, receiverId, receiverType, senderId).then( () => { console.log("mark as read success."); @@ -462,10 +462,10 @@ CometChat.markAsRead(messageId, receiverId, receiverType, senderId).then( ```typescript -var messageId: string = "MESSAGE_ID"; -var receiverId: string = "MESSAGE_RECEIVER_GUID"; -var receiverType: string = "group"; -var senderId: string = "MESSAGE_SENDER_UID"; +const messageId: string = "MESSAGE_ID"; +const receiverId: string = "MESSAGE_RECEIVER_GUID"; +const receiverType: string = "group"; +const senderId: string = "MESSAGE_SENDER_UID"; CometChat.markAsRead(messageId, receiverId, receiverType, senderId).then( () => { console.log("mark as read success."); @@ -548,8 +548,8 @@ This method will mark all messages in the conversation as read. ```javascript -var conversationWith = "USER_UID"; -var conversationType = "user"; +const conversationWith = "USER_UID"; +const conversationType = "user"; CometChat.markConversationAsRead(conversationWith, conversationType).then( (response) => { @@ -564,8 +564,8 @@ CometChat.markConversationAsRead(conversationWith, conversationType).then( ```javascript -var conversationWith = "GROUP_GUID"; -var conversationType = "group"; +const conversationWith = "GROUP_GUID"; +const conversationType = "group"; CometChat.markConversationAsRead(conversationWith, conversationType).then( (response) => { @@ -580,8 +580,8 @@ CometChat.markConversationAsRead(conversationWith, conversationType).then( ```typescript -var conversationWith: string = "USER_UID"; -var conversationType: string = "user"; +const conversationWith: string = "USER_UID"; +const conversationType: string = "user"; CometChat.markConversationAsRead(conversationWith, conversationType).then( (response: string) => { @@ -596,8 +596,8 @@ CometChat.markConversationAsRead(conversationWith, conversationType).then( ```typescript -var conversationWith: string = "GROUP_GUID"; -var conversationType: string = "group"; +const conversationWith: string = "GROUP_GUID"; +const conversationType: string = "group"; CometChat.markConversationAsRead(conversationWith, conversationType).then( (response: string) => { @@ -832,6 +832,21 @@ CometChat.removeMessageListener("UNIQUE_LISTENER_ID"); ``` + +- **Mark as delivered on fetch**: Call `markAsDelivered()` when messages are fetched and displayed +- **Mark as read on view**: Call `markAsRead()` when the user actually views/scrolls to a message +- **Use message objects**: Prefer passing the full message object to `markAsDelivered()`/`markAsRead()` for simplicity +- **Batch receipts**: Mark the last message in a batch - all previous messages are automatically marked +- **Handle offline scenarios**: Receipts are queued and sent when the user comes back online + + + +- **Receipts not updating** — Verify `addMessageListener()` includes receipt handlers (`onMessagesDelivered`, `onMessagesRead`). +- **Double-tick not showing** — Call `markAsDelivered()` on message fetch and real-time receive. It won't happen automatically. +- **Read status not syncing** — Use the message object overload for `markAsRead()` for simpler implementation and fewer parameter errors. +- **Group receipts missing** — Enable "Enhanced Messaging Status" in the [CometChat Dashboard](https://app.cometchat.com) for group read receipts. + + --- ## Next Steps diff --git a/sdk/javascript/direct-call.mdx b/sdk/javascript/direct-call.mdx index c7e5c3f46..a72004fb2 100644 --- a/sdk/javascript/direct-call.mdx +++ b/sdk/javascript/direct-call.mdx @@ -723,16 +723,11 @@ CometChatCalls.switchToVideoCall(); Terminates the current call session and releases all media resources (camera, microphone, network connections). After calling this method, the call view should be closed. - + ```javascript CometChatCalls.endSession(); ``` - -```typescript -CometChatCalls.endSession(); -``` - @@ -745,6 +740,26 @@ CometChatCalls.removeCallEventListener("UNIQUE_LISTENER_ID"); --- + + + - **Generate tokens just-in-time** — Generate call tokens immediately before starting a session rather than caching them, as tokens may expire. + - **Handle all listener events** — Implement handlers for all `OngoingCallListener` events to provide a complete user experience and proper resource cleanup. + - **Clean up on session end** — Always call `CometChatCalls.endSession()` in both `onCallEnded` and `onCallEndButtonPressed` callbacks to release media resources. + - **Use unique listener IDs** — Use descriptive, unique listener IDs to prevent accidental overwrites and enable targeted removal. + - **Provide a container element** — Ensure the HTML element passed to `startSession()` exists in the DOM and has appropriate dimensions for the call UI. + + + - **Black video screen** — Check that the HTML container element has explicit width and height. The call UI needs dimensions to render properly. + - **Token generation fails** — Verify the auth token is valid and the user is logged in. Ensure the session ID is a non-empty string. + - **No audio/video after joining** — Check browser permissions for camera and microphone. The user must grant access when prompted. + - **onCallEnded not firing** — This event only fires for 1:1 calls with exactly 2 participants. For group calls, use `onUserLeft` to track participants. + - **Duplicate event callbacks** — Ensure you're not registering the same listener multiple times. Use unique listener IDs and remove listeners when done. + - **Session timeout unexpected** — The default idle timeout is 180 seconds. Use `setIdleTimeoutPeriod()` to customize or disable (set to 0) if needed. + + + +--- + ## Next Steps diff --git a/sdk/javascript/mentions.mdx b/sdk/javascript/mentions.mdx index 19b21bcb7..a94cef3aa 100644 --- a/sdk/javascript/mentions.mdx +++ b/sdk/javascript/mentions.mdx @@ -152,7 +152,7 @@ To get a list of messages in a conversation where users are mentioned along with let UID = "UID"; let limit = 30; -var messagesRequest = new CometChat.MessagesRequestBuilder() +let messagesRequest = new CometChat.MessagesRequestBuilder() .setUID(UID) .setLimit(limit) .mentionsWithTagInfo(true) @@ -179,7 +179,7 @@ messagesRequest.fetchPrevious().then( let GUID = "GUID"; let limit = 30; -var messagesRequest = new CometChat.MessagesRequestBuilder() +let messagesRequest = new CometChat.MessagesRequestBuilder() .setGUID(GUID) .setLimit(limit) .mentionsWithTagInfo(true) @@ -271,7 +271,7 @@ To get a list of messages in a conversation where users are mentioned along with let UID = "UID"; let limit = 30; -var messagesRequest = new CometChat.MessagesRequestBuilder() +let messagesRequest = new CometChat.MessagesRequestBuilder() .setUID(UID) .setLimit(limit) .mentionsWithBlockedInfo(true) @@ -299,7 +299,7 @@ messagesRequest.fetchPrevious().then( let GUID = "GUID"; let limit = 30; -var messagesRequest = new CometChat.MessagesRequestBuilder() +let messagesRequest = new CometChat.MessagesRequestBuilder() .setGUID(GUID) .setLimit(limit) .mentionsWithBlockedInfo(true) @@ -392,6 +392,21 @@ To retrieve the list of users mentioned in the particular message, you can use t message.getMentionedUsers() ``` + +- **Use correct format**: Always use `<@uid:UID>` format for mentions in message text +- **Validate UIDs**: Ensure mentioned UIDs exist before sending +- **Highlight mentions in UI**: Parse message text and style mentions differently +- **Fetch tag info when needed**: Use `mentionsWithTagInfo(true)` to get user tags for mentioned users +- **Handle blocked users**: Use `mentionsWithBlockedInfo(true)` to check blocked relationships + + + +- **Mention not parsed** — Use the `<@uid:UID>` format exactly. Any deviation will prevent parsing. +- **`getMentionedUsers()` returns empty** — This only works on messages received from the server, not locally constructed messages. +- **Missing user tags** — Add `mentionsWithTagInfo(true)` to your request builder to include tag information. +- **Blocked info missing** — Add `mentionsWithBlockedInfo(true)` to your request builder to include blocked relationship data. + + --- ## Next Steps diff --git a/sdk/javascript/reactions.mdx b/sdk/javascript/reactions.mdx index 671283901..7821dd0c3 100644 --- a/sdk/javascript/reactions.mdx +++ b/sdk/javascript/reactions.mdx @@ -393,6 +393,21 @@ action After calling this method, the message instance's reactions are updated. You can then use message.getReactions() to get the latest reactions and refresh your UI accordingly. + +- **Update UI optimistically**: Show the reaction immediately, then sync with server response +- **Use `updateMessageWithReactionInfo()`**: Keep message objects in sync with real-time events +- **Limit reaction options**: Provide a curated set of emojis for better UX +- **Show reaction counts**: Display aggregated counts with `getReactions()` for each message +- **Handle duplicates**: Check `getReactedByMe()` before allowing users to add the same reaction + + + +- **Reaction not appearing** — Call `updateMessageWithReactionInfo()` on real-time events to keep the UI in sync. +- **Duplicate reactions** — Use `getReactedByMe()` to check if the user already reacted before adding. +- **Reactions out of sync** — Ensure `onMessageReactionAdded` and `onMessageReactionRemoved` handlers are registered. +- **Can't remove reaction** — Use the exact same emoji string that was used when adding the reaction. + + --- ## Next Steps diff --git a/sdk/javascript/receive-message.mdx b/sdk/javascript/receive-message.mdx index ed1cd686d..0b4d12f1b 100644 --- a/sdk/javascript/receive-message.mdx +++ b/sdk/javascript/receive-message.mdx @@ -1002,13 +1002,11 @@ It returns an object which will contain the GUID as the key and the unread messa -| Issue | Cause | Solution | -|-------|-------|----------| -| Not receiving messages | Listener not added | Verify `addMessageListener()` was called with correct ID | -| Duplicate messages | Multiple listeners | Ensure only one listener per ID; remove on unmount | -| Missing messages | App was offline | Use `getLastDeliveredMessageId()` + `fetchNext()` for missed messages | -| Wrong message count | Blocked users included | Use `hideMessagesFromBlockedUsers` parameter | -| History not loading | Wrong method | Use `fetchPrevious()` for history, `fetchNext()` for missed messages | +- **Not receiving messages** — Verify `addMessageListener()` was called with the correct listener ID before messages are sent. +- **Duplicate messages** — Ensure only one listener per ID is registered. Remove listeners on component unmount. +- **Missing messages after reconnect** — Use `getLastDeliveredMessageId()` + `fetchNext()` to fetch messages missed while offline. +- **Wrong message count** — Blocked users may be included. Use `hideMessagesFromBlockedUsers` parameter to exclude them. +- **History not loading** — Use `fetchPrevious()` for message history and `fetchNext()` for missed messages. Don't mix them up. --- diff --git a/sdk/javascript/recording.mdx b/sdk/javascript/recording.mdx index ef184040d..a7d57a68f 100644 --- a/sdk/javascript/recording.mdx +++ b/sdk/javascript/recording.mdx @@ -168,6 +168,25 @@ Currently, the call recordings are available on the [CometChat Dashboard](https: --- + + + - **Inform users about recording** — Always notify participants when recording starts. This is often a legal requirement in many jurisdictions. + - **Use auto-start for compliance** — If all calls must be recorded for compliance, use `startRecordingOnCallStart(true)` to ensure no calls are missed. + - **Handle recording events** — Implement `onRecordingStarted` and `onRecordingStopped` listeners to update UI and inform users of recording status. + - **Check recording availability** — Recording is a premium feature. Verify it's enabled for your CometChat plan before implementing. + - **Plan for storage** — Recordings consume storage. Implement a retention policy and regularly download/archive recordings from the Dashboard. + + + - **Recording button not visible** — Ensure `showRecordingButton(true)` is set in CallSettings. The button is hidden by default. + - **Recording not starting** — Verify recording is enabled for your CometChat app in the Dashboard. Check that the call session is active before calling `startRecording()`. + - **Recording not appearing in Dashboard** — Recordings may take several minutes to process after a call ends. Check back later or filter by date range. + - **onRecordingStarted not firing** — Ensure the recording listener is registered before starting the session. Check that you're using the correct listener format. + - **Recording quality issues** — Recording quality depends on the source video/audio quality. Ensure participants have stable connections and good lighting for video. + + + +--- + ## Next Steps diff --git a/sdk/javascript/send-message.mdx b/sdk/javascript/send-message.mdx index 60aa359e5..711d2a8da 100644 --- a/sdk/javascript/send-message.mdx +++ b/sdk/javascript/send-message.mdx @@ -1783,13 +1783,11 @@ It is also possible to send interactive messages from CometChat, to know more [c -| Issue | Cause | Solution | -|-------|-------|----------| -| Message not sent | User not logged in | Ensure `CometChat.login()` succeeded before sending | -| Media upload fails | File too large | Check file size limits in your CometChat plan | -| Custom message not received | Missing listener | Ensure receiver has `onCustomMessageReceived` handler | -| Metadata not appearing | Wrong method | Use `setMetadata()` before calling send method | -| Quoted message fails | Invalid message ID | Verify the quoted message ID exists | +- **Message not sent** — Ensure `CometChat.login()` succeeded before sending. The user must be logged in. +- **Media upload fails** — Check file size limits in your CometChat plan. Verify the file type matches the message type. +- **Custom message not received** — Ensure the receiver has an `onCustomMessageReceived` handler registered. +- **Metadata not appearing** — Use `setMetadata()` before calling the send method, not after. +- **Quoted message fails** — Verify the quoted message ID exists and belongs to the same conversation. --- diff --git a/sdk/javascript/session-timeout.mdx b/sdk/javascript/session-timeout.mdx index 541c17ebe..f07d8414a 100644 --- a/sdk/javascript/session-timeout.mdx +++ b/sdk/javascript/session-timeout.mdx @@ -45,6 +45,23 @@ The `onSessionTimeout` event is triggered when the call automatically terminates --- + + + - **Customize timeout for your use case** — Use `setIdleTimeoutPeriod()` to adjust the timeout based on your application's needs. Longer timeouts for waiting rooms, shorter for quick calls. + - **Handle the warning dialog** — The 60-second warning gives users time to decide. Ensure your UI doesn't block or hide this dialog. + - **Implement onSessionTimeout** — Always handle the `onSessionTimeout` event to properly clean up resources and update your UI when auto-termination occurs. + - **Consider disabling for specific scenarios** — For use cases like webinars or waiting rooms where users may be alone for extended periods, consider increasing or disabling the timeout. + + + - **Timeout happening too quickly** — The default is 180 seconds (3 minutes). Use `setIdleTimeoutPeriod()` to increase if needed. + - **Warning dialog not appearing** — The dialog appears at 120 seconds of being alone. If using a custom layout (`enableDefaultLayout(false)`), you need to implement your own warning UI. + - **onSessionTimeout not firing** — Ensure you've registered the listener before starting the session. This event only fires on auto-termination, not manual end. + - **Timeout not resetting** — The timer resets when another participant joins. If it's not resetting, verify the other participant successfully joined the session. + + + +--- + ## Next Steps diff --git a/sdk/javascript/standalone-calling.mdx b/sdk/javascript/standalone-calling.mdx index 3f48a1202..d576f9f0b 100644 --- a/sdk/javascript/standalone-calling.mdx +++ b/sdk/javascript/standalone-calling.mdx @@ -675,6 +675,25 @@ CometChatCalls.endSession(); --- + + + - **Secure auth token handling** — Never expose auth tokens in client-side code. Generate them server-side and pass securely to the client. + - **Use consistent session IDs** — For participants to join the same call, they must use the same session ID. Generate a unique ID and share it through your backend. + - **Implement proper cleanup** — Always call `endSession()` when leaving a call to release camera, microphone, and network resources. + - **Handle all listener events** — Implement handlers for all `OngoingCallListener` events to provide a complete user experience. + - **Test without Chat SDK** — Standalone calling doesn't require Chat SDK initialization. Verify your implementation works independently. + + + - **Invalid auth token** — Auth tokens obtained from REST API may expire. Implement token refresh logic or generate new tokens as needed. + - **Participants can't join same call** — Ensure all participants are using the exact same session ID. Session IDs are case-sensitive. + - **No user context** — Unlike the Chat SDK flow, standalone calling doesn't have automatic user context. User information comes from the auth token. + - **Call not connecting** — Verify the Calls SDK is initialized with correct App ID and Region. Check that both participants have valid call tokens. + - **Missing user info in callbacks** — User details in callbacks come from the auth token. Ensure the token was generated for a user with complete profile information. + + + +--- + ## Next Steps diff --git a/sdk/javascript/threaded-messages.mdx b/sdk/javascript/threaded-messages.mdx index 90704dd18..082357782 100644 --- a/sdk/javascript/threaded-messages.mdx +++ b/sdk/javascript/threaded-messages.mdx @@ -309,12 +309,10 @@ The above snippet will return messages between the logged in user and `cometchat -| Issue | Cause | Solution | -|-------|-------|----------| -| Thread replies in main chat | `hideReplies` not set | Add `.hideReplies(true)` to MessagesRequestBuilder | -| Missing thread messages | Wrong parent ID | Verify `setParentMessageId()` uses correct message ID | -| Real-time messages not filtered | Not checking parent ID | Compare `getParentMessageId()` with active thread ID | -| Empty thread | Parent message deleted | Handle case where parent message no longer exists | +- **Thread replies appearing in main chat** — Add `.hideReplies(true)` to your `MessagesRequestBuilder` to exclude thread replies from the main conversation. +- **Missing thread messages** — Verify `setParentMessageId()` uses the correct parent message ID. +- **Real-time messages not filtered** — Compare `getParentMessageId()` with the active thread ID to filter incoming messages. +- **Empty thread** — The parent message may have been deleted. Handle this case gracefully in your UI. --- diff --git a/sdk/javascript/typing-indicators.mdx b/sdk/javascript/typing-indicators.mdx index 027ba3e0b..c7296e704 100644 --- a/sdk/javascript/typing-indicators.mdx +++ b/sdk/javascript/typing-indicators.mdx @@ -199,6 +199,21 @@ The `TypingIndicator` class consists of the below parameters: | **receiverType** | This parameter indicates if the typing indicator is to be sent to a user or a group. The possible values are: 1. `CometChat.RECEIVER_TYPE.USER` 2. `CometChat.RECEIVER_TYPE.GROUP` | | **metadata** | A JSONObject to provider additional data. | + +- **Debounce typing events**: Don't call `startTyping()` on every keystroke - debounce to ~300ms intervals +- **Auto-stop typing**: Call `endTyping()` after a period of inactivity (e.g., 3-5 seconds) +- **Stop on send**: Always call `endTyping()` when the user sends a message +- **Use unique listener IDs**: Prevent duplicate events by using component-specific listener IDs +- **Remove listeners on unmount**: Clean up listeners when leaving a conversation view + + + +- **Typing indicator not showing** — Verify `addMessageListener()` is called before typing starts. The listener must be registered first. +- **Indicator stuck on "typing"** — Ensure `endTyping()` is called on message send, input blur, or after a timeout (3-5 seconds of inactivity). +- **Multiple typing events firing** — Use unique listener IDs and remove listeners on component unmount to prevent duplicates. +- **Wrong user shown typing** — Verify the `receiverId` matches the current conversation's UID or GUID. + + --- ## Next Steps diff --git a/sdk/javascript/user-management.mdx b/sdk/javascript/user-management.mdx index 080f5ebc3..88f2e6a81 100644 --- a/sdk/javascript/user-management.mdx +++ b/sdk/javascript/user-management.mdx @@ -214,24 +214,16 @@ Deleting a user can only be achieved via the Restful APIs. For more information - -| Practice | Details | -| --- | --- | -| Backend user creation | Always create and update users from your backend server using the REST API to keep your `Auth Key` secure | -| UID format | Use alphanumeric characters, underscores, and hyphens only. Avoid spaces and special characters | -| Metadata usage | Store additional user info (e.g., department, preferences) in the `metadata` JSON field rather than creating custom fields | -| Sync on registration | Create the CometChat user immediately when a user registers in your app to avoid login failures | - +- **Backend user creation** — Always create and update users from your backend server using the REST API to keep your `Auth Key` secure. +- **UID format** — Use alphanumeric characters, underscores, and hyphens only. Avoid spaces and special characters. +- **Metadata usage** — Store additional user info (e.g., department, preferences) in the `metadata` JSON field rather than creating custom fields. +- **Sync on registration** — Create the CometChat user immediately when a user registers in your app to avoid login failures. - -| Symptom | Cause | Fix | -| --- | --- | --- | -| `createUser()` fails with "Auth Key not found" | Invalid or missing Auth Key | Verify the Auth Key from your [CometChat Dashboard](https://app.cometchat.com) | -| `createUser()` fails with "UID already exists" | A user with that UID was already created | Use `updateUser()` instead, or choose a different UID | -| `updateCurrentUserDetails()` doesn't update role | Role cannot be changed for the logged-in user | Use `updateUser()` with Auth Key from your backend to change roles | -| User not appearing in user list | User was created but not yet indexed | Wait a moment and retry. Ensure `createUser()` resolved successfully | - +- **`createUser()` fails with "Auth Key not found"** — Invalid or missing Auth Key. Verify the Auth Key from your [CometChat Dashboard](https://app.cometchat.com). +- **`createUser()` fails with "UID already exists"** — A user with that UID was already created. Use `updateUser()` instead, or choose a different UID. +- **`updateCurrentUserDetails()` doesn't update role** — Role cannot be changed for the logged-in user. Use `updateUser()` with Auth Key from your backend to change roles. +- **User not appearing in user list** — The user was created but not yet indexed. Wait a moment and retry. Ensure `createUser()` resolved successfully. diff --git a/sdk/javascript/user-presence.mdx b/sdk/javascript/user-presence.mdx index 0652ff3de..31d1665d7 100644 --- a/sdk/javascript/user-presence.mdx +++ b/sdk/javascript/user-presence.mdx @@ -138,24 +138,16 @@ When you fetch the list of users, in the [User](/sdk/javascript/user-management# - -| Practice | Details | -| --- | --- | -| Choose the right subscription | Use `subscribePresenceForFriends()` or `subscribePresenceForRoles()` instead of `subscribePresenceForAllUsers()` in apps with many users to reduce unnecessary events | -| Unique listener IDs | Use unique, descriptive listener IDs (e.g., `"chat-screen-presence"`) to avoid accidentally overwriting other listeners | -| Cleanup on unmount | Always call `removeUserListener()` when the component/view is destroyed | -| Combine with user list | Use the `status` field from `UsersRequest` results for initial state, then update via `UserListener` for real-time changes | - +- **Choose the right subscription** — Use `subscribePresenceForFriends()` or `subscribePresenceForRoles()` instead of `subscribePresenceForAllUsers()` in apps with many users to reduce unnecessary events. +- **Use unique listener IDs** — Use unique, descriptive listener IDs (e.g., `"chat-screen-presence"`) to avoid accidentally overwriting other listeners. +- **Cleanup on unmount** — Always call `removeUserListener()` when the component/view is destroyed. +- **Combine with user list** — Use the `status` field from `UsersRequest` results for initial state, then update via `UserListener` for real-time changes. - -| Symptom | Cause | Fix | -| --- | --- | --- | -| No presence events received | Presence subscription not configured in `AppSettings` | Add `subscribePresenceForAllUsers()`, `subscribePresenceForRoles()`, or `subscribePresenceForFriends()` to your `AppSettingsBuilder` | -| Presence events stop after navigation | Listener was removed or component unmounted | Re-register the listener when the component mounts again | -| Duplicate presence events | Multiple listeners registered with the same or different IDs | Ensure you remove old listeners before adding new ones | -| `lastActiveAt` is `0` or `null` | User has never been online or data not yet available | Handle this case in your UI with a fallback like "Never active" | - +- **No presence events received** — Presence subscription not configured in `AppSettings`. Add `subscribePresenceForAllUsers()`, `subscribePresenceForRoles()`, or `subscribePresenceForFriends()` to your `AppSettingsBuilder`. +- **Presence events stop after navigation** — The listener was removed or the component unmounted. Re-register the listener when the component mounts again. +- **Duplicate presence events** — Multiple listeners registered with the same or different IDs. Ensure you remove old listeners before adding new ones. +- **`lastActiveAt` is `0` or `null`** — The user has never been online or data is not yet available. Handle this in your UI with a fallback like "Never active". From a2d6928f650406a1d68f185dc74d875487cce809 Mon Sep 17 00:00:00 2001 From: PrajwalDhuleCC Date: Fri, 20 Feb 2026 19:13:49 +0530 Subject: [PATCH 06/43] docs(javascript-sdk): enhance documentation with best practices and troubleshooting guides - Add best practices and troubleshooting accordions to ai-agents documentation - Add best practices and troubleshooting accordions to ai-moderation documentation - Add best practices and troubleshooting accordions to all-real-time-listeners documentation - Update variable declarations from `var` to `const` for modern JavaScript best practices across multiple documentation files - Add best practices and troubleshooting sections to block-users, connection-status, create-group, custom-css, delete-group, group-add-members, group-change-member-scope, group-kick-ban-members, join-group, leave-group, managing-web-sockets-connections-manually, presenter-mode, retrieve-group-members, retrieve-groups, retrieve-users, transfer-group-ownership, update-group, upgrading-from-v3, user-management, video-view-customisation, and virtual-background documentation - Improve developer experience by providing actionable guidance for common issues and recommended patterns --- sdk/javascript/ai-agents.mdx | 16 ++++++ sdk/javascript/ai-moderation.mdx | 16 ++++++ sdk/javascript/all-real-time-listeners.mdx | 20 +++++++- sdk/javascript/block-users.mdx | 36 ++++++++++---- sdk/javascript/connection-status.mdx | 22 +++++++-- sdk/javascript/create-group.mdx | 49 +++++++++++++------ sdk/javascript/custom-css.mdx | 16 ++++++ sdk/javascript/delete-group.mdx | 23 +++++++-- sdk/javascript/group-add-members.mdx | 20 +++++++- sdk/javascript/group-change-member-scope.mdx | 16 ++++++ sdk/javascript/group-kick-ban-members.mdx | 28 ++++++++--- sdk/javascript/join-group.mdx | 27 ++++++++-- sdk/javascript/leave-group.mdx | 23 ++++++++- ...aging-web-sockets-connections-manually.mdx | 16 ++++++ sdk/javascript/presenter-mode.mdx | 16 ++++++ sdk/javascript/retrieve-group-members.mdx | 16 ++++++ sdk/javascript/retrieve-groups.mdx | 20 +++++++- sdk/javascript/retrieve-users.mdx | 25 ++++++++-- sdk/javascript/transfer-group-ownership.mdx | 14 ++++++ sdk/javascript/update-group.mdx | 33 ++++++++++--- sdk/javascript/upgrading-from-v3.mdx | 14 ++++++ sdk/javascript/user-management.mdx | 28 +++++------ sdk/javascript/video-view-customisation.mdx | 14 ++++++ sdk/javascript/virtual-background.mdx | 16 ++++++ 24 files changed, 451 insertions(+), 73 deletions(-) diff --git a/sdk/javascript/ai-agents.mdx b/sdk/javascript/ai-agents.mdx index 2df8401c2..8525c4340 100644 --- a/sdk/javascript/ai-agents.mdx +++ b/sdk/javascript/ai-agents.mdx @@ -168,6 +168,22 @@ These events are received via the **`MessageListener`** after the run completes. Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + +- **Register both listeners** — Use `AIAssistantListener` for real-time streaming events and `MessageListener` for persisted agentic messages. Both are needed for a complete experience. +- **Handle streaming progressively** — Use `Text Message Content` events to render the assistant's reply token-by-token for a responsive UI, rather than waiting for the full reply. +- **Track run lifecycle** — Use `Run Start` and `Run Finished` events to show loading indicators and know when the agent is done processing. +- **Remove listeners on cleanup** — Always call both `removeAIAssistantListener()` and `removeMessageListener()` when the component unmounts. +- **Handle tool calls gracefully** — Tool call events may occur multiple times in a single run. Display appropriate UI feedback for each tool invocation. + + + +- **No events received** — Ensure the AI Agent is configured in the CometChat Dashboard and the user is sending text messages (agents only respond to text). +- **`onAIAssistantEventReceived` not firing** — Verify the `AIAssistantListener` is registered after successful `CometChat.init()` and `login()`. +- **Agentic messages not arriving** — These come via `MessageListener` after the run completes. Make sure you've registered `onAIAssistantMessageReceived`, `onAIToolResultReceived`, and `onAIToolArgumentsReceived`. +- **Duplicate events** — Check that you're not registering multiple listeners with different IDs. Remove old listeners before adding new ones. +- **Streaming events arrive but no final message** — The run may have failed. Check for error events in the `onAIAssistantEventReceived` callback. + + --- ## Next Steps diff --git a/sdk/javascript/ai-moderation.mdx b/sdk/javascript/ai-moderation.mdx index 0bedaeab8..008d2d905 100644 --- a/sdk/javascript/ai-moderation.mdx +++ b/sdk/javascript/ai-moderation.mdx @@ -333,6 +333,22 @@ Here's a complete implementation showing the full moderation flow: Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + +- **Show pending state in UI** — When `getModerationStatus()` returns `PENDING`, display a visual indicator (spinner, dimmed message) so users know the message is being reviewed. +- **Handle disapproved messages gracefully** — Don't just hide blocked messages silently. Show a placeholder or notification so the sender understands what happened. +- **Register the listener early** — Add the `onMessageModerated` listener before sending messages so you don't miss any moderation results. +- **Track pending messages** — Maintain a local map of pending message IDs so you can update the UI when moderation results arrive. +- **Test with moderation rules** — Configure moderation rules in the Dashboard before testing. Without rules, messages won't be moderated. + + + +- **`onMessageModerated` never fires** — Ensure moderation is enabled in the CometChat Dashboard and rules are configured under Moderation > Rules. +- **All messages show `PENDING` but never resolve** — Check that your moderation rules are properly configured and the moderation service is active in your plan. +- **Custom messages not being moderated** — AI Moderation only supports Text, Image, and Video messages. Custom messages are not subject to moderation. +- **Moderation status is `undefined`** — You may be using an older SDK version that doesn't support moderation. Update to the latest version. +- **Disapproved messages still visible to recipients** — The SDK handles this automatically. If recipients still see blocked messages, verify your `onMessageModerated` handler is updating the UI correctly. + + ## Next Steps diff --git a/sdk/javascript/all-real-time-listeners.mdx b/sdk/javascript/all-real-time-listeners.mdx index f4293a5d6..54a209640 100644 --- a/sdk/javascript/all-real-time-listeners.mdx +++ b/sdk/javascript/all-real-time-listeners.mdx @@ -61,7 +61,7 @@ To add the `UserListener`, you need to use the `addUserListener()` method provid ```js -var listenerID = "UNIQUE_LISTENER_ID"; +const listenerID = "UNIQUE_LISTENER_ID"; CometChat.addUserListener( listenerID, new CometChat.UserListener({ @@ -79,7 +79,7 @@ CometChat.addUserListener( ```typescript -var listenerID: string = "UNIQUE_LISTENER_ID"; +const listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addUserListener( listenerID, new CometChat.UserListener({ @@ -568,6 +568,22 @@ CometChat.removeCallListener(listenerID); + +- **Use unique listener IDs** — Each listener must have a unique ID. Using the same ID for multiple listeners will overwrite the previous one, causing missed events. +- **Register listeners early** — Add listeners right after `CometChat.init()` and `login()` succeed so you don't miss any events. +- **Always clean up** — Remove all listeners when they're no longer needed (component unmount, page navigation, logout) to prevent memory leaks and duplicate callbacks. +- **Keep listener callbacks lightweight** — Avoid heavy processing inside listener callbacks. Dispatch events to your state management layer and process asynchronously. +- **Use specific listeners** — Only register the listener types you need. Don't register a `GroupListener` if your page only handles messages. + + + +- **Events not firing** — Ensure listeners are registered after a successful `CometChat.init()` and `login()`. Listeners registered before init have no effect. +- **Duplicate events received** — You likely have multiple listeners registered with the same or different IDs. Check that you're removing old listeners before adding new ones. +- **Missing events after page navigation** — Listeners are removed when the component unmounts. Re-register them when the new component mounts. +- **`onMessagesDelivered` / `onMessagesRead` not triggering** — Delivery and read receipts must be explicitly sent by the recipient using `markAsDelivered()` / `markAsRead()`. +- **Call events not received** — Ensure you've registered a `CallListener` and that the CometChat Calling SDK is properly initialized. + + --- ## Next Steps diff --git a/sdk/javascript/block-users.mdx b/sdk/javascript/block-users.mdx index ba7c72bca..5baa2dcaf 100644 --- a/sdk/javascript/block-users.mdx +++ b/sdk/javascript/block-users.mdx @@ -35,7 +35,7 @@ You can block users using the `blockUsers()` method. Once any user is blocked, a ```javascript -var usersList = ["UID1", "UID2", "UID3"]; +const usersList = ["UID1", "UID2", "UID3"]; CometChat.blockUsers(usersList).then( list => { @@ -50,7 +50,7 @@ list => { ```typescript -var usersList: String[] = ["UID1", "UID2", "UID3"]; +const usersList: String[] = ["UID1", "UID2", "UID3"]; CometChat.blockUsers(usersList).then( (list: Object) => { @@ -65,7 +65,7 @@ CometChat.blockUsers(usersList).then( ```javascript -var usersList = ["UID1", "UID2", "UID3"]; +const usersList = ["UID1", "UID2", "UID3"]; try { const list = await CometChat.blockUsers(usersList); @@ -90,7 +90,7 @@ You can unblock the already blocked users using the `unblockUsers()` method. You ```javascript -var usersList = ["UID1", "UID2", "UID3"]; +const usersList = ["UID1", "UID2", "UID3"]; CometChat.unblockUsers(usersList).then( list => { @@ -105,7 +105,7 @@ list => { ```typescript -var usersList: String[] = ["UID1", "UID2", "UID3"]; +const usersList: String[] = ["UID1", "UID2", "UID3"]; CometChat.unblockUsers(usersList).then( (list: Object) => { @@ -120,7 +120,7 @@ CometChat.unblockUsers(usersList).then( ```javascript -var usersList = ["UID1", "UID2", "UID3"]; +const usersList = ["UID1", "UID2", "UID3"]; try { const list = await CometChat.unblockUsers(usersList); @@ -238,10 +238,10 @@ Finally, once all the parameters are set to the builder class, you need to call Once you have the object of the `BlockedUsersRequest` class, you need to call the `fetchNext()` method. Calling this method will return a list of `User` objects containing n number of blocked users where N is the limit set in the builder class. - + ```javascript -var limit = 30; -var blockedUsersRequest = new CometChat.BlockedUsersRequestBuilder() +const limit = 30; +const blockedUsersRequest = new CometChat.BlockedUsersRequestBuilder() .setLimit(limit) .build(); blockedUsersRequest.fetchNext().then( @@ -275,6 +275,24 @@ blockedUsersRequest.fetchNext().then( +--- + + + + - **Block in batches** — You can block multiple users in a single call by passing an array of UIDs. This is more efficient than blocking one at a time. + - **Update UI immediately** — After blocking/unblocking, update your user list and conversation list to reflect the change. + - **Use direction filters** — Use `BLOCKED_BY_ME` to show users you've blocked, `HAS_BLOCKED_ME` to detect who blocked you, or `BOTH` for the full picture. + - **Hide blocked users in lists** — Use `hideBlockedUsers(true)` in `UsersRequestBuilder` to automatically exclude blocked users from user lists. + - **Handle block status in messaging** — Messages from blocked users won't be delivered. Inform users that blocking prevents all communication. + + + - **Block operation returns "fail" for a UID** — The UID may not exist or may already be blocked. Verify the UID is correct. + - **Still receiving messages after blocking** — Ensure the block operation completed successfully. Check the response object for "success" status on each UID. + - **Blocked user list empty** — Verify the direction filter. Default is `BOTH`, but if you set `HAS_BLOCKED_ME` and no one has blocked you, the list will be empty. + - **Unblock not working** — Ensure you're passing the correct UIDs. The unblock operation only works on users you've blocked (`BLOCKED_BY_ME`). + - **Blocked user still appears in user list** — Use `hideBlockedUsers(true)` in your `UsersRequestBuilder` to filter them out automatically. + + --- diff --git a/sdk/javascript/connection-status.mdx b/sdk/javascript/connection-status.mdx index 85070d9ff..839bc4bff 100644 --- a/sdk/javascript/connection-status.mdx +++ b/sdk/javascript/connection-status.mdx @@ -9,7 +9,7 @@ description: "Monitor real-time WebSocket connection status and respond to conne ```javascript // Get current status: "connecting" | "connected" | "disconnected" -var status = CometChat.getConnectionStatus(); +const status = CometChat.getConnectionStatus(); // Listen for connection changes CometChat.addConnectionListener("LISTENER_ID", new CometChat.ConnectionListener({ @@ -93,14 +93,14 @@ You can also get the current connection status by using `getConnectionStatus` pr ```javascript -var connectionStatus = CometChat.getConnectionStatus(); +const connectionStatus = CometChat.getConnectionStatus(); ``` ```typescript -var connectionStatus: string = CometChat.getConnectionStatus(); +const connectionStatus: string = CometChat.getConnectionStatus(); ``` @@ -118,6 +118,22 @@ The `CometChat.getConnectionStatus` method will return either of the below 3 val Always remove connection listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + +- **Register early** — Add the connection listener right after `CometChat.init()` succeeds, ideally in your app's entry point, so you catch all connection state changes. +- **Show connection status in UI** — Display a banner or indicator when the connection is `"disconnected"` or `"connecting"` so users know messages may be delayed. +- **Queue actions during disconnection** — If the connection drops, queue user actions (like sending messages) and retry once `onConnected` fires. +- **Remove listeners on cleanup** — Always call `CometChat.removeConnectionListener()` when the component unmounts or the app shuts down. +- **Don't poll `getConnectionStatus()`** — Use the listener-based approach instead. Polling adds unnecessary overhead when the SDK already pushes state changes. + + + +- **Listener never fires** — Ensure you register the listener after a successful `CometChat.init()` call. Registering before init has no effect. +- **Stuck in "connecting" state** — Check your network connection and firewall settings. Also verify your `appId` and `region` are correct in the init configuration. +- **Frequent disconnections** — This usually indicates network instability. The SDK automatically reconnects, but if it persists, check for WebSocket-blocking proxies or VPNs. +- **`getConnectionStatus()` returns `undefined`** — The SDK hasn't been initialized yet. Call `CometChat.init()` first. +- **Multiple `onConnected` callbacks** — You likely have multiple listeners registered with different IDs. Remove old listeners before adding new ones. + + --- ## Next Steps diff --git a/sdk/javascript/create-group.mdx b/sdk/javascript/create-group.mdx index 057256d0d..c2a08be2e 100644 --- a/sdk/javascript/create-group.mdx +++ b/sdk/javascript/create-group.mdx @@ -47,12 +47,12 @@ The `groupType` needs to be either of the below 3 values: ```javascript -var GUID = "GUID"; -var groupName = "Hello Group!"; -var groupType = CometChat.GROUP_TYPE.PUBLIC; -var password = ""; +const GUID = "GUID"; +const groupName = "Hello Group!"; +const groupType = CometChat.GROUP_TYPE.PUBLIC; +const password = ""; -var group = new CometChat.Group(GUID, groupName, groupType, password); +const group = new CometChat.Group(GUID, groupName, groupType, password); CometChat.createGroup(group).then( group => { @@ -67,12 +67,12 @@ CometChat.createGroup(group).then( ```typescript -var GUID: string = "GUID"; -var groupName: string = "Hello Group!"; -var groupType: string = CometChat.GROUP_TYPE.PUBLIC; -var password: string = ""; +const GUID: string = "GUID"; +const groupName: string = "Hello Group!"; +const groupType: string = CometChat.GROUP_TYPE.PUBLIC; +const password: string = ""; -var group: CometChat.Group = new CometChat.Group(GUID, groupName, groupType, password); +const group: CometChat.Group = new CometChat.Group(GUID, groupName, groupType, password); CometChat.createGroup(group).then( (group: CometChat.Group) => { @@ -87,12 +87,12 @@ CometChat.createGroup(group).then( ```javascript -var GUID = "GUID"; -var groupName = "Hello Group!"; -var groupType = CometChat.GROUP_TYPE.PUBLIC; -var password = ""; +const GUID = "GUID"; +const groupName = "Hello Group!"; +const groupType = CometChat.GROUP_TYPE.PUBLIC; +const password = ""; -var group = new CometChat.Group(GUID, groupName, groupType, password); +const group = new CometChat.Group(GUID, groupName, groupType, password); try { const createdGroup = await CometChat.createGroup(group); @@ -236,6 +236,25 @@ This method returns an Object which has two keys: `group` & `members` . The grou | tags | Yes | A list of tags to identify specific groups. | +--- + + + + - **Use meaningful GUIDs** — Choose descriptive, unique GUIDs (e.g., `"project-alpha-team"`) that are easy to reference in your codebase. + - **Set group type carefully** — Group type cannot be changed after creation. Choose between PUBLIC, PASSWORD, and PRIVATE based on your use case. + - **Add members at creation** — Use `createGroupWithMembers()` to add initial members in a single API call instead of creating the group and adding members separately. + - **Store metadata** — Use the `metadata` field to store custom data (e.g., project ID, department) rather than encoding it in the group name. + - **Handle GUID conflicts** — If a GUID already exists, creation will fail. Check for existing groups or use unique identifiers. + + + - **"GUID already exists" error** — A group with that GUID already exists. Use a different GUID or retrieve the existing group. + - **"User not authorized" error** — The logged-in user may not have permission to create groups. Check your app's role settings in the Dashboard. + - **Members not added during creation** — Check the response object's `members` key. Individual member additions can fail (e.g., invalid UID) while the group creation succeeds. + - **Password group not requiring password** — Ensure `groupType` is set to `CometChat.GROUP_TYPE.PASSWORD` and a non-empty password is provided. + - **GUID validation error** — GUIDs can only contain alphanumeric characters, underscores, and hyphens. No spaces or special characters. + + + --- ## Next Steps diff --git a/sdk/javascript/custom-css.mdx b/sdk/javascript/custom-css.mdx index 99bd9f5ff..363177b19 100644 --- a/sdk/javascript/custom-css.mdx +++ b/sdk/javascript/custom-css.mdx @@ -189,6 +189,22 @@ The above example results in the below output:- By following these recommendations, you can maintain a stable and visually consistent grid layout. + +- **Only use documented CSS classes** — Applying styles to undocumented internal classes may break with SDK updates. Stick to the classes listed in this guide. +- **Don't resize the grid container** — Altering the grid container dimensions can break the layout. Only customize colors, borders, and visibility. +- **Use `!important` sparingly** — Some SDK styles may need `!important` to override, but overusing it makes maintenance harder. +- **Test across modes** — CSS changes may look different in `DEFAULT`, `TILE`, and `SPOTLIGHT` modes. Test all three. +- **Keep button sizes accessible** — When customizing button dimensions, ensure they remain large enough for easy interaction (minimum 44x44px for touch targets). + + + +- **CSS changes not applying** — The SDK may use inline styles or higher-specificity selectors. Try adding `!important` to your rules. +- **Layout breaks after customization** — You may have resized the grid container or applied conflicting `display` or `position` properties. Revert and apply changes incrementally. +- **Styles only work in one mode** — Some CSS classes are mode-specific. Test in `DEFAULT`, `TILE`, and `SPOTLIGHT` modes to ensure consistency. +- **Muted button styles not showing** — Use the `-muted` variant classes (e.g., `cc-audio-icon-container-muted`) for muted state styling. +- **Custom styles disappear on SDK update** — If the SDK updates internal class names, your custom CSS may stop working. Pin your SDK version and test after updates. + + --- diff --git a/sdk/javascript/delete-group.mdx b/sdk/javascript/delete-group.mdx index 1e79e443d..ccb2aeefd 100644 --- a/sdk/javascript/delete-group.mdx +++ b/sdk/javascript/delete-group.mdx @@ -30,7 +30,7 @@ To delete a group you need to use the `deleteGroup()` method. The user must be a ```javascript -var GUID = "GUID"; +const GUID = "GUID"; CometChat.deleteGroup(GUID).then( response => { @@ -45,7 +45,7 @@ response => { ```typescript -var GUID: string = "GUID"; +const GUID: string = "GUID"; CometChat.deleteGroup(GUID).then( (response: boolean) => { @@ -60,7 +60,7 @@ CometChat.deleteGroup(GUID).then( ```javascript -var GUID = "GUID"; +const GUID = "GUID"; try { const response = await CometChat.deleteGroup(GUID); @@ -81,6 +81,23 @@ The `deleteGroup()` method takes the following parameters: | `GUID` | The GUID of the group you would like to delete | +--- + + + + - **Confirm before deleting** — Always show a confirmation dialog. Group deletion is irreversible and removes all messages and member associations. + - **Verify admin status** — Only group admins can delete groups. Check the user's scope before showing the delete option in your UI. + - **Notify members** — Consider sending a final message or notification before deleting so members are aware. + - **Clean up local state** — After deletion, remove the group from local caches, conversation lists, and any UI references. + + + - **"Not authorized" error** — Only admins can delete groups. Verify the logged-in user's scope is `ADMIN` for this group. + - **Group not found** — The GUID may be incorrect or the group was already deleted. Verify the GUID exists. + - **Members still see the group** — Other members will receive a group deletion event via `GroupListener`. Ensure they handle `onGroupMemberLeft` or similar cleanup. + - **Deletion seems to hang** — Check network connectivity. The operation requires a server round-trip. + + + --- ## Next Steps diff --git a/sdk/javascript/group-add-members.mdx b/sdk/javascript/group-add-members.mdx index 9b12c24c3..5ade863af 100644 --- a/sdk/javascript/group-add-members.mdx +++ b/sdk/javascript/group-add-members.mdx @@ -97,7 +97,7 @@ To receive real-time events whenever a new member is added to a group, you need ```javascript -var listenerID = "UNIQUE_LISTENER_ID"; +const listenerID = "UNIQUE_LISTENER_ID"; CometChat.addGroupListener( listenerID, @@ -118,7 +118,7 @@ CometChat.addGroupListener( ```typescript -var listenerID: string = "UNIQUE_LISTENER_ID"; +const listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addGroupListener( listenerID, @@ -165,6 +165,22 @@ For the group member added event, in the `Action` object received, the following 3. `actionBy` - User object containing the details of the user who added the member to the group 4. `actionFor` - Group object containing the details of the group to which the member was added + +- **Batch member additions** — Add multiple members in a single `addMembersToGroup()` call rather than calling it once per user. +- **Set appropriate scopes** — Assign `PARTICIPANT` by default. Only use `ADMIN` or `MODERATOR` when the user genuinely needs elevated permissions. +- **Handle partial failures** — The response array contains per-user results. Check each entry for `"success"` or an error message to handle failures gracefully. +- **Remove listeners on cleanup** — Always call `CometChat.removeGroupListener()` when the component unmounts or the page navigates away. +- **Validate UIDs before adding** — Ensure the UIDs exist and are not already members to avoid unnecessary API calls and confusing error responses. + + + +- **"ERR_NOT_A_MEMBER" error** — Only admins or moderators can add members. Verify the logged-in user has the correct scope in the group. +- **Some members fail while others succeed** — `addMembersToGroup()` returns per-user results. Check the response object for individual error messages (e.g., user already a member, invalid UID). +- **`onMemberAddedToGroup` not firing** — Ensure the group listener is registered before the add operation. Also verify the listener ID is unique and not being overwritten. +- **Duplicate events received** — You likely have multiple listeners registered with different IDs. Remove old listeners before adding new ones. +- **Banned members can't be added** — A banned user must be unbanned first before they can be added back to the group. + + --- ## Next Steps diff --git a/sdk/javascript/group-change-member-scope.mdx b/sdk/javascript/group-change-member-scope.mdx index f3aac9a4b..ac6617555 100644 --- a/sdk/javascript/group-change-member-scope.mdx +++ b/sdk/javascript/group-change-member-scope.mdx @@ -139,6 +139,22 @@ For the group member scope changed event, in the `Action` object received, the f 5. `oldScope` - The original scope of the member 6. `newScope` - The updated scope of the member + +- **Only admins can change scope** — The logged-in user must be the group admin to change another member's scope. Moderators cannot change scopes. +- **Confirm before promoting** — Promoting a user to admin gives them full control over the group. Add a confirmation dialog in your UI. +- **Remove listeners on cleanup** — Always call `CometChat.removeGroupListener()` when the component unmounts or the page navigates away. +- **Use scope constants** — Always use `CometChat.GROUP_MEMBER_SCOPE.ADMIN`, `CometChat.GROUP_MEMBER_SCOPE.MODERATOR`, or `CometChat.GROUP_MEMBER_SCOPE.PARTICIPANT` instead of raw strings. +- **Update UI after scope change** — Refresh the member list or update the local state after a successful scope change to reflect the new role immediately. + + + +- **"ERR_NOT_A_MEMBER" or permission error** — Only the group admin can change member scopes. Verify the logged-in user is the admin. +- **Cannot demote another admin** — Only the group owner can demote admins. Regular admins can only change scope of moderators and participants. +- **`onGroupMemberScopeChanged` not firing** — Ensure the group listener is registered before the scope change and the listener ID is unique. +- **Scope change succeeds but UI doesn't update** — The API call returns a boolean. You need to manually update your local member list or re-fetch members after the change. +- **Invalid scope value error** — Use the SDK constants (`CometChat.GROUP_MEMBER_SCOPE.ADMIN`, etc.) rather than raw strings like `"admin"`. + + --- ## Next Steps diff --git a/sdk/javascript/group-kick-ban-members.mdx b/sdk/javascript/group-kick-ban-members.mdx index 237d8421f..5528815a8 100644 --- a/sdk/javascript/group-kick-ban-members.mdx +++ b/sdk/javascript/group-kick-ban-members.mdx @@ -43,8 +43,8 @@ The Admin or Moderator of a group can kick a member out of the group using the ` ```javascript -var GUID = "GUID"; -var UID = "UID"; +const GUID = "GUID"; +const UID = "UID"; CometChat.kickGroupMember(GUID, UID).then( response => { @@ -91,8 +91,8 @@ The Admin or Moderator of the group can ban a member from the group using the `b ```javascript -var GUID = "GUID"; -var UID = "UID"; +const GUID = "GUID"; +const UID = "UID"; CometChat.banGroupMember(GUID, UID).then( response => { @@ -139,8 +139,8 @@ Only Admin or Moderators of the group can unban a previously banned member from ```javascript -var GUID = "GUID"; -var UID = "UID"; +const GUID = "GUID"; +const UID = "UID"; CometChat.unbanGroupMember(GUID, UID).then( response => { @@ -387,6 +387,22 @@ For group member unbanned event, the details can be obtained using the below fie 3. `actionOn` - User object containing the details of the member that has been unbanned 4. `actionFor` - Group object containing the details of the Group from which the member was unbanned + +- **Kick vs. Ban** — Use kick when you want the user to be able to rejoin. Use ban when the user should be permanently removed until explicitly unbanned. +- **Confirm before banning** — Banning is a stronger action than kicking. Add a confirmation dialog in your UI before calling `banGroupMember()`. +- **Remove listeners on cleanup** — Always call `CometChat.removeGroupListener()` when the component unmounts or the page navigates away. +- **Paginate banned members** — Use `BannedMembersRequestBuilder` with a reasonable limit (10–30) and call `fetchNext()` in a loop for large banned lists. +- **Handle permissions gracefully** — Only admins and moderators can kick/ban. Check the user's scope before showing these actions in the UI. + + + +- **"ERR_NOT_A_MEMBER" or permission error** — Only admins or moderators can kick/ban members. Verify the logged-in user's scope in the group. +- **Kicked user can still see the group** — Kicking removes the user but doesn't prevent rejoining. If you need to block access, use `banGroupMember()` instead. +- **Banned user can rejoin** — This shouldn't happen. Verify you called `banGroupMember()` and not `kickGroupMember()`. Check the banned members list to confirm. +- **`onGroupMemberBanned` not firing** — Ensure the group listener is registered before the ban operation and the listener ID is unique. +- **Unban fails with error** — Verify the user is actually banned in the group. You can confirm by fetching the banned members list first. + + --- ## Next Steps diff --git a/sdk/javascript/join-group.mdx b/sdk/javascript/join-group.mdx index 6dda9a744..6c8e688eb 100644 --- a/sdk/javascript/join-group.mdx +++ b/sdk/javascript/join-group.mdx @@ -34,9 +34,9 @@ In order to start participating in group conversations, you will have to join a ```javascript -var GUID = "GUID"; -var password = ""; -var groupType = CometChat.GROUP_TYPE.PUBLIC; +const GUID = "GUID"; +const password = ""; +const groupType = CometChat.GROUP_TYPE.PUBLIC; CometChat.joinGroup(GUID, groupType, password).then( group => { @@ -51,7 +51,7 @@ group => { ```typescript -var GUID: string = "GUID"; +const GUID: string = "GUID"; CometChat.joinGroup(GUID, CometChat.GroupType.Public).then( (group: CometChat.Group) => { @@ -139,6 +139,25 @@ For the group member joined event, in the `Action` object received, the followin --- + + + - **Check `hasJoined` first** — Before calling `joinGroup()`, check the group's `hasJoined` property to avoid unnecessary API calls. + - **Handle password groups** — For password-protected groups, prompt the user for the password before calling `joinGroup()`. + - **Update UI on join** — After successfully joining, update your group list and enable messaging for that group. + - **Listen for join events** — Register `GroupListener` to receive real-time notifications when other members join. + - **Clean up listeners** — Remove group listeners when leaving the screen or component to prevent memory leaks. + + + - **"Already a member" error** — The user has already joined this group. Check `hasJoined` before attempting to join. + - **"Invalid password" error** — The password provided doesn't match. Ensure the password is correct for password-protected groups. + - **Can't join private group** — Private groups require an invitation. Users must be added by an admin using `addMembersToGroup()`. + - **Join events not received** — Ensure `addGroupListener()` is called before the join event occurs. Verify the listener ID is unique. + - **Group not found** — The GUID may be incorrect or the group may have been deleted. Verify the GUID exists. + + + +--- + ## Next Steps diff --git a/sdk/javascript/leave-group.mdx b/sdk/javascript/leave-group.mdx index cc5f56435..7bcb9581a 100644 --- a/sdk/javascript/leave-group.mdx +++ b/sdk/javascript/leave-group.mdx @@ -31,7 +31,7 @@ In order to stop receiving updates and messages for any particular joined group, ```javascript -var GUID = "GUID"; +const GUID = "GUID"; CometChat.leaveGroup(GUID).then( hasLeft => { @@ -46,7 +46,7 @@ hasLeft => { ```typescript -var GUID: string = "GUID"; +const GUID: string = "GUID"; CometChat.leaveGroup(GUID).then( (hasLeft: boolean) => { @@ -126,6 +126,25 @@ For the group member left event, in the `Action` object received, the following --- + + + - **Confirm before leaving** — Show a confirmation dialog before leaving a group, especially for groups with important conversations. + - **Update UI immediately** — Remove the group from the active list and disable messaging after successfully leaving. + - **Handle owner leaving** — If the group owner leaves, ownership should be transferred first using [Transfer Group Ownership](/sdk/javascript/transfer-group-ownership). + - **Clean up listeners** — Remove any group-specific listeners after leaving to prevent memory leaks and stale event handling. + - **Check missed events** — When re-joining a group, fetch missed messages and action events to stay up to date. + + + - **"Not a member" error** — The user is not a member of this group. Verify the GUID and check `hasJoined` status. + - **Owner can't leave** — Group owners must transfer ownership before leaving. Use `transferGroupOwnership()` first. + - **Leave events not received** — Ensure `addGroupListener()` is registered before the leave event occurs. Check listener IDs are unique. + - **Still receiving group messages** — Ensure `leaveGroup()` completed successfully. Check the promise resolved without errors. + - **Group still in conversation list** — Refresh the conversation list after leaving. The group may still appear until the list is re-fetched. + + + +--- + ## Next Steps diff --git a/sdk/javascript/managing-web-sockets-connections-manually.mdx b/sdk/javascript/managing-web-sockets-connections-manually.mdx index f5b671f63..38189663a 100644 --- a/sdk/javascript/managing-web-sockets-connections-manually.mdx +++ b/sdk/javascript/managing-web-sockets-connections-manually.mdx @@ -116,6 +116,22 @@ CometChat.disconnect(); + +- **Only disable auto-connect when needed** — The default auto-connect behavior works well for most apps. Only manage connections manually if you need fine-grained control (e.g., background/foreground transitions, battery optimization). +- **Check login status before connecting** — Always verify the user is logged in with `CometChat.getLoggedInUser()` before calling `CometChat.connect()`. +- **Pair with Connection Listener** — Use `CometChat.addConnectionListener()` alongside manual connection management to track the actual connection state. +- **Reconnect on app foreground** — If you disconnect when the app goes to background, call `CometChat.connect()` when the app returns to foreground. +- **Don't call connect/disconnect rapidly** — Allow time for the connection to establish or close before toggling again. + + + +- **No real-time events after login** — If you set `autoEstablishSocketConnection(false)`, you must call `CometChat.connect()` manually after login. +- **`connect()` doesn't seem to work** — Ensure the user is logged in first. `connect()` requires an authenticated session. +- **Events stop after calling `disconnect()`** — This is expected. Call `CometChat.connect()` to resume receiving events. +- **Connection drops intermittently** — This is usually a network issue. The SDK auto-reconnects by default, but if you're managing connections manually, you need to handle reconnection logic yourself. +- **`autoEstablishSocketConnection(false)` not taking effect** — Make sure you're passing it to the `AppSettingsBuilder` before calling `CometChat.init()`. It cannot be changed after initialization. + + --- ## Next Steps diff --git a/sdk/javascript/presenter-mode.mdx b/sdk/javascript/presenter-mode.mdx index 83e5c091c..d7f94aa34 100644 --- a/sdk/javascript/presenter-mode.mdx +++ b/sdk/javascript/presenter-mode.mdx @@ -172,6 +172,22 @@ CometChatCalls.removeCallEventListener("UNIQUE_ID"); ``` + +- **Generate a fresh call token** — Always generate a new call token using `generateToken()` before starting a presentation. Reusing expired tokens will fail. +- **Set presenter role explicitly** — Use `setIsPresenter(true)` for presenters and `setIsPresenter(false)` for viewers. The default is viewer. +- **Limit presenters to 5** — The maximum number of presenters is 5. Additional users should join as viewers. +- **Remove listeners on cleanup** — Always call `CometChatCalls.removeCallEventListener()` when the component unmounts or the presentation ends. +- **Handle `onCallEnded` and `onCallEndButtonPressed`** — These are different events. `onCallEnded` fires when the call ends server-side, while `onCallEndButtonPressed` fires when the user clicks the end button locally. + + + +- **Presentation doesn't start** — Ensure you've generated a valid call token and the HTML element exists in the DOM before calling `joinPresentation()`. +- **Viewer can send audio/video** — Verify `setIsPresenter(false)` is set for viewers. Viewers should not have outgoing streams. +- **`onUserJoined` not firing** — Ensure the call event listener is registered before joining the presentation. +- **Black screen after joining** — Check that the HTML element passed to `joinPresentation()` is visible and has proper dimensions (width/height). +- **More than 5 presenters needed** — Presenter Mode supports a maximum of 5 presenters. Consider using a standard group call for more active participants. + + --- ## Next Steps diff --git a/sdk/javascript/retrieve-group-members.mdx b/sdk/javascript/retrieve-group-members.mdx index 8b506e3c5..ea304c691 100644 --- a/sdk/javascript/retrieve-group-members.mdx +++ b/sdk/javascript/retrieve-group-members.mdx @@ -210,6 +210,22 @@ groupMembersRequest.fetchNext().then( + +- **Paginate results** — Always use `fetchNext()` in a loop or on-scroll. Set a reasonable limit (10–30) per request to avoid large payloads. +- **Reuse the request object** — Create the `GroupMembersRequest` once and call `fetchNext()` repeatedly. Creating a new builder each time resets pagination. +- **Filter by scope for admin panels** — Use `setScopes(["admin", "moderator"])` when building admin views to show only privileged members. +- **Use status filter for presence** — Filter by `CometChat.USER_STATUS.ONLINE` to show active members in real-time collaboration features. +- **Combine filters** — You can chain `setSearchKeyword()`, `setScopes()`, and `setStatus()` on the same builder for precise results. + + + +- **Empty member list returned** — Verify the GUID is correct and the logged-in user is a member of the group. Non-members cannot fetch member lists. +- **`fetchNext()` returns the same results** — You're likely creating a new `GroupMembersRequest` each time. Reuse the same instance for pagination. +- **Search not finding members** — `setSearchKeyword()` matches against member names. Ensure the keyword is correct and partially matches. +- **Scope filter returns no results** — Double-check the scope strings. Valid values are `"admin"`, `"moderator"`, and `"participant"`. +- **Status filter not working** — Use `CometChat.USER_STATUS.ONLINE` or `CometChat.USER_STATUS.OFFLINE` constants, not raw strings. + + --- ## Next Steps diff --git a/sdk/javascript/retrieve-groups.mdx b/sdk/javascript/retrieve-groups.mdx index a60efe03b..a3c2c03e0 100644 --- a/sdk/javascript/retrieve-groups.mdx +++ b/sdk/javascript/retrieve-groups.mdx @@ -237,7 +237,7 @@ To get the information of a group, you can use the `getGroup()` method. ```javascript -var GUID = "GUID"; +const GUID = "GUID"; CometChat.getGroup(GUID).then( group => { console.log("Group details fetched successfully:", group); @@ -251,7 +251,7 @@ group => { ```typescript -var GUID: string = "GUID"; +const GUID: string = "GUID"; CometChat.getGroup(GUID).then( (group: CometChat.Group) => { console.log("Group details fetched successfully:", group); @@ -308,6 +308,22 @@ CometChat.getOnlineGroupMemberCount(guids).then( This method returns a JSON Object with the GUID as the key and the online member count for that group as the value. + +- **Use pagination** — Always call `fetchNext()` in a loop or on-scroll rather than fetching all groups at once. Set a reasonable limit (10–30) per page. +- **Cache group details** — If you call `getGroup()` frequently for the same GUID, cache the result locally to reduce API calls. +- **Use `joinedOnly(true)` for navigation** — When building a sidebar or group list, filter to joined groups so users only see groups they belong to. +- **Combine filters wisely** — You can chain `setSearchKeyword()`, `setTags()`, and `joinedOnly()` on the same builder for precise results. +- **Use `withTags(true)` only when needed** — Fetching tags adds payload size. Only enable it when your UI displays or filters by tags. + + + +- **Empty group list returned** — Ensure the logged-in user has the correct permissions. Private groups only appear if the user is a member. +- **`fetchNext()` returns the same results** — You're likely creating a new `GroupsRequest` object each time. Reuse the same instance across pagination calls. +- **`getGroup()` fails with "Group not found"** — Verify the GUID is correct and the group hasn't been deleted. Password/private groups require membership. +- **Online member count returns 0** — The user must be a member of the group. Also confirm the GUIDs array is not empty. +- **Search not returning expected results** — `setSearchKeyword()` matches against the group name. Ensure the keyword is spelled correctly and is at least partially matching. + + --- ## Next Steps diff --git a/sdk/javascript/retrieve-users.mdx b/sdk/javascript/retrieve-users.mdx index 87160c09e..cc07b4100 100644 --- a/sdk/javascript/retrieve-users.mdx +++ b/sdk/javascript/retrieve-users.mdx @@ -443,10 +443,10 @@ Finally, once all the parameters are set to the builder class, you need to call Once you have the object of the UsersRequest class, you need to call the fetchNext() method. Calling this method will return a list of User objects containing n number of users where n is the limit set in the builder class. - + ```javascript -var limit = 30; -var usersRequest = new CometChat.UsersRequestBuilder() +const limit = 30; +const usersRequest = new CometChat.UsersRequestBuilder() .setLimit(limit) .build(); @@ -561,6 +561,25 @@ This method returns the total online user count for your app. --- + + + - **Paginate results** — Use `setLimit()` with reasonable values (30-50) and call `fetchNext()` for subsequent pages. Don't fetch all users at once. + - **Reuse the request object** — Call `fetchNext()` on the same `UsersRequest` instance for pagination. Creating a new object resets the cursor. + - **Filter strategically** — Combine `setStatus()`, `setRoles()`, and `setTags()` to narrow results efficiently rather than filtering client-side. + - **Cache user details** — Store frequently accessed user objects locally to reduce API calls, especially for `getUser()`. + - **Use `hideBlockedUsers(true)`** — Enable this in user lists to respect block relationships and provide a cleaner experience. + + + - **Empty user list returned** — Check that users exist in your CometChat app. Verify filters aren't too restrictive by removing them one at a time. + - **Pagination not working** — Ensure you're reusing the same `UsersRequest` object for `fetchNext()` calls. Creating a new builder resets pagination. + - **`getUser()` returns error** — Verify the UID exists and is spelled correctly. UIDs are case-sensitive. + - **Online count seems wrong** — `getOnlineUserCount()` returns the total across your app, not just the current user's contacts. Users must have an active connection. + - **Search not finding users** — By default, search checks both UID and name. Use `searchIn()` to limit search scope if needed. + + + +--- + ## Next Steps diff --git a/sdk/javascript/transfer-group-ownership.mdx b/sdk/javascript/transfer-group-ownership.mdx index f3e6311c0..32db039a4 100644 --- a/sdk/javascript/transfer-group-ownership.mdx +++ b/sdk/javascript/transfer-group-ownership.mdx @@ -58,6 +58,20 @@ CometChat.transferGroupOwnership(GUID, UID).then( + +- **Transfer before leaving** — The owner cannot leave a group without first transferring ownership. Always call `transferGroupOwnership()` before `leaveGroup()`. +- **Choose a trusted member** — Transfer ownership to an active admin or moderator who can manage the group responsibly. +- **Confirm in UI** — Ownership transfer is irreversible. Add a confirmation dialog before calling the method. +- **Update local state** — After a successful transfer, update your local group data to reflect the new owner. + + + +- **"ERR_NOT_A_MEMBER" or permission error** — Only the current group owner can transfer ownership. Verify the logged-in user is the owner. +- **Transfer fails with "User not found"** — The target UID must be an existing member of the group. Verify the UID and their membership status. +- **Owner still can't leave after transfer** — Ensure the `transferGroupOwnership()` promise resolved successfully before calling `leaveGroup()`. +- **New owner doesn't have admin privileges** — After ownership transfer, the new owner automatically gets the owner role. If the UI doesn't reflect this, re-fetch the group details. + + --- ## Next Steps diff --git a/sdk/javascript/update-group.mdx b/sdk/javascript/update-group.mdx index 8d90ab334..6e2b791ef 100644 --- a/sdk/javascript/update-group.mdx +++ b/sdk/javascript/update-group.mdx @@ -26,10 +26,10 @@ You can update the existing details of the group using the `updateGroup()` metho ```javascript -var GUID = "GUID"; -var groupName = "Hello Group"; -var groupType = CometChat.GROUP_TYPE.PUBLIC; -var group = new CometChat.Group(GUID, groupName, groupType); +const GUID = "GUID"; +const groupName = "Hello Group"; +const groupType = CometChat.GROUP_TYPE.PUBLIC; +const group = new CometChat.Group(GUID, groupName, groupType); CometChat.updateGroup(group).then( group => { @@ -44,11 +44,11 @@ group => { ```typescript -var GUID: string = "GUID"; -var groupName: string = "Hello Group!"; -var groupType: string = CometChat.GROUP_TYPE.PUBLIC; +const GUID: string = "GUID"; +const groupName: string = "Hello Group!"; +const groupType: string = CometChat.GROUP_TYPE.PUBLIC; -var group: CometChat.Group = new CometChat.Group(GUID, groupName, groupType); +const group: CometChat.Group = new CometChat.Group(GUID, groupName, groupType); CometChat.updateGroup(group).then( (group: CometChat.Group) => { @@ -75,6 +75,23 @@ For more information on the `Group` class, please check [here](/sdk/javascript/c --- + + + - **Only update changed fields** — Set only the fields you want to change on the Group object. Unchanged fields retain their current values. + - **Validate before updating** — Check that the user has admin or moderator scope before showing update options in your UI. + - **Update metadata carefully** — When updating metadata, merge with existing data rather than replacing it entirely to avoid losing other fields. + - **Refresh after update** — After a successful update, refresh the group details in your UI to reflect the changes. + + + - **"Not authorized" error** — Only admins and moderators can update group details. Check the user's scope. + - **Group type not changing** — Group type cannot be changed after creation. This is by design. + - **Update not reflected** — Ensure the update promise resolved successfully. Other members receive the update via `GroupListener`. + - **Metadata overwritten** — When updating metadata, the entire metadata object is replaced. Merge with existing metadata before updating. + + + +--- + ## Next Steps diff --git a/sdk/javascript/upgrading-from-v3.mdx b/sdk/javascript/upgrading-from-v3.mdx index 633bb9c2c..c5d1aff1c 100644 --- a/sdk/javascript/upgrading-from-v3.mdx +++ b/sdk/javascript/upgrading-from-v3.mdx @@ -73,6 +73,20 @@ import {CometChatCalls} from '@cometchat/calls-sdk-javascript'; + +- **Follow the setup guide first** — Complete the v4 [setup instructions](/sdk/javascript/setup-sdk) before changing imports, so you have the latest SDK version installed. +- **Update all imports at once** — Use find-and-replace across your project to change all `@cometchat-pro/chat` imports to `@cometchat/chat-sdk-javascript` in one pass. +- **Test incrementally** — After updating dependencies and imports, test each feature area (messaging, calling, groups) individually to catch any breaking changes. +- **Remove old packages** — After migration, uninstall the v3 packages (`npm uninstall @cometchat-pro/chat`) to avoid conflicts. + + + +- **"Module not found" errors after upgrade** — You likely have old import paths. Search your project for `@cometchat-pro/chat` and replace with `@cometchat/chat-sdk-javascript`. +- **Calls SDK not working** — The calls SDK package name also changed. Use `@cometchat/calls-sdk-javascript` instead of the v3 package. +- **TypeScript type errors** — Some type definitions may have changed between v3 and v4. Check the [changelog](https://github.com/cometchat/chat-sdk-javascript/releases) for breaking type changes. +- **Both v3 and v4 installed** — Having both versions can cause conflicts. Remove the v3 package completely before installing v4. + + --- ## Next Steps diff --git a/sdk/javascript/user-management.mdx b/sdk/javascript/user-management.mdx index 88f2e6a81..440592067 100644 --- a/sdk/javascript/user-management.mdx +++ b/sdk/javascript/user-management.mdx @@ -56,10 +56,10 @@ However, if you wish to create users on the fly, you can use the `createUser()` ```javascript let authKey = "AUTH_KEY"; -var uid = "user1"; -var name = "Kevin"; +let uid = "user1"; +let name = "Kevin"; -var user = new CometChat.User(uid); +let user = new CometChat.User(uid); user.setName(name); @@ -75,10 +75,10 @@ CometChat.createUser(user, authKey).then( ```typescript let authKey: string = "AUTH_KEY"; -var uid: string = "user1"; -var name: string = "Kevin"; +let uid: string = "user1"; +let name: string = "Kevin"; -var user: CometChat.User = new CometChat.User(uid); +let user: CometChat.User = new CometChat.User(uid); user.setName(name); @@ -110,7 +110,7 @@ let authKey = "AUTH_KEY"; let uid = "user1"; let name = "Kevin Fernandez"; -var user = new CometChat.User(uid); +let user = new CometChat.User(uid); user.setName(name); @@ -126,10 +126,10 @@ CometChat.updateUser(user, authKey).then( ```typescript let authKey: string = "AUTH_KEY"; -var uid: string = "user1"; -var name: string = "Kevin Fernandez"; +let uid: string = "user1"; +let name: string = "Kevin Fernandez"; -var user: CometChat.User = new CometChat.User(uid); +let user: CometChat.User = new CometChat.User(uid); user.setName(name); @@ -156,7 +156,7 @@ Updating a logged-in user is similar to updating a user. The only difference bei let uid = "user1"; let name = "Kevin Fernandez"; -var user = new CometChat.User(uid); +let user = new CometChat.User(uid); user.setName(name); @@ -171,10 +171,10 @@ CometChat.updateCurrentUserDetails(user).then( ```typescript -var uid: string = "user1"; -var name: string = "Kevin Fernandez"; +let uid: string = "user1"; +let name: string = "Kevin Fernandez"; -var user: CometChat.User = new CometChat.User(uid); +let user: CometChat.User = new CometChat.User(uid); user.setName(name); diff --git a/sdk/javascript/video-view-customisation.mdx b/sdk/javascript/video-view-customisation.mdx index 57611379e..6fc990afb 100644 --- a/sdk/javascript/video-view-customisation.mdx +++ b/sdk/javascript/video-view-customisation.mdx @@ -56,6 +56,20 @@ videoSettings.setNetworkLabelParams(CometChat.CallSettings.POSITION_BOTTOM_RIGHT + +- **Use position constants** — Always use `CometChat.CallSettings.POSITION_*` constants instead of raw strings for positioning parameters. +- **Test all aspect ratios** — Try both `ASPECT_RATIO_CONTAIN` and `ASPECT_RATIO_COVER` to see which works best for your layout. +- **Keep name labels visible** — Name labels help users identify participants. Only hide them if your UI provides an alternative way to show participant names. +- **Apply settings before starting the call** — Pass the `MainVideoContainerSetting` object to `CallSettingsBuilder` before calling `startCall()`. + + + +- **Settings not applied** — Ensure you pass the `MainVideoContainerSetting` object to `setMainVideoContainerSetting()` on the `CallSettingsBuilder` before starting the call. +- **Full screen button not visible** — Check that `setFullScreenButtonParams()` has `visibility` set to `true` and the position doesn't overlap with other UI elements. +- **Name label background color not changing** — Verify the color string format is correct (e.g., `"rgba(27, 27, 27, 0.4)"` or `"#1B1B1B"`). +- **Video aspect ratio looks wrong** — Try switching between `ASPECT_RATIO_CONTAIN` (shows full video with letterboxing) and `ASPECT_RATIO_COVER` (fills container, may crop). + + ## Next Steps diff --git a/sdk/javascript/virtual-background.mdx b/sdk/javascript/virtual-background.mdx index 5e6f0a9b7..7c21455d4 100644 --- a/sdk/javascript/virtual-background.mdx +++ b/sdk/javascript/virtual-background.mdx @@ -130,6 +130,22 @@ The `VirtualBackground` Class is the required in case you want to change how the | `enforceBackgroundBlur(enforceBackgroundBlur: number)` | This method starts the call with background blurred. To blur the background you need to pass an integer value between 1-99 which decides the blur level. **Default = 0** | | `enforceBackgroundImage(enforceBackgroundImage: string)` | This methods starts the call with the provided background image. | + +- **Use `enforceBackgroundBlur` for privacy** — If your app requires background privacy (e.g., healthcare, finance), enforce blur at the settings level so users can't disable it. +- **Provide default images** — Use `setImages()` to provide a curated set of background images so users have good options without uploading their own. +- **Test blur levels** — Blur levels range from 1–99. Test different values to find the right balance between privacy and visual quality for your use case. +- **Optimize image URLs** — Use compressed images for custom backgrounds. Large images can slow down rendering and increase bandwidth usage. +- **Combine with CallSettings** — Pass the `VirtualBackground` object to `CallSettingsBuilder.setVirtualBackground()` to apply settings before the call starts. + + + +- **Virtual background not appearing** — Ensure the Calls SDK is properly initialized and the call is active before calling `setBackgroundBlur()` or `setBackgroundImage()`. +- **`openVirtualBackground()` does nothing** — The call must be active and the default layout must be enabled for the settings popup to appear. +- **Background image not loading** — Verify the image URL is accessible (CORS-enabled) and the image format is supported (JPEG, PNG). +- **Performance issues with blur** — High blur levels (close to 99) require more processing power. Lower the blur level on less powerful devices. +- **Settings not persisting between calls** — Virtual background settings are per-session. Use `enforceBackgroundBlur()` or `enforceBackgroundImage()` in `VirtualBackground` to apply defaults automatically. + + ## Next Steps From 1169d911224d67b6617ad3be9c542b24db04f31d Mon Sep 17 00:00:00 2001 From: PrajwalDhuleCC Date: Tue, 10 Mar 2026 14:56:06 +0530 Subject: [PATCH 07/43] docs(sdk/javascript): Add message response documentation for "Send A Message" & "Additional Message Filtering" - Add comprehensive response schema documentation for "Send A Message" and "Additional Message Filtering" pages. - Include detailed Message Object parameter tables with types and sample values - Include note about setLimit() best practices for production pagination --- .../additional-message-filtering.mdx | 2444 +++++++++++++++++ sdk/javascript/send-message.mdx | 1335 +++++++++ 2 files changed, 3779 insertions(+) diff --git a/sdk/javascript/additional-message-filtering.mdx b/sdk/javascript/additional-message-filtering.mdx index aa8916377..ba11a3093 100644 --- a/sdk/javascript/additional-message-filtering.mdx +++ b/sdk/javascript/additional-message-filtering.mdx @@ -114,6 +114,115 @@ let messagesRequest: CometChat.MessagesRequest = +When messages are fetched successfully, the response will include an array of message objects containing all information related to each message. + + +The examples on this page use a small `setLimit()` value for brevity. In production, use a higher limit (up to 100) for efficient pagination. + + + +**On Success** — Returns an array of `TextMessage` objects for the specified user conversation: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message ID | `"125641"` | +| `muid` | string | Client-generated unique message ID | `"_19v4y6elj"` | +| `receiverId` | string | UID of the receiver | `"superhero2"` | +| `type` | string | Message type | `"text"` | +| `receiverType` | string | Receiver type | `"user"` | +| `category` | string | Message category | `"message"` | +| `text` | string | The text content of the message | `"hi"` | +| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | +| `sender` | object | Sender user details | [See below ↓](#user-conversation-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#user-conversation-receiver-object) | +| `sentAt` | number | Timestamp when the message was sent (epoch) | `1772706632` | +| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1772706632` | +| `metadata` | object | Extension metadata (data masking, link preview, etc.) | [See below ↓](#user-conversation-metadata-object) | +| `data` | object | Additional message data including entities | [See below ↓](#user-conversation-data-object) | +| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero1"` | +| `name` | string | Display name | `"Iron Man"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772703126` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"online"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero2"` | +| `name` | string | Display name | `"Captain America"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772450329` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Server-injected extension data | Contains `extensions` object | + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "hi", ...}` | +| `link-preview` | object | Link preview extension results | `{"links": []}` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | The text content | `"hi"` | +| `resource` | string | SDK resource identifier | `"WEB-4_1_8-85fc027f-..."` | +| `metadata` | object | Same as top-level metadata | [See above ↑](#user-conversation-metadata-object) | +| `moderation` | object | Moderation status | `{"status": "approved"}` | +| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#user-conversation-entities-object) | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#user-conversation-sender-object) | +| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#user-conversation-receiver-object) | + + + ## Messages for a group conversation *In other words, how do I fetch messages for any group conversation* @@ -143,6 +252,115 @@ let messagesRequest: CometChat.MessagesRequest = +When messages are fetched successfully, the response will include an array of message objects containing all information related to each message. + + +**On Success** — Returns an array of `TextMessage` objects for the specified group conversation: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message ID | `"125647"` | +| `muid` | string | Client-generated unique message ID | `"_wldd52695"` | +| `receiverId` | string | GUID of the group | `"group_1772706842135"` | +| `type` | string | Message type | `"text"` | +| `receiverType` | string | Receiver type | `"group"` | +| `category` | string | Message category | `"message"` | +| `text` | string | The text content of the message | `"how's it going"` | +| `conversationId` | string | Unique conversation identifier | `"group_group_1772706842135"` | +| `sender` | object | Sender user details | [See below ↓](#group-conversation-sender-object) | +| `receiver` | object | Receiver group details | [See below ↓](#group-conversation-receiver-object) | +| `sentAt` | number | Timestamp when the message was sent (epoch) | `1772706897` | +| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1772706897` | +| `metadata` | object | Extension metadata (data masking, link preview, etc.) | [See below ↓](#group-conversation-metadata-object) | +| `data` | object | Additional message data including entities | [See below ↓](#group-conversation-data-object) | +| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero1"` | +| `name` | string | Display name | `"Iron Man"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772706892` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`receiver` Object (Group):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Unique group ID | `"group_1772706842135"` | +| `name` | string | Group name | `"Avengers Group"` | +| `type` | string | Group type | `"public"` | +| `owner` | string | UID of the group owner | `"superhero1"` | +| `scope` | string | Logged-in user's scope in the group | `"admin"` | +| `membersCount` | number | Number of members in the group | `2` | +| `hasJoined` | boolean | Whether the logged-in user has joined | `true` | +| `isBanned` | boolean | Whether the logged-in user is banned | `false` | +| `conversationId` | string | Unique conversation identifier | `"group_group_1772706842135"` | +| `createdAt` | number | Group creation timestamp (epoch) | `1772706842` | +| `joinedAt` | number | Timestamp when the user joined (epoch) | `1772706842` | +| `updatedAt` | number | Last updated timestamp (epoch) | `1772706877` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Server-injected extension data | Contains `extensions` object | + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "how's it going", ...}` | +| `link-preview` | object | Link preview extension results | `{"links": []}` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | The text content | `"how's it going"` | +| `resource` | string | SDK resource identifier | `"WEB-4_1_8-85fc027f-..."` | +| `metadata` | object | Same as top-level metadata | [See above ↑](#group-conversation-metadata-object) | +| `moderation` | object | Moderation status | `{"status": "approved"}` | +| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#group-conversation-entities-object) | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#group-conversation-sender-object) | +| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "group"` — entity matches [receiver ↑](#group-conversation-receiver-object) | + + + If none of the above two methods `setUID()` and `setGUID()` is used, all the messages for the logged-in user will be fetched. This means that messages from all the one-on-one and group conversations which the logged-in user is a part of will be returned.> All the parameters discussed below can be used along with the setUID() or setGUID() or without any of the two to fetch all the messages that the logged-in user is a part of. @@ -218,6 +436,114 @@ let GUID: string = "GUID", This method can be used along with `setUID()` or `setGUID()` methods to fetch messages after/before any specific message-id for a particular user/group conversation. +When messages are fetched successfully, the response will include an array of message objects containing all information related to each message. + + +**On Success** — Returns an array of `TextMessage` objects before or after the specified message ID: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message ID | `"125334"` | +| `muid` | string | Client-generated unique message ID | `"cc_1772437741542_6_zz3xjd2"` | +| `receiverId` | string | UID of the receiver | `"superhero2"` | +| `type` | string | Message type | `"text"` | +| `receiverType` | string | Receiver type | `"user"` | +| `category` | string | Message category | `"message"` | +| `text` | string | The text content of the message | `"hello there"` | +| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | +| `sender` | object | Sender user details | [See below ↓](#before-after-message-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#before-after-message-receiver-object) | +| `sentAt` | number | Timestamp when the message was sent (epoch) | `1772437744` | +| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1772437744` | +| `replyCount` | number | Number of threaded replies to this message | `5` | +| `deliveredAt` | number | Timestamp when the message was delivered (epoch) | `1772450305` | +| `readAt` | number | Timestamp when the message was read (epoch) | `1772450305` | +| `metadata` | object | Extension metadata (data masking, link preview, etc.) | [See below ↓](#before-after-message-metadata-object) | +| `data` | object | Additional message data including entities | [See below ↓](#before-after-message-data-object) | +| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero1"` | +| `name` | string | Display name | `"Iron Man"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772437730` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"online"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero2"` | +| `name` | string | Display name | `"Captain America"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772384727` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Server-injected extension data | Contains `extensions` object | + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "hello there", ...}` | +| `link-preview` | object | Link preview extension results | `{"links": []}` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | The text content | `"hello there"` | +| `resource` | string | SDK resource identifier | `"WEB-4_1_5-bd01135d-..."` | +| `metadata` | object | Same as top-level metadata | [See above ↑](#before-after-message-metadata-object) | +| `moderation` | object | Moderation status | `{"status": "approved"}` | +| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#before-after-message-entities-object) | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#before-after-message-sender-object) | +| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#before-after-message-receiver-object) | + + + ## Messages before/after a given time *In other words, how do I fetch messages before or after a particular date or time* @@ -287,6 +613,111 @@ let GUID: string = "GUID", This method can be used along with `setUID()` or `setGUID()` methods to fetch messages after/before any specific date or time for a particular user/group conversation. +When messages are fetched successfully, the response will include an array of message objects containing all information related to each message. + + +**On Success** — Returns an array of `TextMessage` objects before or after the specified timestamp: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message ID | `"125641"` | +| `muid` | string | Client-generated unique message ID | `"_19v4y6elj"` | +| `receiverId` | string | UID of the receiver | `"superhero2"` | +| `type` | string | Message type | `"text"` | +| `receiverType` | string | Receiver type | `"user"` | +| `category` | string | Message category | `"message"` | +| `text` | string | The text content of the message | `"hi"` | +| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | +| `sender` | object | Sender user details | [See below ↓](#before-after-time-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#before-after-time-receiver-object) | +| `sentAt` | number | Timestamp when the message was sent (epoch) | `1772706632` | +| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1772706632` | +| `metadata` | object | Extension metadata (data masking, link preview, etc.) | [See below ↓](#before-after-time-metadata-object) | +| `data` | object | Additional message data including entities | [See below ↓](#before-after-time-data-object) | +| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero1"` | +| `name` | string | Display name | `"Iron Man"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772703126` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"online"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero2"` | +| `name` | string | Display name | `"Captain America"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772450329` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Server-injected extension data | Contains `extensions` object | + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "hi", ...}` | +| `link-preview` | object | Link preview extension results | `{"links": []}` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | The text content | `"hi"` | +| `resource` | string | SDK resource identifier | `"WEB-4_1_8-85fc027f-..."` | +| `metadata` | object | Same as top-level metadata | [See above ↑](#before-after-time-metadata-object) | +| `moderation` | object | Moderation status | `{"status": "approved"}` | +| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#before-after-time-entities-object) | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#before-after-time-sender-object) | +| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#before-after-time-receiver-object) | + + + ## Unread messages *In other words, how do I fetch unread messages* @@ -352,6 +783,111 @@ let GUID: string = "GUID", This method along with `setGUID()` or `setUID()` can be used to fetch unread messages for a particular group or user conversation respectively. +When messages are fetched successfully, the response will include an array of unread message objects. + + +**On Success** — Returns an array of unread `TextMessage` objects for the specified conversation: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message ID | `"125652"` | +| `muid` | string | Client-generated unique message ID | `"_363o8rfag"` | +| `receiverId` | string | UID of the receiver | `"superhero1"` | +| `type` | string | Message type | `"text"` | +| `receiverType` | string | Receiver type | `"user"` | +| `category` | string | Message category | `"message"` | +| `text` | string | The text content of the message | `"I'm fine"` | +| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | +| `sender` | object | Sender user details | [See below ↓](#unread-messages-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#unread-messages-receiver-object) | +| `sentAt` | number | Timestamp when the message was sent (epoch) | `1772708621` | +| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1772708622` | +| `deliveredAt` | number | Timestamp when the message was delivered (epoch) | `1772708622` | +| `metadata` | object | Extension metadata (data masking, link preview, etc.) | [See below ↓](#unread-messages-metadata-object) | +| `data` | object | Additional message data including entities | [See below ↓](#unread-messages-data-object) | +| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero2"` | +| `name` | string | Display name | `"Captain America"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772708593` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"online"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero1"` | +| `name` | string | Display name | `"Iron Man"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772708586` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"online"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Server-injected extension data | Contains `extensions` object | + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "I'm fine", ...}` | +| `link-preview` | object | Link preview extension results | `{"links": []}` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | The text content | `"I'm fine"` | +| `resource` | string | SDK resource identifier | `"WEB-4_1_8-1b3edc1d-..."` | +| `metadata` | object | Same as top-level metadata | [See above ↑](#unread-messages-metadata-object) | +| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#unread-messages-entities-object) | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#unread-messages-sender-object) | +| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#unread-messages-receiver-object) | + + + ## Exclude messages from blocked users *In other words, how do I fetch messages excluding the messages from the users I have blocked* @@ -417,6 +953,10 @@ let GUID: string = "GUID", This method can be used to hide the messages by users blocked by logged in user in groups that both the members are a part of. + +**On Success** — The response structure is the same as a regular message fetch. The only difference is that messages from blocked users will be absent from the results. For one such regular response structure, see [Messages for group conversation ↑](#group-conversation-response). + + ## Updated and received messages *In other words, how do I fetch messages that have been received or updated after a particular date or time* @@ -486,6 +1026,123 @@ let GUID: string = "GUID", This can be useful in finding the messages that have been received or updated after a certain time. Can prove very useful if you are saving the messages locally and would like to know the messages that have been updated or received after the last message available in your local databases. +When messages are fetched successfully, the response may include both action messages (for updates like edits, deletes, read/delivered status changes) and regular messages (for newly received messages). + + +**On Success** — Returns an array containing action messages (for updates) and regular messages (for new messages received after the specified timestamp): + + + +**Action Message Object (for edited/deleted/read/delivered updates):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message ID | `"125657"` | +| `receiverId` | string | UID of the receiver | `"superhero2"` | +| `type` | string | Message type | `"message"` | +| `receiverType` | string | Receiver type | `"user"` | +| `category` | string | Message category | `"action"` | +| `action` | string | The action that was performed | `"edited"` | +| `message` | string | Action message text | `""` | +| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | +| `actionBy` | object | User who performed the action | [See below ↓](#updated-received-actionby-object) | +| `actionFor` | object | User the action was performed for | [See below ↓](#updated-received-actionfor-object) | +| `actionOn` | object | The message that was acted upon | [See below ↓](#updated-received-actionon-object) | +| `sender` | object | Sender user details (same as actionBy) | [See below ↓](#updated-received-actionby-object) | +| `receiver` | object | Receiver user details | [See below ↓](#updated-received-actionfor-object) | +| `sentAt` | number | Timestamp when the action occurred (epoch) | `1772709041` | +| `updatedAt` | number | Timestamp when the action was last updated (epoch) | `1772709041` | +| `data` | object | Action data including entities | [See below ↓](#updated-received-data-object) | +| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | + +--- + + + +**`actionBy` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero1"` | +| `name` | string | Display name | `"Iron Man"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772709037` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`actionFor` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero2"` | +| `name` | string | Display name | `"Captain America"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772709006` | +| `conversationId` | string | Conversation identifier | `"superhero1_user_superhero2"` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"online"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`actionOn` Object (the message that was edited/deleted):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message ID | `"125654"` | +| `muid` | string | Client-generated unique message ID | `"_umdly7vy7"` | +| `receiverId` | string | UID of the receiver | `"superhero2"` | +| `type` | string | Message type | `"text"` | +| `receiverType` | string | Receiver type | `"user"` | +| `category` | string | Message category | `"message"` | +| `text` | string | The updated text content | `"hello edited"` | +| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | +| `sender` | object | Sender user details | Same structure as [actionBy ↑](#updated-received-actionby-object) | +| `receiver` | object | Receiver user details | Same structure as [actionFor ↑](#updated-received-actionfor-object) | +| `sentAt` | number | Original sent timestamp (epoch) | `1772709026` | +| `updatedAt` | number | Last updated timestamp (epoch) | `1772709027` | +| `deliveredAt` | number | Delivered timestamp (epoch) | `1772709027` | +| `editedAt` | number | Timestamp when the message was edited (epoch) | `1772709041` | +| `editedBy` | string | UID of the user who edited the message | `"superhero1"` | +| `metadata` | object | Extension metadata | Same structure as regular message metadata | +| `data` | object | Message data with entities and text | Contains `text`, `resource`, `metadata`, `moderation`, `entities` | +| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | + +--- + + + +**`data` Object (Action Message):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `action` | string | The action type | `"edited"` | +| `resource` | string | SDK resource identifier | `"WEB-4_1_8-85fc027f-..."` | +| `entities` | object | Entity wrappers for the action | [See below ↓](#updated-received-entities-object) | + +--- + + + +**`data.entities` Object (Action Message):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `by` | object | Entity wrapper for who performed the action (`{entity, entityType}`) | `entityType: "user"` — entity matches [actionBy ↑](#updated-received-actionby-object) | +| `for` | object | Entity wrapper for who the action was for (`{entity, entityType}`) | `entityType: "user"` — entity matches [actionFor ↑](#updated-received-actionfor-object) | +| `on` | object | Entity wrapper for the message acted upon (`{entity, entityType}`) | `entityType: "message"` — entity matches [actionOn ↑](#updated-received-actionon-object) | + + + ## Updated messages only *In other words, how do I fetch messages that have been updated after a particular date or time* @@ -557,6 +1214,115 @@ let GUID: string = "GUID", +When messages are fetched successfully, the response will include only the messages that have been updated (edited, deleted, read/delivered status changed) after the specified timestamp — not newly received messages. + + +**On Success** — Returns an array of updated `TextMessage` objects (edited messages in this example): + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message ID | `"125671"` | +| `muid` | string | Client-generated unique message ID | `"_bf82a3mae"` | +| `receiverId` | string | UID of the receiver | `"superhero2"` | +| `type` | string | Message type | `"text"` | +| `receiverType` | string | Receiver type | `"user"` | +| `category` | string | Message category | `"message"` | +| `text` | string | The updated text content of the message | `"one - edited"` | +| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | +| `sender` | object | Sender user details | [See below ↓](#updated-only-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#updated-only-receiver-object) | +| `sentAt` | number | Timestamp when the message was originally sent (epoch) | `1772710689` | +| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1772710741` | +| `editedAt` | number | Timestamp when the message was edited (epoch) | `1772710741` | +| `editedBy` | string | UID of the user who edited the message | `"superhero1"` | +| `deliveredAt` | number | Timestamp when the message was delivered (epoch) | `1772710690` | +| `readAt` | number | Timestamp when the message was read (epoch) | `1772710690` | +| `metadata` | object | Extension metadata (data masking, link preview, etc.) | [See below ↓](#updated-only-metadata-object) | +| `data` | object | Additional message data including entities | [See below ↓](#updated-only-data-object) | +| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero1"` | +| `name` | string | Display name | `"Iron Man"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772710681` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero2"` | +| `name` | string | Display name | `"Captain America"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772710682` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Server-injected extension data | Contains `extensions` object | + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "one", ...}` | +| `link-preview` | object | Link preview extension results | `{"links": []}` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | The updated text content | `"one - edited"` | +| `resource` | string | SDK resource identifier | `"WEB-4_1_8-85fc027f-..."` | +| `metadata` | object | Same as top-level metadata | [See above ↑](#updated-only-metadata-object) | +| `moderation` | object | Moderation status | `{"status": "approved"}` | +| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#updated-only-entities-object) | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#updated-only-sender-object) | +| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#updated-only-receiver-object) | + + + ## Messages for multiple categories *In other words, how do I fetch messages belonging to multiple categories* @@ -628,6 +1394,176 @@ let GUID: string = "GUID", The above snippet will help you get only the messages belonging to the `message` and `custom` category. This can also be used to disable certain categories of messages like `call` and `action`. + +**On Success** — Returns an array containing messages from the specified categories (`custom` and `call` in this example). The response includes different message structures depending on the category: + + + +**Custom Message Object (category: `custom`):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message ID | `"125679"` | +| `muid` | string | Client-generated unique message ID | `"_0jfpc22x9"` | +| `receiverId` | string | UID of the receiver | `"superhero2"` | +| `type` | string | Message type (extension-specific) | `"extension_sticker"` | +| `receiverType` | string | Receiver type | `"user"` | +| `category` | string | Message category | `"custom"` | +| `customData` | object | Custom data payload for this message | `{"sticker_name": "happy ghost", "sticker_url": "https://..."}` | +| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | +| `sender` | object | Sender user details | [See below ↓](#multiple-categories-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#multiple-categories-receiver-object) | +| `sentAt` | number | Timestamp when the message was sent (epoch) | `1772710916` | +| `deliveredAt` | number | Timestamp when the message was delivered (epoch) | `1772710917` | +| `readAt` | number | Timestamp when the message was read (epoch) | `1772710917` | +| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1772710917` | +| `metadata` | object | Message metadata | [See below ↓](#multiple-categories-custom-metadata-object) | +| `data` | object | Additional message data including entities | [See below ↓](#multiple-categories-custom-data-object) | +| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero1"` | +| `name` | string | Display name | `"Iron Man"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772710911` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"online"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero2"` | +| `name` | string | Display name | `"Captain America"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772710895` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`metadata` Object (Custom Message):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `incrementUnreadCount` | boolean | Whether this message increments the unread count | `true` | + +--- + + + +**`data` Object (Custom Message):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `customData` | object | Custom data payload | `{"sticker_name": "happy ghost", "sticker_url": "https://..."}` | +| `resource` | string | SDK resource identifier | `"WEB-4_1_8-85fc027f-..."` | +| `updateConversation` | boolean | Whether this message updates the conversation list | `true` | +| `metadata` | object | Message metadata | `{"incrementUnreadCount": true}` | +| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#multiple-categories-custom-entities-object) | + +--- + + + +**`data.entities` Object (Custom Message):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#multiple-categories-sender-object) | +| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#multiple-categories-receiver-object) | + +--- + + + +**Call Message Object (category: `call`):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message ID | `"125680"` | +| `receiverId` | string | UID of the receiver | `"superhero2"` | +| `type` | string | Call type | `"audio"` | +| `receiverType` | string | Receiver type | `"user"` | +| `category` | string | Message category | `"call"` | +| `action` | string | Call action | `"initiated"` or `"cancelled"` | +| `sessionId` | string | Unique call session identifier | `"v1.us.208136f5ba34a5a2.1772711101..."` | +| `status` | string | Call status | `"initiated"` or `"cancelled"` | +| `initiatedAt` | number | Timestamp when the call was initiated (epoch) | `1772711101` | +| `joinedAt` | number | Timestamp when the caller joined (epoch, present for `initiated`) | `1772711101` | +| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | +| `sender` | object | Sender user details | [See above ↑](#multiple-categories-sender-object) | +| `receiver` | object | Receiver user details | [See above ↑](#multiple-categories-receiver-object) | +| `sentAt` | number | Timestamp when the message was sent (epoch) | `1772711101` | +| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1772711101` | +| `callInitiator` | object | User who initiated the call | Same structure as [sender ↑](#multiple-categories-sender-object) | +| `callReceiver` | object | User who received the call | Same structure as [receiver ↑](#multiple-categories-receiver-object) | +| `data` | object | Call data including action entities | [See below ↓](#multiple-categories-call-data-object) | +| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | + +--- + + + +**`data` Object (Call Message):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `action` | string | Call action type | `"initiated"` or `"cancelled"` | +| `resource` | string | SDK resource identifier | `"WEB-4_1_8-85fc027f-..."` | +| `entities` | object | Call entity wrappers | [See below ↓](#multiple-categories-call-entities-object) | + +--- + + + +**`data.entities` Object (Call Message):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `by` | object | User who performed the action (`{entity, entityType}`) | `entityType: "user"` — the call initiator | +| `for` | object | User the action was performed for (`{entity, entityType}`) | `entityType: "user"` — the call receiver | +| `on` | object | The call session entity (`{entity, entityType}`) | `entityType: "call"` — [See below ↓](#multiple-categories-call-on-entity) | + +--- + + + +**`data.entities.on.entity` Object (Call Session):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `conversationId` | string | Conversation identifier | `"superhero1_user_superhero2"` | +| `sender` | string | UID of the call sender | `"superhero1"` | +| `receiver` | string | UID of the call receiver | `"superhero2"` | +| `receiverType` | string | Receiver type | `"user"` | +| `type` | string | Call type | `"audio"` | +| `status` | string | Call status | `"initiated"` or `"cancelled"` | +| `sessionid` | string | Call session ID | `"v1.us.208136f5ba34a5a2.1772711101..."` | +| `initiatedAt` | number | Timestamp when the call was initiated (epoch) | `1772711101` | +| `joinedAt` | number | Timestamp when the caller joined (epoch, present for `initiated`) | `1772711101` | +| `data` | object | Nested entities for sender/receiver | Contains `entities` with `sender` and `receiver` wrappers | +| `wsChannel` | object | WebSocket channel details for the call | `{"identity": "...", "secret": "...", "service": "..."}` | + + + ## Messages for multiple types *In other words, how do I fetch messages belonging to multiple types* @@ -707,6 +1643,139 @@ let GUID: string = "GUID", Using the above code snippet, you can fetch all the media messages. + +**On Success** — Returns an array of media `Message` objects matching the specified types (`image` and `audio` in this example): + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message ID | `"125754"` | +| `muid` | string | Client-generated unique message ID | `"_i62mzac34"` | +| `receiverId` | string | UID of the receiver | `"superhero2"` | +| `type` | string | Message type (matches the requested types) | `"audio"` or `"image"` | +| `receiverType` | string | Receiver type | `"user"` | +| `category` | string | Message category | `"message"` | +| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | +| `sender` | object | Sender user details | [See below ↓](#multiple-types-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#multiple-types-receiver-object) | +| `sentAt` | number | Timestamp when the message was sent (epoch) | `1772791833` | +| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1772791833` | +| `metadata` | object | File and extension metadata | [See below ↓](#multiple-types-metadata-object) | +| `data` | object | Additional message data including attachments and entities | [See below ↓](#multiple-types-data-object) | +| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero1"` | +| `name` | string | Display name | `"Iron Man"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772791811` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"online"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero2"` | +| `name` | string | Display name | `"Captain America"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772719315` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`metadata` Object:** + +The metadata structure varies by message type: + +**For `audio` messages:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `file` | array | File reference array | `[]` | +| `fileName` | string | Name of the audio file | `"recording.wav"` | +| `fileSize` | number | File size in bytes | `409004` | +| `fileType` | string | MIME type of the file | `"audio/wav"` | + +**For `image` messages:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Server-injected extension data | Contains `extensions` object | +| `file` | array | File reference array | `[]` | +| `fileName` | string | Name of the image file | `"dummy.webp"` | +| `fileSize` | number | File size in bytes | `19554` | +| `fileType` | string | MIME type of the file | `"image/webp"` | + +**`metadata.@injected.extensions` Object (Image):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `thumbnail-generation` | object | Generated thumbnail URLs for the image | Contains `url_small`, `url_medium`, `url_large`, and `attachments` array | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `attachments` | array | Array of attachment objects | [See below ↓](#multiple-types-attachments-object) | +| `url` | string | Direct URL to the media file | `"https://data-us.cometchat.io/..."` | +| `resource` | string | SDK resource identifier | `"WEB-4_1_8-3893da9d-..."` | +| `metadata` | object | Same as top-level metadata | [See above ↑](#multiple-types-metadata-object) | +| `moderation` | object | Moderation status | `{"status": "approved"}` | +| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#multiple-types-entities-object) | + +--- + + + +**`data.attachments` Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extension` | string | File extension | `"wav"` or `"webp"` | +| `mimeType` | string | MIME type | `"audio/wav"` or `"image/webp"` | +| `name` | string | File name | `"recording.wav"` | +| `size` | number | File size in bytes | `409004` | +| `url` | string | Direct URL to the file | `"https://data-us.cometchat.io/..."` | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#multiple-types-sender-object) | +| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#multiple-types-receiver-object) | + + + ## Messages for a specific thread *In other words, how do I fetch messages that are a part of a thread and not directly a user/group conversations* @@ -776,6 +1845,110 @@ let GUID: string = "GUID", The above code snippet returns the messages that belong to the thread with parent id 100. + +**On Success** — Returns an array of `TextMessage` objects that belong to the specified thread (replies to the parent message): + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message ID | `"125758"` | +| `muid` | string | Client-generated unique message ID | `"_angx5llih"` | +| `receiverId` | string | UID of the receiver | `"superhero2"` | +| `type` | string | Message type | `"text"` | +| `receiverType` | string | Receiver type | `"user"` | +| `category` | string | Message category | `"message"` | +| `text` | string | The text content of the thread reply | `"thread reply 1"` | +| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | +| `parentMessageId` | string | ID of the parent message this reply belongs to | `"125751"` | +| `sender` | object | Sender user details | [See below ↓](#thread-messages-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#thread-messages-receiver-object) | +| `sentAt` | number | Timestamp when the message was sent (epoch) | `1772797901` | +| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1772797901` | +| `metadata` | object | Extension metadata (data masking, link preview, etc.) | [See below ↓](#thread-messages-metadata-object) | +| `data` | object | Additional message data including entities | [See below ↓](#thread-messages-data-object) | +| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero1"` | +| `name` | string | Display name | `"Iron Man"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772797895` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero2"` | +| `name` | string | Display name | `"Captain America"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772719315` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Server-injected extension data | Contains `extensions` object | + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "thread reply 1", ...}` | +| `link-preview` | object | Link preview extension results | `{"links": []}` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | The text content of the thread reply | `"thread reply 1"` | +| `resource` | string | SDK resource identifier | `"WEB-4_1_8-7cf7e736-..."` | +| `metadata` | object | Same as top-level metadata | [See above ↑](#thread-messages-metadata-object) | +| `moderation` | object | Moderation status | `{"status": "approved"}` | +| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#thread-messages-entities-object) | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#thread-messages-sender-object) | +| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#thread-messages-receiver-object) | + + + ## Hide threaded messages in user/group conversations *In other words, how do I exclude threaded messages from the normal user/group conversations* @@ -839,6 +2012,110 @@ let GUID: string = "GUID", + +**On Success** — Returns an array of `TextMessage` objects from the main conversation only (thread replies are excluded). Messages that are thread parents will still appear with their `replyCount`: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message ID | `"125884"` | +| `muid` | string | Client-generated unique message ID | `"_g5o26um1n"` | +| `receiverId` | string | UID of the receiver | `"superhero2"` | +| `type` | string | Message type | `"text"` | +| `receiverType` | string | Receiver type | `"user"` | +| `category` | string | Message category | `"message"` | +| `text` | string | The text content of the message | `"hello"` | +| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | +| `replyCount` | number | Number of thread replies (present only on thread parent messages) | `2` | +| `sender` | object | Sender user details | [See below ↓](#hide-threaded-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#hide-threaded-receiver-object) | +| `sentAt` | number | Timestamp when the message was sent (epoch) | `1773060107` | +| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1773060107` | +| `metadata` | object | Extension metadata (data masking, link preview, etc.) | [See below ↓](#hide-threaded-metadata-object) | +| `data` | object | Additional message data including entities | [See below ↓](#hide-threaded-data-object) | +| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero1"` | +| `name` | string | Display name | `"Iron Man"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1773060100` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"online"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero2"` | +| `name` | string | Display name | `"Captain America"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1773041090` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Server-injected extension data | Contains `extensions` object | + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "hello", ...}` | +| `link-preview` | object | Link preview extension results | `{"links": []}` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | The text content | `"hello"` | +| `resource` | string | SDK resource identifier | `"WEB-4_1_8-5c0e1cd7-..."` | +| `metadata` | object | Same as top-level metadata | [See above ↑](#hide-threaded-metadata-object) | +| `moderation` | object | Moderation status | `{"status": "approved"}` | +| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#hide-threaded-entities-object) | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#hide-threaded-sender-object) | +| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#hide-threaded-receiver-object) | + + + ## Hide deleted messages in user/group conversations *In other words, how do I exclude deleted messages a user/group conversations* @@ -902,6 +2179,110 @@ let GUID: string = "GUID", + + +On Success — Returns an array of `TextMessage` objects from the conversation, excluding any messages that have been deleted. Deleted messages are simply absent from the results. In this example, `categories: ["message"]` was also set to filter for standard messages only. + + + +**Message Object (per element in the array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message ID | `"125904"` | +| `muid` | string | Client-generated unique message ID | `"_nj0d6qk3v"` | +| `receiverId` | string | UID of the receiver | `"superhero2"` | +| `type` | string | Message type | `"text"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Text content of the message | `"msg before deleted msg"` | +| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | +| `sender` | object | Sender user details | [See below ↓](#hide-deleted-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#hide-deleted-receiver-object) | +| `sentAt` | number | Timestamp when the message was sent (epoch) | `1773129488` | +| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1773129488` | +| `metadata` | object | Extension metadata (data masking, link preview, etc.) | [See below ↓](#hide-deleted-metadata-object) | +| `data` | object | Additional message data including entities | [See below ↓](#hide-deleted-data-object) | +| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero1"` | +| `name` | string | Display name | `"Iron Man"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1773129390` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"online"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero2"` | +| `name` | string | Display name | `"Captain America"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1773124800` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Server-injected extension data | Contains `extensions` object | + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "msg before deleted msg", ...}` | +| `link-preview` | object | Link preview extension results | `{"links": []}` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | The text content of the message | `"msg before deleted msg"` | +| `resource` | string | SDK resource identifier | `"WEB-4_1_8-939a34c6-..."` | +| `metadata` | object | Same as top-level metadata | [See above ↑](#hide-deleted-metadata-object) | +| `moderation` | object | Moderation status | `{"status": "approved"}` | +| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#hide-deleted-entities-object) | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#hide-deleted-sender-object) | +| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#hide-deleted-receiver-object) | + + + ## Hide quoted messages in user/group conversations *In other words, how do I exclude quoted messages in a user/group conversations* @@ -965,6 +2346,109 @@ let GUID: string = "GUID", + +**On Success** — Returns an array of `TextMessage` objects from the conversation, excluding any messages that were sent as quoted replies. Only original (non-quoted) messages are included: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message ID | `"125889"` | +| `muid` | string | Client-generated unique message ID | `"_5d8kekzrn"` | +| `receiverId` | string | UID of the receiver | `"superhero2"` | +| `type` | string | Message type | `"text"` | +| `receiverType` | string | Receiver type | `"user"` | +| `category` | string | Message category | `"message"` | +| `text` | string | The text content of the message | `"hello"` | +| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | +| `sender` | object | Sender user details | [See below ↓](#hide-quoted-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#hide-quoted-receiver-object) | +| `sentAt` | number | Timestamp when the message was sent (epoch) | `1773060624` | +| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1773060624` | +| `metadata` | object | Extension metadata (data masking, link preview, etc.) | [See below ↓](#hide-quoted-metadata-object) | +| `data` | object | Additional message data including entities | [See below ↓](#hide-quoted-data-object) | +| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero1"` | +| `name` | string | Display name | `"Iron Man"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1773060591` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"online"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero2"` | +| `name` | string | Display name | `"Captain America"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1773041090` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Server-injected extension data | Contains `extensions` object | + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "hello", ...}` | +| `link-preview` | object | Link preview extension results | `{"links": []}` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | The text content | `"hello"` | +| `resource` | string | SDK resource identifier | `"WEB-4_1_8-5c0e1cd7-..."` | +| `metadata` | object | Same as top-level metadata | [See above ↑](#hide-quoted-metadata-object) | +| `moderation` | object | Moderation status | `{"status": "approved"}` | +| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#hide-quoted-entities-object) | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#hide-quoted-sender-object) | +| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#hide-quoted-receiver-object) | + + + ## Messages by tags *In other words, how do I fetch messages by tags* @@ -1032,6 +2516,109 @@ let GUID: string = "GUID", + +**On Success** — Returns an array of `TextMessage` objects that match the specified tags (`tags: ["tag1"]` in this example). Only messages tagged with the provided tags are returned: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message ID | `"125893"` | +| `receiverId` | string | UID of the receiver | `"superhero2"` | +| `type` | string | Message type | `"text"` | +| `receiverType` | string | Receiver type | `"user"` | +| `category` | string | Message category | `"message"` | +| `text` | string | The text content of the message | `"message 1 with tag1"` | +| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | +| `sender` | object | Sender user details | [See below ↓](#messages-by-tags-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#messages-by-tags-receiver-object) | +| `sentAt` | number | Timestamp when the message was sent (epoch) | `1773123536` | +| `deliveredAt` | number | Timestamp when the message was delivered (epoch) | `1773123537` | +| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1773123537` | +| `metadata` | object | Extension metadata (data masking, link preview, etc.) | [See below ↓](#messages-by-tags-metadata-object) | +| `data` | object | Additional message data including entities | [See below ↓](#messages-by-tags-data-object) | +| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero1"` | +| `name` | string | Display name | `"Iron Man"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1773123450` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"online"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero2"` | +| `name` | string | Display name | `"Captain America"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1773123510` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"online"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Server-injected extension data | Contains `extensions` object | + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "message 1 with tag1", ...}` | +| `link-preview` | object | Link preview extension results | `{"links": []}` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | The text content | `"message 1 with tag1"` | +| `resource` | string | SDK resource identifier | `"WEB-4_1_8-705024e4-..."` | +| `metadata` | object | Same as top-level metadata | [See above ↑](#messages-by-tags-metadata-object) | +| `moderation` | object | Moderation status | `{"status": "approved"}` | +| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#messages-by-tags-entities-object) | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#messages-by-tags-sender-object) | +| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#messages-by-tags-receiver-object) | + + + ## Messages with tags *In other words, how do I fetch messages with the tags information* @@ -1095,6 +2682,110 @@ let GUID: string = "GUID", + +**On Success** — Returns an array of `TextMessage` objects with the `tags` information included on each message. Messages that have tags will include a `tags` array, while messages without tags will not have this field: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message ID | `"125894"` | +| `receiverId` | string | UID of the receiver | `"superhero2"` | +| `type` | string | Message type | `"text"` | +| `receiverType` | string | Receiver type | `"user"` | +| `category` | string | Message category | `"message"` | +| `text` | string | The text content of the message | `"hello"` | +| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | +| `tags` | array | Array of tag strings associated with this message (only present on tagged messages) | `["tag1"]` | +| `sender` | object | Sender user details | [See below ↓](#messages-with-tags-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#messages-with-tags-receiver-object) | +| `sentAt` | number | Timestamp when the message was sent (epoch) | `1773123546` | +| `deliveredAt` | number | Timestamp when the message was delivered (epoch) | `1773123547` | +| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1773123547` | +| `metadata` | object | Extension metadata (data masking, link preview, etc.) | [See below ↓](#messages-with-tags-metadata-object) | +| `data` | object | Additional message data including entities | [See below ↓](#messages-with-tags-data-object) | +| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero1"` | +| `name` | string | Display name | `"Iron Man"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1773123450` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"online"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero2"` | +| `name` | string | Display name | `"Captain America"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1773123510` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"online"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Server-injected extension data | Contains `extensions` object | + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "hello", ...}` | +| `link-preview` | object | Link preview extension results | `{"links": []}` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | The text content | `"hello"` | +| `resource` | string | SDK resource identifier | `"WEB-4_1_8-705024e4-..."` | +| `metadata` | object | Same as top-level metadata | [See above ↑](#messages-with-tags-metadata-object) | +| `moderation` | object | Moderation status | `{"status": "approved"}` | +| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#messages-with-tags-entities-object) | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#messages-with-tags-sender-object) | +| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#messages-with-tags-receiver-object) | + + + ## Messages with links In other words, as a logged-in user, how do I fetch messages that contains links? @@ -1164,6 +2855,110 @@ let GUID: string = "GUID", + +**On Success** — Returns an array of `TextMessage` objects that contain links in their text content: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message ID | `"125896"` | +| `receiverId` | string | UID of the receiver | `"superhero2"` | +| `type` | string | Message type | `"text"` | +| `receiverType` | string | Receiver type | `"user"` | +| `category` | string | Message category | `"message"` | +| `text` | string | The text content containing a link | `"hey, check out: https://www.example.com"` | +| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | +| `sender` | object | Sender user details | [See below ↓](#messages-with-links-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#messages-with-links-receiver-object) | +| `sentAt` | number | Timestamp when the message was sent (epoch) | `1773123969` | +| `deliveredAt` | number | Timestamp when the message was delivered (epoch) | `1773123969` | +| `readAt` | number | Timestamp when the message was read (epoch) | `1773123983` | +| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1773123983` | +| `metadata` | object | Extension metadata (data masking, link preview, etc.) | [See below ↓](#messages-with-links-metadata-object) | +| `data` | object | Additional message data including entities | [See below ↓](#messages-with-links-data-object) | +| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero1"` | +| `name` | string | Display name | `"Iron Man"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1773123450` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"online"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero2"` | +| `name` | string | Display name | `"Captain America"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1773123678` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"online"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Server-injected extension data | Contains `extensions` object | + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "hey, check out: https://www.example.com", ...}` | +| `link-preview` | object | Link preview extension results | `{"links": []}` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | The text content containing a link | `"hey, check out: https://www.example.com"` | +| `resource` | string | SDK resource identifier | `"WEB-4_1_8-705024e4-..."` | +| `metadata` | object | Same as top-level metadata | [See above ↑](#messages-with-links-metadata-object) | +| `moderation` | object | Moderation status | `{"status": "approved"}` | +| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#messages-with-links-entities-object) | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#messages-with-links-sender-object) | +| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#messages-with-links-receiver-object) | + + + ## Messages with attachments In other words, as a logged-in user, how do I fetch messages that contains attachments? @@ -1233,6 +3028,130 @@ let GUID: string = "GUID", +The response will contain a list of media message objects with attachment details, including file metadata and thumbnail URLs. + + + +On Success — Returns an array of `MediaMessage` objects. Each message includes an `attachments` array with file details, plus thumbnail generation metadata when available. + + + +**Message Object (per element in the array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message ID | `"125898"` | +| `muid` | string | Client-generated unique message ID | `"_boivkgy41"` | +| `receiverId` | string | UID of the receiver | `"superhero2"` | +| `type` | string | Message type (image, audio, video, file) | `"image"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Text content (empty for media messages) | — | +| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | +| `sender` | object | Sender user details | [See below ↓](#messages-with-attachments-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#messages-with-attachments-receiver-object) | +| `sentAt` | number | Timestamp when the message was sent (epoch) | `1773124815` | +| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1773124815` | +| `metadata` | object | Extension metadata (thumbnail generation, file info) | [See below ↓](#messages-with-attachments-metadata-object) | +| `data` | object | Additional message data including attachments and entities | [See below ↓](#messages-with-attachments-data-object) | +| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero1"` | +| `name` | string | Display name | `"Iron Man"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1773124809` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero2"` | +| `name` | string | Display name | `"Captain America"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1773124800` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Server-injected extension data | Contains `extensions` object | +| `file` | array | File reference array | `[]` | +| `fileName` | string | Original file name | `"dummy.jpg"` | +| `fileSize` | number | File size in bytes | `5253` | +| `fileType` | string | MIME type of the file | `"image/jpeg"` | + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `thumbnail-generation` | object | Thumbnail generation results with URLs for small, medium, and large thumbnails | `{"url_small": "https://..._small.jpg", "url_medium": "https://..._medium.jpg", "url_large": "https://..._large.jpg", "attachments": [...]}` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `url` | string | Direct URL to the media file | `"https://data-us.cometchat.io/.../image.jpg"` | +| `attachments` | array | Array of attachment objects | [See below ↓](#messages-with-attachments-attachments-array) | +| `resource` | string | SDK resource identifier | `"WEB-4_1_8-939a34c6-..."` | +| `metadata` | object | Same as top-level metadata | [See above ↑](#messages-with-attachments-metadata-object) | +| `moderation` | object | Moderation status | `{"status": "approved"}` | +| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#messages-with-attachments-entities-object) | + +--- + + + +**`data.attachments` Array (per element):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extension` | string | File extension | `"jpg"` | +| `mimeType` | string | MIME type | `"image/jpeg"` | +| `name` | string | File name | `"dummy.jpg"` | +| `size` | number | File size in bytes | `5253` | +| `url` | string | Direct URL to the file | `"https://data-us.cometchat.io/.../image.jpg"` | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#messages-with-attachments-sender-object) | +| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#messages-with-attachments-receiver-object) | + + + ## Messages with reactions In other words, as a logged-in user, how do I fetch messages that contains reactions? @@ -1302,6 +3221,126 @@ let GUID: string = "GUID", +The response will contain a list of message objects that have reactions. Each message's `data` object includes a `reactions` array with emoji details. + + + +On Success — Returns an array of `BaseMessage` objects (text, media, etc.) that have reactions. Each message's `data` object contains a `reactions` array with reaction emoji, count, and whether the logged-in user reacted. + + + +**Message Object (per element in the array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message ID | `"125896"` | +| `receiverId` | string | UID of the receiver | `"superhero2"` | +| `type` | string | Message type | `"text"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Text content of the message | `"hey, check out: https://www.example.com"` | +| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | +| `sender` | object | Sender user details | [See below ↓](#messages-with-reactions-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#messages-with-reactions-receiver-object) | +| `sentAt` | number | Timestamp when the message was sent (epoch) | `1773123969` | +| `deliveredAt` | number | Timestamp when the message was delivered (epoch) | `1773123969` | +| `readAt` | number | Timestamp when the message was read (epoch) | `1773123983` | +| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1773123983` | +| `metadata` | object | Extension metadata (data masking, link preview, etc.) | [See below ↓](#messages-with-reactions-metadata-object) | +| `data` | object | Additional message data including reactions and entities | [See below ↓](#messages-with-reactions-data-object) | +| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero1"` | +| `name` | string | Display name | `"Iron Man"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1773123450` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"online"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero2"` | +| `name` | string | Display name | `"Captain America"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1773123678` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"online"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Server-injected extension data | Contains `extensions` object | + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "hey, check out: https://www.example.com", ...}` | +| `link-preview` | object | Link preview extension results | `{"links": []}` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | The text content of the message | `"hey, check out: https://www.example.com"` | +| `resource` | string | SDK resource identifier | `"WEB-4_1_8-705024e4-..."` | +| `reactions` | array | Array of reaction objects | [See below ↓](#messages-with-reactions-reactions-array) | +| `metadata` | object | Same as top-level metadata | [See above ↑](#messages-with-reactions-metadata-object) | +| `moderation` | object | Moderation status | `{"status": "approved"}` | +| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#messages-with-reactions-entities-object) | + +--- + + + +**`data.reactions` Array (per element):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `reaction` | string | The emoji reaction | `"🤡"` | +| `count` | number | Number of users who reacted with this emoji | `1` | +| `reactedByMe` | boolean | Whether the logged-in user reacted with this emoji | `true` | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#messages-with-reactions-sender-object) | +| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#messages-with-reactions-receiver-object) | + + + ## Messages with mentions In other words, as a logged-in user, how do I fetch messages that contains mentions? @@ -1371,6 +3410,147 @@ let GUID: string = "GUID", +The response will contain a list of text message objects that include mentions. Each message has a `mentionedUsers` array, a `mentionedMe` boolean, and a `data.mentions` object keyed by UID. + + + +On Success — Returns an array of `TextMessage` objects that contain mentions. Each message includes `mentionedUsers` (array of user objects), `mentionedMe` (boolean), and `data.mentions` (object keyed by mentioned user UID). + + + +**Message Object (per element in the array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message ID | `"125900"` | +| `muid` | string | Client-generated unique message ID | `"_7ua87khcz"` | +| `receiverId` | string | UID of the receiver | `"superhero2"` | +| `type` | string | Message type | `"text"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Text content with mention syntax | `"🏃 <@uid:superhero2>"` | +| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | +| `sender` | object | Sender user details | [See below ↓](#messages-with-mentions-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#messages-with-mentions-receiver-object) | +| `sentAt` | number | Timestamp when the message was sent (epoch) | `1773125275` | +| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1773125275` | +| `mentionedUsers` | array | Array of mentioned user objects | [See below ↓](#messages-with-mentions-mentionedusers-array) | +| `mentionedMe` | boolean | Whether the logged-in user was mentioned | `false` | +| `metadata` | object | Extension metadata (data masking, link preview, etc.) | [See below ↓](#messages-with-mentions-metadata-object) | +| `data` | object | Additional message data including mentions and entities | [See below ↓](#messages-with-mentions-data-object) | +| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero1"` | +| `name` | string | Display name | `"Iron Man"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1773125266` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"online"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero2"` | +| `name` | string | Display name | `"Captain America"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1773124800` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`mentionedUsers` Array (per element):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID of the mentioned user | `"superhero2"` | +| `name` | string | Display name | `"Captain America"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1773124800` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Server-injected extension data | Contains `extensions` object | + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "🏃 <@uid:superhero2>", ...}` | +| `link-preview` | object | Link preview extension results | `{"links": []}` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | The text content with mention syntax | `"🏃 <@uid:superhero2>"` | +| `resource` | string | SDK resource identifier | `"WEB-4_1_8-939a34c6-..."` | +| `mentions` | object | Mentioned users keyed by UID | [See below ↓](#messages-with-mentions-data-mentions-object) | +| `metadata` | object | Same as top-level metadata | [See above ↑](#messages-with-mentions-metadata-object) | +| `moderation` | object | Moderation status | `{"status": "approved"}` | +| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#messages-with-mentions-entities-object) | + +--- + + + +**`data.mentions` Object (keyed by UID):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero2"` | +| `name` | string | Display name | `"Captain America"` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1773124800` | +| `conversationId` | string | Conversation ID with this user | `"superhero1_user_superhero2"` | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#messages-with-mentions-sender-object) | +| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#messages-with-mentions-receiver-object) | + + + ## Messages with particular user mentions In other words, as a logged-in user, how do I fetch messages that mentions specific users? @@ -1440,6 +3620,147 @@ let GUID: string = "GUID", +The response will contain a list of text message objects that mention the specific user(s) passed in `setMentionedUIDs()`. Each message includes `mentionedUsers`, `mentionedMe`, and `data.mentions` — filtered to only return messages where the specified UIDs are mentioned. + + + +On Success — Returns an array of `TextMessage` objects where the specified user(s) are mentioned. For example, when filtering with `mentions: ["superhero2"]`, only messages that mention `superhero2` are returned. Each message includes `mentionedUsers` (array of user objects), `mentionedMe` (boolean), and `data.mentions` (object keyed by mentioned user UID). + + + +**Message Object (per element in the array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message ID | `"125900"` | +| `muid` | string | Client-generated unique message ID | `"_7ua87khcz"` | +| `receiverId` | string | UID of the receiver | `"superhero2"` | +| `type` | string | Message type | `"text"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Text content with mention syntax | `"🏃 <@uid:superhero2>"` | +| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | +| `sender` | object | Sender user details | [See below ↓](#particular-mentions-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#particular-mentions-receiver-object) | +| `sentAt` | number | Timestamp when the message was sent (epoch) | `1773125275` | +| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1773125275` | +| `mentionedUsers` | array | Array of mentioned user objects | [See below ↓](#particular-mentions-mentionedusers-array) | +| `mentionedMe` | boolean | Whether the logged-in user was mentioned | `false` | +| `metadata` | object | Extension metadata (data masking, link preview, etc.) | [See below ↓](#particular-mentions-metadata-object) | +| `data` | object | Additional message data including mentions and entities | [See below ↓](#particular-mentions-data-object) | +| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero1"` | +| `name` | string | Display name | `"Iron Man"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1773125266` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"online"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero2"` | +| `name` | string | Display name | `"Captain America"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1773124800` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`mentionedUsers` Array (per element):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID of the mentioned user | `"superhero2"` | +| `name` | string | Display name | `"Captain America"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1773124800` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Server-injected extension data | Contains `extensions` object | + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "🏃 <@uid:superhero2>", ...}` | +| `link-preview` | object | Link preview extension results | `{"links": []}` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | The text content with mention syntax | `"🏃 <@uid:superhero2>"` | +| `resource` | string | SDK resource identifier | `"WEB-4_1_8-939a34c6-..."` | +| `mentions` | object | Mentioned users keyed by UID | [See below ↓](#particular-mentions-data-mentions-object) | +| `metadata` | object | Same as top-level metadata | [See above ↑](#particular-mentions-metadata-object) | +| `moderation` | object | Moderation status | `{"status": "approved"}` | +| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#particular-mentions-entities-object) | + +--- + + + +**`data.mentions` Object (keyed by UID):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero2"` | +| `name` | string | Display name | `"Captain America"` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1773124800` | +| `conversationId` | string | Conversation ID with this user | `"superhero1_user_superhero2"` | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#particular-mentions-sender-object) | +| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#particular-mentions-receiver-object) | + + + ## Messages with specific attachment types In other words, as a logged-in user, how do I fetch messages that contain specific types of attachments? @@ -1509,6 +3830,129 @@ let GUID: string = "GUID", +The response will contain a list of media message objects filtered to only the specified attachment types (e.g., image and video). Each message includes an `attachments` array with file details and thumbnail generation metadata. + + + +On Success — Returns an array of `MediaMessage` objects matching the specified attachment types. For example, when filtering with `setAttachmentTypes([IMAGE, VIDEO])`, only image and video messages are returned. Each message includes `attachments`, file metadata, and thumbnail URLs. + + + +**Message Object (per element in the array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message ID | `"125898"` | +| `muid` | string | Client-generated unique message ID | `"_boivkgy41"` | +| `receiverId` | string | UID of the receiver | `"superhero2"` | +| `type` | string | Message type (matches the filtered attachment types) | `"image"` or `"video"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `category` | string | Message category | `"message"` | +| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | +| `sender` | object | Sender user details | [See below ↓](#specific-attachment-types-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#specific-attachment-types-receiver-object) | +| `sentAt` | number | Timestamp when the message was sent (epoch) | `1773124815` | +| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1773124815` | +| `metadata` | object | Extension metadata (thumbnail generation, file info) | [See below ↓](#specific-attachment-types-metadata-object) | +| `data` | object | Additional message data including attachments and entities | [See below ↓](#specific-attachment-types-data-object) | +| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero1"` | +| `name` | string | Display name | `"Iron Man"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1773124809` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero2"` | +| `name` | string | Display name | `"Captain America"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1773124800` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Server-injected extension data | Contains `extensions` object | +| `file` | array | File reference array | `[]` | +| `fileName` | string | Original file name | `"dummy.jpg"` | +| `fileSize` | number | File size in bytes | `5253` | +| `fileType` | string | MIME type of the file | `"image/jpeg"` | + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `thumbnail-generation` | object | Thumbnail generation results with URLs for small, medium, and large thumbnails | `{"url_small": "https://..._small.jpg", "url_medium": "https://..._medium.jpg", "url_large": "https://..._large.jpg", "attachments": [...]}` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `url` | string | Direct URL to the media file | `"https://data-us.cometchat.io/.../image.jpg"` | +| `attachments` | array | Array of attachment objects | [See below ↓](#specific-attachment-types-attachments-array) | +| `resource` | string | SDK resource identifier | `"WEB-4_1_8-939a34c6-..."` | +| `metadata` | object | Same as top-level metadata | [See above ↑](#specific-attachment-types-metadata-object) | +| `moderation` | object | Moderation status | `{"status": "approved"}` | +| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#specific-attachment-types-entities-object) | + +--- + + + +**`data.attachments` Array (per element):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extension` | string | File extension | `"jpg"` or `"mov"` | +| `mimeType` | string | MIME type | `"image/jpeg"` or `"video/quicktime"` | +| `name` | string | File name | `"dummy.jpg"` | +| `size` | number | File size in bytes | `5253` | +| `url` | string | Direct URL to the file | `"https://data-us.cometchat.io/.../image.jpg"` | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#specific-attachment-types-sender-object) | +| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#specific-attachment-types-receiver-object) | + + + - **Combine filters strategically**: Use `setCategories()` with `setTypes()` for precise filtering - **Set reasonable limits**: Use 30-50 messages per fetch for optimal performance diff --git a/sdk/javascript/send-message.mdx b/sdk/javascript/send-message.mdx index 711d2a8da..fac28f6d2 100644 --- a/sdk/javascript/send-message.mdx +++ b/sdk/javascript/send-message.mdx @@ -347,6 +347,295 @@ The `TextMessage` class constructor takes the following parameters: When a text message is sent successfully, the response will include a `TextMessage` object which includes all information related to the sent message. + +**On Success** — Returns a `TextMessage` object with metadata, tags, quoted message, and parent message ID if set: + + + +**TextMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message ID | `"20004"` | +| `receiverId` | string | UID of the receiver | `"cometchat-uid-2"` | +| `type` | string | Message type | `"text"` | +| `receiverType` | string | Receiver type | `"user"` | +| `category` | string | Message category | `"message"` | +| `text` | string | The text content of the message | `"sent from explorer 2"` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `sender` | object | Sender user details | [See below ↓](#send-text-message-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#send-text-message-receiver-object) | +| `sentAt` | number | Timestamp when the message was sent (epoch) | `1772181842` | +| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1772181842` | +| `tags` | array | List of tags attached to the message | `["tag1"]` | +| `metadata` | object | Custom metadata attached to the message | `{"someKey": "someValue"}` | +| `parentMessageId` | string | ID of the parent message (for threaded messages) | `"20001"` | +| `quotedMessageId` | string | ID of the quoted message | `"16001"` | +| `quotedMessage` | object | The full quoted message object | [See below ↓](#send-text-message-quoted-message-object) | +| `data` | object | Additional message data including entities | [See below ↓](#send-text-message-data-object) | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"cometchat-uid-1"` | +| `name` | string | Display name | `"Andrew Joseph"` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772179705` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"cometchat-uid-2"` | +| `name` | string | Display name | `"George Alan"` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1770898112` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | The text content | `"sent from explorer 2"` | +| `metadata` | object | Custom metadata | `{"someKey": "someValue"}` | +| `resource` | string | SDK resource identifier | `"WEB-4_1_7-dd86d365-4843-41e4-b275-a020edadd82c-1771944198900"` | +| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#send-text-message-data-entities-object) | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#send-text-message-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#send-text-message-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entity` | object | The sender user entity | [See below ↓](#send-text-message-data-entities-sender-entity-object) | +| `entityType` | string | Type of entity | `"user"` | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"cometchat-uid-1"` | +| `name` | string | Display name | `"Andrew Joseph"` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772179705` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entity` | object | The receiver user entity | [See below ↓](#send-text-message-data-entities-receiver-entity-object) | +| `entityType` | string | Type of entity | `"user"` | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"cometchat-uid-2"` | +| `name` | string | Display name | `"George Alan"` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1770898112` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | + +--- + + + +**`quotedMessage` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message ID of the quoted message | `"16001"` | +| `receiverId` | string | UID of the receiver | `"cometchat-uid-2"` | +| `type` | string | Message type | `"image"` | +| `receiverType` | string | Receiver type | `"user"` | +| `category` | string | Message category | `"message"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `sender` | object | Sender of the quoted message | [See below ↓](#send-text-message-quoted-sender-object) | +| `receiver` | object | Receiver of the quoted message | [See below ↓](#send-text-message-quoted-receiver-object) | +| `sentAt` | number | Timestamp when the quoted message was sent (epoch) | `1771926928` | +| `updatedAt` | number | Timestamp when the quoted message was last updated (epoch) | `1771926928` | +| `data` | object | Additional data of the quoted message | [See below ↓](#send-text-message-quoted-data-object) | + +--- + + + +**`quotedMessage.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"cometchat-uid-1"` | +| `name` | string | Display name | `"Andrew Joseph"` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1771926864` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`quotedMessage.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"cometchat-uid-2"` | +| `name` | string | Display name | `"George Alan"` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1770898112` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`quotedMessage.data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `url` | string | Media file URL | `"https://files-us.cometchat-staging.com/..."` | +| `resource` | string | SDK resource identifier | `"WEB-4_1_6-a16c1881-ae5c-4ea2-9252-b70f08a50454-1770977997631"` | +| `attachments` | array | List of file attachments | [See below ↓](#send-text-message-quoted-data-attachments-array) | +| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#send-text-message-quoted-data-entities-object) | + +--- + + + +**`quotedMessage.data.attachments` Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extension` | string | File extension | `"gif"` | +| `mimeType` | string | MIME type of the file | `"image/gif"` | +| `name` | string | File name | `"shivaji-the-boss-rajinikanth.gif"` | +| `size` | number | File size in bytes | `865027` | +| `url` | string | File download URL | `"https://files-us.cometchat-staging.com/..."` | + +--- + + + +**`quotedMessage.data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#send-text-message-quoted-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#send-text-message-quoted-data-entities-receiver-object) | + +--- + + + +**`quotedMessage.data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entity` | object | The sender user entity | [See below ↓](#send-text-message-quoted-data-entities-sender-entity-object) | +| `entityType` | string | Type of entity | `"user"` | + +--- + + + +**`quotedMessage.data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"cometchat-uid-1"` | +| `name` | string | Display name | `"Andrew Joseph"` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1771926864` | + +--- + + + +**`quotedMessage.data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entity` | object | The receiver user entity | [See below ↓](#send-text-message-quoted-data-entities-receiver-entity-object) | +| `entityType` | string | Type of entity | `"user"` | + +--- + + + +**`quotedMessage.data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"cometchat-uid-2"` | +| `name` | string | Display name | `"George Alan"` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1770898112` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | + + + ## Media Message *In other words, as a sender, how do I send a media message like photos, videos & files?* @@ -863,6 +1152,375 @@ CometChat.sendMediaMessage(mediaMessage).then( When a media message is sent successfully, the response will include a `MediaMessage` object which includes all information related to the sent message. + +**On Success** — Returns a `MediaMessage` object with file attachment details, metadata, tags, caption, quoted message, and parent message ID if set: + + + +**MediaMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message ID | `"125629"` | +| `receiverId` | string | UID of the receiver | `"superhero2"` | +| `type` | string | Message type | `"image"` | +| `receiverType` | string | Receiver type | `"user"` | +| `category` | string | Message category | `"message"` | +| `caption` | string | Caption text for the media message | `"this is a caption for the image"` | +| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | +| `sender` | object | Sender user details | [See below ↓](#send-media-file-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#send-media-file-receiver-object) | +| `sentAt` | number | Timestamp when the message was sent (epoch) | `1772693133` | +| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1772693133` | +| `tags` | array | List of tags attached to the message | `["tag1"]` | +| `metadata` | object | Custom metadata attached to the message | [See below ↓](#send-media-file-metadata-object) | +| `parentMessageId` | string | ID of the parent message (for threaded messages) | `"125334"` | +| `quotedMessageId` | string | ID of the quoted message | `"125623"` | +| `quotedMessage` | object | The full quoted message object | [See below ↓](#send-media-file-quoted-message-object) | +| `data` | object | Additional message data including attachments and entities | [See below ↓](#send-media-file-data-object) | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero1"` | +| `name` | string | Display name | `"Iron Man"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772693031` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"online"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero2"` | +| `name` | string | Display name | `"Captain America"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772450329` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `latitude` | string | Latitude coordinate | `"50.6192171633316"` | +| `longitude` | string | Longitude coordinate | `"-72.68182268750002"` | +| `@injected` | object | Server-injected extension data | [See below ↓](#send-media-file-metadata-injected-object) | + +--- + + + +**`metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extension data | [See below ↓](#send-media-file-metadata-injected-extensions-object) | + +--- + + + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "this is a caption for the image", ...}` | +| `link-preview` | object | Link preview extension results | `{"links": []}` | +| `thumbnail-generation` | object | Thumbnail generation extension results | [See below ↓](#send-media-file-thumbnail-generation-object) | + +--- + + + +**`metadata.@injected.extensions.thumbnail-generation` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `url_small` | string | Small thumbnail URL | `"https://data-us.cc-cluster-2.io/.../small.webp"` | +| `url_medium` | string | Medium thumbnail URL | `"https://data-us.cc-cluster-2.io/.../medium.webp"` | +| `url_large` | string | Large thumbnail URL | `"https://data-us.cc-cluster-2.io/.../large.webp"` | +| `attachments` | array | Thumbnail attachment details | [See below ↓](#send-media-file-thumbnail-attachments-array) | + +--- + + + +**`metadata.@injected.extensions.thumbnail-generation.attachments` Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `data` | object | Thumbnail data | [See below ↓](#send-media-file-thumbnail-attachments-data-object) | +| `error` | null | Error if any | `null` | + +--- + + + +**`metadata.@injected.extensions.thumbnail-generation.attachments[].data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `name` | string | File name | `"dummy.webp"` | +| `extension` | string | File extension | `"webp"` | +| `url` | string | File URL | `"https://data-us.cometchat.io/.../dummy.webp"` | +| `mimeType` | string | MIME type | `"image/webp"` | +| `thumbnails` | object | Thumbnail URLs | [See below ↓](#send-media-file-thumbnail-attachments-data-thumbnails-object) | + +--- + + + +**`metadata.@injected.extensions.thumbnail-generation.attachments[].data.thumbnails` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `url_small` | string | Small thumbnail URL | `"https://data-us.cc-cluster-2.io/.../small.webp"` | +| `url_medium` | string | Medium thumbnail URL | `"https://data-us.cc-cluster-2.io/.../medium.webp"` | +| `url_large` | string | Large thumbnail URL | `"https://data-us.cc-cluster-2.io/.../large.webp"` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Caption text | `"this is a caption for the image"` | +| `metadata` | object | Custom metadata | [See above ↑](#send-media-file-metadata-object) | +| `resource` | string | SDK resource identifier | `"WEB-4_1_8-36a59fde-..."` | +| `url` | string | Uploaded file URL | `"https://data-us.cometchat.io/.../dummy.webp"` | +| `attachments` | array | List of file attachments | [See below ↓](#send-media-file-data-attachments-array) | +| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#send-media-file-data-entities-object) | +| `moderation` | object | Moderation status | `{"status": "pending"}` | + +--- + + + +**`data.attachments` Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `name` | string | File name | `"dummy.webp"` | +| `extension` | string | File extension | `"webp"` | +| `size` | number | File size in bytes | `19554` | +| `mimeType` | string | MIME type of the file | `"image/webp"` | +| `url` | string | File download URL | `"https://data-us.cometchat.io/.../dummy.webp"` | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#send-media-file-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#send-media-file-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entity` | object | The sender user entity | [See below ↓](#send-media-file-data-entities-sender-entity-object) | +| `entityType` | string | Type of entity | `"user"` | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero1"` | +| `name` | string | Display name | `"Iron Man"` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772693031` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entity` | object | The receiver user entity | [See below ↓](#send-media-file-data-entities-receiver-entity-object) | +| `entityType` | string | Type of entity | `"user"` | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero2"` | +| `name` | string | Display name | `"Captain America"` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772450329` | +| `conversationId` | string | Conversation identifier | `"superhero1_user_superhero2"` | + +--- + + + +**`quotedMessage` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message ID of the quoted message | `"125623"` | +| `receiverId` | string | UID of the receiver | `"cometchat-uid-1"` | +| `type` | string | Message type | `"text"` | +| `receiverType` | string | Receiver type | `"user"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Text content of the quoted message | `"Hello"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-1_user_superhero1"` | +| `sender` | object | Sender of the quoted message | [See below ↓](#send-media-file-quoted-sender-object) | +| `receiver` | object | Receiver of the quoted message | [See below ↓](#send-media-file-quoted-receiver-object) | +| `sentAt` | number | Timestamp when the quoted message was sent (epoch) | `1772692447` | +| `updatedAt` | number | Timestamp when the quoted message was last updated (epoch) | `1772692447` | +| `data` | object | Additional data of the quoted message | [See below ↓](#send-media-file-quoted-data-object) | + +--- + + + +**`quotedMessage.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero1"` | +| `name` | string | Display name | `"Iron Man"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772692439` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"online"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`quotedMessage.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"cometchat-uid-1"` | +| `name` | string | Display name | `"cometchat-uid-1"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772630028` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`quotedMessage.data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Text content | `"Hello"` | +| `resource` | string | SDK resource identifier | `"WEB-4_1_5-2af689b1-..."` | +| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#send-media-file-quoted-data-entities-object) | +| `moderation` | object | Moderation status | `{"status": "approved"}` | + +--- + + + +**`quotedMessage.data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#send-media-file-quoted-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#send-media-file-quoted-data-entities-receiver-object) | + +--- + + + +**`quotedMessage.data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entity` | object | The sender user entity | [See below ↓](#send-media-file-quoted-data-entities-sender-entity-object) | +| `entityType` | string | Type of entity | `"user"` | + +--- + + + +**`quotedMessage.data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero1"` | +| `name` | string | Display name | `"Iron Man"` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772692439` | + +--- + + + +**`quotedMessage.data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entity` | object | The receiver user entity | [See below ↓](#send-media-file-quoted-data-entities-receiver-entity-object) | +| `entityType` | string | Type of entity | `"user"` | + +--- + + + +**`quotedMessage.data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"cometchat-uid-1"` | +| `name` | string | Display name | `"cometchat-uid-1"` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772630028` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-1_user_superhero1"` | + + + ## Multiple Attachments in a Media Message Starting version 3.0.9 & above the SDK supports sending multiple attachments in a single media message. As in the case of a single attachment in a media message, there are two ways you can send Media Messages using the CometChat SDK: @@ -1185,6 +1843,376 @@ When a media message is sent successfully, the response will include a `MediaMes You can use the `setMetadata()`, `setCaption()` & `setTags()` methods to add metadata, caption and tags respectively in exactly the same way as it is done while sending a single file or attachment in a Media Message. + +**On Success** — Returns a `MediaMessage` object with multiple file attachments, metadata, tags, caption, quoted message, and parent message ID if set: + + + +**MediaMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message ID | `"125632"` | +| `receiverId` | string | UID of the receiver | `"superhero2"` | +| `type` | string | Message type | `"image"` | +| `receiverType` | string | Receiver type | `"user"` | +| `category` | string | Message category | `"message"` | +| `caption` | string | Caption text for the media message | `"this is a caption for multi attachments media message"` | +| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | +| `sender` | object | Sender user details | [See below ↓](#send-media-urls-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#send-media-urls-receiver-object) | +| `sentAt` | number | Timestamp when the message was sent (epoch) | `1772696147` | +| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1772696147` | +| `tags` | array | List of tags attached to the message | `["tag1"]` | +| `metadata` | object | Custom metadata attached to the message | [See below ↓](#send-media-urls-metadata-object) | +| `parentMessageId` | string | ID of the parent message (for threaded messages) | `"125332"` | +| `quotedMessageId` | string | ID of the quoted message | `"125625"` | +| `quotedMessage` | object | The full quoted message object | [See below ↓](#send-media-urls-quoted-message-object) | +| `data` | object | Additional message data including attachments and entities | [See below ↓](#send-media-urls-data-object) | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero1"` | +| `name` | string | Display name | `"Iron Man"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772696124` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero2"` | +| `name` | string | Display name | `"Captain America"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772450329` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `latitude` | string | Latitude coordinate | `"50.6192171633316"` | +| `longitude` | string | Longitude coordinate | `"-72.68182268750002"` | +| `@injected` | object | Server-injected extension data | [See below ↓](#send-media-urls-metadata-injected-object) | + +--- + + + +**`metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extension data | [See below ↓](#send-media-urls-metadata-injected-extensions-object) | + +--- + + + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "this is a caption for multi attachments media message", ...}` | +| `link-preview` | object | Link preview extension results | `{"links": []}` | +| `thumbnail-generation` | object | Thumbnail generation extension results | [See below ↓](#send-media-urls-thumbnail-generation-object) | + +--- + + + +**`metadata.@injected.extensions.thumbnail-generation` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `url_small` | string | Small thumbnail URL | `"https://data-us.cc-cluster-2.io/.../small.png"` | +| `url_medium` | string | Medium thumbnail URL | `"https://data-us.cc-cluster-2.io/.../medium.png"` | +| `url_large` | string | Large thumbnail URL | `"https://data-us.cc-cluster-2.io/.../large.png"` | +| `attachments` | array | Thumbnail attachment details per file | [See below ↓](#send-media-urls-thumbnail-attachments-array) | + +--- + + + +**`metadata.@injected.extensions.thumbnail-generation.attachments` Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `data` | object | Thumbnail data | [See below ↓](#send-media-urls-thumbnail-attachments-data-object) | +| `error` | null | Error if any | `null` | + +--- + + + +**`metadata.@injected.extensions.thumbnail-generation.attachments[].data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `name` | string | File name | `"mario"` | +| `extension` | string | File extension | `"png"` | +| `url` | string | File URL | `"https://pngimg.com/uploads/mario/mario_PNG125.png"` | +| `mimeType` | string | MIME type | `"image/png"` | +| `thumbnails` | object | Thumbnail URLs | [See below ↓](#send-media-urls-thumbnail-attachments-data-thumbnails-object) | + +--- + + + +**`metadata.@injected.extensions.thumbnail-generation.attachments[].data.thumbnails` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `url_small` | string | Small thumbnail URL | `"https://data-us.cc-cluster-2.io/.../small.png"` | +| `url_medium` | string | Medium thumbnail URL | `"https://data-us.cc-cluster-2.io/.../medium.png"` | +| `url_large` | string | Large thumbnail URL | `"https://data-us.cc-cluster-2.io/.../large.png"` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `url` | string | Primary file URL (empty for multi-attachment) | `""` | +| `text` | string | Caption text | `"this is a caption for multi attachments media message"` | +| `metadata` | object | Custom metadata | [See above ↑](#send-media-urls-metadata-object) | +| `resource` | string | SDK resource identifier | `"WEB-4_1_8-36a59fde-..."` | +| `attachments` | array | List of file attachments | [See below ↓](#send-media-urls-data-attachments-array) | +| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#send-media-urls-data-entities-object) | +| `moderation` | object | Moderation status | `{"status": "pending"}` | + +--- + + + +**`data.attachments` Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `name` | string | File name | `"mario"` | +| `extension` | string | File extension | `"png"` | +| `mimeType` | string | MIME type of the file | `"image/png"` | +| `url` | string | File download URL | `"https://pngimg.com/uploads/mario/mario_PNG125.png"` | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#send-media-urls-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#send-media-urls-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entity` | object | The sender user entity | [See below ↓](#send-media-urls-data-entities-sender-entity-object) | +| `entityType` | string | Type of entity | `"user"` | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero1"` | +| `name` | string | Display name | `"Iron Man"` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772696124` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entity` | object | The receiver user entity | [See below ↓](#send-media-urls-data-entities-receiver-entity-object) | +| `entityType` | string | Type of entity | `"user"` | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero2"` | +| `name` | string | Display name | `"Captain America"` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772450329` | +| `conversationId` | string | Conversation identifier | `"superhero1_user_superhero2"` | + +--- + + + +**`quotedMessage` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message ID of the quoted message | `"125625"` | +| `receiverId` | string | UID of the receiver | `"fb421b69-f259-4418-b287-1f3fd7a1af2d"` | +| `type` | string | Message type | `"text"` | +| `receiverType` | string | Receiver type | `"user"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Text content of the quoted message | `"send this again to me, i want to test my code"` | +| `conversationId` | string | Conversation identifier | `"fb421b69-f259-4418-b287-1f3fd7a1af2d_user_superhero1"` | +| `sender` | object | Sender of the quoted message | [See below ↓](#send-media-urls-quoted-sender-object) | +| `receiver` | object | Receiver of the quoted message | [See below ↓](#send-media-urls-quoted-receiver-object) | +| `sentAt` | number | Timestamp when the quoted message was sent (epoch) | `1772692502` | +| `readAt` | number | Timestamp when the quoted message was read (epoch) | `1772692502` | +| `updatedAt` | number | Timestamp when the quoted message was last updated (epoch) | `1772692518` | +| `replyCount` | number | Number of replies to this message | `1` | +| `data` | object | Additional data of the quoted message | [See below ↓](#send-media-urls-quoted-data-object) | + +--- + + + +**`quotedMessage.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero1"` | +| `name` | string | Display name | `"Iron Man"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772692497` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"online"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`quotedMessage.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"fb421b69-f259-4418-b287-1f3fd7a1af2d"` | +| `name` | string | Display name | `"test agent"` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/ai-agents/default-agent-profile-picture.png"` | +| `role` | string | User role | `"@agentic"` | +| `status` | string | Online status | `"online"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`quotedMessage.data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Text content | `"send this again to me, i want to test my code"` | +| `resource` | string | SDK resource identifier | `"WEB-4_1_5-2af689b1-..."` | +| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#send-media-urls-quoted-data-entities-object) | +| `moderation` | object | Moderation status | `{"status": "approved"}` | + +--- + + + +**`quotedMessage.data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#send-media-urls-quoted-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#send-media-urls-quoted-data-entities-receiver-object) | + +--- + + + +**`quotedMessage.data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entity` | object | The sender user entity | [See below ↓](#send-media-urls-quoted-data-entities-sender-entity-object) | +| `entityType` | string | Type of entity | `"user"` | + +--- + + + +**`quotedMessage.data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero1"` | +| `name` | string | Display name | `"Iron Man"` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772692497` | + +--- + + + +**`quotedMessage.data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entity` | object | The receiver user entity | [See below ↓](#send-media-urls-quoted-data-entities-receiver-entity-object) | +| `entityType` | string | Type of entity | `"user"` | + +--- + + + +**`quotedMessage.data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"fb421b69-f259-4418-b287-1f3fd7a1af2d"` | +| `name` | string | Display name | `"test agent"` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/ai-agents/default-agent-profile-picture.png"` | +| `status` | string | Online status | `"available"` | +| `role` | string | User role | `"@agentic"` | +| `conversationId` | string | Conversation identifier | `"fb421b69-f259-4418-b287-1f3fd7a1af2d_user_superhero1"` | + + + ## Custom Message *In other words, as a sender, how do I send a custom message like location coordinates?* @@ -1767,6 +2795,313 @@ CometChat.sendCustomMessage(customMessage).then( +When a custom message is sent successfully, the response will include a `CustomMessage` object which includes all information related to the sent message. + + +**On Success** — Returns a `CustomMessage` object with custom type, custom data, metadata, tags, subtype, quoted message, and parent message ID if set: + + + +**CustomMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message ID | `"125633"` | +| `receiverId` | string | UID of the receiver | `"superhero2"` | +| `type` | string | Custom message type | `"custom_type"` | +| `receiverType` | string | Receiver type | `"user"` | +| `category` | string | Message category | `"custom"` | +| `subType` | string | Message subtype | `"subtype"` | +| `customData` | object | Custom data payload | `{"customField": "customValue"}` | +| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | +| `sender` | object | Sender user details | [See below ↓](#send-custom-message-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#send-custom-message-receiver-object) | +| `sentAt` | number | Timestamp when the message was sent (epoch) | `1772697015` | +| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1772697015` | +| `tags` | array | List of tags attached to the message | `["tag1"]` | +| `metadata` | object | Custom metadata attached to the message | [See below ↓](#send-custom-message-metadata-object) | +| `parentMessageId` | string | ID of the parent message (for threaded messages) | `"125334"` | +| `quotedMessageId` | string | ID of the quoted message | `"125627"` | +| `quotedMessage` | object | The full quoted message object | [See below ↓](#send-custom-message-quoted-message-object) | +| `data` | object | Additional message data including entities | [See below ↓](#send-custom-message-data-object) | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero1"` | +| `name` | string | Display name | `"Iron Man"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772696930` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"online"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero2"` | +| `name` | string | Display name | `"Captain America"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772450329` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `metaDataField` | string | Custom metadata field | `"value"` | +| `@injected` | object | Server-injected extension data | [See below ↓](#send-custom-message-metadata-injected-object) | + +--- + + + +**`metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extension data | [See below ↓](#send-custom-message-metadata-injected-extensions-object) | + +--- + + + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "Custom notification body", ...}` | +| `link-preview` | object | Link preview extension results | `{"links": []}` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `customData` | object | Custom data payload | `{"customField": "customValue"}` | +| `metadata` | object | Metadata with extension data | [See above ↑](#send-custom-message-metadata-object) | +| `text` | string | Conversation notification text | `"Custom notification body"` | +| `subType` | string | Message subtype | `"subtype"` | +| `resource` | string | SDK resource identifier | `"WEB-4_1_8-36a59fde-..."` | +| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#send-custom-message-data-entities-object) | +| `moderation` | object | Moderation status | `{"status": "pending"}` | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#send-custom-message-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#send-custom-message-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entity` | object | The sender user entity | [See below ↓](#send-custom-message-data-entities-sender-entity-object) | +| `entityType` | string | Type of entity | `"user"` | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero1"` | +| `name` | string | Display name | `"Iron Man"` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772696930` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entity` | object | The receiver user entity | [See below ↓](#send-custom-message-data-entities-receiver-entity-object) | +| `entityType` | string | Type of entity | `"user"` | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero2"` | +| `name` | string | Display name | `"Captain America"` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772450329` | +| `conversationId` | string | Conversation identifier | `"superhero1_user_superhero2"` | + +--- + + + +**`quotedMessage` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message ID of the quoted message | `"125627"` | +| `receiverId` | string | UID of the receiver | `"superhero2"` | +| `type` | string | Message type | `"text"` | +| `receiverType` | string | Receiver type | `"user"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Text content of the quoted message | `"hello"` | +| `conversationId` | string | Conversation identifier | `"superhero1_user_superhero2"` | +| `sender` | object | Sender of the quoted message | [See below ↓](#send-custom-message-quoted-sender-object) | +| `receiver` | object | Receiver of the quoted message | [See below ↓](#send-custom-message-quoted-receiver-object) | +| `sentAt` | number | Timestamp when the quoted message was sent (epoch) | `1772693110` | +| `updatedAt` | number | Timestamp when the quoted message was last updated (epoch) | `1772693110` | +| `parentMessageId` | string | Parent message ID of the quoted message | `"125334"` | +| `data` | object | Additional data of the quoted message | [See below ↓](#send-custom-message-quoted-data-object) | + +--- + + + +**`quotedMessage.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero1"` | +| `name` | string | Display name | `"Iron Man"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772693031` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"online"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`quotedMessage.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero2"` | +| `name` | string | Display name | `"Captain America"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772450329` | +| `role` | string | User role | `"default"` | +| `status` | string | Online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`quotedMessage.data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Text content | `"hello"` | +| `resource` | string | SDK resource identifier | `"WEB-4_1_8-c214150f-..."` | +| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#send-custom-message-quoted-data-entities-object) | +| `moderation` | object | Moderation status | `{"status": "approved"}` | + +--- + + + +**`quotedMessage.data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#send-custom-message-quoted-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#send-custom-message-quoted-data-entities-receiver-object) | + +--- + + + +**`quotedMessage.data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entity` | object | The sender user entity | [See below ↓](#send-custom-message-quoted-data-entities-sender-entity-object) | +| `entityType` | string | Type of entity | `"user"` | + +--- + + + +**`quotedMessage.data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero1"` | +| `name` | string | Display name | `"Iron Man"` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772693031` | + +--- + + + +**`quotedMessage.data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entity` | object | The receiver user entity | [See below ↓](#send-custom-message-quoted-data-entities-receiver-entity-object) | +| `entityType` | string | Type of entity | `"user"` | + +--- + + + +**`quotedMessage.data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user ID | `"superhero2"` | +| `name` | string | Display name | `"Captain America"` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Last active timestamp (epoch) | `1772450329` | +| `conversationId` | string | Conversation identifier | `"superhero1_user_superhero2"` | + + + It is also possible to send interactive messages from CometChat, to know more [click here](/sdk/javascript/interactive-messages) From 4128de32ab12bc541b23fd9914ee4b3090ecf8b8 Mon Sep 17 00:00:00 2001 From: PrajwalDhuleCC Date: Fri, 13 Mar 2026 17:11:35 +0530 Subject: [PATCH 08/43] docs(sdk): Add initial global message reference documentation and tags field support - Create new messages reference page documenting BaseMessage class hierarchy and properties - Document all BaseMessage properties including getters and return types - Add TextMessage class documentation with text-specific properties - Document conditional properties for reactions, mentions, and quoted messages - Add tags field documentation to additional-message-filtering guide - Include tags getter method and table describing tags field access - Provide comprehensive class hierarchy overview for message objects --- .../additional-message-filtering.mdx | 6 ++ sdk/reference/messages.mdx | 91 +++++++++++++++++++ 2 files changed, 97 insertions(+) create mode 100644 sdk/reference/messages.mdx diff --git a/sdk/javascript/additional-message-filtering.mdx b/sdk/javascript/additional-message-filtering.mdx index ba11a3093..8cb2cfd83 100644 --- a/sdk/javascript/additional-message-filtering.mdx +++ b/sdk/javascript/additional-message-filtering.mdx @@ -2786,6 +2786,12 @@ let GUID: string = "GUID", +When `.withTags(true)` is set on the request builder, each message returned will have its `tags` field populated if it has any tags set. The messages are returned as [`BaseMessage`](/sdk/reference/messages#basemessage) objects (which may be [`TextMessage`](/sdk/reference/messages#textmessage) or other subclasses). You can access the tags using `getTags()`. + +| Additional Field | Getter | Return Type | Description | +|-----------------|--------|-------------|-------------| +| tags | `getTags()` | `string[]` | Tags associated with the message | + ## Messages with links In other words, as a logged-in user, how do I fetch messages that contains links? diff --git a/sdk/reference/messages.mdx b/sdk/reference/messages.mdx new file mode 100644 index 000000000..5ef7c19f2 --- /dev/null +++ b/sdk/reference/messages.mdx @@ -0,0 +1,91 @@ +--- +title: "Messages" +description: "Class reference for message objects returned by CometChat SDK methods. Covers BaseMessage and its subclasses like TextMessage." +--- + +This page documents the message classes used across all CometChat SDKs. All message objects share the same structure regardless of platform. + +All properties are accessed via getter methods. + +## Class Hierarchy + +``` +BaseMessage +├── TextMessage +├── MediaMessage +├── CustomMessage +├── InteractiveMessage +└── Action +``` + +--- + +## BaseMessage + +`BaseMessage` is the base class for all message types. Every message object — whether it's a text message, media message, or custom message — extends this class. + +### Properties + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| id | `getId()` | `number` | Unique message ID | +| conversationId | `getConversationId()` | `string` | ID of the conversation this message belongs to | +| parentMessageId | `getParentMessageId()` | `number` | ID of the parent message (for threaded messages) | +| muid | `getMuid()` | `string` | Client-generated unique message ID | +| sender | `getSender()` | `User` | Sender of the message | +| receiver | `getReceiver()` | `User` \| `Group` | Receiver of the message | +| receiverId | `getReceiverId()` | `string` | UID/GUID of the receiver | +| type | `getType()` | `string` | Message type (e.g., `"text"`, `"image"`, `"file"`, `"custom"`) | +| receiverType | `getReceiverType()` | `string` | Receiver type (`"user"` or `"group"`) | +| category | `getCategory()` | `MessageCategory` | Message category (e.g., `"message"`, `"action"`, `"call"`, `"custom"`) | +| sentAt | `getSentAt()` | `number` | Timestamp when the message was sent (epoch seconds) | +| deliveredAt | `getDeliveredAt()` | `number` | Timestamp when the message was delivered | +| readAt | `getReadAt()` | `number` | Timestamp when the message was read | +| deliveredToMeAt | `getDeliveredToMeAt()` | `number` | Timestamp when the message was delivered to the logged-in user | +| readByMeAt | `getReadByMeAt()` | `number` | Timestamp when the message was read by the logged-in user | +| editedAt | `getEditedAt()` | `number` | Timestamp when the message was edited | +| editedBy | `getEditedBy()` | `string` | UID of the user who edited the message | +| deletedAt | `getDeletedAt()` | `number` | Timestamp when the message was deleted | +| deletedBy | `getDeletedBy()` | `string` | UID of the user who deleted the message | +| replyCount | `getReplyCount()` | `number` | Number of replies to this message | +| unreadRepliesCount | `getUnreadRepliesCount()` | `number` | Number of unread replies | +| data | `getData()` | `Object` | Raw data payload of the message | +| metadata | `getMetadata()` | `Object` | Custom metadata attached to the message | +| rawMessage | `getRawMessage()` | `Object` | Raw JSON of the message as received from the server | + +### Conditional Properties + +These properties may or may not be populated depending on the method or request configuration used to fetch the message. + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| reactions | `getReactions()` | `ReactionCount[]` | Array of reaction counts on the message | +| mentionedUsers | `getMentionedUsers()` | `User[]` | Array of users mentioned in the message | +| hasMentionedMe | `hasMentionedMe()` | `boolean` | Whether the logged-in user was mentioned in the message | +| quotedMessageId | `getQuotedMessageId()` | `number` | ID of the quoted message (if this is a reply) | +| quotedMessage | `getQuotedMessage()` | `BaseMessage` | The quoted message object (if this is a reply) | + +--- + +## TextMessage + +`TextMessage` extends [BaseMessage](#basemessage) and represents a text-based chat message. + +It inherits all properties from `BaseMessage` and adds the following. + +### Properties + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| text | `getText()` | `string` | The text content of the message | +| metadata | `getMetadata()` | `Object` | Custom metadata attached to the message (includes extension data like data masking, link preview, etc.) | +| data | `getData()` | `Object` | Raw data payload including `text`, `resource`, `metadata`, `moderation`, and `entities` | +| moderationStatus | `getModerationStatus()` | `ModerationStatus` | Moderation status of the message. Returns `"unmoderated"` if not moderated. | + +### Conditional Properties + +These properties may or may not be populated depending on the method or request configuration used to fetch the message. + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| tags | `getTags()` | `string[]` | Tags associated with the message | From a33f85fb13814cbcb839116435a334ace2151957 Mon Sep 17 00:00:00 2001 From: PrajwalDhuleCC Date: Mon, 16 Mar 2026 19:49:03 +0530 Subject: [PATCH 09/43] docs(sdk/javascript): Add method payloads reference and update documentation structure - Add comprehensive JS SDK method payloads documentation with send message examples - Create new reference section for auxiliary and entities documentation - Update messages reference documentation with additional details - Reorganize docs.json to include new Reference group in SDK navigation - Update all JavaScript SDK documentation files with enhanced content and structure - Improve documentation consistency across messaging, groups, users, and call features --- docs.json | 6 + .../additional-message-filtering.mdx | 2556 +---------------- sdk/javascript/block-users.mdx | 18 + sdk/javascript/call-logs.mdx | 11 + sdk/javascript/connection-status.mdx | 9 + sdk/javascript/create-group.mdx | 11 + sdk/javascript/default-call.mdx | 21 + sdk/javascript/delete-conversation.mdx | 2 + sdk/javascript/delete-group.mdx | 2 + sdk/javascript/delete-message.mdx | 18 + sdk/javascript/delivery-read-receipts.mdx | 13 + sdk/javascript/direct-call.mdx | 10 + sdk/javascript/edit-message.mdx | 19 + sdk/javascript/flag-message.mdx | 9 + sdk/javascript/group-add-members.mdx | 2 + sdk/javascript/group-change-member-scope.mdx | 2 + sdk/javascript/group-kick-ban-members.mdx | 4 + sdk/javascript/interactive-messages.mdx | 9 + sdk/javascript/join-group.mdx | 11 + sdk/javascript/leave-group.mdx | 2 + sdk/javascript/mentions.mdx | 7 + sdk/javascript/reactions.mdx | 17 + sdk/javascript/receive-message.mdx | 31 + sdk/javascript/retrieve-conversations.mdx | 45 +- sdk/javascript/retrieve-group-members.mdx | 10 + sdk/javascript/retrieve-groups.mdx | 22 + sdk/javascript/retrieve-users.mdx | 33 + sdk/javascript/send-message.mdx | 1337 --------- sdk/javascript/setup-sdk.mdx | 12 + sdk/javascript/threaded-messages.mdx | 11 + sdk/javascript/transfer-group-ownership.mdx | 2 + sdk/javascript/transient-messages.mdx | 9 + sdk/javascript/typing-indicators.mdx | 9 + sdk/javascript/update-group.mdx | 12 + sdk/javascript/user-management.mdx | 20 + sdk/javascript/user-presence.mdx | 9 + sdk/reference/auxiliary.mdx | 103 + sdk/reference/entities.mdx | 108 + sdk/reference/messages.mdx | 126 + 39 files changed, 819 insertions(+), 3839 deletions(-) create mode 100644 sdk/reference/auxiliary.mdx create mode 100644 sdk/reference/entities.mdx diff --git a/docs.json b/docs.json index 5e6b79214..fe310ab40 100644 --- a/docs.json +++ b/docs.json @@ -2607,6 +2607,12 @@ "sdk/javascript/managing-web-sockets-connections-manually" ] }, + { + "group": "Reference", + "pages": [ + "sdk/reference/messages" + ] + }, { "group": "UI Kits", "pages": [ diff --git a/sdk/javascript/additional-message-filtering.mdx b/sdk/javascript/additional-message-filtering.mdx index 8cb2cfd83..a2a971a10 100644 --- a/sdk/javascript/additional-message-filtering.mdx +++ b/sdk/javascript/additional-message-filtering.mdx @@ -119,110 +119,6 @@ When messages are fetched successfully, the response will include an array of me The examples on this page use a small `setLimit()` value for brevity. In production, use a higher limit (up to 100) for efficient pagination. - - -**On Success** — Returns an array of `TextMessage` objects for the specified user conversation: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message ID | `"125641"` | -| `muid` | string | Client-generated unique message ID | `"_19v4y6elj"` | -| `receiverId` | string | UID of the receiver | `"superhero2"` | -| `type` | string | Message type | `"text"` | -| `receiverType` | string | Receiver type | `"user"` | -| `category` | string | Message category | `"message"` | -| `text` | string | The text content of the message | `"hi"` | -| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | -| `sender` | object | Sender user details | [See below ↓](#user-conversation-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#user-conversation-receiver-object) | -| `sentAt` | number | Timestamp when the message was sent (epoch) | `1772706632` | -| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1772706632` | -| `metadata` | object | Extension metadata (data masking, link preview, etc.) | [See below ↓](#user-conversation-metadata-object) | -| `data` | object | Additional message data including entities | [See below ↓](#user-conversation-data-object) | -| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero1"` | -| `name` | string | Display name | `"Iron Man"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772703126` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"online"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero2"` | -| `name` | string | Display name | `"Captain America"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772450329` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Server-injected extension data | Contains `extensions` object | - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "hi", ...}` | -| `link-preview` | object | Link preview extension results | `{"links": []}` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | The text content | `"hi"` | -| `resource` | string | SDK resource identifier | `"WEB-4_1_8-85fc027f-..."` | -| `metadata` | object | Same as top-level metadata | [See above ↑](#user-conversation-metadata-object) | -| `moderation` | object | Moderation status | `{"status": "approved"}` | -| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#user-conversation-entities-object) | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#user-conversation-sender-object) | -| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#user-conversation-receiver-object) | - - - ## Messages for a group conversation *In other words, how do I fetch messages for any group conversation* @@ -253,114 +149,6 @@ let messagesRequest: CometChat.MessagesRequest = When messages are fetched successfully, the response will include an array of message objects containing all information related to each message. - - -**On Success** — Returns an array of `TextMessage` objects for the specified group conversation: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message ID | `"125647"` | -| `muid` | string | Client-generated unique message ID | `"_wldd52695"` | -| `receiverId` | string | GUID of the group | `"group_1772706842135"` | -| `type` | string | Message type | `"text"` | -| `receiverType` | string | Receiver type | `"group"` | -| `category` | string | Message category | `"message"` | -| `text` | string | The text content of the message | `"how's it going"` | -| `conversationId` | string | Unique conversation identifier | `"group_group_1772706842135"` | -| `sender` | object | Sender user details | [See below ↓](#group-conversation-sender-object) | -| `receiver` | object | Receiver group details | [See below ↓](#group-conversation-receiver-object) | -| `sentAt` | number | Timestamp when the message was sent (epoch) | `1772706897` | -| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1772706897` | -| `metadata` | object | Extension metadata (data masking, link preview, etc.) | [See below ↓](#group-conversation-metadata-object) | -| `data` | object | Additional message data including entities | [See below ↓](#group-conversation-data-object) | -| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero1"` | -| `name` | string | Display name | `"Iron Man"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772706892` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`receiver` Object (Group):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `guid` | string | Unique group ID | `"group_1772706842135"` | -| `name` | string | Group name | `"Avengers Group"` | -| `type` | string | Group type | `"public"` | -| `owner` | string | UID of the group owner | `"superhero1"` | -| `scope` | string | Logged-in user's scope in the group | `"admin"` | -| `membersCount` | number | Number of members in the group | `2` | -| `hasJoined` | boolean | Whether the logged-in user has joined | `true` | -| `isBanned` | boolean | Whether the logged-in user is banned | `false` | -| `conversationId` | string | Unique conversation identifier | `"group_group_1772706842135"` | -| `createdAt` | number | Group creation timestamp (epoch) | `1772706842` | -| `joinedAt` | number | Timestamp when the user joined (epoch) | `1772706842` | -| `updatedAt` | number | Last updated timestamp (epoch) | `1772706877` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Server-injected extension data | Contains `extensions` object | - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "how's it going", ...}` | -| `link-preview` | object | Link preview extension results | `{"links": []}` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | The text content | `"how's it going"` | -| `resource` | string | SDK resource identifier | `"WEB-4_1_8-85fc027f-..."` | -| `metadata` | object | Same as top-level metadata | [See above ↑](#group-conversation-metadata-object) | -| `moderation` | object | Moderation status | `{"status": "approved"}` | -| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#group-conversation-entities-object) | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#group-conversation-sender-object) | -| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "group"` — entity matches [receiver ↑](#group-conversation-receiver-object) | - - - If none of the above two methods `setUID()` and `setGUID()` is used, all the messages for the logged-in user will be fetched. This means that messages from all the one-on-one and group conversations which the logged-in user is a part of will be returned.> All the parameters discussed below can be used along with the setUID() or setGUID() or without any of the two to fetch all the messages that the logged-in user is a part of. @@ -437,113 +225,6 @@ let GUID: string = "GUID", This method can be used along with `setUID()` or `setGUID()` methods to fetch messages after/before any specific message-id for a particular user/group conversation. When messages are fetched successfully, the response will include an array of message objects containing all information related to each message. - - -**On Success** — Returns an array of `TextMessage` objects before or after the specified message ID: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message ID | `"125334"` | -| `muid` | string | Client-generated unique message ID | `"cc_1772437741542_6_zz3xjd2"` | -| `receiverId` | string | UID of the receiver | `"superhero2"` | -| `type` | string | Message type | `"text"` | -| `receiverType` | string | Receiver type | `"user"` | -| `category` | string | Message category | `"message"` | -| `text` | string | The text content of the message | `"hello there"` | -| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | -| `sender` | object | Sender user details | [See below ↓](#before-after-message-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#before-after-message-receiver-object) | -| `sentAt` | number | Timestamp when the message was sent (epoch) | `1772437744` | -| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1772437744` | -| `replyCount` | number | Number of threaded replies to this message | `5` | -| `deliveredAt` | number | Timestamp when the message was delivered (epoch) | `1772450305` | -| `readAt` | number | Timestamp when the message was read (epoch) | `1772450305` | -| `metadata` | object | Extension metadata (data masking, link preview, etc.) | [See below ↓](#before-after-message-metadata-object) | -| `data` | object | Additional message data including entities | [See below ↓](#before-after-message-data-object) | -| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero1"` | -| `name` | string | Display name | `"Iron Man"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772437730` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"online"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero2"` | -| `name` | string | Display name | `"Captain America"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772384727` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Server-injected extension data | Contains `extensions` object | - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "hello there", ...}` | -| `link-preview` | object | Link preview extension results | `{"links": []}` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | The text content | `"hello there"` | -| `resource` | string | SDK resource identifier | `"WEB-4_1_5-bd01135d-..."` | -| `metadata` | object | Same as top-level metadata | [See above ↑](#before-after-message-metadata-object) | -| `moderation` | object | Moderation status | `{"status": "approved"}` | -| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#before-after-message-entities-object) | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#before-after-message-sender-object) | -| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#before-after-message-receiver-object) | - - - ## Messages before/after a given time *In other words, how do I fetch messages before or after a particular date or time* @@ -614,110 +295,6 @@ let GUID: string = "GUID", This method can be used along with `setUID()` or `setGUID()` methods to fetch messages after/before any specific date or time for a particular user/group conversation. When messages are fetched successfully, the response will include an array of message objects containing all information related to each message. - - -**On Success** — Returns an array of `TextMessage` objects before or after the specified timestamp: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message ID | `"125641"` | -| `muid` | string | Client-generated unique message ID | `"_19v4y6elj"` | -| `receiverId` | string | UID of the receiver | `"superhero2"` | -| `type` | string | Message type | `"text"` | -| `receiverType` | string | Receiver type | `"user"` | -| `category` | string | Message category | `"message"` | -| `text` | string | The text content of the message | `"hi"` | -| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | -| `sender` | object | Sender user details | [See below ↓](#before-after-time-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#before-after-time-receiver-object) | -| `sentAt` | number | Timestamp when the message was sent (epoch) | `1772706632` | -| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1772706632` | -| `metadata` | object | Extension metadata (data masking, link preview, etc.) | [See below ↓](#before-after-time-metadata-object) | -| `data` | object | Additional message data including entities | [See below ↓](#before-after-time-data-object) | -| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero1"` | -| `name` | string | Display name | `"Iron Man"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772703126` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"online"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero2"` | -| `name` | string | Display name | `"Captain America"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772450329` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Server-injected extension data | Contains `extensions` object | - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "hi", ...}` | -| `link-preview` | object | Link preview extension results | `{"links": []}` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | The text content | `"hi"` | -| `resource` | string | SDK resource identifier | `"WEB-4_1_8-85fc027f-..."` | -| `metadata` | object | Same as top-level metadata | [See above ↑](#before-after-time-metadata-object) | -| `moderation` | object | Moderation status | `{"status": "approved"}` | -| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#before-after-time-entities-object) | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#before-after-time-sender-object) | -| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#before-after-time-receiver-object) | - - - ## Unread messages *In other words, how do I fetch unread messages* @@ -784,110 +361,6 @@ let GUID: string = "GUID", This method along with `setGUID()` or `setUID()` can be used to fetch unread messages for a particular group or user conversation respectively. When messages are fetched successfully, the response will include an array of unread message objects. - - -**On Success** — Returns an array of unread `TextMessage` objects for the specified conversation: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message ID | `"125652"` | -| `muid` | string | Client-generated unique message ID | `"_363o8rfag"` | -| `receiverId` | string | UID of the receiver | `"superhero1"` | -| `type` | string | Message type | `"text"` | -| `receiverType` | string | Receiver type | `"user"` | -| `category` | string | Message category | `"message"` | -| `text` | string | The text content of the message | `"I'm fine"` | -| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | -| `sender` | object | Sender user details | [See below ↓](#unread-messages-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#unread-messages-receiver-object) | -| `sentAt` | number | Timestamp when the message was sent (epoch) | `1772708621` | -| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1772708622` | -| `deliveredAt` | number | Timestamp when the message was delivered (epoch) | `1772708622` | -| `metadata` | object | Extension metadata (data masking, link preview, etc.) | [See below ↓](#unread-messages-metadata-object) | -| `data` | object | Additional message data including entities | [See below ↓](#unread-messages-data-object) | -| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero2"` | -| `name` | string | Display name | `"Captain America"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772708593` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"online"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero1"` | -| `name` | string | Display name | `"Iron Man"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772708586` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"online"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Server-injected extension data | Contains `extensions` object | - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "I'm fine", ...}` | -| `link-preview` | object | Link preview extension results | `{"links": []}` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | The text content | `"I'm fine"` | -| `resource` | string | SDK resource identifier | `"WEB-4_1_8-1b3edc1d-..."` | -| `metadata` | object | Same as top-level metadata | [See above ↑](#unread-messages-metadata-object) | -| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#unread-messages-entities-object) | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#unread-messages-sender-object) | -| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#unread-messages-receiver-object) | - - - ## Exclude messages from blocked users *In other words, how do I fetch messages excluding the messages from the users I have blocked* @@ -952,11 +425,6 @@ let GUID: string = "GUID", This method can be used to hide the messages by users blocked by logged in user in groups that both the members are a part of. - - -**On Success** — The response structure is the same as a regular message fetch. The only difference is that messages from blocked users will be absent from the results. For one such regular response structure, see [Messages for group conversation ↑](#group-conversation-response). - - ## Updated and received messages *In other words, how do I fetch messages that have been received or updated after a particular date or time* @@ -1027,122 +495,6 @@ let GUID: string = "GUID", This can be useful in finding the messages that have been received or updated after a certain time. Can prove very useful if you are saving the messages locally and would like to know the messages that have been updated or received after the last message available in your local databases. When messages are fetched successfully, the response may include both action messages (for updates like edits, deletes, read/delivered status changes) and regular messages (for newly received messages). - - -**On Success** — Returns an array containing action messages (for updates) and regular messages (for new messages received after the specified timestamp): - - - -**Action Message Object (for edited/deleted/read/delivered updates):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message ID | `"125657"` | -| `receiverId` | string | UID of the receiver | `"superhero2"` | -| `type` | string | Message type | `"message"` | -| `receiverType` | string | Receiver type | `"user"` | -| `category` | string | Message category | `"action"` | -| `action` | string | The action that was performed | `"edited"` | -| `message` | string | Action message text | `""` | -| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | -| `actionBy` | object | User who performed the action | [See below ↓](#updated-received-actionby-object) | -| `actionFor` | object | User the action was performed for | [See below ↓](#updated-received-actionfor-object) | -| `actionOn` | object | The message that was acted upon | [See below ↓](#updated-received-actionon-object) | -| `sender` | object | Sender user details (same as actionBy) | [See below ↓](#updated-received-actionby-object) | -| `receiver` | object | Receiver user details | [See below ↓](#updated-received-actionfor-object) | -| `sentAt` | number | Timestamp when the action occurred (epoch) | `1772709041` | -| `updatedAt` | number | Timestamp when the action was last updated (epoch) | `1772709041` | -| `data` | object | Action data including entities | [See below ↓](#updated-received-data-object) | -| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | - ---- - - - -**`actionBy` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero1"` | -| `name` | string | Display name | `"Iron Man"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772709037` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`actionFor` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero2"` | -| `name` | string | Display name | `"Captain America"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772709006` | -| `conversationId` | string | Conversation identifier | `"superhero1_user_superhero2"` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"online"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`actionOn` Object (the message that was edited/deleted):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message ID | `"125654"` | -| `muid` | string | Client-generated unique message ID | `"_umdly7vy7"` | -| `receiverId` | string | UID of the receiver | `"superhero2"` | -| `type` | string | Message type | `"text"` | -| `receiverType` | string | Receiver type | `"user"` | -| `category` | string | Message category | `"message"` | -| `text` | string | The updated text content | `"hello edited"` | -| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | -| `sender` | object | Sender user details | Same structure as [actionBy ↑](#updated-received-actionby-object) | -| `receiver` | object | Receiver user details | Same structure as [actionFor ↑](#updated-received-actionfor-object) | -| `sentAt` | number | Original sent timestamp (epoch) | `1772709026` | -| `updatedAt` | number | Last updated timestamp (epoch) | `1772709027` | -| `deliveredAt` | number | Delivered timestamp (epoch) | `1772709027` | -| `editedAt` | number | Timestamp when the message was edited (epoch) | `1772709041` | -| `editedBy` | string | UID of the user who edited the message | `"superhero1"` | -| `metadata` | object | Extension metadata | Same structure as regular message metadata | -| `data` | object | Message data with entities and text | Contains `text`, `resource`, `metadata`, `moderation`, `entities` | -| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | - ---- - - - -**`data` Object (Action Message):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `action` | string | The action type | `"edited"` | -| `resource` | string | SDK resource identifier | `"WEB-4_1_8-85fc027f-..."` | -| `entities` | object | Entity wrappers for the action | [See below ↓](#updated-received-entities-object) | - ---- - - - -**`data.entities` Object (Action Message):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `by` | object | Entity wrapper for who performed the action (`{entity, entityType}`) | `entityType: "user"` — entity matches [actionBy ↑](#updated-received-actionby-object) | -| `for` | object | Entity wrapper for who the action was for (`{entity, entityType}`) | `entityType: "user"` — entity matches [actionFor ↑](#updated-received-actionfor-object) | -| `on` | object | Entity wrapper for the message acted upon (`{entity, entityType}`) | `entityType: "message"` — entity matches [actionOn ↑](#updated-received-actionon-object) | - - - ## Updated messages only *In other words, how do I fetch messages that have been updated after a particular date or time* @@ -1215,114 +567,6 @@ let GUID: string = "GUID", When messages are fetched successfully, the response will include only the messages that have been updated (edited, deleted, read/delivered status changed) after the specified timestamp — not newly received messages. - - -**On Success** — Returns an array of updated `TextMessage` objects (edited messages in this example): - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message ID | `"125671"` | -| `muid` | string | Client-generated unique message ID | `"_bf82a3mae"` | -| `receiverId` | string | UID of the receiver | `"superhero2"` | -| `type` | string | Message type | `"text"` | -| `receiverType` | string | Receiver type | `"user"` | -| `category` | string | Message category | `"message"` | -| `text` | string | The updated text content of the message | `"one - edited"` | -| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | -| `sender` | object | Sender user details | [See below ↓](#updated-only-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#updated-only-receiver-object) | -| `sentAt` | number | Timestamp when the message was originally sent (epoch) | `1772710689` | -| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1772710741` | -| `editedAt` | number | Timestamp when the message was edited (epoch) | `1772710741` | -| `editedBy` | string | UID of the user who edited the message | `"superhero1"` | -| `deliveredAt` | number | Timestamp when the message was delivered (epoch) | `1772710690` | -| `readAt` | number | Timestamp when the message was read (epoch) | `1772710690` | -| `metadata` | object | Extension metadata (data masking, link preview, etc.) | [See below ↓](#updated-only-metadata-object) | -| `data` | object | Additional message data including entities | [See below ↓](#updated-only-data-object) | -| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero1"` | -| `name` | string | Display name | `"Iron Man"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772710681` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero2"` | -| `name` | string | Display name | `"Captain America"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772710682` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Server-injected extension data | Contains `extensions` object | - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "one", ...}` | -| `link-preview` | object | Link preview extension results | `{"links": []}` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | The updated text content | `"one - edited"` | -| `resource` | string | SDK resource identifier | `"WEB-4_1_8-85fc027f-..."` | -| `metadata` | object | Same as top-level metadata | [See above ↑](#updated-only-metadata-object) | -| `moderation` | object | Moderation status | `{"status": "approved"}` | -| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#updated-only-entities-object) | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#updated-only-sender-object) | -| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#updated-only-receiver-object) | - - - ## Messages for multiple categories *In other words, how do I fetch messages belonging to multiple categories* @@ -1393,217 +637,46 @@ let GUID: string = "GUID", The above snippet will help you get only the messages belonging to the `message` and `custom` category. This can also be used to disable certain categories of messages like `call` and `action`. +## Messages for multiple types - -**On Success** — Returns an array containing messages from the specified categories (`custom` and `call` in this example). The response includes different message structures depending on the category: - - - -**Custom Message Object (category: `custom`):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message ID | `"125679"` | -| `muid` | string | Client-generated unique message ID | `"_0jfpc22x9"` | -| `receiverId` | string | UID of the receiver | `"superhero2"` | -| `type` | string | Message type (extension-specific) | `"extension_sticker"` | -| `receiverType` | string | Receiver type | `"user"` | -| `category` | string | Message category | `"custom"` | -| `customData` | object | Custom data payload for this message | `{"sticker_name": "happy ghost", "sticker_url": "https://..."}` | -| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | -| `sender` | object | Sender user details | [See below ↓](#multiple-categories-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#multiple-categories-receiver-object) | -| `sentAt` | number | Timestamp when the message was sent (epoch) | `1772710916` | -| `deliveredAt` | number | Timestamp when the message was delivered (epoch) | `1772710917` | -| `readAt` | number | Timestamp when the message was read (epoch) | `1772710917` | -| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1772710917` | -| `metadata` | object | Message metadata | [See below ↓](#multiple-categories-custom-metadata-object) | -| `data` | object | Additional message data including entities | [See below ↓](#multiple-categories-custom-data-object) | -| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero1"` | -| `name` | string | Display name | `"Iron Man"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772710911` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"online"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - +*In other words, how do I fetch messages belonging to multiple types* -**`receiver` Object:** +We recommend before trying this, you refer to the [Message structure and hierarchy guide](/sdk/javascript/message-structure-and-hierarchy) to get familiar with the various types of messages. -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero2"` | -| `name` | string | Display name | `"Captain America"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772710895` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +This can be easily achieved using the `setTypes()` method. This method accepts a list of types. This tells the SDK to fetch messages only belonging to these types. ---- + + +```javascript +let UID = "UID"; +let limit = 30; +let categories = ["message"]; +let types = ["image", "video", "audio", "file"]; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setCategories(categories) + .setTypes(types) + .setLimit(limit) + .build(); +``` - + -**`metadata` Object (Custom Message):** + +```javascript +let GUID = "GUID"; +let limit = 30; +let categories = ["message"]; +let types = ["image", "video", "audio", "file"]; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setCategories(categories) + .setTypes(types) + .setLimit(limit) + .build(); +``` -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `incrementUnreadCount` | boolean | Whether this message increments the unread count | `true` | - ---- - - - -**`data` Object (Custom Message):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `customData` | object | Custom data payload | `{"sticker_name": "happy ghost", "sticker_url": "https://..."}` | -| `resource` | string | SDK resource identifier | `"WEB-4_1_8-85fc027f-..."` | -| `updateConversation` | boolean | Whether this message updates the conversation list | `true` | -| `metadata` | object | Message metadata | `{"incrementUnreadCount": true}` | -| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#multiple-categories-custom-entities-object) | - ---- - - - -**`data.entities` Object (Custom Message):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#multiple-categories-sender-object) | -| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#multiple-categories-receiver-object) | - ---- - - - -**Call Message Object (category: `call`):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message ID | `"125680"` | -| `receiverId` | string | UID of the receiver | `"superhero2"` | -| `type` | string | Call type | `"audio"` | -| `receiverType` | string | Receiver type | `"user"` | -| `category` | string | Message category | `"call"` | -| `action` | string | Call action | `"initiated"` or `"cancelled"` | -| `sessionId` | string | Unique call session identifier | `"v1.us.208136f5ba34a5a2.1772711101..."` | -| `status` | string | Call status | `"initiated"` or `"cancelled"` | -| `initiatedAt` | number | Timestamp when the call was initiated (epoch) | `1772711101` | -| `joinedAt` | number | Timestamp when the caller joined (epoch, present for `initiated`) | `1772711101` | -| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | -| `sender` | object | Sender user details | [See above ↑](#multiple-categories-sender-object) | -| `receiver` | object | Receiver user details | [See above ↑](#multiple-categories-receiver-object) | -| `sentAt` | number | Timestamp when the message was sent (epoch) | `1772711101` | -| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1772711101` | -| `callInitiator` | object | User who initiated the call | Same structure as [sender ↑](#multiple-categories-sender-object) | -| `callReceiver` | object | User who received the call | Same structure as [receiver ↑](#multiple-categories-receiver-object) | -| `data` | object | Call data including action entities | [See below ↓](#multiple-categories-call-data-object) | -| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | - ---- - - - -**`data` Object (Call Message):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `action` | string | Call action type | `"initiated"` or `"cancelled"` | -| `resource` | string | SDK resource identifier | `"WEB-4_1_8-85fc027f-..."` | -| `entities` | object | Call entity wrappers | [See below ↓](#multiple-categories-call-entities-object) | - ---- - - - -**`data.entities` Object (Call Message):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `by` | object | User who performed the action (`{entity, entityType}`) | `entityType: "user"` — the call initiator | -| `for` | object | User the action was performed for (`{entity, entityType}`) | `entityType: "user"` — the call receiver | -| `on` | object | The call session entity (`{entity, entityType}`) | `entityType: "call"` — [See below ↓](#multiple-categories-call-on-entity) | - ---- - - - -**`data.entities.on.entity` Object (Call Session):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `conversationId` | string | Conversation identifier | `"superhero1_user_superhero2"` | -| `sender` | string | UID of the call sender | `"superhero1"` | -| `receiver` | string | UID of the call receiver | `"superhero2"` | -| `receiverType` | string | Receiver type | `"user"` | -| `type` | string | Call type | `"audio"` | -| `status` | string | Call status | `"initiated"` or `"cancelled"` | -| `sessionid` | string | Call session ID | `"v1.us.208136f5ba34a5a2.1772711101..."` | -| `initiatedAt` | number | Timestamp when the call was initiated (epoch) | `1772711101` | -| `joinedAt` | number | Timestamp when the caller joined (epoch, present for `initiated`) | `1772711101` | -| `data` | object | Nested entities for sender/receiver | Contains `entities` with `sender` and `receiver` wrappers | -| `wsChannel` | object | WebSocket channel details for the call | `{"identity": "...", "secret": "...", "service": "..."}` | - - - -## Messages for multiple types - -*In other words, how do I fetch messages belonging to multiple types* - -We recommend before trying this, you refer to the [Message structure and hierarchy guide](/sdk/javascript/message-structure-and-hierarchy) to get familiar with the various types of messages. - -This can be easily achieved using the `setTypes()` method. This method accepts a list of types. This tells the SDK to fetch messages only belonging to these types. - - - -```javascript -let UID = "UID"; -let limit = 30; -let categories = ["message"]; -let types = ["image", "video", "audio", "file"]; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setCategories(categories) - .setTypes(types) - .setLimit(limit) - .build(); -``` - - - - -```javascript -let GUID = "GUID"; -let limit = 30; -let categories = ["message"]; -let types = ["image", "video", "audio", "file"]; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setCategories(categories) - .setTypes(types) - .setLimit(limit) - .build(); -``` - - + ```typescript @@ -1642,140 +715,6 @@ let GUID: string = "GUID", Using the above code snippet, you can fetch all the media messages. - - -**On Success** — Returns an array of media `Message` objects matching the specified types (`image` and `audio` in this example): - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message ID | `"125754"` | -| `muid` | string | Client-generated unique message ID | `"_i62mzac34"` | -| `receiverId` | string | UID of the receiver | `"superhero2"` | -| `type` | string | Message type (matches the requested types) | `"audio"` or `"image"` | -| `receiverType` | string | Receiver type | `"user"` | -| `category` | string | Message category | `"message"` | -| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | -| `sender` | object | Sender user details | [See below ↓](#multiple-types-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#multiple-types-receiver-object) | -| `sentAt` | number | Timestamp when the message was sent (epoch) | `1772791833` | -| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1772791833` | -| `metadata` | object | File and extension metadata | [See below ↓](#multiple-types-metadata-object) | -| `data` | object | Additional message data including attachments and entities | [See below ↓](#multiple-types-data-object) | -| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero1"` | -| `name` | string | Display name | `"Iron Man"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772791811` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"online"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero2"` | -| `name` | string | Display name | `"Captain America"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772719315` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`metadata` Object:** - -The metadata structure varies by message type: - -**For `audio` messages:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `file` | array | File reference array | `[]` | -| `fileName` | string | Name of the audio file | `"recording.wav"` | -| `fileSize` | number | File size in bytes | `409004` | -| `fileType` | string | MIME type of the file | `"audio/wav"` | - -**For `image` messages:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Server-injected extension data | Contains `extensions` object | -| `file` | array | File reference array | `[]` | -| `fileName` | string | Name of the image file | `"dummy.webp"` | -| `fileSize` | number | File size in bytes | `19554` | -| `fileType` | string | MIME type of the file | `"image/webp"` | - -**`metadata.@injected.extensions` Object (Image):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `thumbnail-generation` | object | Generated thumbnail URLs for the image | Contains `url_small`, `url_medium`, `url_large`, and `attachments` array | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `attachments` | array | Array of attachment objects | [See below ↓](#multiple-types-attachments-object) | -| `url` | string | Direct URL to the media file | `"https://data-us.cometchat.io/..."` | -| `resource` | string | SDK resource identifier | `"WEB-4_1_8-3893da9d-..."` | -| `metadata` | object | Same as top-level metadata | [See above ↑](#multiple-types-metadata-object) | -| `moderation` | object | Moderation status | `{"status": "approved"}` | -| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#multiple-types-entities-object) | - ---- - - - -**`data.attachments` Array (per item):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extension` | string | File extension | `"wav"` or `"webp"` | -| `mimeType` | string | MIME type | `"audio/wav"` or `"image/webp"` | -| `name` | string | File name | `"recording.wav"` | -| `size` | number | File size in bytes | `409004` | -| `url` | string | Direct URL to the file | `"https://data-us.cometchat.io/..."` | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#multiple-types-sender-object) | -| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#multiple-types-receiver-object) | - - - ## Messages for a specific thread *In other words, how do I fetch messages that are a part of a thread and not directly a user/group conversations* @@ -1844,111 +783,6 @@ let GUID: string = "GUID", The above code snippet returns the messages that belong to the thread with parent id 100. - - -**On Success** — Returns an array of `TextMessage` objects that belong to the specified thread (replies to the parent message): - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message ID | `"125758"` | -| `muid` | string | Client-generated unique message ID | `"_angx5llih"` | -| `receiverId` | string | UID of the receiver | `"superhero2"` | -| `type` | string | Message type | `"text"` | -| `receiverType` | string | Receiver type | `"user"` | -| `category` | string | Message category | `"message"` | -| `text` | string | The text content of the thread reply | `"thread reply 1"` | -| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | -| `parentMessageId` | string | ID of the parent message this reply belongs to | `"125751"` | -| `sender` | object | Sender user details | [See below ↓](#thread-messages-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#thread-messages-receiver-object) | -| `sentAt` | number | Timestamp when the message was sent (epoch) | `1772797901` | -| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1772797901` | -| `metadata` | object | Extension metadata (data masking, link preview, etc.) | [See below ↓](#thread-messages-metadata-object) | -| `data` | object | Additional message data including entities | [See below ↓](#thread-messages-data-object) | -| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero1"` | -| `name` | string | Display name | `"Iron Man"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772797895` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero2"` | -| `name` | string | Display name | `"Captain America"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772719315` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Server-injected extension data | Contains `extensions` object | - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "thread reply 1", ...}` | -| `link-preview` | object | Link preview extension results | `{"links": []}` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | The text content of the thread reply | `"thread reply 1"` | -| `resource` | string | SDK resource identifier | `"WEB-4_1_8-7cf7e736-..."` | -| `metadata` | object | Same as top-level metadata | [See above ↑](#thread-messages-metadata-object) | -| `moderation` | object | Moderation status | `{"status": "approved"}` | -| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#thread-messages-entities-object) | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#thread-messages-sender-object) | -| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#thread-messages-receiver-object) | - - - ## Hide threaded messages in user/group conversations *In other words, how do I exclude threaded messages from the normal user/group conversations* @@ -2011,111 +845,6 @@ let GUID: string = "GUID", - - -**On Success** — Returns an array of `TextMessage` objects from the main conversation only (thread replies are excluded). Messages that are thread parents will still appear with their `replyCount`: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message ID | `"125884"` | -| `muid` | string | Client-generated unique message ID | `"_g5o26um1n"` | -| `receiverId` | string | UID of the receiver | `"superhero2"` | -| `type` | string | Message type | `"text"` | -| `receiverType` | string | Receiver type | `"user"` | -| `category` | string | Message category | `"message"` | -| `text` | string | The text content of the message | `"hello"` | -| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | -| `replyCount` | number | Number of thread replies (present only on thread parent messages) | `2` | -| `sender` | object | Sender user details | [See below ↓](#hide-threaded-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#hide-threaded-receiver-object) | -| `sentAt` | number | Timestamp when the message was sent (epoch) | `1773060107` | -| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1773060107` | -| `metadata` | object | Extension metadata (data masking, link preview, etc.) | [See below ↓](#hide-threaded-metadata-object) | -| `data` | object | Additional message data including entities | [See below ↓](#hide-threaded-data-object) | -| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero1"` | -| `name` | string | Display name | `"Iron Man"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1773060100` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"online"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero2"` | -| `name` | string | Display name | `"Captain America"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1773041090` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Server-injected extension data | Contains `extensions` object | - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "hello", ...}` | -| `link-preview` | object | Link preview extension results | `{"links": []}` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | The text content | `"hello"` | -| `resource` | string | SDK resource identifier | `"WEB-4_1_8-5c0e1cd7-..."` | -| `metadata` | object | Same as top-level metadata | [See above ↑](#hide-threaded-metadata-object) | -| `moderation` | object | Moderation status | `{"status": "approved"}` | -| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#hide-threaded-entities-object) | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#hide-threaded-sender-object) | -| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#hide-threaded-receiver-object) | - - - ## Hide deleted messages in user/group conversations *In other words, how do I exclude deleted messages a user/group conversations* @@ -2178,111 +907,6 @@ let GUID: string = "GUID", - - - -On Success — Returns an array of `TextMessage` objects from the conversation, excluding any messages that have been deleted. Deleted messages are simply absent from the results. In this example, `categories: ["message"]` was also set to filter for standard messages only. - - - -**Message Object (per element in the array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message ID | `"125904"` | -| `muid` | string | Client-generated unique message ID | `"_nj0d6qk3v"` | -| `receiverId` | string | UID of the receiver | `"superhero2"` | -| `type` | string | Message type | `"text"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Text content of the message | `"msg before deleted msg"` | -| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | -| `sender` | object | Sender user details | [See below ↓](#hide-deleted-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#hide-deleted-receiver-object) | -| `sentAt` | number | Timestamp when the message was sent (epoch) | `1773129488` | -| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1773129488` | -| `metadata` | object | Extension metadata (data masking, link preview, etc.) | [See below ↓](#hide-deleted-metadata-object) | -| `data` | object | Additional message data including entities | [See below ↓](#hide-deleted-data-object) | -| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero1"` | -| `name` | string | Display name | `"Iron Man"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1773129390` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"online"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero2"` | -| `name` | string | Display name | `"Captain America"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1773124800` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Server-injected extension data | Contains `extensions` object | - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "msg before deleted msg", ...}` | -| `link-preview` | object | Link preview extension results | `{"links": []}` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | The text content of the message | `"msg before deleted msg"` | -| `resource` | string | SDK resource identifier | `"WEB-4_1_8-939a34c6-..."` | -| `metadata` | object | Same as top-level metadata | [See above ↑](#hide-deleted-metadata-object) | -| `moderation` | object | Moderation status | `{"status": "approved"}` | -| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#hide-deleted-entities-object) | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#hide-deleted-sender-object) | -| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#hide-deleted-receiver-object) | - - - ## Hide quoted messages in user/group conversations *In other words, how do I exclude quoted messages in a user/group conversations* @@ -2345,110 +969,6 @@ let GUID: string = "GUID", - - -**On Success** — Returns an array of `TextMessage` objects from the conversation, excluding any messages that were sent as quoted replies. Only original (non-quoted) messages are included: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message ID | `"125889"` | -| `muid` | string | Client-generated unique message ID | `"_5d8kekzrn"` | -| `receiverId` | string | UID of the receiver | `"superhero2"` | -| `type` | string | Message type | `"text"` | -| `receiverType` | string | Receiver type | `"user"` | -| `category` | string | Message category | `"message"` | -| `text` | string | The text content of the message | `"hello"` | -| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | -| `sender` | object | Sender user details | [See below ↓](#hide-quoted-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#hide-quoted-receiver-object) | -| `sentAt` | number | Timestamp when the message was sent (epoch) | `1773060624` | -| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1773060624` | -| `metadata` | object | Extension metadata (data masking, link preview, etc.) | [See below ↓](#hide-quoted-metadata-object) | -| `data` | object | Additional message data including entities | [See below ↓](#hide-quoted-data-object) | -| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero1"` | -| `name` | string | Display name | `"Iron Man"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1773060591` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"online"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero2"` | -| `name` | string | Display name | `"Captain America"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1773041090` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Server-injected extension data | Contains `extensions` object | - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "hello", ...}` | -| `link-preview` | object | Link preview extension results | `{"links": []}` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | The text content | `"hello"` | -| `resource` | string | SDK resource identifier | `"WEB-4_1_8-5c0e1cd7-..."` | -| `metadata` | object | Same as top-level metadata | [See above ↑](#hide-quoted-metadata-object) | -| `moderation` | object | Moderation status | `{"status": "approved"}` | -| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#hide-quoted-entities-object) | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#hide-quoted-sender-object) | -| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#hide-quoted-receiver-object) | - - - ## Messages by tags *In other words, how do I fetch messages by tags* @@ -2515,110 +1035,6 @@ let GUID: string = "GUID", - - -**On Success** — Returns an array of `TextMessage` objects that match the specified tags (`tags: ["tag1"]` in this example). Only messages tagged with the provided tags are returned: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message ID | `"125893"` | -| `receiverId` | string | UID of the receiver | `"superhero2"` | -| `type` | string | Message type | `"text"` | -| `receiverType` | string | Receiver type | `"user"` | -| `category` | string | Message category | `"message"` | -| `text` | string | The text content of the message | `"message 1 with tag1"` | -| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | -| `sender` | object | Sender user details | [See below ↓](#messages-by-tags-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#messages-by-tags-receiver-object) | -| `sentAt` | number | Timestamp when the message was sent (epoch) | `1773123536` | -| `deliveredAt` | number | Timestamp when the message was delivered (epoch) | `1773123537` | -| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1773123537` | -| `metadata` | object | Extension metadata (data masking, link preview, etc.) | [See below ↓](#messages-by-tags-metadata-object) | -| `data` | object | Additional message data including entities | [See below ↓](#messages-by-tags-data-object) | -| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero1"` | -| `name` | string | Display name | `"Iron Man"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1773123450` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"online"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero2"` | -| `name` | string | Display name | `"Captain America"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1773123510` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"online"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Server-injected extension data | Contains `extensions` object | - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "message 1 with tag1", ...}` | -| `link-preview` | object | Link preview extension results | `{"links": []}` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | The text content | `"message 1 with tag1"` | -| `resource` | string | SDK resource identifier | `"WEB-4_1_8-705024e4-..."` | -| `metadata` | object | Same as top-level metadata | [See above ↑](#messages-by-tags-metadata-object) | -| `moderation` | object | Moderation status | `{"status": "approved"}` | -| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#messages-by-tags-entities-object) | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#messages-by-tags-sender-object) | -| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#messages-by-tags-receiver-object) | - - - ## Messages with tags *In other words, how do I fetch messages with the tags information* @@ -2650,142 +1066,37 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() .build(); ``` - - - -```typescript -let UID: string = "UID", - limit: number = 30, - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setGUID(UID) - .setLimit(limit) - .withTags(true) - .build(); -``` - - - - -```typescript -let GUID: string = "GUID", - limit: number = 30, - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setLimit(limit) - .withTags(true) - .build(); -``` - - - - - - -**On Success** — Returns an array of `TextMessage` objects with the `tags` information included on each message. Messages that have tags will include a `tags` array, while messages without tags will not have this field: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message ID | `"125894"` | -| `receiverId` | string | UID of the receiver | `"superhero2"` | -| `type` | string | Message type | `"text"` | -| `receiverType` | string | Receiver type | `"user"` | -| `category` | string | Message category | `"message"` | -| `text` | string | The text content of the message | `"hello"` | -| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | -| `tags` | array | Array of tag strings associated with this message (only present on tagged messages) | `["tag1"]` | -| `sender` | object | Sender user details | [See below ↓](#messages-with-tags-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#messages-with-tags-receiver-object) | -| `sentAt` | number | Timestamp when the message was sent (epoch) | `1773123546` | -| `deliveredAt` | number | Timestamp when the message was delivered (epoch) | `1773123547` | -| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1773123547` | -| `metadata` | object | Extension metadata (data masking, link preview, etc.) | [See below ↓](#messages-with-tags-metadata-object) | -| `data` | object | Additional message data including entities | [See below ↓](#messages-with-tags-data-object) | -| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero1"` | -| `name` | string | Display name | `"Iron Man"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1773123450` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"online"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero2"` | -| `name` | string | Display name | `"Captain America"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1773123510` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"online"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Server-injected extension data | Contains `extensions` object | - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "hello", ...}` | -| `link-preview` | object | Link preview extension results | `{"links": []}` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | The text content | `"hello"` | -| `resource` | string | SDK resource identifier | `"WEB-4_1_8-705024e4-..."` | -| `metadata` | object | Same as top-level metadata | [See above ↑](#messages-with-tags-metadata-object) | -| `moderation` | object | Moderation status | `{"status": "approved"}` | -| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#messages-with-tags-entities-object) | - ---- + - + +```typescript +let UID: string = "UID", + limit: number = 30, + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setGUID(UID) + .setLimit(limit) + .withTags(true) + .build(); +``` -**`data.entities` Object:** + -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#messages-with-tags-sender-object) | -| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#messages-with-tags-receiver-object) | + +```typescript +let GUID: string = "GUID", + limit: number = 30, + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setLimit(limit) + .withTags(true) + .build(); +``` - + + When `.withTags(true)` is set on the request builder, each message returned will have its `tags` field populated if it has any tags set. The messages are returned as [`BaseMessage`](/sdk/reference/messages#basemessage) objects (which may be [`TextMessage`](/sdk/reference/messages#textmessage) or other subclasses). You can access the tags using `getTags()`. | Additional Field | Getter | Return Type | Description | @@ -2860,111 +1171,6 @@ let GUID: string = "GUID", - - -**On Success** — Returns an array of `TextMessage` objects that contain links in their text content: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message ID | `"125896"` | -| `receiverId` | string | UID of the receiver | `"superhero2"` | -| `type` | string | Message type | `"text"` | -| `receiverType` | string | Receiver type | `"user"` | -| `category` | string | Message category | `"message"` | -| `text` | string | The text content containing a link | `"hey, check out: https://www.example.com"` | -| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | -| `sender` | object | Sender user details | [See below ↓](#messages-with-links-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#messages-with-links-receiver-object) | -| `sentAt` | number | Timestamp when the message was sent (epoch) | `1773123969` | -| `deliveredAt` | number | Timestamp when the message was delivered (epoch) | `1773123969` | -| `readAt` | number | Timestamp when the message was read (epoch) | `1773123983` | -| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1773123983` | -| `metadata` | object | Extension metadata (data masking, link preview, etc.) | [See below ↓](#messages-with-links-metadata-object) | -| `data` | object | Additional message data including entities | [See below ↓](#messages-with-links-data-object) | -| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero1"` | -| `name` | string | Display name | `"Iron Man"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1773123450` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"online"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero2"` | -| `name` | string | Display name | `"Captain America"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1773123678` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"online"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Server-injected extension data | Contains `extensions` object | - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "hey, check out: https://www.example.com", ...}` | -| `link-preview` | object | Link preview extension results | `{"links": []}` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | The text content containing a link | `"hey, check out: https://www.example.com"` | -| `resource` | string | SDK resource identifier | `"WEB-4_1_8-705024e4-..."` | -| `metadata` | object | Same as top-level metadata | [See above ↑](#messages-with-links-metadata-object) | -| `moderation` | object | Moderation status | `{"status": "approved"}` | -| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#messages-with-links-entities-object) | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#messages-with-links-sender-object) | -| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#messages-with-links-receiver-object) | - - - ## Messages with attachments In other words, as a logged-in user, how do I fetch messages that contains attachments? @@ -3035,129 +1241,6 @@ let GUID: string = "GUID", The response will contain a list of media message objects with attachment details, including file metadata and thumbnail URLs. - - - -On Success — Returns an array of `MediaMessage` objects. Each message includes an `attachments` array with file details, plus thumbnail generation metadata when available. - - - -**Message Object (per element in the array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message ID | `"125898"` | -| `muid` | string | Client-generated unique message ID | `"_boivkgy41"` | -| `receiverId` | string | UID of the receiver | `"superhero2"` | -| `type` | string | Message type (image, audio, video, file) | `"image"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Text content (empty for media messages) | — | -| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | -| `sender` | object | Sender user details | [See below ↓](#messages-with-attachments-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#messages-with-attachments-receiver-object) | -| `sentAt` | number | Timestamp when the message was sent (epoch) | `1773124815` | -| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1773124815` | -| `metadata` | object | Extension metadata (thumbnail generation, file info) | [See below ↓](#messages-with-attachments-metadata-object) | -| `data` | object | Additional message data including attachments and entities | [See below ↓](#messages-with-attachments-data-object) | -| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero1"` | -| `name` | string | Display name | `"Iron Man"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1773124809` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero2"` | -| `name` | string | Display name | `"Captain America"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1773124800` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Server-injected extension data | Contains `extensions` object | -| `file` | array | File reference array | `[]` | -| `fileName` | string | Original file name | `"dummy.jpg"` | -| `fileSize` | number | File size in bytes | `5253` | -| `fileType` | string | MIME type of the file | `"image/jpeg"` | - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `thumbnail-generation` | object | Thumbnail generation results with URLs for small, medium, and large thumbnails | `{"url_small": "https://..._small.jpg", "url_medium": "https://..._medium.jpg", "url_large": "https://..._large.jpg", "attachments": [...]}` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `url` | string | Direct URL to the media file | `"https://data-us.cometchat.io/.../image.jpg"` | -| `attachments` | array | Array of attachment objects | [See below ↓](#messages-with-attachments-attachments-array) | -| `resource` | string | SDK resource identifier | `"WEB-4_1_8-939a34c6-..."` | -| `metadata` | object | Same as top-level metadata | [See above ↑](#messages-with-attachments-metadata-object) | -| `moderation` | object | Moderation status | `{"status": "approved"}` | -| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#messages-with-attachments-entities-object) | - ---- - - - -**`data.attachments` Array (per element):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extension` | string | File extension | `"jpg"` | -| `mimeType` | string | MIME type | `"image/jpeg"` | -| `name` | string | File name | `"dummy.jpg"` | -| `size` | number | File size in bytes | `5253` | -| `url` | string | Direct URL to the file | `"https://data-us.cometchat.io/.../image.jpg"` | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#messages-with-attachments-sender-object) | -| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#messages-with-attachments-receiver-object) | - - - ## Messages with reactions In other words, as a logged-in user, how do I fetch messages that contains reactions? @@ -3228,125 +1311,6 @@ let GUID: string = "GUID", The response will contain a list of message objects that have reactions. Each message's `data` object includes a `reactions` array with emoji details. - - - -On Success — Returns an array of `BaseMessage` objects (text, media, etc.) that have reactions. Each message's `data` object contains a `reactions` array with reaction emoji, count, and whether the logged-in user reacted. - - - -**Message Object (per element in the array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message ID | `"125896"` | -| `receiverId` | string | UID of the receiver | `"superhero2"` | -| `type` | string | Message type | `"text"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Text content of the message | `"hey, check out: https://www.example.com"` | -| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | -| `sender` | object | Sender user details | [See below ↓](#messages-with-reactions-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#messages-with-reactions-receiver-object) | -| `sentAt` | number | Timestamp when the message was sent (epoch) | `1773123969` | -| `deliveredAt` | number | Timestamp when the message was delivered (epoch) | `1773123969` | -| `readAt` | number | Timestamp when the message was read (epoch) | `1773123983` | -| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1773123983` | -| `metadata` | object | Extension metadata (data masking, link preview, etc.) | [See below ↓](#messages-with-reactions-metadata-object) | -| `data` | object | Additional message data including reactions and entities | [See below ↓](#messages-with-reactions-data-object) | -| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero1"` | -| `name` | string | Display name | `"Iron Man"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1773123450` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"online"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero2"` | -| `name` | string | Display name | `"Captain America"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1773123678` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"online"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Server-injected extension data | Contains `extensions` object | - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "hey, check out: https://www.example.com", ...}` | -| `link-preview` | object | Link preview extension results | `{"links": []}` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | The text content of the message | `"hey, check out: https://www.example.com"` | -| `resource` | string | SDK resource identifier | `"WEB-4_1_8-705024e4-..."` | -| `reactions` | array | Array of reaction objects | [See below ↓](#messages-with-reactions-reactions-array) | -| `metadata` | object | Same as top-level metadata | [See above ↑](#messages-with-reactions-metadata-object) | -| `moderation` | object | Moderation status | `{"status": "approved"}` | -| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#messages-with-reactions-entities-object) | - ---- - - - -**`data.reactions` Array (per element):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `reaction` | string | The emoji reaction | `"🤡"` | -| `count` | number | Number of users who reacted with this emoji | `1` | -| `reactedByMe` | boolean | Whether the logged-in user reacted with this emoji | `true` | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#messages-with-reactions-sender-object) | -| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#messages-with-reactions-receiver-object) | - - - ## Messages with mentions In other words, as a logged-in user, how do I fetch messages that contains mentions? @@ -3417,146 +1381,6 @@ let GUID: string = "GUID", The response will contain a list of text message objects that include mentions. Each message has a `mentionedUsers` array, a `mentionedMe` boolean, and a `data.mentions` object keyed by UID. - - - -On Success — Returns an array of `TextMessage` objects that contain mentions. Each message includes `mentionedUsers` (array of user objects), `mentionedMe` (boolean), and `data.mentions` (object keyed by mentioned user UID). - - - -**Message Object (per element in the array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message ID | `"125900"` | -| `muid` | string | Client-generated unique message ID | `"_7ua87khcz"` | -| `receiverId` | string | UID of the receiver | `"superhero2"` | -| `type` | string | Message type | `"text"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Text content with mention syntax | `"🏃 <@uid:superhero2>"` | -| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | -| `sender` | object | Sender user details | [See below ↓](#messages-with-mentions-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#messages-with-mentions-receiver-object) | -| `sentAt` | number | Timestamp when the message was sent (epoch) | `1773125275` | -| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1773125275` | -| `mentionedUsers` | array | Array of mentioned user objects | [See below ↓](#messages-with-mentions-mentionedusers-array) | -| `mentionedMe` | boolean | Whether the logged-in user was mentioned | `false` | -| `metadata` | object | Extension metadata (data masking, link preview, etc.) | [See below ↓](#messages-with-mentions-metadata-object) | -| `data` | object | Additional message data including mentions and entities | [See below ↓](#messages-with-mentions-data-object) | -| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero1"` | -| `name` | string | Display name | `"Iron Man"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1773125266` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"online"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero2"` | -| `name` | string | Display name | `"Captain America"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1773124800` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`mentionedUsers` Array (per element):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID of the mentioned user | `"superhero2"` | -| `name` | string | Display name | `"Captain America"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1773124800` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Server-injected extension data | Contains `extensions` object | - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "🏃 <@uid:superhero2>", ...}` | -| `link-preview` | object | Link preview extension results | `{"links": []}` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | The text content with mention syntax | `"🏃 <@uid:superhero2>"` | -| `resource` | string | SDK resource identifier | `"WEB-4_1_8-939a34c6-..."` | -| `mentions` | object | Mentioned users keyed by UID | [See below ↓](#messages-with-mentions-data-mentions-object) | -| `metadata` | object | Same as top-level metadata | [See above ↑](#messages-with-mentions-metadata-object) | -| `moderation` | object | Moderation status | `{"status": "approved"}` | -| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#messages-with-mentions-entities-object) | - ---- - - - -**`data.mentions` Object (keyed by UID):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero2"` | -| `name` | string | Display name | `"Captain America"` | -| `status` | string | Online status | `"offline"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1773124800` | -| `conversationId` | string | Conversation ID with this user | `"superhero1_user_superhero2"` | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#messages-with-mentions-sender-object) | -| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#messages-with-mentions-receiver-object) | - - - ## Messages with particular user mentions In other words, as a logged-in user, how do I fetch messages that mentions specific users? @@ -3627,146 +1451,6 @@ let GUID: string = "GUID", The response will contain a list of text message objects that mention the specific user(s) passed in `setMentionedUIDs()`. Each message includes `mentionedUsers`, `mentionedMe`, and `data.mentions` — filtered to only return messages where the specified UIDs are mentioned. - - - -On Success — Returns an array of `TextMessage` objects where the specified user(s) are mentioned. For example, when filtering with `mentions: ["superhero2"]`, only messages that mention `superhero2` are returned. Each message includes `mentionedUsers` (array of user objects), `mentionedMe` (boolean), and `data.mentions` (object keyed by mentioned user UID). - - - -**Message Object (per element in the array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message ID | `"125900"` | -| `muid` | string | Client-generated unique message ID | `"_7ua87khcz"` | -| `receiverId` | string | UID of the receiver | `"superhero2"` | -| `type` | string | Message type | `"text"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Text content with mention syntax | `"🏃 <@uid:superhero2>"` | -| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | -| `sender` | object | Sender user details | [See below ↓](#particular-mentions-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#particular-mentions-receiver-object) | -| `sentAt` | number | Timestamp when the message was sent (epoch) | `1773125275` | -| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1773125275` | -| `mentionedUsers` | array | Array of mentioned user objects | [See below ↓](#particular-mentions-mentionedusers-array) | -| `mentionedMe` | boolean | Whether the logged-in user was mentioned | `false` | -| `metadata` | object | Extension metadata (data masking, link preview, etc.) | [See below ↓](#particular-mentions-metadata-object) | -| `data` | object | Additional message data including mentions and entities | [See below ↓](#particular-mentions-data-object) | -| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero1"` | -| `name` | string | Display name | `"Iron Man"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1773125266` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"online"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero2"` | -| `name` | string | Display name | `"Captain America"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1773124800` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`mentionedUsers` Array (per element):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID of the mentioned user | `"superhero2"` | -| `name` | string | Display name | `"Captain America"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1773124800` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Server-injected extension data | Contains `extensions` object | - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "🏃 <@uid:superhero2>", ...}` | -| `link-preview` | object | Link preview extension results | `{"links": []}` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | The text content with mention syntax | `"🏃 <@uid:superhero2>"` | -| `resource` | string | SDK resource identifier | `"WEB-4_1_8-939a34c6-..."` | -| `mentions` | object | Mentioned users keyed by UID | [See below ↓](#particular-mentions-data-mentions-object) | -| `metadata` | object | Same as top-level metadata | [See above ↑](#particular-mentions-metadata-object) | -| `moderation` | object | Moderation status | `{"status": "approved"}` | -| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#particular-mentions-entities-object) | - ---- - - - -**`data.mentions` Object (keyed by UID):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero2"` | -| `name` | string | Display name | `"Captain America"` | -| `status` | string | Online status | `"offline"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1773124800` | -| `conversationId` | string | Conversation ID with this user | `"superhero1_user_superhero2"` | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#particular-mentions-sender-object) | -| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#particular-mentions-receiver-object) | - - - ## Messages with specific attachment types In other words, as a logged-in user, how do I fetch messages that contain specific types of attachments? @@ -3837,128 +1521,6 @@ let GUID: string = "GUID", The response will contain a list of media message objects filtered to only the specified attachment types (e.g., image and video). Each message includes an `attachments` array with file details and thumbnail generation metadata. - - - -On Success — Returns an array of `MediaMessage` objects matching the specified attachment types. For example, when filtering with `setAttachmentTypes([IMAGE, VIDEO])`, only image and video messages are returned. Each message includes `attachments`, file metadata, and thumbnail URLs. - - - -**Message Object (per element in the array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message ID | `"125898"` | -| `muid` | string | Client-generated unique message ID | `"_boivkgy41"` | -| `receiverId` | string | UID of the receiver | `"superhero2"` | -| `type` | string | Message type (matches the filtered attachment types) | `"image"` or `"video"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `category` | string | Message category | `"message"` | -| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | -| `sender` | object | Sender user details | [See below ↓](#specific-attachment-types-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#specific-attachment-types-receiver-object) | -| `sentAt` | number | Timestamp when the message was sent (epoch) | `1773124815` | -| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1773124815` | -| `metadata` | object | Extension metadata (thumbnail generation, file info) | [See below ↓](#specific-attachment-types-metadata-object) | -| `data` | object | Additional message data including attachments and entities | [See below ↓](#specific-attachment-types-data-object) | -| `rawMessage` | object | Raw message object as received from the server | Same structure as the parent message object (without the `rawMessage` field) | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero1"` | -| `name` | string | Display name | `"Iron Man"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1773124809` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero2"` | -| `name` | string | Display name | `"Captain America"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1773124800` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Server-injected extension data | Contains `extensions` object | -| `file` | array | File reference array | `[]` | -| `fileName` | string | Original file name | `"dummy.jpg"` | -| `fileSize` | number | File size in bytes | `5253` | -| `fileType` | string | MIME type of the file | `"image/jpeg"` | - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `thumbnail-generation` | object | Thumbnail generation results with URLs for small, medium, and large thumbnails | `{"url_small": "https://..._small.jpg", "url_medium": "https://..._medium.jpg", "url_large": "https://..._large.jpg", "attachments": [...]}` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `url` | string | Direct URL to the media file | `"https://data-us.cometchat.io/.../image.jpg"` | -| `attachments` | array | Array of attachment objects | [See below ↓](#specific-attachment-types-attachments-array) | -| `resource` | string | SDK resource identifier | `"WEB-4_1_8-939a34c6-..."` | -| `metadata` | object | Same as top-level metadata | [See above ↑](#specific-attachment-types-metadata-object) | -| `moderation` | object | Moderation status | `{"status": "approved"}` | -| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#specific-attachment-types-entities-object) | - ---- - - - -**`data.attachments` Array (per element):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extension` | string | File extension | `"jpg"` or `"mov"` | -| `mimeType` | string | MIME type | `"image/jpeg"` or `"video/quicktime"` | -| `name` | string | File name | `"dummy.jpg"` | -| `size` | number | File size in bytes | `5253` | -| `url` | string | Direct URL to the file | `"https://data-us.cometchat.io/.../image.jpg"` | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [sender ↑](#specific-attachment-types-sender-object) | -| `receiver` | object | Receiver entity wrapper (`{entity, entityType}`) | `entityType: "user"` — entity matches [receiver ↑](#specific-attachment-types-receiver-object) | - - - - **Combine filters strategically**: Use `setCategories()` with `setTypes()` for precise filtering - **Set reasonable limits**: Use 30-50 messages per fetch for optimal performance diff --git a/sdk/javascript/block-users.mdx b/sdk/javascript/block-users.mdx index 5baa2dcaf..d126facc1 100644 --- a/sdk/javascript/block-users.mdx +++ b/sdk/javascript/block-users.mdx @@ -81,6 +81,15 @@ try { It returns a Array which contains `UID's` as the keys and "success" or "fail" as the value based on if the block operation for the `UID` was successful or not. +The method returns an array of [`User`](/sdk/reference/entities#user) objects with the `blockedByMe` field set to `true`. Access the response data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| uid | `getUid()` | `string` | Unique user ID | +| name | `getName()` | `string` | Display name of the user | +| blockedByMe | `getBlockedByMe()` | `boolean` | Whether the logged-in user has blocked this user | +| hasBlockedMe | `getHasBlockedMe()` | `boolean` | Whether this user has blocked the logged-in user | + ## Unblock Users *In other words, as a logged-in user, how do I unblock a user I previously blocked?* @@ -136,6 +145,15 @@ try { It returns a Array which contains `UID's` as the keys and `success` or `fail` as the value based on if the unblock operation for the `UID` was successful or not. +The method returns an array of [`User`](/sdk/reference/entities#user) objects with the `blockedByMe` field set to `false`. Access the response data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| uid | `getUid()` | `string` | Unique user ID | +| name | `getName()` | `string` | Display name of the user | +| blockedByMe | `getBlockedByMe()` | `boolean` | Whether the logged-in user has blocked this user | +| hasBlockedMe | `getHasBlockedMe()` | `boolean` | Whether this user has blocked the logged-in user | + ## Get List of Blocked Users *In other words, as a logged-in user, how do I get a list of all users I've blocked?* diff --git a/sdk/javascript/call-logs.mdx b/sdk/javascript/call-logs.mdx index 9fb4addad..221a7a895 100644 --- a/sdk/javascript/call-logs.mdx +++ b/sdk/javascript/call-logs.mdx @@ -102,6 +102,17 @@ callLogRequestBuilder.fetchPrevious() }); ``` +The `fetchNext()` and `fetchPrevious()` methods return an array of [`Call`](/sdk/reference/messages#call) log objects. Access the response data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| sessionId | `getSessionId()` | `string` | Unique session ID for the call | +| callInitiator | `getCallInitiator()` | `User` | The user who initiated the call | +| callReceiver | `getCallReceiver()` | `User` \| `Group` | The user or group that received the call | +| action | `getAction()` | `string` | Call action/status | +| initiatedAt | `getInitiatedAt()` | `number` | Timestamp when the call was initiated | +| joinedAt | `getJoinedAt()` | `number` | Timestamp when the user joined the call | + ## Get Call Details To retrieve the specific details of a call, use the `getCallDetails()` method. This method requires the Auth token of the logged-in user and the session ID along with a callback listener. diff --git a/sdk/javascript/connection-status.mdx b/sdk/javascript/connection-status.mdx index 839bc4bff..f4b73613b 100644 --- a/sdk/javascript/connection-status.mdx +++ b/sdk/javascript/connection-status.mdx @@ -113,6 +113,15 @@ The `CometChat.getConnectionStatus` method will return either of the below 3 val 2. connected 3. disconnected +The connection listener callbacks and `getConnectionStatus()` return string enum values representing the current WebSocket connection state: + +| Value | Callback | Description | +|-------|----------|-------------| +| `"connected"` | `onConnected()` | SDK has an active connection to CometChat servers | +| `"connecting"` | `inConnecting()` | SDK is attempting to establish or re-establish a connection | +| `"disconnected"` | `onDisconnected()` | SDK is disconnected due to network issues or other errors | +| `"featureThrottled"` | — | A feature has been throttled due to rate limiting | + Always remove connection listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. diff --git a/sdk/javascript/create-group.mdx b/sdk/javascript/create-group.mdx index c2a08be2e..4f8883c2c 100644 --- a/sdk/javascript/create-group.mdx +++ b/sdk/javascript/create-group.mdx @@ -114,6 +114,17 @@ The createGroup() method takes the following parameters: After successful creation of the group, you will receive an instance of `Group` class which contains all the information about the particular group. +The method returns a [`Group`](/sdk/reference/entities#group) object. Access the response data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| guid | `getGuid()` | `string` | Unique group ID | +| name | `getName()` | `string` | Display name of the group | +| type | `getType()` | `string` | Group type (`"public"`, `"private"`, or `"password"`) | +| owner | `getOwner()` | `string` | UID of the group owner | +| membersCount | `getMembersCount()` | `number` | Total number of members in the group | +| createdAt | `getCreatedAt()` | `number` | Timestamp when the group was created | + GUID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. diff --git a/sdk/javascript/default-call.mdx b/sdk/javascript/default-call.mdx index 2ed0138a6..8f62558b4 100644 --- a/sdk/javascript/default-call.mdx +++ b/sdk/javascript/default-call.mdx @@ -141,6 +141,17 @@ CometChat.initiateCall(call).then( On success, a `Call` object is returned containing the call details including a unique `sessionId` required for starting the call session. +The `initiateCall()` method returns a [`Call`](/sdk/reference/messages#call) object. Access the response data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| sessionId | `getSessionId()` | `string` | Unique session ID for the call | +| callInitiator | `getCallInitiator()` | `User` | The user who initiated the call | +| callReceiver | `getCallReceiver()` | `User` \| `Group` | The user or group receiving the call | +| type | `getType()` | `string` | Type of call (`"audio"` or `"video"`) | +| action | `getAction()` | `string` | Current call action/status | +| initiatedAt | `getInitiatedAt()` | `number` | Timestamp when the call was initiated | + ## Call Listeners Register the `CallListener` to receive real-time call events. Each listener requires a unique `listenerId` string to prevent duplicate registrations and enable targeted removal. @@ -223,6 +234,16 @@ CometChat.removeCallListener(listenerId); | `onIncomingCallCancelled(call)` | Invoked on the receiver's device when the caller cancels before answering. Dismiss incoming call UI here. | | `onCallEndedMessageReceived(call)` | Invoked when a call ends. The `call` contains final status and duration. Update call history here. | +All call listener callbacks receive a [`Call`](/sdk/reference/messages#call) object. Access the data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| sessionId | `getSessionId()` | `string` | Unique session ID for the call | +| callInitiator | `getCallInitiator()` | `User` | The user who initiated the call | +| callReceiver | `getCallReceiver()` | `User` \| `Group` | The user or group receiving the call | +| action | `getAction()` | `string` | Current call action/status | +| initiatedAt | `getInitiatedAt()` | `number` | Timestamp when the call was initiated | + ## Accept Call When an incoming call is received via `onIncomingCallReceived()`, use `acceptCall()` to accept it. On success, start the call session. diff --git a/sdk/javascript/delete-conversation.mdx b/sdk/javascript/delete-conversation.mdx index edfe350d3..308e789fc 100644 --- a/sdk/javascript/delete-conversation.mdx +++ b/sdk/javascript/delete-conversation.mdx @@ -102,6 +102,8 @@ The `deleteConversation()` method takes the following parameters: | conversationWith | `UID` of the user or `GUID` of the group whose conversation you want to delete. | YES | | conversationType | The type of conversation you want to delete . It can be either `user` or `group`. | YES | +On success, the `deleteConversation()` method resolves with a success message string confirming the operation. + - **Confirm before deleting**: Always show a confirmation dialog before deleting conversations - **Update UI immediately**: Remove the conversation from the list optimistically, then handle errors diff --git a/sdk/javascript/delete-group.mdx b/sdk/javascript/delete-group.mdx index ccb2aeefd..ee9741f64 100644 --- a/sdk/javascript/delete-group.mdx +++ b/sdk/javascript/delete-group.mdx @@ -80,6 +80,8 @@ The `deleteGroup()` method takes the following parameters: | --------- | ---------------------------------------------- | | `GUID` | The GUID of the group you would like to delete | +On success, the method resolves with a success message string confirming the operation. + --- diff --git a/sdk/javascript/delete-message.mdx b/sdk/javascript/delete-message.mdx index 400c3916e..d25092cb7 100644 --- a/sdk/javascript/delete-message.mdx +++ b/sdk/javascript/delete-message.mdx @@ -91,6 +91,15 @@ try { Once the message is deleted, In the `onSuccess()` callback, you get an object of the `BaseMessage` class, with the `deletedAt` field set with the timestamp of the time the message was deleted. Also, the `deletedBy` field is set. These two fields can be used to identify if the message is deleted while iterating through a list of messages. +The `deleteMessage()` method returns a [`BaseMessage`](/sdk/reference/messages#basemessage) object. Access the response data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| id | `getId()` | `number` | Unique message ID | +| sender | `getSender()` | [`User`](/sdk/reference/entities#user) | The user who sent the message | +| deletedAt | `getDeletedAt()` | `number` | Timestamp when the message was deleted | +| deletedBy | `getDeletedBy()` | `string` | UID of the user who deleted the message | + By default, CometChat allows certain roles to delete a message. | User Role | Conversation Type | Deletion Capabilities | @@ -141,6 +150,15 @@ CometChat.addMessageListener( +The `onMessageDeleted` callback receives a [`BaseMessage`](/sdk/reference/messages#basemessage) object with the `deletedAt` and `deletedBy` fields set. Access the data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| id | `getId()` | `number` | Unique message ID | +| sender | `getSender()` | [`User`](/sdk/reference/entities#user) | The user who sent the message | +| deletedAt | `getDeletedAt()` | `number` | Timestamp when the message was deleted | +| deletedBy | `getDeletedBy()` | `string` | UID of the user who deleted the message | + ## Missed Message Delete Events *In other words, as a recipient, how do I know if someone deleted a message when my app was not running?* diff --git a/sdk/javascript/delivery-read-receipts.mdx b/sdk/javascript/delivery-read-receipts.mdx index 446e577fc..5eb7474be 100644 --- a/sdk/javascript/delivery-read-receipts.mdx +++ b/sdk/javascript/delivery-read-receipts.mdx @@ -767,6 +767,19 @@ You will receive events in the form of `MessageReceipt` objects. The message rec | `deliveredAt` | The timestamp of the time when the message was delivered. This will only be present if the receiptType is delivered. | | `readAt` | The timestamp of the time when the message was read. This will only be present when the receiptType is read. | +The listener callbacks receive a [`MessageReceipt`](/sdk/reference/auxiliary#messagereceipt) object. Access the data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| messageId | `getMessageId()` | `string` | ID of the message this receipt is for | +| sender | `getSender()` | `User` | User who triggered the receipt | +| receiptType | `getReceiptType()` | `string` | Type of receipt (`"delivery"` or `"read"`) | +| timestamp | `getTimestamp()` | `number` | Timestamp of the receipt event | +| deliveredAt | `getDeliveredAt()` | `number` | Timestamp when the message was delivered | +| readAt | `getReadAt()` | `number` | Timestamp when the message was read | + +The `markAsDelivered()` and `markAsRead()` methods are fire-and-forget — they do not return a `MessageReceipt` object. Use the listener callbacks above to receive delivery and read confirmations. + ### Missed Receipts You will receive message receipts when you load offline messages. While fetching messages in bulk, the message object will have two fields i.e. `deliveredAt` and `readAt` which hold the timestamp for the time the message was delivered and read respectively. Using these two variables, the delivery and read status for a message can be obtained. diff --git a/sdk/javascript/direct-call.mdx b/sdk/javascript/direct-call.mdx index a72004fb2..ee7538645 100644 --- a/sdk/javascript/direct-call.mdx +++ b/sdk/javascript/direct-call.mdx @@ -360,6 +360,16 @@ CometChatCalls.removeCallEventListener(listenerId); | `onCallSwitchedToVideo(event)` | Invoked when an audio call is upgraded to a video call. Contains `sessionId`, `initiator`, and `responder`. | | `onError(error)` | Invoked when an error occurs during the call session. | +The ringing flow methods (`initiateCall()`, `acceptCall()`, `rejectCall()`, `endCall()`) return [`Call`](/sdk/reference/messages#call) objects. Access the data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| sessionId | `getSessionId()` | `string` | Unique session ID for the call | +| callInitiator | `getCallInitiator()` | `User` | The user who initiated the call | +| callReceiver | `getCallReceiver()` | `User` \| `Group` | The user or group receiving the call | +| action | `getAction()` | `string` | Current call action/status | +| initiatedAt | `getInitiatedAt()` | `number` | Timestamp when the call was initiated | + ## End Call Session Ending a call session properly is essential to release media resources (camera, microphone, network connections) and update call state across all participants. The termination process differs based on whether you're using the Ringing flow or Session Only flow. diff --git a/sdk/javascript/edit-message.mdx b/sdk/javascript/edit-message.mdx index 6949d2812..ca502e46d 100644 --- a/sdk/javascript/edit-message.mdx +++ b/sdk/javascript/edit-message.mdx @@ -147,6 +147,16 @@ try { The object of the edited message will be returned in the `onSuccess()` callback method of the listener. The message object will contain the `editedAt` field set with the timestamp of the time the message was edited. This will help you identify if the message was edited while iterating through the list of messages. The `editedBy` field is also set to the UID of the user who edited the message. +The `editMessage()` method returns a [`BaseMessage`](/sdk/reference/messages#basemessage) object (or a subclass like [`TextMessage`](/sdk/reference/messages#textmessage)). Access the response data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| id | `getId()` | `number` | Unique message ID | +| text | `getText()` | `string` | Updated text content (TextMessage only) | +| sender | `getSender()` | [`User`](/sdk/reference/entities#user) | The user who sent the message | +| editedAt | `getEditedAt()` | `number` | Timestamp when the message was edited | +| editedBy | `getEditedBy()` | `string` | UID of the user who edited the message | + By default, CometChat allows certain roles to edit a message. | User Role | Conversation Type | Edit Capabilities | @@ -205,6 +215,15 @@ CometChat.removeMessageListener("UNIQUE_LISTENER_ID"); ``` +The `onMessageEdited` callback receives a [`BaseMessage`](/sdk/reference/messages#basemessage) object with the `editedAt` and `editedBy` fields set. Access the data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| id | `getId()` | `number` | Unique message ID | +| sender | `getSender()` | [`User`](/sdk/reference/entities#user) | The user who sent the message | +| editedAt | `getEditedAt()` | `number` | Timestamp when the message was edited | +| editedBy | `getEditedBy()` | `string` | UID of the user who edited the message | + ## Missed Message Edit Events *In other words, as a recipient, how do I know when someone edited their message when my app was not running?* diff --git a/sdk/javascript/flag-message.mdx b/sdk/javascript/flag-message.mdx index 486ed70fc..ab3bd4257 100644 --- a/sdk/javascript/flag-message.mdx +++ b/sdk/javascript/flag-message.mdx @@ -170,6 +170,15 @@ To flag a message, use the `flagMessage()` method with the message ID and a payl } ``` +The `flagMessage()` method flags a [`BaseMessage`](/sdk/reference/messages#basemessage) object for moderation. The flagged message can be identified using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| id | `getId()` | `number` | Unique message ID | +| sender | `getSender()` | [`User`](/sdk/reference/entities#user) | The user who sent the message | +| type | `getType()` | `string` | Message type (`text`, `image`, `custom`, etc.) | +| sentAt | `getSentAt()` | `number` | Timestamp when the message was sent | + ## Complete Example Here's a complete implementation showing how to build a report message flow: diff --git a/sdk/javascript/group-add-members.mdx b/sdk/javascript/group-add-members.mdx index 5ade863af..59394f930 100644 --- a/sdk/javascript/group-add-members.mdx +++ b/sdk/javascript/group-add-members.mdx @@ -80,6 +80,8 @@ CometChat.addMembersToGroup(GUID, membersList, []).then( It will return a Array which will contain the `UID` of the users and the value will either be `success` or an error message describing why the operation to add the user to the group. +The method returns a response object (map) where each key is a `UID` and the value is either `"success"` or an error message describing why the operation failed for that user. + ## Real-Time Group Member Added Events *In other words, as a member of a group, how do I know when someone is added to the group when my app is running?* diff --git a/sdk/javascript/group-change-member-scope.mdx b/sdk/javascript/group-change-member-scope.mdx index ac6617555..2730d7cc2 100644 --- a/sdk/javascript/group-change-member-scope.mdx +++ b/sdk/javascript/group-change-member-scope.mdx @@ -75,6 +75,8 @@ This method takes the below parameters: The default scope of any member is `participant`. Only the **Admin** of the group can change the scope of any participant in the group. +On success, the method resolves with a success message string confirming the operation. + ## Real-Time Group Member Scope Changed Events *In other words, as a member of a group, how do I know when someone's scope is changed when my app is running?* diff --git a/sdk/javascript/group-kick-ban-members.mdx b/sdk/javascript/group-kick-ban-members.mdx index 5528815a8..99c0d3ce4 100644 --- a/sdk/javascript/group-kick-ban-members.mdx +++ b/sdk/javascript/group-kick-ban-members.mdx @@ -84,6 +84,8 @@ The `kickGroupMember()` takes following parameters The kicked user will be no longer part of the group and can not perform any actions in the group, but the kicked user can rejoin the group. +On success, the method resolves with a success message string confirming the operation. + ## Ban a Group Member The Admin or Moderator of the group can ban a member from the group using the `banGroupMember()` method. @@ -132,6 +134,8 @@ The `banGroupMember()` method takes the following parameters: The banned user will be no longer part of the group and can not perform any actions in the group. A banned user cannot rejoin the same group without being unbanned. +On success, the method resolves with a success message string confirming the operation. + ## Unban a Banned Group Member from a Group Only Admin or Moderators of the group can unban a previously banned member from the group using the `unbanGroupMember()` method. diff --git a/sdk/javascript/interactive-messages.mdx b/sdk/javascript/interactive-messages.mdx index 99fefb199..a934cf2b9 100644 --- a/sdk/javascript/interactive-messages.mdx +++ b/sdk/javascript/interactive-messages.mdx @@ -166,6 +166,15 @@ CometChat.sendInteractiveMessage(interactiveMessage) +The `sendInteractiveMessage()` method returns an [`InteractiveMessage`](/sdk/reference/messages#interactivemessage) object. Access the response data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| interactiveData | `getInteractiveData()` | `Object` | The structured JSON data for the interactive element | +| interactionGoal | `getInteractionGoal()` | `InteractionGoal` | The intended outcome of interacting with the message | +| interactions | `getInteractions()` | `Interaction[]` | List of user interactions performed on the message | +| allowSenderInteraction | `getAllowSenderInteraction()` | `boolean` | Whether the sender can interact with the message | + ## Event Listeners CometChat SDK provides event listeners to handle real-time events related to `InteractiveMessage`. diff --git a/sdk/javascript/join-group.mdx b/sdk/javascript/join-group.mdx index 6c8e688eb..7a6ba0f11 100644 --- a/sdk/javascript/join-group.mdx +++ b/sdk/javascript/join-group.mdx @@ -80,6 +80,17 @@ CometChat keeps a track of the groups joined and you do not need to join the gro You can identify if a group is joined using the `hasJoined` parameter in the `Group` object. +The method returns a [`Group`](/sdk/reference/entities#group) object with `hasJoined` set to `true`. Access the response data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| guid | `getGuid()` | `string` | Unique group ID | +| name | `getName()` | `string` | Display name of the group | +| type | `getType()` | `string` | Group type (`"public"`, `"private"`, or `"password"`) | +| hasJoined | `getHasJoined()` | `boolean` | Whether the logged-in user has joined this group | +| scope | `getScope()` | `string` | Scope of the logged-in user in the group | +| membersCount | `getMembersCount()` | `number` | Total number of members in the group | + ## Real-time Group Member Joined Events *In other words, as a member of a group, how do I know if someone joins the group when my app is running?* diff --git a/sdk/javascript/leave-group.mdx b/sdk/javascript/leave-group.mdx index 7bcb9581a..a94d85675 100644 --- a/sdk/javascript/leave-group.mdx +++ b/sdk/javascript/leave-group.mdx @@ -67,6 +67,8 @@ CometChat.leaveGroup(GUID).then( Once a group is left, the user will no longer receive any updates or messages pertaining to the group. +On success, the method resolves with a success message string confirming the operation. + ## Real-time Group Member Left Events *In other words, as a member of a group, how do I know if someone has left it?* diff --git a/sdk/javascript/mentions.mdx b/sdk/javascript/mentions.mdx index a94cef3aa..5c3995e17 100644 --- a/sdk/javascript/mentions.mdx +++ b/sdk/javascript/mentions.mdx @@ -392,6 +392,13 @@ To retrieve the list of users mentioned in the particular message, you can use t message.getMentionedUsers() ``` +Messages containing mentions are returned as [`BaseMessage`](/sdk/reference/messages#basemessage) objects with mention-related fields populated. Access the mention data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| mentionedUsers | `getMentionedUsers()` | [`User[]`](/sdk/reference/entities#user) | Array of users mentioned in the message | +| hasMentionedMe | `hasMentionedMe()` | `boolean` | Whether the logged-in user is mentioned in the message | + - **Use correct format**: Always use `<@uid:UID>` format for mentions in message text - **Validate UIDs**: Ensure mentioned UIDs exist before sending diff --git a/sdk/javascript/reactions.mdx b/sdk/javascript/reactions.mdx index 7821dd0c3..3148fbf1f 100644 --- a/sdk/javascript/reactions.mdx +++ b/sdk/javascript/reactions.mdx @@ -113,6 +113,14 @@ CometChat.removeReaction(messageId, emoji) +Both `addReaction()` and `removeReaction()` return a [`BaseMessage`](/sdk/reference/messages#basemessage) object with the updated reactions. Access the reaction data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| id | `getId()` | `number` | Unique message ID | +| sender | `getSender()` | [`User`](/sdk/reference/entities#user) | The user who sent the message | +| reactions | `getReactions()` | [`ReactionCount[]`](/sdk/reference/auxiliary#reactioncount) | Array of reaction counts on the message | + ## Fetch Reactions for a Message To get all reactions for a specific message, first create a `ReactionRequest` using `ReactionRequestBuilder`. You can specify the number of reactions to fetch with setLimit with max limit 100. For this, you will require the ID of the message. This ID needs to be passed to the `setMessageId()` method of the builder class. The `setReaction()` will allow you to fetch details for specific reaction or emoji. @@ -267,6 +275,15 @@ CometChat.addMessageListener(listenerID, { +Each reaction listener callback receives a [`ReactionEvent`](/sdk/reference/auxiliary#reactionevent) object. Access the event data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| reaction | `getReaction()` | `string` | The emoji reaction that was added or removed | +| receiverId | `getReceiverId()` | `string` | UID or GUID of the receiver | +| receiverType | `getReceiverType()` | `string` | Type of receiver (`user` or `group`) | +| conversationId | `getConversationId()` | `string` | ID of the conversation | + ## Removing a Reaction Listener To stop listening for reaction events, remove the listener as follows: diff --git a/sdk/javascript/receive-message.mdx b/sdk/javascript/receive-message.mdx index 0b4d12f1b..aeb5e40de 100644 --- a/sdk/javascript/receive-message.mdx +++ b/sdk/javascript/receive-message.mdx @@ -130,6 +130,17 @@ As a sender, you will not receive your own message in a real-time message event. +Each listener callback receives the specific message subclass — [`TextMessage`](/sdk/reference/messages#textmessage), [`MediaMessage`](/sdk/reference/messages#mediamessage), or [`CustomMessage`](/sdk/reference/messages#custommessage) — depending on the message type. Access the data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| id | `getId()` | `number` | Unique message ID | +| sender | `getSender()` | [`User`](/sdk/reference/entities#user) | The user who sent the message | +| receiverId | `getReceiverId()` | `string` | UID or GUID of the receiver | +| type | `getType()` | `string` | Message type (`text`, `image`, `custom`, etc.) | +| sentAt | `getSentAt()` | `number` | Timestamp when the message was sent | +| text | `getText()` | `string` | Text content (TextMessage only) | + ## Missed Messages *In other words, as a recipient, how do I receive messages that I missed when my app was not running?* @@ -248,6 +259,16 @@ messagesRequest.fetchNext().then( +The `fetchNext()` method returns an array of [`BaseMessage`](/sdk/reference/messages#basemessage) objects (which may be [`TextMessage`](/sdk/reference/messages#textmessage), [`MediaMessage`](/sdk/reference/messages#mediamessage), or other subclasses). Access the data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| id | `getId()` | `number` | Unique message ID | +| sender | `getSender()` | [`User`](/sdk/reference/entities#user) | The user who sent the message | +| type | `getType()` | `string` | Message type (`text`, `image`, `custom`, etc.) | +| sentAt | `getSentAt()` | `number` | Timestamp when the message was sent | +| conversationId | `getConversationId()` | `string` | ID of the conversation the message belongs to | + ## Unread Messages *In other words, as a logged-in user, how do I fetch the messages I've not read?* @@ -466,6 +487,16 @@ messagesRequest.fetchPrevious().then( Calling the `fetchPrevious()` method on the same object repeatedly allows you to fetch the entire conversation for the group. This can be implemented with upward scrolling to display the entire conversation. +The `fetchPrevious()` method returns an array of [`BaseMessage`](/sdk/reference/messages#basemessage) objects (which may be [`TextMessage`](/sdk/reference/messages#textmessage), [`MediaMessage`](/sdk/reference/messages#mediamessage), or other subclasses). Access the data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| id | `getId()` | `number` | Unique message ID | +| sender | `getSender()` | [`User`](/sdk/reference/entities#user) | The user who sent the message | +| type | `getType()` | `string` | Message type (`text`, `image`, `custom`, etc.) | +| sentAt | `getSentAt()` | `number` | Timestamp when the message was sent | +| conversationId | `getConversationId()` | `string` | ID of the conversation the message belongs to | + ## Search Messages In other words, as a logged-in user, how do I search a message? diff --git a/sdk/javascript/retrieve-conversations.mdx b/sdk/javascript/retrieve-conversations.mdx index c31330ef3..737e5f88c 100644 --- a/sdk/javascript/retrieve-conversations.mdx +++ b/sdk/javascript/retrieve-conversations.mdx @@ -101,6 +101,11 @@ let limit: number = 30, + +The default value for `setLimit` is 30 and the max value is 50. + + +When conversations are fetched successfully, the response will include an array of `Conversation` objects filtered by the specified type. ### With User and Group Tags This method can be used to fetch the user/group tags in the `Conversation` Object. By default the value is `false`. @@ -130,6 +135,7 @@ let limit: number = 30, +When conversations are fetched successfully, the response will include `tags` arrays on the `conversationWith` objects (user or group). ### Set User Tags This method fetches user conversations that have the specified tags. @@ -161,6 +167,7 @@ let limit: number = 30, +When conversations are fetched successfully, the response will include only user conversations where the user has the specified tags. ### Set Group Tags This method fetches group conversations that have the specified tags. @@ -192,6 +199,7 @@ let limit: number = 30, +When conversations are fetched successfully, the response will include only group conversations where the group has the specified tags. ### With Tags This method makes sure that the tags associated with the conversations are returned along with the other details of the conversations. The default value for this parameter is `false` @@ -220,7 +228,6 @@ conversationRequest: CometChat.ConversationsRequest = new CometChat.Conversation - ### Set Tags This method helps you fetch the conversations based on the specified tags. @@ -251,7 +258,6 @@ let limit: number = 30, - ### Include Blocked Users This method helps you fetch the conversations of users whom the logged-in user has blocked. @@ -281,6 +287,7 @@ let limit: number = 30, +When conversations are fetched successfully, the response will include conversations with blocked users. To also get the blocked info details (`blockedByMe`, `blockedByMeAt`, `blockedAt`), set `withBlockedInfo` to `true` as well. ### With Blocked Info This method can be used to fetch the blocked information of the blocked user in the `ConversationWith` object. @@ -309,7 +316,6 @@ let limit: number = 30, - ### Search Conversations This method helps you search a conversation based on User or Group name. @@ -345,6 +351,7 @@ let limit: number = 30, +When conversations are fetched successfully, the response will include conversations where the user or group name matches the search keyword. ### Unread Conversations This method helps you fetch unread conversations. @@ -380,6 +387,7 @@ let limit: number = 30, +When conversations are fetched successfully, the response will include only conversations that have unread messages (where `unreadMessageCount` is greater than 0). ### Hide Agentic Conversations This method allows you to exclude agent conversations from the conversation list. When set to `true`, conversations with AI agents will be filtered out. @@ -408,7 +416,6 @@ let limit: number = 30, - ### Only Agentic Conversations This method allows you to fetch only agent conversations. When set to `true`, only conversations with AI agents will be returned in the list. @@ -444,6 +451,7 @@ The `setHideAgentic()` and `setOnlyAgentic()` methods are mutually exclusive. Yo +When conversations are fetched successfully, the response will include only conversations with AI agents. Agent users have `role: "@agentic"` and include agent-specific metadata. Finally, once all the parameters are set to the builder class, you need to call the `build()` method to get the object of the `ConversationsRequest` class. Once you have the object of the `ConversationsRequest` class, you need to call the `fetchNext()` method. Calling this method will return a list of `Conversation` objects containing X number of users depending on the limit set. @@ -500,6 +508,21 @@ The `Conversation` Object consists of the following fields: | lastMessage | Last message the conversation. | | conversationWith | User or Group object containing the details of the user or group. | | unreadMessageCount | Unread message count for the conversation. | +| unreadMentionsCount | Count of unread mentions in the conversation. | +| lastReadMessageId | ID of the last read message in the conversation. | +| latestMessageId | ID of the latest message in the conversation. | +| tags | Array of tags associated with the conversation (when using `withTags`). | + +The `fetchNext()` method returns an array of [`Conversation`](/sdk/reference/entities#conversation) objects. Access the response data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| conversationId | `getConversationId()` | `string` | Unique conversation ID | +| conversationType | `getConversationType()` | `string` | Type of conversation (`"user"` or `"group"`) | +| lastMessage | `getLastMessage()` | `BaseMessage` | The last message in the conversation | +| conversationWith | `getConversationWith()` | `User` \| `Group` | The user or group this conversation is with | +| unreadMessageCount | `getUnreadMessageCount()` | `number` | Number of unread messages | +| tags | `getTags()` | `string[]` | Tags associated with the conversation (when using `withTags`) | ## Tag Conversation @@ -559,6 +582,7 @@ The tags for conversations are one-way. This means that if user A tags a convers +When the conversation is tagged successfully, the response will return a single `Conversation` object (not an array) with the `tags` field included. ## Retrieve Single Conversation *In other words, as a logged-in user, how do I retrieve a specific conversation?* @@ -606,6 +630,18 @@ CometChat.getConversation(conversationWith, conversationType).then( +When the conversation is fetched successfully, the response will return a single `Conversation` object (not an array). +The `getConversation()` method returns a single [`Conversation`](/sdk/reference/entities#conversation) object. Access the response data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| conversationId | `getConversationId()` | `string` | Unique conversation ID | +| conversationType | `getConversationType()` | `string` | Type of conversation (`"user"` or `"group"`) | +| lastMessage | `getLastMessage()` | `BaseMessage` | The last message in the conversation | +| conversationWith | `getConversationWith()` | `User` \| `Group` | The user or group this conversation is with | +| unreadMessageCount | `getUnreadMessageCount()` | `number` | Number of unread messages | +| tags | `getTags()` | `string[]` | Tags associated with the conversation (when using `withTags`) | + ## Convert Messages to Conversations As per our [receive messages](/sdk/javascript/receive-message) guide, for real-time messages, you will always receive `Message` objects and not `Conversation` objects. Thus, you will need a mechanism to convert the Message object to the `Conversation` object. You can use the `getConversationFromMessage(BaseMessage message)` of the `CometChatHelper` class. @@ -646,7 +682,6 @@ CometChat.CometChatHelper.getConversationFromMessage(message).then( While converting the `Message` object to the `Conversation` object, the `unreadMessageCount` & `tags` will not be available in the `Conversation` object. The unread message count needs to be managed in your client-side code. - --- ## Next Steps diff --git a/sdk/javascript/retrieve-group-members.mdx b/sdk/javascript/retrieve-group-members.mdx index ea304c691..5eb5820f7 100644 --- a/sdk/javascript/retrieve-group-members.mdx +++ b/sdk/javascript/retrieve-group-members.mdx @@ -210,6 +210,16 @@ groupMembersRequest.fetchNext().then( +The `fetchNext()` method returns an array of [`GroupMember`](/sdk/reference/entities#groupmember) objects. `GroupMember` extends `User` and adds group-specific fields. Access the response data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| uid | `getUid()` | `string` | Unique user ID | +| name | `getName()` | `string` | Display name of the member | +| scope | `getScope()` | `string` | Scope in the group (`"admin"`, `"moderator"`, or `"participant"`) | +| joinedAt | `getJoinedAt()` | `number` | Timestamp when the member joined the group | +| guid | `getGuid()` | `string` | GUID of the group this member belongs to | + - **Paginate results** — Always use `fetchNext()` in a loop or on-scroll. Set a reasonable limit (10–30) per request to avoid large payloads. - **Reuse the request object** — Create the `GroupMembersRequest` once and call `fetchNext()` repeatedly. Creating a new builder each time resets pagination. diff --git a/sdk/javascript/retrieve-groups.mdx b/sdk/javascript/retrieve-groups.mdx index a3c2c03e0..1e74e2898 100644 --- a/sdk/javascript/retrieve-groups.mdx +++ b/sdk/javascript/retrieve-groups.mdx @@ -228,6 +228,17 @@ groupsRequest.fetchNext().then( +The `fetchNext()` method returns an array of [`Group`](/sdk/reference/entities#group) objects. Access the response data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| guid | `getGuid()` | `string` | Unique group ID | +| name | `getName()` | `string` | Display name of the group | +| type | `getType()` | `string` | Group type (`"public"`, `"private"`, or `"password"`) | +| membersCount | `getMembersCount()` | `number` | Total number of members in the group | +| owner | `getOwner()` | `string` | UID of the group owner | +| hasJoined | `getHasJoined()` | `boolean` | Whether the logged-in user has joined this group | + ## Retrieve Particular Group Details *In other words, as a logged-in user, how do I retrieve information for a specific group?* @@ -271,6 +282,17 @@ CometChat.getGroup(GUID).then( It returns `Group` object containing the details of the group. +The method returns a [`Group`](/sdk/reference/entities#group) object. Access the response data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| guid | `getGuid()` | `string` | Unique group ID | +| name | `getName()` | `string` | Display name of the group | +| type | `getType()` | `string` | Group type (`"public"`, `"private"`, or `"password"`) | +| membersCount | `getMembersCount()` | `number` | Total number of members in the group | +| owner | `getOwner()` | `string` | UID of the group owner | +| hasJoined | `getHasJoined()` | `boolean` | Whether the logged-in user has joined this group | + ## Get online group member count To get the total count of online users in particular groups, you can use the `getOnlineGroupMemberCount()` method. diff --git a/sdk/javascript/retrieve-users.mdx b/sdk/javascript/retrieve-users.mdx index cc07b4100..e3dcb9e3a 100644 --- a/sdk/javascript/retrieve-users.mdx +++ b/sdk/javascript/retrieve-users.mdx @@ -62,6 +62,17 @@ CometChat.getLoggedinUser().then( This method will return a `User` object containing all the information related to the logged-in user. +The method returns a [`User`](/sdk/reference/entities#user) object. Access the response data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| uid | `getUid()` | `string` | Unique user ID | +| name | `getName()` | `string` | Display name of the user | +| avatar | `getAvatar()` | `string` | URL of the user's avatar image | +| status | `getStatus()` | `string` | Online status of the user | +| lastActiveAt | `getLastActiveAt()` | `number` | Timestamp when the user was last active | +| role | `getRole()` | `string` | Role assigned to the user | + ## Retrieve List of Users In order to fetch the list of users, you can use the `UsersRequest` class. To use this class i.e to create an object of the `UsersRequest` class, you need to use the `UsersRequestBuilder` class. The `UsersRequestBuilder` class allows you to set the parameters based on which the users are to be fetched. @@ -481,6 +492,17 @@ usersRequest.fetchNext().then( +The `fetchNext()` method returns an array of [`User`](/sdk/reference/entities#user) objects. Access the response data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| uid | `getUid()` | `string` | Unique user ID | +| name | `getName()` | `string` | Display name of the user | +| avatar | `getAvatar()` | `string` | URL of the user's avatar image | +| status | `getStatus()` | `string` | Online status of the user | +| lastActiveAt | `getLastActiveAt()` | `number` | Timestamp when the user was last active | +| role | `getRole()` | `string` | Role assigned to the user | + ## Retrieve Particular User Details To get the information of a user, you can use the `getUser()` method. @@ -524,6 +546,17 @@ The `getUser()` method takes the following parameters: It returns the `User` object containing the details of the user. +The method returns a [`User`](/sdk/reference/entities#user) object. Access the response data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| uid | `getUid()` | `string` | Unique user ID | +| name | `getName()` | `string` | Display name of the user | +| avatar | `getAvatar()` | `string` | URL of the user's avatar image | +| status | `getStatus()` | `string` | Online status of the user | +| lastActiveAt | `getLastActiveAt()` | `number` | Timestamp when the user was last active | +| role | `getRole()` | `string` | Role assigned to the user | + ## Get online user count To get the total count of online users for your app, you can use the `getOnlineUserCount()` method. diff --git a/sdk/javascript/send-message.mdx b/sdk/javascript/send-message.mdx index fac28f6d2..9b0cf7af5 100644 --- a/sdk/javascript/send-message.mdx +++ b/sdk/javascript/send-message.mdx @@ -346,296 +346,6 @@ The `TextMessage` class constructor takes the following parameters: | **receiverType** | The type of the receiver - `CometChat.RECEIVER_TYPE.USER` or `CometChat.RECEIVER_TYPE.GROUP` | Required | When a text message is sent successfully, the response will include a `TextMessage` object which includes all information related to the sent message. - - -**On Success** — Returns a `TextMessage` object with metadata, tags, quoted message, and parent message ID if set: - - - -**TextMessage Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message ID | `"20004"` | -| `receiverId` | string | UID of the receiver | `"cometchat-uid-2"` | -| `type` | string | Message type | `"text"` | -| `receiverType` | string | Receiver type | `"user"` | -| `category` | string | Message category | `"message"` | -| `text` | string | The text content of the message | `"sent from explorer 2"` | -| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | -| `sender` | object | Sender user details | [See below ↓](#send-text-message-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#send-text-message-receiver-object) | -| `sentAt` | number | Timestamp when the message was sent (epoch) | `1772181842` | -| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1772181842` | -| `tags` | array | List of tags attached to the message | `["tag1"]` | -| `metadata` | object | Custom metadata attached to the message | `{"someKey": "someValue"}` | -| `parentMessageId` | string | ID of the parent message (for threaded messages) | `"20001"` | -| `quotedMessageId` | string | ID of the quoted message | `"16001"` | -| `quotedMessage` | object | The full quoted message object | [See below ↓](#send-text-message-quoted-message-object) | -| `data` | object | Additional message data including entities | [See below ↓](#send-text-message-data-object) | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"cometchat-uid-1"` | -| `name` | string | Display name | `"Andrew Joseph"` | -| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772179705` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"cometchat-uid-2"` | -| `name` | string | Display name | `"George Alan"` | -| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1770898112` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | The text content | `"sent from explorer 2"` | -| `metadata` | object | Custom metadata | `{"someKey": "someValue"}` | -| `resource` | string | SDK resource identifier | `"WEB-4_1_7-dd86d365-4843-41e4-b275-a020edadd82c-1771944198900"` | -| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#send-text-message-data-entities-object) | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#send-text-message-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#send-text-message-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entity` | object | The sender user entity | [See below ↓](#send-text-message-data-entities-sender-entity-object) | -| `entityType` | string | Type of entity | `"user"` | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"cometchat-uid-1"` | -| `name` | string | Display name | `"Andrew Joseph"` | -| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | -| `status` | string | Online status | `"offline"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772179705` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entity` | object | The receiver user entity | [See below ↓](#send-text-message-data-entities-receiver-entity-object) | -| `entityType` | string | Type of entity | `"user"` | - ---- - - - -**`data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"cometchat-uid-2"` | -| `name` | string | Display name | `"George Alan"` | -| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | Online status | `"offline"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1770898112` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | - ---- - - - -**`quotedMessage` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message ID of the quoted message | `"16001"` | -| `receiverId` | string | UID of the receiver | `"cometchat-uid-2"` | -| `type` | string | Message type | `"image"` | -| `receiverType` | string | Receiver type | `"user"` | -| `category` | string | Message category | `"message"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | -| `sender` | object | Sender of the quoted message | [See below ↓](#send-text-message-quoted-sender-object) | -| `receiver` | object | Receiver of the quoted message | [See below ↓](#send-text-message-quoted-receiver-object) | -| `sentAt` | number | Timestamp when the quoted message was sent (epoch) | `1771926928` | -| `updatedAt` | number | Timestamp when the quoted message was last updated (epoch) | `1771926928` | -| `data` | object | Additional data of the quoted message | [See below ↓](#send-text-message-quoted-data-object) | - ---- - - - -**`quotedMessage.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"cometchat-uid-1"` | -| `name` | string | Display name | `"Andrew Joseph"` | -| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1771926864` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`quotedMessage.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"cometchat-uid-2"` | -| `name` | string | Display name | `"George Alan"` | -| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1770898112` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`quotedMessage.data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `url` | string | Media file URL | `"https://files-us.cometchat-staging.com/..."` | -| `resource` | string | SDK resource identifier | `"WEB-4_1_6-a16c1881-ae5c-4ea2-9252-b70f08a50454-1770977997631"` | -| `attachments` | array | List of file attachments | [See below ↓](#send-text-message-quoted-data-attachments-array) | -| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#send-text-message-quoted-data-entities-object) | - ---- - - - -**`quotedMessage.data.attachments` Array (per item):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extension` | string | File extension | `"gif"` | -| `mimeType` | string | MIME type of the file | `"image/gif"` | -| `name` | string | File name | `"shivaji-the-boss-rajinikanth.gif"` | -| `size` | number | File size in bytes | `865027` | -| `url` | string | File download URL | `"https://files-us.cometchat-staging.com/..."` | - ---- - - - -**`quotedMessage.data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#send-text-message-quoted-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#send-text-message-quoted-data-entities-receiver-object) | - ---- - - - -**`quotedMessage.data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entity` | object | The sender user entity | [See below ↓](#send-text-message-quoted-data-entities-sender-entity-object) | -| `entityType` | string | Type of entity | `"user"` | - ---- - - - -**`quotedMessage.data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"cometchat-uid-1"` | -| `name` | string | Display name | `"Andrew Joseph"` | -| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | -| `status` | string | Online status | `"offline"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1771926864` | - ---- - - - -**`quotedMessage.data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entity` | object | The receiver user entity | [See below ↓](#send-text-message-quoted-data-entities-receiver-entity-object) | -| `entityType` | string | Type of entity | `"user"` | - ---- - - - -**`quotedMessage.data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"cometchat-uid-2"` | -| `name` | string | Display name | `"George Alan"` | -| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | Online status | `"offline"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1770898112` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | - - - ## Media Message *In other words, as a sender, how do I send a media message like photos, videos & files?* @@ -1151,376 +861,6 @@ CometChat.sendMediaMessage(mediaMessage).then( When a media message is sent successfully, the response will include a `MediaMessage` object which includes all information related to the sent message. - - -**On Success** — Returns a `MediaMessage` object with file attachment details, metadata, tags, caption, quoted message, and parent message ID if set: - - - -**MediaMessage Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message ID | `"125629"` | -| `receiverId` | string | UID of the receiver | `"superhero2"` | -| `type` | string | Message type | `"image"` | -| `receiverType` | string | Receiver type | `"user"` | -| `category` | string | Message category | `"message"` | -| `caption` | string | Caption text for the media message | `"this is a caption for the image"` | -| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | -| `sender` | object | Sender user details | [See below ↓](#send-media-file-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#send-media-file-receiver-object) | -| `sentAt` | number | Timestamp when the message was sent (epoch) | `1772693133` | -| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1772693133` | -| `tags` | array | List of tags attached to the message | `["tag1"]` | -| `metadata` | object | Custom metadata attached to the message | [See below ↓](#send-media-file-metadata-object) | -| `parentMessageId` | string | ID of the parent message (for threaded messages) | `"125334"` | -| `quotedMessageId` | string | ID of the quoted message | `"125623"` | -| `quotedMessage` | object | The full quoted message object | [See below ↓](#send-media-file-quoted-message-object) | -| `data` | object | Additional message data including attachments and entities | [See below ↓](#send-media-file-data-object) | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero1"` | -| `name` | string | Display name | `"Iron Man"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772693031` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"online"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero2"` | -| `name` | string | Display name | `"Captain America"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772450329` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `latitude` | string | Latitude coordinate | `"50.6192171633316"` | -| `longitude` | string | Longitude coordinate | `"-72.68182268750002"` | -| `@injected` | object | Server-injected extension data | [See below ↓](#send-media-file-metadata-injected-object) | - ---- - - - -**`metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extension data | [See below ↓](#send-media-file-metadata-injected-extensions-object) | - ---- - - - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "this is a caption for the image", ...}` | -| `link-preview` | object | Link preview extension results | `{"links": []}` | -| `thumbnail-generation` | object | Thumbnail generation extension results | [See below ↓](#send-media-file-thumbnail-generation-object) | - ---- - - - -**`metadata.@injected.extensions.thumbnail-generation` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `url_small` | string | Small thumbnail URL | `"https://data-us.cc-cluster-2.io/.../small.webp"` | -| `url_medium` | string | Medium thumbnail URL | `"https://data-us.cc-cluster-2.io/.../medium.webp"` | -| `url_large` | string | Large thumbnail URL | `"https://data-us.cc-cluster-2.io/.../large.webp"` | -| `attachments` | array | Thumbnail attachment details | [See below ↓](#send-media-file-thumbnail-attachments-array) | - ---- - - - -**`metadata.@injected.extensions.thumbnail-generation.attachments` Array (per item):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `data` | object | Thumbnail data | [See below ↓](#send-media-file-thumbnail-attachments-data-object) | -| `error` | null | Error if any | `null` | - ---- - - - -**`metadata.@injected.extensions.thumbnail-generation.attachments[].data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `name` | string | File name | `"dummy.webp"` | -| `extension` | string | File extension | `"webp"` | -| `url` | string | File URL | `"https://data-us.cometchat.io/.../dummy.webp"` | -| `mimeType` | string | MIME type | `"image/webp"` | -| `thumbnails` | object | Thumbnail URLs | [See below ↓](#send-media-file-thumbnail-attachments-data-thumbnails-object) | - ---- - - - -**`metadata.@injected.extensions.thumbnail-generation.attachments[].data.thumbnails` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `url_small` | string | Small thumbnail URL | `"https://data-us.cc-cluster-2.io/.../small.webp"` | -| `url_medium` | string | Medium thumbnail URL | `"https://data-us.cc-cluster-2.io/.../medium.webp"` | -| `url_large` | string | Large thumbnail URL | `"https://data-us.cc-cluster-2.io/.../large.webp"` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Caption text | `"this is a caption for the image"` | -| `metadata` | object | Custom metadata | [See above ↑](#send-media-file-metadata-object) | -| `resource` | string | SDK resource identifier | `"WEB-4_1_8-36a59fde-..."` | -| `url` | string | Uploaded file URL | `"https://data-us.cometchat.io/.../dummy.webp"` | -| `attachments` | array | List of file attachments | [See below ↓](#send-media-file-data-attachments-array) | -| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#send-media-file-data-entities-object) | -| `moderation` | object | Moderation status | `{"status": "pending"}` | - ---- - - - -**`data.attachments` Array (per item):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `name` | string | File name | `"dummy.webp"` | -| `extension` | string | File extension | `"webp"` | -| `size` | number | File size in bytes | `19554` | -| `mimeType` | string | MIME type of the file | `"image/webp"` | -| `url` | string | File download URL | `"https://data-us.cometchat.io/.../dummy.webp"` | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#send-media-file-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#send-media-file-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entity` | object | The sender user entity | [See below ↓](#send-media-file-data-entities-sender-entity-object) | -| `entityType` | string | Type of entity | `"user"` | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero1"` | -| `name` | string | Display name | `"Iron Man"` | -| `status` | string | Online status | `"online"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772693031` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entity` | object | The receiver user entity | [See below ↓](#send-media-file-data-entities-receiver-entity-object) | -| `entityType` | string | Type of entity | `"user"` | - ---- - - - -**`data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero2"` | -| `name` | string | Display name | `"Captain America"` | -| `status` | string | Online status | `"offline"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772450329` | -| `conversationId` | string | Conversation identifier | `"superhero1_user_superhero2"` | - ---- - - - -**`quotedMessage` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message ID of the quoted message | `"125623"` | -| `receiverId` | string | UID of the receiver | `"cometchat-uid-1"` | -| `type` | string | Message type | `"text"` | -| `receiverType` | string | Receiver type | `"user"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Text content of the quoted message | `"Hello"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-1_user_superhero1"` | -| `sender` | object | Sender of the quoted message | [See below ↓](#send-media-file-quoted-sender-object) | -| `receiver` | object | Receiver of the quoted message | [See below ↓](#send-media-file-quoted-receiver-object) | -| `sentAt` | number | Timestamp when the quoted message was sent (epoch) | `1772692447` | -| `updatedAt` | number | Timestamp when the quoted message was last updated (epoch) | `1772692447` | -| `data` | object | Additional data of the quoted message | [See below ↓](#send-media-file-quoted-data-object) | - ---- - - - -**`quotedMessage.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero1"` | -| `name` | string | Display name | `"Iron Man"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772692439` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"online"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`quotedMessage.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"cometchat-uid-1"` | -| `name` | string | Display name | `"cometchat-uid-1"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772630028` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`quotedMessage.data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Text content | `"Hello"` | -| `resource` | string | SDK resource identifier | `"WEB-4_1_5-2af689b1-..."` | -| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#send-media-file-quoted-data-entities-object) | -| `moderation` | object | Moderation status | `{"status": "approved"}` | - ---- - - - -**`quotedMessage.data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#send-media-file-quoted-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#send-media-file-quoted-data-entities-receiver-object) | - ---- - - - -**`quotedMessage.data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entity` | object | The sender user entity | [See below ↓](#send-media-file-quoted-data-entities-sender-entity-object) | -| `entityType` | string | Type of entity | `"user"` | - ---- - - - -**`quotedMessage.data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero1"` | -| `name` | string | Display name | `"Iron Man"` | -| `status` | string | Online status | `"online"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772692439` | - ---- - - - -**`quotedMessage.data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entity` | object | The receiver user entity | [See below ↓](#send-media-file-quoted-data-entities-receiver-entity-object) | -| `entityType` | string | Type of entity | `"user"` | - ---- - - - -**`quotedMessage.data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"cometchat-uid-1"` | -| `name` | string | Display name | `"cometchat-uid-1"` | -| `status` | string | Online status | `"offline"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772630028` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-1_user_superhero1"` | - - - ## Multiple Attachments in a Media Message Starting version 3.0.9 & above the SDK supports sending multiple attachments in a single media message. As in the case of a single attachment in a media message, there are two ways you can send Media Messages using the CometChat SDK: @@ -1842,377 +1182,6 @@ CometChat.sendMediaMessage(mediaMessage).then( When a media message is sent successfully, the response will include a `MediaMessage` object which includes all information related to the sent message. You can use the `setMetadata()`, `setCaption()` & `setTags()` methods to add metadata, caption and tags respectively in exactly the same way as it is done while sending a single file or attachment in a Media Message. - - -**On Success** — Returns a `MediaMessage` object with multiple file attachments, metadata, tags, caption, quoted message, and parent message ID if set: - - - -**MediaMessage Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message ID | `"125632"` | -| `receiverId` | string | UID of the receiver | `"superhero2"` | -| `type` | string | Message type | `"image"` | -| `receiverType` | string | Receiver type | `"user"` | -| `category` | string | Message category | `"message"` | -| `caption` | string | Caption text for the media message | `"this is a caption for multi attachments media message"` | -| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | -| `sender` | object | Sender user details | [See below ↓](#send-media-urls-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#send-media-urls-receiver-object) | -| `sentAt` | number | Timestamp when the message was sent (epoch) | `1772696147` | -| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1772696147` | -| `tags` | array | List of tags attached to the message | `["tag1"]` | -| `metadata` | object | Custom metadata attached to the message | [See below ↓](#send-media-urls-metadata-object) | -| `parentMessageId` | string | ID of the parent message (for threaded messages) | `"125332"` | -| `quotedMessageId` | string | ID of the quoted message | `"125625"` | -| `quotedMessage` | object | The full quoted message object | [See below ↓](#send-media-urls-quoted-message-object) | -| `data` | object | Additional message data including attachments and entities | [See below ↓](#send-media-urls-data-object) | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero1"` | -| `name` | string | Display name | `"Iron Man"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772696124` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero2"` | -| `name` | string | Display name | `"Captain America"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772450329` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `latitude` | string | Latitude coordinate | `"50.6192171633316"` | -| `longitude` | string | Longitude coordinate | `"-72.68182268750002"` | -| `@injected` | object | Server-injected extension data | [See below ↓](#send-media-urls-metadata-injected-object) | - ---- - - - -**`metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extension data | [See below ↓](#send-media-urls-metadata-injected-extensions-object) | - ---- - - - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "this is a caption for multi attachments media message", ...}` | -| `link-preview` | object | Link preview extension results | `{"links": []}` | -| `thumbnail-generation` | object | Thumbnail generation extension results | [See below ↓](#send-media-urls-thumbnail-generation-object) | - ---- - - - -**`metadata.@injected.extensions.thumbnail-generation` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `url_small` | string | Small thumbnail URL | `"https://data-us.cc-cluster-2.io/.../small.png"` | -| `url_medium` | string | Medium thumbnail URL | `"https://data-us.cc-cluster-2.io/.../medium.png"` | -| `url_large` | string | Large thumbnail URL | `"https://data-us.cc-cluster-2.io/.../large.png"` | -| `attachments` | array | Thumbnail attachment details per file | [See below ↓](#send-media-urls-thumbnail-attachments-array) | - ---- - - - -**`metadata.@injected.extensions.thumbnail-generation.attachments` Array (per item):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `data` | object | Thumbnail data | [See below ↓](#send-media-urls-thumbnail-attachments-data-object) | -| `error` | null | Error if any | `null` | - ---- - - - -**`metadata.@injected.extensions.thumbnail-generation.attachments[].data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `name` | string | File name | `"mario"` | -| `extension` | string | File extension | `"png"` | -| `url` | string | File URL | `"https://pngimg.com/uploads/mario/mario_PNG125.png"` | -| `mimeType` | string | MIME type | `"image/png"` | -| `thumbnails` | object | Thumbnail URLs | [See below ↓](#send-media-urls-thumbnail-attachments-data-thumbnails-object) | - ---- - - - -**`metadata.@injected.extensions.thumbnail-generation.attachments[].data.thumbnails` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `url_small` | string | Small thumbnail URL | `"https://data-us.cc-cluster-2.io/.../small.png"` | -| `url_medium` | string | Medium thumbnail URL | `"https://data-us.cc-cluster-2.io/.../medium.png"` | -| `url_large` | string | Large thumbnail URL | `"https://data-us.cc-cluster-2.io/.../large.png"` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `url` | string | Primary file URL (empty for multi-attachment) | `""` | -| `text` | string | Caption text | `"this is a caption for multi attachments media message"` | -| `metadata` | object | Custom metadata | [See above ↑](#send-media-urls-metadata-object) | -| `resource` | string | SDK resource identifier | `"WEB-4_1_8-36a59fde-..."` | -| `attachments` | array | List of file attachments | [See below ↓](#send-media-urls-data-attachments-array) | -| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#send-media-urls-data-entities-object) | -| `moderation` | object | Moderation status | `{"status": "pending"}` | - ---- - - - -**`data.attachments` Array (per item):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `name` | string | File name | `"mario"` | -| `extension` | string | File extension | `"png"` | -| `mimeType` | string | MIME type of the file | `"image/png"` | -| `url` | string | File download URL | `"https://pngimg.com/uploads/mario/mario_PNG125.png"` | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#send-media-urls-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#send-media-urls-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entity` | object | The sender user entity | [See below ↓](#send-media-urls-data-entities-sender-entity-object) | -| `entityType` | string | Type of entity | `"user"` | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero1"` | -| `name` | string | Display name | `"Iron Man"` | -| `status` | string | Online status | `"offline"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772696124` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entity` | object | The receiver user entity | [See below ↓](#send-media-urls-data-entities-receiver-entity-object) | -| `entityType` | string | Type of entity | `"user"` | - ---- - - - -**`data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero2"` | -| `name` | string | Display name | `"Captain America"` | -| `status` | string | Online status | `"offline"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772450329` | -| `conversationId` | string | Conversation identifier | `"superhero1_user_superhero2"` | - ---- - - - -**`quotedMessage` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message ID of the quoted message | `"125625"` | -| `receiverId` | string | UID of the receiver | `"fb421b69-f259-4418-b287-1f3fd7a1af2d"` | -| `type` | string | Message type | `"text"` | -| `receiverType` | string | Receiver type | `"user"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Text content of the quoted message | `"send this again to me, i want to test my code"` | -| `conversationId` | string | Conversation identifier | `"fb421b69-f259-4418-b287-1f3fd7a1af2d_user_superhero1"` | -| `sender` | object | Sender of the quoted message | [See below ↓](#send-media-urls-quoted-sender-object) | -| `receiver` | object | Receiver of the quoted message | [See below ↓](#send-media-urls-quoted-receiver-object) | -| `sentAt` | number | Timestamp when the quoted message was sent (epoch) | `1772692502` | -| `readAt` | number | Timestamp when the quoted message was read (epoch) | `1772692502` | -| `updatedAt` | number | Timestamp when the quoted message was last updated (epoch) | `1772692518` | -| `replyCount` | number | Number of replies to this message | `1` | -| `data` | object | Additional data of the quoted message | [See below ↓](#send-media-urls-quoted-data-object) | - ---- - - - -**`quotedMessage.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero1"` | -| `name` | string | Display name | `"Iron Man"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772692497` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"online"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`quotedMessage.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"fb421b69-f259-4418-b287-1f3fd7a1af2d"` | -| `name` | string | Display name | `"test agent"` | -| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/ai-agents/default-agent-profile-picture.png"` | -| `role` | string | User role | `"@agentic"` | -| `status` | string | Online status | `"online"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`quotedMessage.data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Text content | `"send this again to me, i want to test my code"` | -| `resource` | string | SDK resource identifier | `"WEB-4_1_5-2af689b1-..."` | -| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#send-media-urls-quoted-data-entities-object) | -| `moderation` | object | Moderation status | `{"status": "approved"}` | - ---- - - - -**`quotedMessage.data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#send-media-urls-quoted-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#send-media-urls-quoted-data-entities-receiver-object) | - ---- - - - -**`quotedMessage.data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entity` | object | The sender user entity | [See below ↓](#send-media-urls-quoted-data-entities-sender-entity-object) | -| `entityType` | string | Type of entity | `"user"` | - ---- - - - -**`quotedMessage.data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero1"` | -| `name` | string | Display name | `"Iron Man"` | -| `status` | string | Online status | `"online"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772692497` | - ---- - - - -**`quotedMessage.data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entity` | object | The receiver user entity | [See below ↓](#send-media-urls-quoted-data-entities-receiver-entity-object) | -| `entityType` | string | Type of entity | `"user"` | - ---- - - - -**`quotedMessage.data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"fb421b69-f259-4418-b287-1f3fd7a1af2d"` | -| `name` | string | Display name | `"test agent"` | -| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/ai-agents/default-agent-profile-picture.png"` | -| `status` | string | Online status | `"available"` | -| `role` | string | User role | `"@agentic"` | -| `conversationId` | string | Conversation identifier | `"fb421b69-f259-4418-b287-1f3fd7a1af2d_user_superhero1"` | - - - ## Custom Message *In other words, as a sender, how do I send a custom message like location coordinates?* @@ -2796,312 +1765,6 @@ CometChat.sendCustomMessage(customMessage).then( When a custom message is sent successfully, the response will include a `CustomMessage` object which includes all information related to the sent message. - - -**On Success** — Returns a `CustomMessage` object with custom type, custom data, metadata, tags, subtype, quoted message, and parent message ID if set: - - - -**CustomMessage Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message ID | `"125633"` | -| `receiverId` | string | UID of the receiver | `"superhero2"` | -| `type` | string | Custom message type | `"custom_type"` | -| `receiverType` | string | Receiver type | `"user"` | -| `category` | string | Message category | `"custom"` | -| `subType` | string | Message subtype | `"subtype"` | -| `customData` | object | Custom data payload | `{"customField": "customValue"}` | -| `conversationId` | string | Unique conversation identifier | `"superhero1_user_superhero2"` | -| `sender` | object | Sender user details | [See below ↓](#send-custom-message-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#send-custom-message-receiver-object) | -| `sentAt` | number | Timestamp when the message was sent (epoch) | `1772697015` | -| `updatedAt` | number | Timestamp when the message was last updated (epoch) | `1772697015` | -| `tags` | array | List of tags attached to the message | `["tag1"]` | -| `metadata` | object | Custom metadata attached to the message | [See below ↓](#send-custom-message-metadata-object) | -| `parentMessageId` | string | ID of the parent message (for threaded messages) | `"125334"` | -| `quotedMessageId` | string | ID of the quoted message | `"125627"` | -| `quotedMessage` | object | The full quoted message object | [See below ↓](#send-custom-message-quoted-message-object) | -| `data` | object | Additional message data including entities | [See below ↓](#send-custom-message-data-object) | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero1"` | -| `name` | string | Display name | `"Iron Man"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772696930` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"online"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero2"` | -| `name` | string | Display name | `"Captain America"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772450329` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `metaDataField` | string | Custom metadata field | `"value"` | -| `@injected` | object | Server-injected extension data | [See below ↓](#send-custom-message-metadata-injected-object) | - ---- - - - -**`metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extension data | [See below ↓](#send-custom-message-metadata-injected-extensions-object) | - ---- - - - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `data-masking` | object | Data masking extension results | `{"sensitive_data": "no", "message_masked": "Custom notification body", ...}` | -| `link-preview` | object | Link preview extension results | `{"links": []}` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `customData` | object | Custom data payload | `{"customField": "customValue"}` | -| `metadata` | object | Metadata with extension data | [See above ↑](#send-custom-message-metadata-object) | -| `text` | string | Conversation notification text | `"Custom notification body"` | -| `subType` | string | Message subtype | `"subtype"` | -| `resource` | string | SDK resource identifier | `"WEB-4_1_8-36a59fde-..."` | -| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#send-custom-message-data-entities-object) | -| `moderation` | object | Moderation status | `{"status": "pending"}` | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#send-custom-message-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#send-custom-message-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entity` | object | The sender user entity | [See below ↓](#send-custom-message-data-entities-sender-entity-object) | -| `entityType` | string | Type of entity | `"user"` | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero1"` | -| `name` | string | Display name | `"Iron Man"` | -| `status` | string | Online status | `"online"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772696930` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entity` | object | The receiver user entity | [See below ↓](#send-custom-message-data-entities-receiver-entity-object) | -| `entityType` | string | Type of entity | `"user"` | - ---- - - - -**`data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero2"` | -| `name` | string | Display name | `"Captain America"` | -| `status` | string | Online status | `"offline"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772450329` | -| `conversationId` | string | Conversation identifier | `"superhero1_user_superhero2"` | - ---- - - - -**`quotedMessage` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message ID of the quoted message | `"125627"` | -| `receiverId` | string | UID of the receiver | `"superhero2"` | -| `type` | string | Message type | `"text"` | -| `receiverType` | string | Receiver type | `"user"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Text content of the quoted message | `"hello"` | -| `conversationId` | string | Conversation identifier | `"superhero1_user_superhero2"` | -| `sender` | object | Sender of the quoted message | [See below ↓](#send-custom-message-quoted-sender-object) | -| `receiver` | object | Receiver of the quoted message | [See below ↓](#send-custom-message-quoted-receiver-object) | -| `sentAt` | number | Timestamp when the quoted message was sent (epoch) | `1772693110` | -| `updatedAt` | number | Timestamp when the quoted message was last updated (epoch) | `1772693110` | -| `parentMessageId` | string | Parent message ID of the quoted message | `"125334"` | -| `data` | object | Additional data of the quoted message | [See below ↓](#send-custom-message-quoted-data-object) | - ---- - - - -**`quotedMessage.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero1"` | -| `name` | string | Display name | `"Iron Man"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772693031` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"online"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`quotedMessage.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero2"` | -| `name` | string | Display name | `"Captain America"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772450329` | -| `role` | string | User role | `"default"` | -| `status` | string | Online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`quotedMessage.data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Text content | `"hello"` | -| `resource` | string | SDK resource identifier | `"WEB-4_1_8-c214150f-..."` | -| `entities` | object | Sender and receiver entity wrappers | [See below ↓](#send-custom-message-quoted-data-entities-object) | -| `moderation` | object | Moderation status | `{"status": "approved"}` | - ---- - - - -**`quotedMessage.data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#send-custom-message-quoted-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#send-custom-message-quoted-data-entities-receiver-object) | - ---- - - - -**`quotedMessage.data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entity` | object | The sender user entity | [See below ↓](#send-custom-message-quoted-data-entities-sender-entity-object) | -| `entityType` | string | Type of entity | `"user"` | - ---- - - - -**`quotedMessage.data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero1"` | -| `name` | string | Display name | `"Iron Man"` | -| `status` | string | Online status | `"online"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772693031` | - ---- - - - -**`quotedMessage.data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entity` | object | The receiver user entity | [See below ↓](#send-custom-message-quoted-data-entities-receiver-entity-object) | -| `entityType` | string | Type of entity | `"user"` | - ---- - - - -**`quotedMessage.data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user ID | `"superhero2"` | -| `name` | string | Display name | `"Captain America"` | -| `status` | string | Online status | `"offline"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Last active timestamp (epoch) | `1772450329` | -| `conversationId` | string | Conversation identifier | `"superhero1_user_superhero2"` | - - - It is also possible to send interactive messages from CometChat, to know more [click here](/sdk/javascript/interactive-messages) diff --git a/sdk/javascript/setup-sdk.mdx b/sdk/javascript/setup-sdk.mdx index c6a0a5943..342b8f4b3 100644 --- a/sdk/javascript/setup-sdk.mdx +++ b/sdk/javascript/setup-sdk.mdx @@ -200,6 +200,18 @@ Make sure you replace the `APP_ID` with your CometChat **App ID** and `APP_REGIO **Server-Side Rendering (SSR):** CometChat SDK requires browser APIs (`window`, `WebSocket`). For Next.js, Nuxt, or other SSR frameworks, initialize the SDK only on the client side using dynamic imports or `useEffect`. See the [Overview page](/sdk/javascript/overview#server-side-rendering-ssr-compatibility) for framework-specific examples. +After initialization, `CometChat.login()` returns a [`User`](/sdk/reference/entities#user) object representing the logged-in user. Access the response data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| uid | `getUid()` | `string` | Unique user ID | +| name | `getName()` | `string` | Display name of the user | +| avatar | `getAvatar()` | `string` | URL of the user's avatar | +| authToken | `getAuthToken()` | `string` | Auth token for the session | +| status | `getStatus()` | `string` | Online status (`"online"` or `"offline"`) | + +See the [Authentication](/sdk/javascript/authentication-overview) page for full login details. + ## Best Practices diff --git a/sdk/javascript/threaded-messages.mdx b/sdk/javascript/threaded-messages.mdx index 082357782..0fee3d530 100644 --- a/sdk/javascript/threaded-messages.mdx +++ b/sdk/javascript/threaded-messages.mdx @@ -207,6 +207,17 @@ messagesRequest.fetchPrevious().then( +The `fetchPrevious()` method returns an array of [`BaseMessage`](/sdk/reference/messages#basemessage) objects representing thread replies. Access the data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| id | `getId()` | `number` | Unique message ID | +| sender | `getSender()` | [`User`](/sdk/reference/entities#user) | The user who sent the message | +| type | `getType()` | `string` | Message type (`text`, `image`, `custom`, etc.) | +| sentAt | `getSentAt()` | `number` | Timestamp when the message was sent | +| parentMessageId | `getParentMessageId()` | `number` | ID of the parent message this reply belongs to | +| replyCount | `getReplyCount()` | `number` | Number of replies on the parent message | + ## Avoid Threaded Messages in User/Group Conversations While fetching messages for normal user/group conversations using the `MessagesRequest`, the threaded messages by default will be a part of the list of messages received. In order to exclude the threaded messages from the list of user/group messages, you need to use the `hideReplies()` method of the `MessagesRequestBuilder` class. This method takes a boolean argument which when set to true excludes the messages belonging to threads from the list of messages. diff --git a/sdk/javascript/transfer-group-ownership.mdx b/sdk/javascript/transfer-group-ownership.mdx index 32db039a4..871a2ab0d 100644 --- a/sdk/javascript/transfer-group-ownership.mdx +++ b/sdk/javascript/transfer-group-ownership.mdx @@ -58,6 +58,8 @@ CometChat.transferGroupOwnership(GUID, UID).then( +On success, the method resolves with a success message string confirming the operation. + - **Transfer before leaving** — The owner cannot leave a group without first transferring ownership. Always call `transferGroupOwnership()` before `leaveGroup()`. - **Choose a trusted member** — Transfer ownership to an active admin or moderator who can manage the group responsibly. diff --git a/sdk/javascript/transient-messages.mdx b/sdk/javascript/transient-messages.mdx index d6bda9cb3..e326eff37 100644 --- a/sdk/javascript/transient-messages.mdx +++ b/sdk/javascript/transient-messages.mdx @@ -134,6 +134,15 @@ The `TransientMessage` class consists of the below parameters: | **receiverType** | The type of the receiver - `CometChat.RECEIVER_TYPE.USER` or `CometChat.RECEIVER_TYPE.GROUP` | | **data** | A JSONObject to provide data. | +The listener callback receives a [`TransientMessage`](/sdk/reference/auxiliary#transientmessage) object. Access the data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| sender | `getSender()` | [`User`](/sdk/reference/entities#user) | The user who sent the transient message | +| receiverId | `getReceiverId()` | `string` | UID or GUID of the receiver | +| receiverType | `getReceiverType()` | `string` | Type of receiver (`user` or `group`) | +| data | `getData()` | `Object` | Custom JSON data payload | + --- ## Next Steps diff --git a/sdk/javascript/typing-indicators.mdx b/sdk/javascript/typing-indicators.mdx index c7296e704..04ead8e2a 100644 --- a/sdk/javascript/typing-indicators.mdx +++ b/sdk/javascript/typing-indicators.mdx @@ -199,6 +199,15 @@ The `TypingIndicator` class consists of the below parameters: | **receiverType** | This parameter indicates if the typing indicator is to be sent to a user or a group. The possible values are: 1. `CometChat.RECEIVER_TYPE.USER` 2. `CometChat.RECEIVER_TYPE.GROUP` | | **metadata** | A JSONObject to provider additional data. | +The `onTypingStarted` and `onTypingEnded` listener callbacks receive a [`TypingIndicator`](/sdk/reference/auxiliary#typingindicator) object. Access the data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| receiverId | `getReceiverId()` | `string` | UID or GUID of the typing indicator recipient | +| receiverType | `getReceiverType()` | `string` | Type of receiver (`"user"` or `"group"`) | +| sender | `getSender()` | `User` | The user who is typing | +| metadata | `getMetadata()` | `Object` | Additional custom data sent with the indicator | + - **Debounce typing events**: Don't call `startTyping()` on every keystroke - debounce to ~300ms intervals - **Auto-stop typing**: Call `endTyping()` after a period of inactivity (e.g., 3-5 seconds) diff --git a/sdk/javascript/update-group.mdx b/sdk/javascript/update-group.mdx index 6e2b791ef..aa9aaf5f0 100644 --- a/sdk/javascript/update-group.mdx +++ b/sdk/javascript/update-group.mdx @@ -71,6 +71,18 @@ This method takes an instance of the `Group` class as a parameter which should c After a successful update of the group, you will receive an instance of `Group` class containing update information of the group. +The method returns a [`Group`](/sdk/reference/entities#group) object. Access the response data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| guid | `getGuid()` | `string` | Unique group ID | +| name | `getName()` | `string` | Display name of the group | +| type | `getType()` | `string` | Group type (`"public"`, `"private"`, or `"password"`) | +| description | `getDescription()` | `string` | Description of the group | +| icon | `getIcon()` | `string` | URL of the group icon | +| owner | `getOwner()` | `string` | UID of the group owner | +| updatedAt | `getUpdatedAt()` | `number` | Timestamp when the group was last updated | + For more information on the `Group` class, please check [here](/sdk/javascript/create-group#create-a-group). --- diff --git a/sdk/javascript/user-management.mdx b/sdk/javascript/user-management.mdx index 440592067..b7d4d0809 100644 --- a/sdk/javascript/user-management.mdx +++ b/sdk/javascript/user-management.mdx @@ -93,6 +93,16 @@ CometChat.createUser(user, authKey).then( +The method returns a [`User`](/sdk/reference/entities#user) object. Access the response data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| uid | `getUid()` | `string` | Unique user ID | +| name | `getName()` | `string` | Display name of the user | +| avatar | `getAvatar()` | `string` | URL of the user's avatar image | +| role | `getRole()` | `string` | Role assigned to the user | +| status | `getStatus()` | `string` | Online status of the user | + UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. @@ -146,6 +156,16 @@ CometChat.updateUser(user, authKey).then( Please make sure the `User` object provided to the `updateUser()` method has the `UID` of the user to be updated set. +The method returns a [`User`](/sdk/reference/entities#user) object. Access the response data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| uid | `getUid()` | `string` | Unique user ID | +| name | `getName()` | `string` | Display name of the user | +| avatar | `getAvatar()` | `string` | URL of the user's avatar image | +| role | `getRole()` | `string` | Role assigned to the user | +| metadata | `getMetadata()` | `Object` | Custom metadata attached to the user | + ## Updating logged-in user Updating a logged-in user is similar to updating a user. The only difference being this method does not require an AuthKey. This method takes a `User` object as input and returns the updated `User` object on the successful execution of the request. diff --git a/sdk/javascript/user-presence.mdx b/sdk/javascript/user-presence.mdx index 31d1665d7..807a92862 100644 --- a/sdk/javascript/user-presence.mdx +++ b/sdk/javascript/user-presence.mdx @@ -96,6 +96,15 @@ CometChat.addUserListener( You will receive an object of the `User` class in the listener methods. +The listener callbacks provide a [`User`](/sdk/reference/entities#user) object with presence fields populated. Access the response data using getter methods: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| uid | `getUid()` | `string` | Unique user ID | +| name | `getName()` | `string` | Display name of the user | +| status | `getStatus()` | `string` | Online status of the user (`"online"` or `"offline"`) | +| lastActiveAt | `getLastActiveAt()` | `number` | Timestamp when the user was last active | + **Listener Cleanup:** Always remove the listener when the component or view is unmounted/destroyed to prevent memory leaks and duplicate callbacks. Use `CometChat.removeUserListener(listenerID)` in your cleanup logic. diff --git a/sdk/reference/auxiliary.mdx b/sdk/reference/auxiliary.mdx new file mode 100644 index 000000000..8bf7179f6 --- /dev/null +++ b/sdk/reference/auxiliary.mdx @@ -0,0 +1,103 @@ +--- +title: "Auxiliary" +description: "Class reference for auxiliary objects returned by CometChat SDK methods. Covers MessageReceipt, ReactionCount, ReactionEvent, TypingIndicator, TransientMessage, and Attachment." +--- + +This page documents the auxiliary classes used across all CometChat SDKs. These objects are returned by listener callbacks and specific SDK methods. + +All properties are accessed via getter methods. + +--- + +## MessageReceipt + +`MessageReceipt` represents a delivery or read receipt for a message. It is received via the `onMessagesDelivered` and `onMessagesRead` listener callbacks. + +### Properties + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| messageId | `getMessageId()` | `string` | ID of the message this receipt is for | +| sender | `getSender()` | `User` | The user who triggered the receipt | +| receiver | `getReceiver()` | `string` | UID or GUID of the receiver | +| receiverType | `getReceiverType()` | `string` | Receiver type (`"user"` or `"group"`) | +| receiptType | `getReceiptType()` | `string` | Type of receipt (`"read"`, `"delivery"`, `"readByAll"`, or `"deliveredToAll"`) | +| timestamp | `getTimestamp()` | `string` | Timestamp of the receipt | +| readAt | `getReadAt()` | `number` | Timestamp when the message was read (epoch seconds) | +| deliveredAt | `getDeliveredAt()` | `number` | Timestamp when the message was delivered (epoch seconds) | + +--- + +## ReactionCount + +`ReactionCount` represents the count of a specific reaction on a message. It is available via `getReactions()` on a `BaseMessage` object. + +### Properties + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| reaction | `getReaction()` | `string` | The reaction emoji (e.g., `"😀"`, `"👍"`) | +| count | `getCount()` | `number` | Number of users who reacted with this reaction | +| reactedByMe | `getReactedByMe()` | `boolean` | Whether the logged-in user reacted with this reaction | + +--- + +## ReactionEvent + +`ReactionEvent` represents a real-time reaction event. It is received via the `onMessageReactionAdded` and `onMessageReactionRemoved` listener callbacks. + +### Properties + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| reaction | `getReaction()` | `Reaction` | The reaction details object | +| receiverId | `getReceiverId()` | `string` | UID or GUID of the receiver | +| receiverType | `getReceiverType()` | `string` | Receiver type (`"user"` or `"group"`) | +| conversationId | `getConversationId()` | `string` | ID of the conversation | +| parentMessageId | `getParentMessageId()` | `string` | ID of the parent message (if the reacted message is in a thread) | + +--- + +## TypingIndicator + +`TypingIndicator` represents a typing event. It is received via the `onTypingStarted` and `onTypingEnded` listener callbacks. + +### Properties + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| receiverId | `getReceiverId()` | `string` | UID or GUID of the receiver | +| receiverType | `getReceiverType()` | `string` | Receiver type (`"user"` or `"group"`) | +| sender | `getSender()` | `User` | The user who is typing | +| metadata | `getMetadata()` | `Object` | Custom metadata attached to the typing indicator | + +--- + +## TransientMessage + +`TransientMessage` represents a transient (non-persistent) message. It is received via the `onTransientMessageReceived` listener callback. Transient messages are not stored on the server. + +### Properties + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| receiverId | `getReceiverId()` | `string` | UID or GUID of the receiver | +| receiverType | `getReceiverType()` | `string` | Receiver type (`"user"` or `"group"`) | +| sender | `getSender()` | `User` | The user who sent the transient message | +| data | `getData()` | `any` | Custom data payload of the transient message | + +--- + +## Attachment + +`Attachment` represents a file attachment on a `MediaMessage`. It is available via `getAttachment()` or `getAttachments()` on a `MediaMessage` object. + +### Properties + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| name | `getName()` | `string` | Name of the file | +| extension | `getExtension()` | `string` | File extension (e.g., `"png"`, `"pdf"`) | +| mimeType | `getMimeType()` | `string` | MIME type of the file (e.g., `"image/png"`) | +| size | `getSize()` | `number` | Size of the file in bytes | +| url | `getUrl()` | `string` | URL to download the file | diff --git a/sdk/reference/entities.mdx b/sdk/reference/entities.mdx new file mode 100644 index 000000000..7c0fd4e90 --- /dev/null +++ b/sdk/reference/entities.mdx @@ -0,0 +1,108 @@ +--- +title: "Entities" +description: "Class reference for entity objects returned by CometChat SDK methods. Covers User, Group, Conversation, and GroupMember." +--- + +This page documents the entity classes used across all CometChat SDKs. All entity objects share the same structure regardless of platform. + +All properties are accessed via getter methods. + +--- + +## User + +`User` represents a CometChat user. It is returned by methods like `CometChat.login()`, `CometChat.getUser()`, and user list requests. + +### Properties + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| uid | `getUid()` | `string` | Unique user ID | +| name | `getName()` | `string` | Display name of the user | +| avatar | `getAvatar()` | `string` | URL of the user's avatar image | +| link | `getLink()` | `string` | URL link associated with the user | +| role | `getRole()` | `string` | Role assigned to the user | +| metadata | `getMetadata()` | `Object` | Custom metadata attached to the user | +| status | `getStatus()` | `string` | Online status of the user (`"online"` or `"offline"`) | +| statusMessage | `getStatusMessage()` | `string` | Custom status message set by the user | +| lastActiveAt | `getLastActiveAt()` | `number` | Timestamp when the user was last active (epoch seconds) | +| tags | `getTags()` | `string[]` | Tags associated with the user | +| deactivatedAt | `getDeactivatedAt()` | `number` | Timestamp when the user was deactivated (epoch seconds) | + +### Conditional Properties + +These properties may or may not be populated depending on the method or request configuration used. + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| hasBlockedMe | `getHasBlockedMe()` | `boolean` | Whether this user has blocked the logged-in user | +| blockedByMe | `getBlockedByMe()` | `boolean` | Whether the logged-in user has blocked this user | +| authToken | `getAuthToken()` | `string` | Auth token of the user (only available after login) | + +--- + +## Group + +`Group` represents a CometChat group. It is returned by methods like `CometChat.createGroup()`, `CometChat.getGroup()`, and group list requests. + +### Properties + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| guid | `getGuid()` | `string` | Unique group ID | +| name | `getName()` | `string` | Display name of the group | +| type | `getType()` | `string` | Group type (`"public"`, `"private"`, or `"password"`) | +| icon | `getIcon()` | `string` | URL of the group icon | +| description | `getDescription()` | `string` | Description of the group | +| owner | `getOwner()` | `string` | UID of the group owner | +| metadata | `getMetadata()` | `Object` | Custom metadata attached to the group | +| createdAt | `getCreatedAt()` | `number` | Timestamp when the group was created (epoch seconds) | +| updatedAt | `getUpdatedAt()` | `number` | Timestamp when the group was last updated (epoch seconds) | +| hasJoined | `getHasJoined()` | `boolean` | Whether the logged-in user has joined this group | +| scope | `getScope()` | `string` | Scope of the logged-in user in the group (`"admin"`, `"moderator"`, or `"participant"`) | +| joinedAt | `getJoinedAt()` | `string` | Timestamp when the logged-in user joined the group | +| membersCount | `getMembersCount()` | `number` | Total number of members in the group | +| tags | `getTags()` | `string[]` | Tags associated with the group | + +### Conditional Properties + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| password | `getPassword()` | `string` | Group password (only for password-protected groups, only available during creation) | +| isBanned | `isBannedFromGroup()` | `boolean` | Whether the logged-in user is banned from the group | + +--- + +## Conversation + +`Conversation` represents a chat conversation. It is returned by `CometChat.getConversation()` and conversation list requests. + +### Properties + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| conversationId | `getConversationId()` | `string` | Unique conversation ID | +| conversationType | `getConversationType()` | `string` | Type of conversation (`"user"` or `"group"`) | +| lastMessage | `getLastMessage()` | `BaseMessage` | The last message in the conversation | +| conversationWith | `getConversationWith()` | `User` \| `Group` | The user or group this conversation is with | +| unreadMessageCount | `getUnreadMessageCount()` | `number` | Number of unread messages in the conversation | +| unreadMentionsCount | `getUnreadMentionsCount()` | `number` | Number of unread mentions in the conversation | +| lastReadMessageId | `getLastReadMessageId()` | `string` | ID of the last message read by the logged-in user | +| latestMessageId | `getLatestMessageId()` | `string` | ID of the latest message in the conversation | +| tags | `getTags()` | `string[]` | Tags associated with the conversation | + +--- + +## GroupMember + +`GroupMember` extends [User](#user) and represents a member of a CometChat group. It is returned by group member list requests. + +It inherits all properties from `User` and adds the following. + +### Properties + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| scope | `getScope()` | `string` | Scope of the member in the group (`"admin"`, `"moderator"`, or `"participant"`) | +| joinedAt | `getJoinedAt()` | `number` | Timestamp when the member joined the group (epoch seconds) | +| guid | `getGuid()` | `string` | GUID of the group this member belongs to | diff --git a/sdk/reference/messages.mdx b/sdk/reference/messages.mdx index 5ef7c19f2..b789a66e9 100644 --- a/sdk/reference/messages.mdx +++ b/sdk/reference/messages.mdx @@ -89,3 +89,129 @@ These properties may or may not be populated depending on the method or request | Property | Getter | Return Type | Description | |----------|--------|-------------|-------------| | tags | `getTags()` | `string[]` | Tags associated with the message | + +--- + +## MediaMessage + +`MediaMessage` extends [BaseMessage](#basemessage) and represents a message with media attachments such as images, videos, audio files, or documents. + +It inherits all properties from `BaseMessage` and adds the following. + +### Properties + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| caption | `getCaption()` | `string` | Caption text for the media message | +| attachment | `getAttachment()` | `Attachment` | The primary attachment of the media message | +| attachments | `getAttachments()` | `Attachment[]` | All attachments of the media message | +| url | `getURL()` | `string` | URL of the media file | +| metadata | `getMetadata()` | `Object` | Custom metadata attached to the message | +| data | `getData()` | `Object` | Raw data payload of the message | +| moderationStatus | `getModerationStatus()` | `ModerationStatus` | Moderation status of the message. Returns `"unmoderated"` if not moderated. | + +### Conditional Properties + +These properties may or may not be populated depending on the method or request configuration used to fetch the message. + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| tags | `getTags()` | `string[]` | Tags associated with the message | + +--- + +## CustomMessage + +`CustomMessage` extends [BaseMessage](#basemessage) and represents a developer-defined message with a custom data payload. + +It inherits all properties from `BaseMessage` and adds the following. + +### Properties + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| customData | `getCustomData()` | `Object` | The custom data payload set by the developer | +| subType | `getSubType()` | `string` | Sub type of the custom message | +| conversationText | `getConversationText()` | `string` | Preview text displayed in the conversation list | +| updateConversation | `willUpdateConversation()` | `boolean` | Whether this message updates the conversation's last message | +| sendNotification | `willSendNotification()` | `boolean` | Whether a push notification is sent for this message | +| metadata | `getMetadata()` | `Object` | Custom metadata attached to the message | +| data | `getData()` | `Object` | Raw data payload of the message | + +### Conditional Properties + +These properties may or may not be populated depending on the method or request configuration used to fetch the message. + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| tags | `getTags()` | `string[]` | Tags associated with the message | + +--- + +## InteractiveMessage + +`InteractiveMessage` extends [BaseMessage](#basemessage) and represents a message with interactive UI elements such as forms, cards, or buttons. + +It inherits all properties from `BaseMessage` and adds the following. + +### Properties + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| interactiveData | `getInteractiveData()` | `Object` | The interactive element data (form fields, buttons, etc.) | +| interactionGoal | `getInteractionGoal()` | `InteractionGoal` | The goal that defines when the interaction is considered complete | +| interactions | `getInteractions()` | `Interaction[]` | Array of interactions that have occurred on this message | +| allowSenderInteraction | `getIsSenderInteractionAllowed()` | `boolean` | Whether the sender is allowed to interact with the message | +| metadata | `getMetadata()` | `Object` | Custom metadata attached to the message | +| data | `getData()` | `Object` | Raw data payload of the message | + +### Conditional Properties + +These properties may or may not be populated depending on the method or request configuration used to fetch the message. + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| tags | `getTags()` | `string[]` | Tags associated with the message | + +--- + +## Action + +`Action` extends [BaseMessage](#basemessage) and represents a system-generated action message such as a member joining, leaving, or being banned from a group. + +It inherits all properties from `BaseMessage` and adds the following. + +### Properties + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| action | `getAction()` | `string` | The action being performed (e.g., `"joined"`, `"left"`, `"kicked"`, `"banned"`) | +| message | `getMessage()` | `string` | The default human-readable action message | +| actionBy | `getActionBy()` | `User` \| `Group` \| `BaseMessage` | The entity that performed the action | +| actionOn | `getActionOn()` | `User` \| `Group` \| `BaseMessage` | The entity on which the action was performed | +| actionFor | `getActionFor()` | `User` \| `Group` \| `BaseMessage` | The entity for whom the action was performed | +| oldScope | `getOldScope()` | `string` | Previous scope of the member (for scope change actions) | +| newScope | `getNewScope()` | `string` | New scope of the member (for scope change actions) | +| rawData | `getRawData()` | `Object` | Raw JSON data of the action message | +| metadata | `getMetadata()` | `Object` | Custom metadata attached to the action message | + +--- + +## Call + +`Call` extends [BaseMessage](#basemessage) and represents a voice or video call message. + +It inherits all properties from `BaseMessage` and adds the following. + +### Properties + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| sessionId | `getSessionId()` | `string` | Unique session ID of the call | +| callInitiator | `getCallInitiator()` | `User` | The user who initiated the call | +| callReceiver | `getCallReceiver()` | `User` \| `Group` | The user or group receiving the call | +| action | `getAction()` | `string` | The call action (e.g., `"initiated"`, `"ongoing"`, `"ended"`, `"cancelled"`, `"rejected"`) | +| initiatedAt | `getInitiatedAt()` | `number` | Timestamp when the call was initiated | +| joinedAt | `getJoinedAt()` | `number` | Timestamp when the call was joined | +| rawData | `getRawData()` | `Object` | Raw JSON data of the call message | +| metadata | `getMetadata()` | `Object` | Custom metadata attached to the call message | From 8e3d6495c70b87a9c974ce46a837121300001470 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Tue, 17 Mar 2026 19:15:03 +0530 Subject: [PATCH 10/43] Update .gitignore --- .gitignore | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/.gitignore b/.gitignore index 96adadbc8..4669a449e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,15 @@ .DS_Store .kiro/ + +# IDE files +.idea/ + +# Python caches +__pycache__/ +*.pyc +/codebase +/doc-auditor +/docs-templates +/docs-test-suite +/prompts From 473ff8f4dfbed5aaea11877ee723d6a68a1c4770 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Tue, 17 Mar 2026 19:15:07 +0530 Subject: [PATCH 11/43] Create .mintignore --- .mintignore | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 .mintignore diff --git a/.mintignore b/.mintignore new file mode 100644 index 000000000..9ddbca1cf --- /dev/null +++ b/.mintignore @@ -0,0 +1,8 @@ +.kiro/ +/codebase +/doc-auditor +/prompts +/docs-templates +/mintignore +/doc-auditor +/docs-test-suite \ No newline at end of file From de627441705981b87cf72254cf29dedd65b95440 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Tue, 17 Mar 2026 19:15:20 +0530 Subject: [PATCH 12/43] Update .gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 4669a449e..2b6c95161 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,4 @@ __pycache__/ /docs-templates /docs-test-suite /prompts +/docs-comparison-tool From 30144b12c24034c14e0dc3646394b4c0c8dda861 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 18 Mar 2026 07:53:20 +0530 Subject: [PATCH 13/43] updates docs --- docs.json | 2 + sdk/javascript/ai-agents.mdx | 4 - .../ai-integration-quick-reference.mdx | 285 ++++++++++++++++++ sdk/javascript/ai-moderation.mdx | 4 - sdk/javascript/block-users.mdx | 4 - sdk/javascript/call-logs.mdx | 4 - sdk/javascript/create-group.mdx | 4 - sdk/javascript/default-call.mdx | 4 - sdk/javascript/delete-conversation.mdx | 4 - sdk/javascript/delete-group.mdx | 4 - sdk/javascript/delete-message.mdx | 4 - sdk/javascript/delivery-read-receipts.mdx | 4 - sdk/javascript/direct-call.mdx | 4 - sdk/javascript/edit-message.mdx | 4 - sdk/javascript/flag-message.mdx | 4 - sdk/javascript/group-add-members.mdx | 4 - sdk/javascript/group-change-member-scope.mdx | 4 - sdk/javascript/group-kick-ban-members.mdx | 4 - sdk/javascript/groups-overview.mdx | 35 ++- sdk/javascript/interactive-messages.mdx | 4 - sdk/javascript/join-group.mdx | 4 - sdk/javascript/leave-group.mdx | 4 - sdk/javascript/mentions.mdx | 4 - sdk/javascript/overview.mdx | 18 ++ sdk/javascript/reactions.mdx | 4 - sdk/javascript/receive-message.mdx | 4 - sdk/javascript/recording.mdx | 4 - sdk/javascript/retrieve-conversations.mdx | 4 - sdk/javascript/retrieve-group-members.mdx | 3 - sdk/javascript/retrieve-groups.mdx | 3 - sdk/javascript/retrieve-users.mdx | 3 - sdk/javascript/send-message.mdx | 4 - sdk/javascript/threaded-messages.mdx | 4 - sdk/javascript/transfer-group-ownership.mdx | 4 - sdk/javascript/transient-messages.mdx | 4 - sdk/javascript/troubleshooting.mdx | 162 ++++++++++ sdk/javascript/typing-indicators.mdx | 3 - sdk/javascript/update-group.mdx | 3 - sdk/javascript/user-management.mdx | 4 - sdk/javascript/user-presence.mdx | 4 - 40 files changed, 499 insertions(+), 138 deletions(-) create mode 100644 sdk/javascript/ai-integration-quick-reference.mdx create mode 100644 sdk/javascript/troubleshooting.mdx diff --git a/docs.json b/docs.json index e631a40b9..6a9b2ec95 100644 --- a/docs.json +++ b/docs.json @@ -2579,10 +2579,12 @@ }, "sdk/javascript/ai-moderation", "sdk/javascript/ai-agents", + "sdk/javascript/ai-integration-quick-reference", { "group": "Resources", "pages": [ "sdk/javascript/resources-overview", + "sdk/javascript/troubleshooting", "sdk/javascript/all-real-time-listeners", "sdk/javascript/upgrading-from-v3" ] diff --git a/sdk/javascript/ai-agents.mdx b/sdk/javascript/ai-agents.mdx index 8525c4340..7e851c472 100644 --- a/sdk/javascript/ai-agents.mdx +++ b/sdk/javascript/ai-agents.mdx @@ -28,10 +28,6 @@ CometChat.removeMessageListener("LISTENER_ID"); **Event flow:** Run Start → Tool Call(s) → Text Message Stream → Run Finished - -**Available via:** SDK | [UI Kits](/ui-kit/react/overview) | [Dashboard](https://app.cometchat.com) - - # AI Agents Overview AI Agents enable intelligent, automated interactions within your application. They can process user messages, trigger tools, and respond with contextually relevant information. For a broader introduction, see the [AI Agents section](/ai-agents). diff --git a/sdk/javascript/ai-integration-quick-reference.mdx b/sdk/javascript/ai-integration-quick-reference.mdx new file mode 100644 index 000000000..8d7317a8b --- /dev/null +++ b/sdk/javascript/ai-integration-quick-reference.mdx @@ -0,0 +1,285 @@ +--- +title: "AI Integration Quick Reference" +sidebarTitle: "AI Quick Reference" +description: "Quick reference for AI features in the CometChat JavaScript SDK: AI Agents, AI Moderation, and AI User Copilot." +--- + +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```javascript +// AI Agents - Listen for real-time streaming events +CometChat.addAIAssistantListener("LISTENER_ID", { + onAIAssistantEventReceived: (event) => console.log("Event:", event) +}); + +// AI Agents - Listen for persisted agentic messages +CometChat.addMessageListener("LISTENER_ID", { + onAIAssistantMessageReceived: (msg) => console.log("Assistant reply:", msg), + onAIToolResultReceived: (msg) => console.log("Tool result:", msg), + onAIToolArgumentsReceived: (msg) => console.log("Tool args:", msg) +}); + +// AI Moderation - Check message status +CometChat.sendMessage(textMessage).then(message => { + const status = message.getModerationStatus(); + // CometChat.ModerationStatus.PENDING | APPROVED | DISAPPROVED +}); +``` + +**Prerequisites:** SDK initialized, user logged in, AI features enabled in [CometChat Dashboard](https://app.cometchat.com) + + + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-javascript` | +| AI Features | AI Agents, AI Moderation, AI User Copilot | +| Activation | Enable from [CometChat Dashboard](https://app.cometchat.com) | +| Prerequisites | `CometChat.init()` + `CometChat.login()` completed | +| AI Agents | Real-time streaming via `AIAssistantListener`, persisted messages via `MessageListener` | +| AI Moderation | Automatic content moderation with `PENDING` → `APPROVED` / `DISAPPROVED` flow | +| AI User Copilot | Smart Replies, Conversation Starter, Conversation Summary (Dashboard-enabled) | + + + +## Overview + +CometChat provides three AI-powered features to enhance your chat application: + +| Feature | Description | Use Case | +| --- | --- | --- | +| [AI Agents](/sdk/javascript/ai-agents) | Intelligent automated conversations with real-time streaming | Chatbots, virtual assistants, automated support | +| [AI Moderation](/sdk/javascript/ai-moderation) | Automatic content moderation for text, image, and video messages | Safety, compliance, content filtering | +| [AI User Copilot](/fundamentals/ai-user-copilot/overview) | Smart replies, conversation starters, and summaries | Enhanced user experience, productivity | + +## AI Features Summary + +### AI Agents + +AI Agents enable intelligent, automated interactions. They process user messages, trigger tools, and respond with contextually relevant information. + +**Key Points:** +- Agents only respond to text messages +- Real-time events via `AIAssistantListener` +- Persisted messages via `MessageListener` +- Event flow: Run Start → Tool Call(s) → Text Message Stream → Run Finished + + + + ```javascript + const listnerId = "unique_listener_id"; + + // Adding the AIAssistantListener for real-time events + CometChat.addAIAssistantListener(listnerId, { + onAIAssistantEventReceived: (message) => { + console.log("AIAssistant event received successfully", message); + } + }); + + // Adding the MessageListener for persisted agentic messages + CometChat.addMessageListener(listnerId, { + onAIAssistantMessageReceived: (message) => { + console.log("AI Assistant message received successfully", message); + }, + onAIToolResultReceived: (message) => { + console.log("AI Tool result message received successfully", message); + }, + onAIToolArgumentsReceived: (message) => { + console.log("AI Tool argument message received successfully", message); + }, + }); + + // Cleanup - always remove listeners when done + CometChat.removeAIAssistantListener(listnerId); + CometChat.removeMessageListener(listnerId); + ``` + + + ```typescript + const listnerId: string = "unique_listener_id"; + + // Adding the AIAssistantListener for real-time events + CometChat.addAIAssistantListener(listnerId, { + onAIAssistantEventReceived: (message: CometChat.AIAssistantBaseEvent) => { + console.log("AIAssistant event received successfully", message); + } + }); + + // Adding the MessageListener for persisted agentic messages + CometChat.addMessageListener(listnerId, { + onAIAssistantMessageReceived: (message: CometChat.AIAssistantMessage) => { + console.log("AI Assistant message received successfully", message); + }, + onAIToolResultReceived: (message: CometChat.AIToolResultMessage) => { + console.log("AI Tool result message received successfully", message); + }, + onAIToolArgumentsReceived: (message: CometChat.AIToolArgumentMessage) => { + console.log("AI Tool argument message received successfully", message); + }, + }); + + // Cleanup - always remove listeners when done + CometChat.removeAIAssistantListener(listnerId); + CometChat.removeMessageListener(listnerId); + ``` + + + +### AI Moderation + +AI Moderation automatically reviews messages for inappropriate content in real-time. + +**Key Points:** +- Supports Text, Image, and Video messages only +- Moderation statuses: `PENDING` → `APPROVED` or `DISAPPROVED` +- Enable and configure rules in the CometChat Dashboard + + + + ```javascript + // Send message and check initial moderation status + const textMessage = new CometChat.TextMessage( + receiverUID, + "Hello, how are you?", + CometChat.RECEIVER_TYPE.USER + ); + + CometChat.sendMessage(textMessage).then( + (message) => { + const status = message.getModerationStatus(); + + if (status === CometChat.ModerationStatus.PENDING) { + console.log("Message is under moderation review"); + } + }, + (error) => { + console.log("Message sending failed:", error); + } + ); + + // Listen for moderation results + const listenerID = "MODERATION_LISTENER"; + + CometChat.addMessageListener( + listenerID, + new CometChat.MessageListener({ + onMessageModerated: (message) => { + const status = message.getModerationStatus(); + const messageId = message.getId(); + + switch (status) { + case CometChat.ModerationStatus.APPROVED: + console.log(`Message ${messageId} approved`); + break; + case CometChat.ModerationStatus.DISAPPROVED: + console.log(`Message ${messageId} blocked`); + break; + } + } + }) + ); + ``` + + + ```typescript + // Send message and check initial moderation status + const textMessage = new CometChat.TextMessage( + receiverUID, + "Hello, how are you?", + CometChat.RECEIVER_TYPE.USER + ); + + CometChat.sendMessage(textMessage).then( + (message: CometChat.TextMessage) => { + const status: string = message.getModerationStatus(); + + if (status === CometChat.ModerationStatus.PENDING) { + console.log("Message is under moderation review"); + } + }, + (error: CometChat.CometChatException) => { + console.log("Message sending failed:", error); + } + ); + + // Listen for moderation results + const listenerID: string = "MODERATION_LISTENER"; + + CometChat.addMessageListener( + listenerID, + new CometChat.MessageListener({ + onMessageModerated: (message: CometChat.BaseMessage) => { + const status: string = message.getModerationStatus(); + const messageId: number = message.getId(); + + switch (status) { + case CometChat.ModerationStatus.APPROVED: + console.log(`Message ${messageId} approved`); + break; + case CometChat.ModerationStatus.DISAPPROVED: + console.log(`Message ${messageId} blocked`); + break; + } + } + }) + ); + ``` + + + +### AI User Copilot + +AI User Copilot provides smart features that enhance user productivity. These features are enabled in the Dashboard and auto-integrate with UI Kits. + +| Feature | Description | Documentation | +| --- | --- | --- | +| Conversation Starter | AI-generated opening lines for new chats | [Learn more](/fundamentals/ai-user-copilot/conversation-starter) | +| Smart Replies | AI-generated response suggestions | [Learn more](/fundamentals/ai-user-copilot/smart-replies) | +| Conversation Summary | AI-generated recap of long conversations | [Learn more](/fundamentals/ai-user-copilot/conversation-summary) | + +## Configuration Options + +### AI Agents Configuration + +| Parameter | Type | Description | +| --- | --- | --- | +| `listenerId` | `string` | Unique identifier for the listener | +| `onAIAssistantEventReceived` | `function` | Callback for real-time streaming events | +| `onAIAssistantMessageReceived` | `function` | Callback for persisted assistant messages | +| `onAIToolResultReceived` | `function` | Callback for tool execution results | +| `onAIToolArgumentsReceived` | `function` | Callback for tool arguments | + +### AI Moderation Configuration + +| Parameter | Type | Description | +| --- | --- | --- | +| `listenerID` | `string` | Unique identifier for the listener | +| `onMessageModerated` | `function` | Callback when moderation result is available | + +### Moderation Status Values + +| Status | Enum | Description | +| --- | --- | --- | +| Pending | `CometChat.ModerationStatus.PENDING` | Message is being processed | +| Approved | `CometChat.ModerationStatus.APPROVED` | Message passed moderation | +| Disapproved | `CometChat.ModerationStatus.DISAPPROVED` | Message was blocked | + +## Next Steps + + + + Full documentation for AI Agents integration + + + Complete AI Moderation implementation guide + + + Smart Replies, Conversation Starter, and Summary + + + Common issues and fixes + + diff --git a/sdk/javascript/ai-moderation.mdx b/sdk/javascript/ai-moderation.mdx index 008d2d905..93e999aff 100644 --- a/sdk/javascript/ai-moderation.mdx +++ b/sdk/javascript/ai-moderation.mdx @@ -27,10 +27,6 @@ CometChat.addMessageListener("MOD_LISTENER", new CometChat.MessageListener({ **Statuses:** `PENDING` → `APPROVED` or `DISAPPROVED` - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) | [Dashboard](https://app.cometchat.com) - - ## Overview AI Moderation in the CometChat SDK helps ensure that your chat application remains safe and compliant by automatically reviewing messages for inappropriate content. This feature leverages AI to moderate messages in real-time, reducing manual intervention and improving user experience. diff --git a/sdk/javascript/block-users.mdx b/sdk/javascript/block-users.mdx index d126facc1..76505a4cf 100644 --- a/sdk/javascript/block-users.mdx +++ b/sdk/javascript/block-users.mdx @@ -22,10 +22,6 @@ let blockedUsers = await request.fetchNext(); **Directions:** `BLOCKED_BY_ME` | `HAS_BLOCKED_ME` | `BOTH` (default) - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) - - ## Block Users *In other words, as a logged-in user, how do I block a user from sending me messages?* diff --git a/sdk/javascript/call-logs.mdx b/sdk/javascript/call-logs.mdx index 221a7a895..6afe4f1c8 100644 --- a/sdk/javascript/call-logs.mdx +++ b/sdk/javascript/call-logs.mdx @@ -24,10 +24,6 @@ let details = await CometChatCalls.getCallDetails("SESSION_ID", authToken); **Filters:** `setCallType()`, `setCallStatus()`, `setCallCategory()`, `setCallDirection()`, `setHasRecording()`, `setUid()`, `setGuid()` - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [Dashboard](https://app.cometchat.com) - - ## Overview CometChat's Web Call SDK provides a comprehensive way to integrate call logs into your application, enhancing your user experience by allowing users to effortlessly keep track of their communication history. Call logs provide crucial information such as call duration, participants, and more. diff --git a/sdk/javascript/create-group.mdx b/sdk/javascript/create-group.mdx index 4f8883c2c..2e42a50a5 100644 --- a/sdk/javascript/create-group.mdx +++ b/sdk/javascript/create-group.mdx @@ -21,10 +21,6 @@ let result = await CometChat.createGroupWithMembers(group, members, []); **Member scopes:** `ADMIN` | `MODERATOR` | `PARTICIPANT` - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) - - ## Create a Group *In other words, as a logged-in user, how do I create a public, private or password-protected group?* diff --git a/sdk/javascript/default-call.mdx b/sdk/javascript/default-call.mdx index 8f62558b4..8afefc588 100644 --- a/sdk/javascript/default-call.mdx +++ b/sdk/javascript/default-call.mdx @@ -29,10 +29,6 @@ await CometChat.rejectCall(sessionId, CometChat.CALL_STATUS.CANCELLED); **Flow:** Initiate → Receiver notified → Accept/Reject → Start session - -**Available via:** SDK | [UI Kits](/ui-kit/react/overview) - - ## Overview This section explains how to implement a complete calling workflow with ringing functionality, including incoming/outgoing call UI, call acceptance, rejection, and cancellation. Previously known as **Default Calling**. diff --git a/sdk/javascript/delete-conversation.mdx b/sdk/javascript/delete-conversation.mdx index 308e789fc..d9e080410 100644 --- a/sdk/javascript/delete-conversation.mdx +++ b/sdk/javascript/delete-conversation.mdx @@ -18,10 +18,6 @@ await CometChat.deleteConversation("GUID", "group"); **Note:** Deletes only for the logged-in user. Use [REST API](https://api-explorer.cometchat.com/reference/resets-user-conversation) to delete for all participants. - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) - - This operation is irreversible. Deleted conversations cannot be recovered for the logged-in user. diff --git a/sdk/javascript/delete-group.mdx b/sdk/javascript/delete-group.mdx index ee9741f64..f3f4d32f4 100644 --- a/sdk/javascript/delete-group.mdx +++ b/sdk/javascript/delete-group.mdx @@ -15,10 +15,6 @@ await CometChat.deleteGroup("GUID"); **Requirement:** Logged-in user must be an Admin of the group. - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) - - This operation is irreversible. Deleted groups and their messages cannot be recovered. diff --git a/sdk/javascript/delete-message.mdx b/sdk/javascript/delete-message.mdx index d25092cb7..a197e00ca 100644 --- a/sdk/javascript/delete-message.mdx +++ b/sdk/javascript/delete-message.mdx @@ -23,10 +23,6 @@ CometChat.addMessageListener("ID", new CometChat.MessageListener({ **Deleted fields:** `deletedAt` (timestamp), `deletedBy` (user who deleted) - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) - - This operation is irreversible. Deleted messages cannot be recovered. diff --git a/sdk/javascript/delivery-read-receipts.mdx b/sdk/javascript/delivery-read-receipts.mdx index 5eb7474be..99a6dfdbb 100644 --- a/sdk/javascript/delivery-read-receipts.mdx +++ b/sdk/javascript/delivery-read-receipts.mdx @@ -32,10 +32,6 @@ CometChat.addMessageListener("receipts", new CometChat.MessageListener({ Delivery and read receipts let you track whether messages have been delivered to and read by recipients. This page covers marking messages as delivered, read, or unread, and receiving real-time receipt events. - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) - - ## Mark Messages as Delivered *In other words, as a recipient, how do I inform the sender that I've received a message?* diff --git a/sdk/javascript/direct-call.mdx b/sdk/javascript/direct-call.mdx index ee7538645..75b8b96a2 100644 --- a/sdk/javascript/direct-call.mdx +++ b/sdk/javascript/direct-call.mdx @@ -32,10 +32,6 @@ This section demonstrates how to start a call session in a web application. Prev Before you begin, we strongly recommend you read the [calling setup guide](/sdk/javascript/calling-setup). - -**Available via:** SDK | [UI Kits](/ui-kit/react/overview) - - If you want to implement a complete calling experience with ringing functionality (incoming/outgoing call UI), follow the [Ringing](/sdk/javascript/default-call) guide first. Once the call is accepted, return here to start the call session. diff --git a/sdk/javascript/edit-message.mdx b/sdk/javascript/edit-message.mdx index ca502e46d..b30ac1019 100644 --- a/sdk/javascript/edit-message.mdx +++ b/sdk/javascript/edit-message.mdx @@ -25,10 +25,6 @@ While [editing a message](/sdk/javascript/edit-message#edit-a-message) is straig 1. Adding a listener to receive [real-time message edits](/sdk/javascript/edit-message#real-time-message-edit-events) when your app is running 2. Calling a method to retrieve [missed message edits](/sdk/javascript/edit-message#missed-message-edit-events) when your app was not running - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) - - ## Edit a Message *In other words, as a sender, how do I edit a message?* diff --git a/sdk/javascript/flag-message.mdx b/sdk/javascript/flag-message.mdx index ab3bd4257..a21134b20 100644 --- a/sdk/javascript/flag-message.mdx +++ b/sdk/javascript/flag-message.mdx @@ -23,10 +23,6 @@ await CometChat.flagMessage("MESSAGE_ID", { Flagging messages allows users to report inappropriate content to moderators or administrators. When a message is flagged, it appears in the [CometChat Dashboard](https://app.cometchat.com) under **Moderation > Flagged Messages** for review. - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | Dashboard - - For a complete understanding of how flagged messages are reviewed and managed, see the [Flagged Messages](/moderation/flagged-messages) documentation. diff --git a/sdk/javascript/group-add-members.mdx b/sdk/javascript/group-add-members.mdx index 59394f930..b1e0ec17c 100644 --- a/sdk/javascript/group-add-members.mdx +++ b/sdk/javascript/group-add-members.mdx @@ -23,10 +23,6 @@ CometChat.addGroupListener("listener", new CometChat.GroupListener({ You can add members to a group programmatically and listen for real-time events when members are added. - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) - - ## Add Members to Group You can add members to the group using the `addMembersToGroup()` method. This method takes the below parameters: diff --git a/sdk/javascript/group-change-member-scope.mdx b/sdk/javascript/group-change-member-scope.mdx index 2730d7cc2..59e63cf8e 100644 --- a/sdk/javascript/group-change-member-scope.mdx +++ b/sdk/javascript/group-change-member-scope.mdx @@ -20,10 +20,6 @@ CometChat.addGroupListener("listener", new CometChat.GroupListener({ You can change the role of a group member between admin, moderator, and participant. - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) - - ## Change Scope of a Group Member In order to change the scope of a group member, you can use the `changeGroupMemberScope()`. diff --git a/sdk/javascript/group-kick-ban-members.mdx b/sdk/javascript/group-kick-ban-members.mdx index 99c0d3ce4..848b29987 100644 --- a/sdk/javascript/group-kick-ban-members.mdx +++ b/sdk/javascript/group-kick-ban-members.mdx @@ -32,10 +32,6 @@ There are certain actions that can be performed on the group members: All the above actions can only be performed by the **Admin** or the **Moderator** of the group. - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) - - ## Kick a Group Member The Admin or Moderator of a group can kick a member out of the group using the `kickGroupMember()` method. diff --git a/sdk/javascript/groups-overview.mdx b/sdk/javascript/groups-overview.mdx index 077147425..cb6e5b5e8 100644 --- a/sdk/javascript/groups-overview.mdx +++ b/sdk/javascript/groups-overview.mdx @@ -20,9 +20,38 @@ Groups help your users to converse together in a single space. You can have thre Each group includes three kinds of users- owner, moderator, member. - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) - +## Group Types + +| Type | Description | Join Behavior | +|------|-------------|---------------| +| **Public** | Open to all users | Any user can join without approval | +| **Private** | Invite-only | Users must be added by admin/moderator | +| **Password** | Protected by password | Users must provide correct password to join | + +## Member Roles + +| Role | Permissions | +|------|-------------| +| **Owner** | Full control: manage members, settings, delete group. Cannot leave without transferring ownership. | +| **Admin** | Manage members (add, kick, ban), change member scope, update group settings | +| **Moderator** | Kick and ban members, moderate content | +| **Member** | Send/receive messages, leave group | + + +- **Choose the right group type** — Use public for open communities, private for invite-only teams, password for semi-restricted access +- **Assign appropriate roles** — Give admin/moderator roles only to trusted users who need management capabilities +- **Transfer ownership before leaving** — Owners must transfer ownership to another member before they can leave the group +- **Use pagination for large groups** — When fetching group members, use `GroupMembersRequestBuilder` with reasonable limits (30-50) +- **Handle group events** — Register `GroupListener` to receive real-time updates for member changes, scope changes, and group updates + + + +- **Can't join private group** — Private groups require an admin to add you. Use `joinGroup()` only for public or password-protected groups. +- **Owner can't leave group** — Transfer ownership first using `transferGroupOwnership()`, then call `leaveGroup()`. +- **Group not appearing in list** — Verify you're a member of the group. Use `getJoinedGroups()` to fetch only groups you've joined. +- **Permission denied errors** — Check the user's scope in the group. Only admins/moderators can perform management actions. +- **Password group join fails** — Ensure the password is correct and passed as the second parameter to `joinGroup()`. + --- diff --git a/sdk/javascript/interactive-messages.mdx b/sdk/javascript/interactive-messages.mdx index a934cf2b9..2f66ee123 100644 --- a/sdk/javascript/interactive-messages.mdx +++ b/sdk/javascript/interactive-messages.mdx @@ -24,10 +24,6 @@ CometChat.addMessageListener("interactive", new CometChat.MessageListener({ An InteractiveMessage is a specialised object that encapsulates an interactive unit within a chat message, such as an embedded form that users can fill out directly within the chat interface. This enhances user engagement by making the chat experience more interactive and responsive to user input. - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) - - ## InteractiveMessage `InteractiveMessage` is a chat message with embedded interactive content. It can contain various properties: diff --git a/sdk/javascript/join-group.mdx b/sdk/javascript/join-group.mdx index 7a6ba0f11..e6858239c 100644 --- a/sdk/javascript/join-group.mdx +++ b/sdk/javascript/join-group.mdx @@ -23,10 +23,6 @@ CometChat.addGroupListener("listener", new CometChat.GroupListener({ You can join groups to start participating in group conversations and receive real-time events when other members join. - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) - - ## Join a Group In order to start participating in group conversations, you will have to join a group. You can do so using the `joinGroup()` method. diff --git a/sdk/javascript/leave-group.mdx b/sdk/javascript/leave-group.mdx index a94d85675..573bb236c 100644 --- a/sdk/javascript/leave-group.mdx +++ b/sdk/javascript/leave-group.mdx @@ -20,10 +20,6 @@ CometChat.addGroupListener("listener", new CometChat.GroupListener({ You can leave a group to stop receiving updates and messages from that group conversation. - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) - - ## Leave a Group In order to stop receiving updates and messages for any particular joined group, you will have to leave the group using the `leaveGroup()` method. diff --git a/sdk/javascript/mentions.mdx b/sdk/javascript/mentions.mdx index 5c3995e17..98cbce7c5 100644 --- a/sdk/javascript/mentions.mdx +++ b/sdk/javascript/mentions.mdx @@ -29,10 +29,6 @@ Mentions in messages enable users to refer to specific individual within a conve Mentions are a powerful tool for enhancing communication in messaging platforms. They streamline interaction by allowing users to easily engage and collaborate with particular individuals, especially in group conversations. - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) - - ## Send Mentioned Messages To send a message with a mentioned user, you must follow a specific format: `<@uid:UID>`. For example, to mention the user with UID `cometchat-uid-1` with the message "`Hello`," your text would be `"Hello, <@uid:cometchat-uid-1>"` diff --git a/sdk/javascript/overview.mdx b/sdk/javascript/overview.mdx index a0c18911f..8a0cecc1a 100644 --- a/sdk/javascript/overview.mdx +++ b/sdk/javascript/overview.mdx @@ -645,6 +645,24 @@ UID can be alphanumeric with an underscore and hyphen. Spaces, punctuation and o * Please refer to the section to integrate [Chat Widget](/widget/html-bootstrap-jquery) into your Website. + +- **Initialize once at app start** — Call `CometChat.init()` only once, preferably in your app's entry point (index.js, App.js, or main.ts) +- **Check login state first** — Always call `getLoggedinUser()` before `login()` to avoid unnecessary login attempts +- **Use Auth Tokens in production** — Never expose Auth Keys in production client code. Generate Auth Tokens on your server. +- **Handle SSR correctly** — For Next.js, Nuxt, or other SSR frameworks, initialize CometChat only on the client side using dynamic imports or `useEffect` +- **Store credentials securely** — Keep App ID, Region, and Auth Keys in environment variables, not hardcoded in source code + + + +- **"SDK not initialized" error** — Ensure `CometChat.init()` is called and completes successfully before any other SDK method +- **Login fails with invalid credentials** — Verify your App ID, Region, and Auth Key match your CometChat Dashboard settings +- **SSR hydration errors** — CometChat requires browser APIs. Use dynamic imports or `useEffect` to initialize only on the client side +- **User not found on login** — The UID must exist. Create the user first with `createUser()` or via the Dashboard/REST API +- **WebSocket connection issues** — Check if `autoEstablishSocketConnection` is set correctly. For manual control, see [Managing WebSocket Connections](/sdk/javascript/managing-web-sockets-connections-manually) + +For more issues, see the [Troubleshooting Guide](/sdk/javascript/troubleshooting). + + --- ## Next Steps diff --git a/sdk/javascript/reactions.mdx b/sdk/javascript/reactions.mdx index 3148fbf1f..2cf0b44c0 100644 --- a/sdk/javascript/reactions.mdx +++ b/sdk/javascript/reactions.mdx @@ -29,10 +29,6 @@ CometChat.addMessageListener("LISTENER_ID", { Enhance user engagement in your chat application with message reactions. Users can express their emotions using reactions to messages. This feature allows users to add or remove reactions, and to fetch all reactions on a message. You can also listen to reaction events in real-time. Let's see how to work with reactions in CometChat's SDK. - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) - - ## Add a Reaction Users can add a reaction to a message by calling `addReaction` with the message ID and the reaction emoji. diff --git a/sdk/javascript/receive-message.mdx b/sdk/javascript/receive-message.mdx index aeb5e40de..40e73a06d 100644 --- a/sdk/javascript/receive-message.mdx +++ b/sdk/javascript/receive-message.mdx @@ -36,10 +36,6 @@ Receiving messages with CometChat has two parts: 1. Adding a listener to receive [real-time messages](/sdk/javascript/receive-message#real-time-messages) when your app is running 2. Calling a method to retrieve [missed messages](/sdk/javascript/receive-message#missed-messages) when your app was not running - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) - - ## Real-Time Messages *In other words, as a recipient, how do I receive messages when my app is running?* diff --git a/sdk/javascript/recording.mdx b/sdk/javascript/recording.mdx index a7d57a68f..68beb23af 100644 --- a/sdk/javascript/recording.mdx +++ b/sdk/javascript/recording.mdx @@ -26,10 +26,6 @@ const callListener = new CometChatCalls.OngoingCallListener({ This section will guide you to implement call recording feature for the voice and video calls. - -**Available via:** SDK | Dashboard - - ## Implementation Once you have decided to implement [Default Calling](/sdk/javascript/default-call) or [Direct Calling](/sdk/javascript/direct-call) calling and followed the steps to implement them. Just few additional listeners and methods will help you quickly implement call recording in your app. diff --git a/sdk/javascript/retrieve-conversations.mdx b/sdk/javascript/retrieve-conversations.mdx index 737e5f88c..0ca12a8af 100644 --- a/sdk/javascript/retrieve-conversations.mdx +++ b/sdk/javascript/retrieve-conversations.mdx @@ -26,10 +26,6 @@ const conversation = await CometChat.CometChatHelper.getConversationFromMessage( Conversations provide the last messages for every one-on-one and group conversation the logged-in user is a part of. This makes it easy for you to build a **Recent Chat** list. - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) - - ## Retrieve List of Conversations *In other words, as a logged-in user, how do I retrieve the latest conversations that I've been a part of?* diff --git a/sdk/javascript/retrieve-group-members.mdx b/sdk/javascript/retrieve-group-members.mdx index 5eb5820f7..5a95ea3e5 100644 --- a/sdk/javascript/retrieve-group-members.mdx +++ b/sdk/javascript/retrieve-group-members.mdx @@ -23,9 +23,6 @@ const request = new CometChat.GroupMembersRequestBuilder("GUID") ``` - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) - ## Retrieve the List of Group Members In order to fetch the list of groups members for a group, you can use the `GroupMembersRequest` class. To use this class i.e to create an object of the GroupMembersRequest class, you need to use the `GroupMembersRequestBuilder` class. The `GroupMembersRequestBuilder` class allows you to set the parameters based on which the groups are to be fetched. diff --git a/sdk/javascript/retrieve-groups.mdx b/sdk/javascript/retrieve-groups.mdx index 1e74e2898..67280feb4 100644 --- a/sdk/javascript/retrieve-groups.mdx +++ b/sdk/javascript/retrieve-groups.mdx @@ -25,9 +25,6 @@ const count = await CometChat.getOnlineGroupMemberCount(["GUID"]); ``` - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) - ## Retrieve List of Groups *In other words, as a logged-in user, how do I retrieve the list of groups I've joined and groups that are available?* diff --git a/sdk/javascript/retrieve-users.mdx b/sdk/javascript/retrieve-users.mdx index e3dcb9e3a..d298cb519 100644 --- a/sdk/javascript/retrieve-users.mdx +++ b/sdk/javascript/retrieve-users.mdx @@ -24,9 +24,6 @@ const count = await CometChat.getOnlineUserCount(); ``` - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) - ## Retrieve Logged In User Details You can get the details of the logged-in user using the `getLoggedInUser()` method. This method can also be used to check if the user is logged in or not. If the method returns `Promise` with reject callback, it indicates that the user is not logged in and you need to log the user into CometChat SDK. diff --git a/sdk/javascript/send-message.mdx b/sdk/javascript/send-message.mdx index 9b0cf7af5..a46b65f4a 100644 --- a/sdk/javascript/send-message.mdx +++ b/sdk/javascript/send-message.mdx @@ -28,10 +28,6 @@ await CometChat.sendCustomMessage(msg); Using CometChat, you can send three types of messages: - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) - - 1. [Text Message](/sdk/javascript/send-message#text-message) is the most common and standard message type. 2. [Media Message](/sdk/javascript/send-message#media-message) for sending photos, videos and files. 3. [Custom Message](/sdk/javascript/send-message#custom-message), for sending completely custom data using JSON structures. diff --git a/sdk/javascript/threaded-messages.mdx b/sdk/javascript/threaded-messages.mdx index 0fee3d530..542fe6921 100644 --- a/sdk/javascript/threaded-messages.mdx +++ b/sdk/javascript/threaded-messages.mdx @@ -26,10 +26,6 @@ const request = new CometChat.MessagesRequestBuilder() Messages that are started from a particular message are called Threaded messages or simply threads. Each Thread is attached to a message which is the Parent message for that thread. - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) - - ## Send Message in a Thread As mentioned in the [Send a Message](/sdk/javascript/send-message) section. You can either send a message to a User or a Group based on the `receiverType` and the UID/GUID specified for the message. A message can belong to either of the below types: diff --git a/sdk/javascript/transfer-group-ownership.mdx b/sdk/javascript/transfer-group-ownership.mdx index 871a2ab0d..8c6512cb0 100644 --- a/sdk/javascript/transfer-group-ownership.mdx +++ b/sdk/javascript/transfer-group-ownership.mdx @@ -17,10 +17,6 @@ await CometChat.transferGroupOwnership("GUID", "NEW_OWNER_UID"); *In other words, as a logged-in user, how do I transfer the ownership of any group if I am the owner of the group?* - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) - - In order to transfer the ownership of any group, the first condition is that you must be the owner of the group. In case you are the owner of the group, you can use the `transferGroupOwnership()` method provided by the `CometChat` class. This will be helpful as the owner is not allowed to leave the group. In case, you as the owner would like to leave the group, you will have to use this method and transfer your ownership first to any other member of the group and only then you will be allowed to leave the group. diff --git a/sdk/javascript/transient-messages.mdx b/sdk/javascript/transient-messages.mdx index e326eff37..67c424a0c 100644 --- a/sdk/javascript/transient-messages.mdx +++ b/sdk/javascript/transient-messages.mdx @@ -21,10 +21,6 @@ CometChat.addMessageListener("LISTENER_ID", new CometChat.MessageListener({ Transient messages are messages that are sent in real-time only and are not saved or tracked anywhere. The receiver of the message will only receive the message if he is online and these messages cannot be retrieved later. - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) - - ## Send a Transient Message You can use the `sendTransientMessage()` method to send a transient message to a user or in a group. The receiver will receive this information in the `onTransientMessageReceived()` method of the `MessageListener` class. In order to send the transient message, you need to use the `TransientMessage` class. diff --git a/sdk/javascript/troubleshooting.mdx b/sdk/javascript/troubleshooting.mdx new file mode 100644 index 000000000..61b2454e9 --- /dev/null +++ b/sdk/javascript/troubleshooting.mdx @@ -0,0 +1,162 @@ +--- +title: "Troubleshooting" +sidebarTitle: "Troubleshooting" +description: "Common failure modes and fixes for the CometChat JavaScript SDK." +--- + +{/* TL;DR for Agents and Quick Reference */} + +**Quick Troubleshooting Reference** + +| Common Issue | Quick Fix | +| --- | --- | +| `init()` fails | Verify App ID and Region from [Dashboard](https://app.cometchat.com) | +| Login fails with "UID not found" | Create user via Dashboard or REST API first | +| SDK methods fail | Ensure `init()` completes before calling other methods | +| No real-time events | Check WebSocket connection, verify listeners registered | +| SSR errors | Use dynamic imports or `useEffect` for client-side only | + +**Need help?** [Open a support ticket](https://help.cometchat.com/hc/en-us/requests/new) + + + + +| Field | Value | +| --- | --- | +| Page type | Troubleshooting reference | +| Scope | All CometChat JavaScript SDK issues — initialization, authentication, messaging, groups, calling, WebSocket, extensions, AI features | +| When to reference | When SDK methods fail, data is missing, real-time events don't fire, or features don't work as expected | + + + +## Initialization and Setup + +| Symptom | Cause | Fix | +| --- | --- | --- | +| `init()` fails with "App ID not found" | Invalid App ID or Region | Verify your App ID and Region match the [CometChat Dashboard](https://app.cometchat.com) → API & Auth Keys | +| `init()` fails silently | Missing or incorrect credentials | Double-check App ID, Region, and ensure they're strings, not undefined | +| SDK methods fail with "CometChat not initialized" | `init()` not called or not awaited | Ensure `init()` resolves successfully before calling `login()`, `sendMessage()`, or registering listeners | +| `init()` works but nothing else does | Wrong SDK version or corrupted install | Run `npm install @cometchat/chat-sdk-javascript@latest` to reinstall | + +--- + +## Authentication + +| Symptom | Cause | Fix | +| --- | --- | --- | +| Login fails with "UID not found" | User doesn't exist in CometChat | Create the user via [Dashboard](https://app.cometchat.com) (testing) or [REST API](https://api-explorer.cometchat.com/reference/creates-user) (production) first | +| Login fails with "Auth Key is not valid" | Wrong Auth Key | Verify Auth Key matches [Dashboard](https://app.cometchat.com) → API & Auth Keys. Don't confuse with REST API Key | +| Login fails with "App not found" | `init()` not completed or wrong App ID | Ensure `init()` completes before `login()`. Verify App ID and Region | +| `getLoggedinUser()` returns null after refresh | Session not persisted or `init()` not called | Call `init()` on every app load before checking `getLoggedinUser()`. Browser storage clearing also clears sessions | +| Auth Token expired | Token has a limited lifetime | Generate a new Auth Token from your server using the [REST API](https://api-explorer.cometchat.com/reference/create-authtoken) | +| Login works but user appears offline | Presence subscription not configured | Use `subscribePresenceForAllUsers()` or appropriate presence method in `AppSettingsBuilder` | + +--- + +## Messaging + +| Symptom | Cause | Fix | +| --- | --- | --- | +| `sendMessage()` fails | User not logged in or invalid receiver | Ensure `login()` completes before sending. Verify receiver UID/GUID exists | +| Messages sent but not received | Message listener not registered | Register `CometChat.addMessageListener()` with `onTextMessageReceived` callback | +| Duplicate messages received | Multiple listeners with same ID | Use unique listener IDs. Remove old listeners before adding new ones | +| Messages not appearing in conversation | Wrong receiver type | Use `CometChat.RECEIVER_TYPE.USER` for 1:1 and `CometChat.RECEIVER_TYPE.GROUP` for groups | +| Media message upload fails | File too large or unsupported format | Check file size limits. Supported formats: images (PNG, JPG, GIF), videos (MP4), audio (MP3, WAV) | +| `onTextMessageReceived` not firing | Listener registered after message sent | Register listeners immediately after `login()` completes | + +--- + +## Groups + +| Symptom | Cause | Fix | +| --- | --- | --- | +| Cannot join group | Group doesn't exist or wrong GUID | Verify GUID. Create group first if it doesn't exist | +| Cannot send message to group | User not a member | Join the group first using `CometChat.joinGroup()` | +| Group members not loading | Insufficient permissions | Only group members can fetch member list. Ensure user has joined | +| Cannot kick/ban members | User lacks admin/moderator scope | Only admins and moderators can kick/ban. Check user's scope in the group | +| Group creation fails | Missing required fields | Ensure GUID, name, and group type are provided | + +--- + +## Calling + +| Symptom | Cause | Fix | +| --- | --- | --- | +| Calls SDK not found | Package not installed | Run `npm install @cometchat/calls-sdk-javascript` | +| No audio/video | Browser permissions denied | Check browser permissions for camera and microphone. User must grant access | +| Call not connecting | Session ID mismatch or SDK not initialized | Verify both participants use same session ID. Initialize Calls SDK before starting | +| One-way audio | Firewall or NAT blocking WebRTC | CometChat uses TURN servers, but corporate networks may block WebRTC traffic | +| Poor call quality | Network bandwidth issues | Check connection stability. Consider audio-only fallback for poor connections | +| Call buttons not appearing | Calls SDK not detected | Ensure `@cometchat/calls-sdk-javascript` is installed — UI Kit auto-detects it | +| Incoming call not showing | Call listener not registered | Register `CometChat.addCallListener()` at app root level | + +--- + +## WebSocket and Connection + +| Symptom | Cause | Fix | +| --- | --- | --- | +| Real-time events not received | WebSocket disconnected | Check `CometChat.getConnectionStatus()`. Reconnect if needed | +| WebSocket connection fails | Firewall blocking WebSocket | Check network configuration. Corporate firewalls may block WebSocket connections | +| Connection drops frequently | Network instability | Implement reconnection logic. Use `CometChat.addConnectionListener()` to monitor status | +| Events delayed or batched | Network latency | This is expected on slow connections. Events are delivered in order | +| `autoEstablishSocketConnection` not working | Set to `false` in AppSettings | If managing connections manually, call `CometChat.connect()` explicitly | + +--- + +## Extensions and AI Features + +| Symptom | Cause | Fix | +| --- | --- | --- | +| AI features not appearing | Feature not enabled in Dashboard | Enable the specific AI feature from [Dashboard](https://app.cometchat.com) → AI Features | +| AI Agents not responding | Agent not configured or text message not sent | Configure Agent in Dashboard. Agents only respond to text messages | +| `onAIAssistantEventReceived` not firing | Listener not registered after login | Register `AIAssistantListener` after successful `init()` and `login()` | +| Moderation status always PENDING | Moderation rules not configured | Configure moderation rules in Dashboard → Moderation → Rules | +| Extension feature not appearing | Extension not activated | Enable the extension from [Dashboard](https://app.cometchat.com) → Extensions | +| Stickers/Polls not showing | Extension not enabled | Activate Stickers or Polls extension in Dashboard | + +--- + +## SSR / Framework-Specific + +| Symptom | Cause | Fix | +| --- | --- | --- | +| SSR hydration error | CometChat uses browser APIs (`window`, `WebSocket`) | Wrap in `useEffect` or use dynamic import with `ssr: false`. See [SSR examples](/sdk/javascript/overview#server-side-rendering-ssr-compatibility) | +| "window is not defined" in Next.js | SDK accessed during server render | Use dynamic imports: `const CometChat = (await import('@cometchat/chat-sdk-javascript')).CometChat` | +| "document is not defined" in Nuxt | SDK accessed during server render | Import SDK in `mounted()` lifecycle hook, not at module level | +| Astro components fail | SSR tries to render on server | Use `client:only="react"` directive for CometChat components | +| React Native errors | Wrong SDK | Use `@cometchat/chat-sdk-react-native` for React Native, not the JavaScript SDK | + +--- + +## Common Error Codes + +| Error Code | Description | Resolution | +| --- | --- | --- | +| `ERR_UID_NOT_FOUND` | User with specified UID doesn't exist | Create user via Dashboard or REST API | +| `ERR_AUTH_KEY_NOT_FOUND` | Invalid Auth Key | Verify Auth Key from Dashboard | +| `ERR_APP_NOT_FOUND` | Invalid App ID or Region | Check App ID and Region in Dashboard | +| `ERR_NOT_LOGGED_IN` | No active user session | Call `login()` before SDK operations | +| `ERR_GUID_NOT_FOUND` | Group with specified GUID doesn't exist | Create group or verify GUID | +| `ERR_NOT_A_MEMBER` | User is not a member of the group | Join group before sending messages | +| `ERR_BLOCKED` | User is blocked | Unblock user via Dashboard or SDK | +| `ERR_RATE_LIMIT_EXCEEDED` | Too many requests | Implement rate limiting. See [Rate Limits](/articles/rate-limits) | + +--- + +## Next Steps + + + + Installation and initialization guide + + + Login methods and session management + + + AI Agents, Moderation, and Copilot features + + + Open a support ticket + + diff --git a/sdk/javascript/typing-indicators.mdx b/sdk/javascript/typing-indicators.mdx index 04ead8e2a..bcb414758 100644 --- a/sdk/javascript/typing-indicators.mdx +++ b/sdk/javascript/typing-indicators.mdx @@ -23,9 +23,6 @@ CometChat.addMessageListener("LISTENER_ID", new CometChat.MessageListener({ ``` - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) - ## Send a Typing Indicator *In other words, as a sender, how do I let the recipient(s) know that I'm typing?* diff --git a/sdk/javascript/update-group.mdx b/sdk/javascript/update-group.mdx index aa9aaf5f0..6696ce0e3 100644 --- a/sdk/javascript/update-group.mdx +++ b/sdk/javascript/update-group.mdx @@ -14,9 +14,6 @@ const updated = await CometChat.updateGroup(group); ``` - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) - ## Update Group *In other words, as a group owner, how can I update the group details?* diff --git a/sdk/javascript/user-management.mdx b/sdk/javascript/user-management.mdx index b7d4d0809..64c491a24 100644 --- a/sdk/javascript/user-management.mdx +++ b/sdk/javascript/user-management.mdx @@ -26,10 +26,6 @@ await CometChat.updateCurrentUserDetails(user); When a user logs into your app, you need to programmatically login the user into CometChat. But before you log in the user to CometChat, you need to create the user. - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) - - Summing up- **When a user registers in your app** diff --git a/sdk/javascript/user-presence.mdx b/sdk/javascript/user-presence.mdx index 807a92862..27641e140 100644 --- a/sdk/javascript/user-presence.mdx +++ b/sdk/javascript/user-presence.mdx @@ -27,10 +27,6 @@ CometChat.removeUserListener("LISTENER_ID"); User Presence helps us understand if a user is available to chat or not. - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) - - ## Real-time Presence *In other words, as a logged-in user, how do I know if a user is online or offline?* From 55a8a50ff68d4b02ff95eb152747fabcb3b5a099 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 18 Mar 2026 08:18:26 +0530 Subject: [PATCH 14/43] I Integration Quick Reference --- sdk/javascript/additional-message-filtering.mdx | 5 ++--- sdk/javascript/advanced-overview.mdx | 5 ++--- sdk/javascript/ai-agents.mdx | 5 ++--- sdk/javascript/ai-integration-quick-reference.mdx | 5 ++--- sdk/javascript/ai-moderation.mdx | 5 ++--- sdk/javascript/all-real-time-listeners.mdx | 5 ++--- sdk/javascript/authentication-overview.mdx | 5 ++--- sdk/javascript/block-users.mdx | 5 ++--- sdk/javascript/call-logs.mdx | 5 ++--- sdk/javascript/calling-overview.mdx | 5 ++--- sdk/javascript/connection-status.mdx | 5 ++--- sdk/javascript/create-group.mdx | 5 ++--- sdk/javascript/custom-css.mdx | 5 ++--- sdk/javascript/default-call.mdx | 5 ++--- sdk/javascript/delete-conversation.mdx | 5 ++--- sdk/javascript/delete-group.mdx | 5 ++--- sdk/javascript/delete-message.mdx | 5 ++--- sdk/javascript/delivery-read-receipts.mdx | 9 ++++----- sdk/javascript/direct-call.mdx | 5 ++--- sdk/javascript/edit-message.mdx | 5 ++--- sdk/javascript/flag-message.mdx | 5 ++--- sdk/javascript/group-add-members.mdx | 5 ++--- sdk/javascript/group-change-member-scope.mdx | 5 ++--- sdk/javascript/group-kick-ban-members.mdx | 5 ++--- sdk/javascript/groups-overview.mdx | 5 ++--- sdk/javascript/interactive-messages.mdx | 5 ++--- sdk/javascript/join-group.mdx | 5 ++--- sdk/javascript/key-concepts.mdx | 5 ++--- sdk/javascript/leave-group.mdx | 5 ++--- sdk/javascript/login-listener.mdx | 5 ++--- .../managing-web-sockets-connections-manually.mdx | 5 ++--- sdk/javascript/mentions.mdx | 5 ++--- sdk/javascript/message-structure-and-hierarchy.mdx | 5 ++--- sdk/javascript/messaging-overview.mdx | 5 ++--- sdk/javascript/presenter-mode.mdx | 5 ++--- sdk/javascript/rate-limits.mdx | 5 ++--- sdk/javascript/reactions.mdx | 5 ++--- sdk/javascript/receive-message.mdx | 5 ++--- sdk/javascript/recording.mdx | 5 ++--- sdk/javascript/resources-overview.mdx | 5 ++--- sdk/javascript/retrieve-conversations.mdx | 5 ++--- sdk/javascript/retrieve-group-members.mdx | 5 ++--- sdk/javascript/retrieve-groups.mdx | 5 ++--- sdk/javascript/retrieve-users.mdx | 5 ++--- sdk/javascript/send-message.mdx | 5 ++--- sdk/javascript/session-timeout.mdx | 5 ++--- sdk/javascript/standalone-calling.mdx | 5 ++--- sdk/javascript/threaded-messages.mdx | 5 ++--- sdk/javascript/transfer-group-ownership.mdx | 5 ++--- sdk/javascript/transient-messages.mdx | 5 ++--- sdk/javascript/typing-indicators.mdx | 5 ++--- sdk/javascript/update-group.mdx | 5 ++--- sdk/javascript/upgrading-from-v3.mdx | 5 ++--- sdk/javascript/user-management.mdx | 5 ++--- sdk/javascript/user-presence.mdx | 5 ++--- sdk/javascript/users-overview.mdx | 5 ++--- 56 files changed, 114 insertions(+), 170 deletions(-) diff --git a/sdk/javascript/additional-message-filtering.mdx b/sdk/javascript/additional-message-filtering.mdx index a2a971a10..1334b05bd 100644 --- a/sdk/javascript/additional-message-filtering.mdx +++ b/sdk/javascript/additional-message-filtering.mdx @@ -4,8 +4,7 @@ description: "Advanced filtering options for fetching messages using MessagesReq --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Filter by category and type @@ -36,7 +35,7 @@ messagesRequest.fetchNext().then(messages => { }); ``` **Key methods:** `setUID()`, `setGUID()`, `setLimit()`, `setCategories()`, `setTypes()`, `setTags()`, `setUnread()`, `setParentMessageId()`, `setMessageId()`, `setTimestamp()`, `hideReplies()`, `hideDeletedMessages()` - + The `MessagesRequest` class as you must be familiar with helps you to fetch messages based on the various parameters provided to it. This document will help you understand better the various options that are available using the `MessagesRequest` class. diff --git a/sdk/javascript/advanced-overview.mdx b/sdk/javascript/advanced-overview.mdx index 87376691e..964125fac 100644 --- a/sdk/javascript/advanced-overview.mdx +++ b/sdk/javascript/advanced-overview.mdx @@ -5,8 +5,7 @@ description: "Advanced SDK features including connection management, real-time l --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Check connection status @@ -24,7 +23,7 @@ CometChat.addLoginListener("LISTENER_ID", new CometChat.LoginListener({ onLogoutSuccess: () => console.log("Logged out") })); ``` - + This section helps you to know about the Connection Listeners. diff --git a/sdk/javascript/ai-agents.mdx b/sdk/javascript/ai-agents.mdx index 7e851c472..7c2a7d495 100644 --- a/sdk/javascript/ai-agents.mdx +++ b/sdk/javascript/ai-agents.mdx @@ -4,8 +4,7 @@ description: "Integrate AI Agents into your app to enable intelligent, automated --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Listen for real-time AI Agent events (streaming) @@ -26,7 +25,7 @@ CometChat.removeMessageListener("LISTENER_ID"); ``` **Event flow:** Run Start → Tool Call(s) → Text Message Stream → Run Finished - + # AI Agents Overview diff --git a/sdk/javascript/ai-integration-quick-reference.mdx b/sdk/javascript/ai-integration-quick-reference.mdx index 8d7317a8b..7ee657163 100644 --- a/sdk/javascript/ai-integration-quick-reference.mdx +++ b/sdk/javascript/ai-integration-quick-reference.mdx @@ -5,8 +5,7 @@ description: "Quick reference for AI features in the CometChat JavaScript SDK: A --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // AI Agents - Listen for real-time streaming events @@ -29,7 +28,7 @@ CometChat.sendMessage(textMessage).then(message => { ``` **Prerequisites:** SDK initialized, user logged in, AI features enabled in [CometChat Dashboard](https://app.cometchat.com) - + diff --git a/sdk/javascript/ai-moderation.mdx b/sdk/javascript/ai-moderation.mdx index 93e999aff..a2eb995cb 100644 --- a/sdk/javascript/ai-moderation.mdx +++ b/sdk/javascript/ai-moderation.mdx @@ -4,8 +4,7 @@ description: "Automatically moderate chat messages using AI to detect and block --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Send message — check moderation status @@ -25,7 +24,7 @@ CometChat.addMessageListener("MOD_LISTENER", new CometChat.MessageListener({ **Supported types:** Text, Image, Video messages only **Statuses:** `PENDING` → `APPROVED` or `DISAPPROVED` - + ## Overview diff --git a/sdk/javascript/all-real-time-listeners.mdx b/sdk/javascript/all-real-time-listeners.mdx index 54a209640..f9323f14c 100644 --- a/sdk/javascript/all-real-time-listeners.mdx +++ b/sdk/javascript/all-real-time-listeners.mdx @@ -4,8 +4,7 @@ description: "Complete reference for all CometChat real-time listeners including --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // User Listener — online/offline presence @@ -34,7 +33,7 @@ CometChat.removeMessageListener("ID"); CometChat.removeGroupListener("ID"); CometChat.removeCallListener("ID"); ``` - + Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. diff --git a/sdk/javascript/authentication-overview.mdx b/sdk/javascript/authentication-overview.mdx index 2a4f6499e..5a6eff608 100644 --- a/sdk/javascript/authentication-overview.mdx +++ b/sdk/javascript/authentication-overview.mdx @@ -5,8 +5,7 @@ description: "Create users, log in with Auth Key or Auth Token, check login stat --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Check existing session @@ -24,7 +23,7 @@ CometChat.logout().then(() => console.log("Logged out")); **Create users via:** [Dashboard](https://app.cometchat.com) (testing) | [REST API](https://api-explorer.cometchat.com/reference/creates-user) (production) **Test UIDs:** `cometchat-uid-1` through `cometchat-uid-5` - + ## Create User diff --git a/sdk/javascript/block-users.mdx b/sdk/javascript/block-users.mdx index 76505a4cf..480e1856b 100644 --- a/sdk/javascript/block-users.mdx +++ b/sdk/javascript/block-users.mdx @@ -4,8 +4,7 @@ description: "Block and unblock users, and retrieve the list of blocked users us --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Block users @@ -20,7 +19,7 @@ let blockedUsers = await request.fetchNext(); ``` **Directions:** `BLOCKED_BY_ME` | `HAS_BLOCKED_ME` | `BOTH` (default) - + ## Block Users diff --git a/sdk/javascript/call-logs.mdx b/sdk/javascript/call-logs.mdx index 6afe4f1c8..d08f3a85b 100644 --- a/sdk/javascript/call-logs.mdx +++ b/sdk/javascript/call-logs.mdx @@ -4,8 +4,7 @@ description: "Fetch, filter, and retrieve call history including duration, parti --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Fetch call logs @@ -22,7 +21,7 @@ let details = await CometChatCalls.getCallDetails("SESSION_ID", authToken); ``` **Filters:** `setCallType()`, `setCallStatus()`, `setCallCategory()`, `setCallDirection()`, `setHasRecording()`, `setUid()`, `setGuid()` - + ## Overview diff --git a/sdk/javascript/calling-overview.mdx b/sdk/javascript/calling-overview.mdx index ce140dedf..7d7e5f99c 100644 --- a/sdk/javascript/calling-overview.mdx +++ b/sdk/javascript/calling-overview.mdx @@ -5,8 +5,7 @@ description: "Overview of CometChat voice and video calling capabilities includi --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + Choose your calling approach: - **Ringing** → [Default Call](/sdk/javascript/default-call) — Full call flow with notifications, accept/reject @@ -19,7 +18,7 @@ npm install @cometchat/calls-sdk-javascript ``` **Features:** Recording, Virtual Background, Screen Sharing, Custom CSS, Call Logs, Session Timeout - + ## Overview diff --git a/sdk/javascript/connection-status.mdx b/sdk/javascript/connection-status.mdx index f4b73613b..afcdbbee7 100644 --- a/sdk/javascript/connection-status.mdx +++ b/sdk/javascript/connection-status.mdx @@ -4,8 +4,7 @@ description: "Monitor real-time WebSocket connection status and respond to conne --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Get current status: "connecting" | "connected" | "disconnected" @@ -21,7 +20,7 @@ CometChat.addConnectionListener("LISTENER_ID", new CometChat.ConnectionListener( // Cleanup CometChat.removeConnectionListener("LISTENER_ID"); ``` - + CometChat SDK provides you with a mechanism to get real-time status of the connection to CometChat web-socket servers. diff --git a/sdk/javascript/create-group.mdx b/sdk/javascript/create-group.mdx index 2e42a50a5..b11d8b991 100644 --- a/sdk/javascript/create-group.mdx +++ b/sdk/javascript/create-group.mdx @@ -4,8 +4,7 @@ description: "Create public, private, or password-protected groups and optionall --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Create a group @@ -19,7 +18,7 @@ let result = await CometChat.createGroupWithMembers(group, members, []); **Group types:** `PUBLIC` | `PASSWORD` | `PRIVATE` **Member scopes:** `ADMIN` | `MODERATOR` | `PARTICIPANT` - + ## Create a Group diff --git a/sdk/javascript/custom-css.mdx b/sdk/javascript/custom-css.mdx index 363177b19..fd0692626 100644 --- a/sdk/javascript/custom-css.mdx +++ b/sdk/javascript/custom-css.mdx @@ -4,8 +4,7 @@ description: "Customize the CometChat calling UI with custom CSS classes for but --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```css /* Key CSS classes for call UI customization */ @@ -20,7 +19,7 @@ description: "Customize the CometChat calling UI with custom CSS classes for but ``` **Modes:** `DEFAULT` | `TILE` | `SPOTLIGHT` - + Passing custom CSS allows you to personalize and enhance the user interface of the call screen. diff --git a/sdk/javascript/default-call.mdx b/sdk/javascript/default-call.mdx index 8afefc588..d04a568d8 100644 --- a/sdk/javascript/default-call.mdx +++ b/sdk/javascript/default-call.mdx @@ -4,8 +4,7 @@ description: "Implement a complete calling workflow with ringing, incoming/outgo --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Initiate a call @@ -27,7 +26,7 @@ await CometChat.rejectCall(sessionId, CometChat.CALL_STATUS.CANCELLED); ``` **Flow:** Initiate → Receiver notified → Accept/Reject → Start session - + ## Overview diff --git a/sdk/javascript/delete-conversation.mdx b/sdk/javascript/delete-conversation.mdx index d9e080410..253f5607e 100644 --- a/sdk/javascript/delete-conversation.mdx +++ b/sdk/javascript/delete-conversation.mdx @@ -4,8 +4,7 @@ description: "Delete user or group conversations for the logged-in user using th --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Delete user conversation @@ -16,7 +15,7 @@ await CometChat.deleteConversation("GUID", "group"); ``` **Note:** Deletes only for the logged-in user. Use [REST API](https://api-explorer.cometchat.com/reference/resets-user-conversation) to delete for all participants. - + This operation is irreversible. Deleted conversations cannot be recovered for the logged-in user. diff --git a/sdk/javascript/delete-group.mdx b/sdk/javascript/delete-group.mdx index f3f4d32f4..dad4a602c 100644 --- a/sdk/javascript/delete-group.mdx +++ b/sdk/javascript/delete-group.mdx @@ -4,8 +4,7 @@ description: "Delete a group permanently using the CometChat JavaScript SDK. Onl --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Delete a group (admin only) @@ -13,7 +12,7 @@ await CometChat.deleteGroup("GUID"); ``` **Requirement:** Logged-in user must be an Admin of the group. - + This operation is irreversible. Deleted groups and their messages cannot be recovered. diff --git a/sdk/javascript/delete-message.mdx b/sdk/javascript/delete-message.mdx index a197e00ca..276b1cbfc 100644 --- a/sdk/javascript/delete-message.mdx +++ b/sdk/javascript/delete-message.mdx @@ -4,8 +4,7 @@ description: "Delete messages, receive real-time deletion events, and handle mis --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Delete a message @@ -21,7 +20,7 @@ CometChat.addMessageListener("ID", new CometChat.MessageListener({ **Who can delete:** Message sender, Group admin, Group moderator **Deleted fields:** `deletedAt` (timestamp), `deletedBy` (user who deleted) - + This operation is irreversible. Deleted messages cannot be recovered. diff --git a/sdk/javascript/delivery-read-receipts.mdx b/sdk/javascript/delivery-read-receipts.mdx index 99a6dfdbb..0d34a52c4 100644 --- a/sdk/javascript/delivery-read-receipts.mdx +++ b/sdk/javascript/delivery-read-receipts.mdx @@ -4,8 +4,7 @@ description: "Learn how to mark messages as delivered, read, or unread and recei --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Mark message as delivered (pass message object) @@ -28,7 +27,7 @@ CometChat.addMessageListener("receipts", new CometChat.MessageListener({ onMessagesReadByAll: (receipt) => { } // Group only })); ``` - + Delivery and read receipts let you track whether messages have been delivered to and read by recipients. This page covers marking messages as delivered, read, or unread, and receiving real-time receipt events. @@ -821,7 +820,7 @@ CometChat.getMessageReceipts(messageId).then( You will receive a list of `MessageReceipt` objects. - + The following features will be available only if the **Enhanced Messaging Status** feature is enabled for your app. @@ -831,7 +830,7 @@ The following features will be available only if the **Enhanced Messaging Status * `readAt` field in a group message. * `markMessageAsUnread` method. - + Always remove message listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. diff --git a/sdk/javascript/direct-call.mdx b/sdk/javascript/direct-call.mdx index 75b8b96a2..11088163d 100644 --- a/sdk/javascript/direct-call.mdx +++ b/sdk/javascript/direct-call.mdx @@ -4,8 +4,7 @@ description: "Learn how to generate call tokens, start and manage call sessions, --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Generate call token @@ -24,7 +23,7 @@ CometChatCalls.startSession(callToken.token, callSettings, htmlElement); // End call session CometChatCalls.endSession(); ``` - + ## Overview diff --git a/sdk/javascript/edit-message.mdx b/sdk/javascript/edit-message.mdx index b30ac1019..c38298d4f 100644 --- a/sdk/javascript/edit-message.mdx +++ b/sdk/javascript/edit-message.mdx @@ -4,8 +4,7 @@ description: "Learn how to edit text and custom messages, receive real-time edit --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Edit a text message @@ -18,7 +17,7 @@ CometChat.addMessageListener("edits", new CometChat.MessageListener({ onMessageEdited: (message) => console.log("Edited:", message) })); ``` - + While [editing a message](/sdk/javascript/edit-message#edit-a-message) is straightforward, receiving events for edited messages with CometChat has two parts: diff --git a/sdk/javascript/flag-message.mdx b/sdk/javascript/flag-message.mdx index a21134b20..f014957ec 100644 --- a/sdk/javascript/flag-message.mdx +++ b/sdk/javascript/flag-message.mdx @@ -4,8 +4,7 @@ description: "Learn how to flag inappropriate messages for moderation review usi --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Get available flag reasons @@ -17,7 +16,7 @@ await CometChat.flagMessage("MESSAGE_ID", { remark: "Promotional content" }); ``` - + ## Overview diff --git a/sdk/javascript/group-add-members.mdx b/sdk/javascript/group-add-members.mdx index b1e0ec17c..75ad5f504 100644 --- a/sdk/javascript/group-add-members.mdx +++ b/sdk/javascript/group-add-members.mdx @@ -4,8 +4,7 @@ description: "Learn how to add members to a group, receive real-time member adde --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Add members to a group @@ -19,7 +18,7 @@ CometChat.addGroupListener("listener", new CometChat.GroupListener({ onMemberAddedToGroup: (message, userAdded, userAddedBy, userAddedIn) => { } })); ``` - + You can add members to a group programmatically and listen for real-time events when members are added. diff --git a/sdk/javascript/group-change-member-scope.mdx b/sdk/javascript/group-change-member-scope.mdx index 59e63cf8e..a179f6d91 100644 --- a/sdk/javascript/group-change-member-scope.mdx +++ b/sdk/javascript/group-change-member-scope.mdx @@ -4,8 +4,7 @@ description: "Learn how to change group member roles (admin, moderator, particip --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Change member scope to admin @@ -16,7 +15,7 @@ CometChat.addGroupListener("listener", new CometChat.GroupListener({ onGroupMemberScopeChanged: (message, changedUser, newScope, oldScope, changedGroup) => { } })); ``` - + You can change the role of a group member between admin, moderator, and participant. diff --git a/sdk/javascript/group-kick-ban-members.mdx b/sdk/javascript/group-kick-ban-members.mdx index 848b29987..6641dce2a 100644 --- a/sdk/javascript/group-kick-ban-members.mdx +++ b/sdk/javascript/group-kick-ban-members.mdx @@ -4,8 +4,7 @@ description: "Learn how to kick, ban, and unban group members, fetch banned memb --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Kick a member @@ -21,7 +20,7 @@ await CometChat.unbanGroupMember("GUID", "UID"); const request = new CometChat.BannedMembersRequestBuilder("GUID").setLimit(30).build(); const bannedMembers = await request.fetchNext(); ``` - + There are certain actions that can be performed on the group members: diff --git a/sdk/javascript/groups-overview.mdx b/sdk/javascript/groups-overview.mdx index cb6e5b5e8..a28cc9af5 100644 --- a/sdk/javascript/groups-overview.mdx +++ b/sdk/javascript/groups-overview.mdx @@ -5,8 +5,7 @@ description: "Overview of group management in the CometChat JavaScript SDK inclu --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + Choose your path: - **Create a Group** → [Create Group](/sdk/javascript/create-group) @@ -14,7 +13,7 @@ Choose your path: - **Retrieve Groups** → [Retrieve Groups](/sdk/javascript/retrieve-groups) - **Manage Members** → [Add](/sdk/javascript/group-add-members) | [Kick/Ban](/sdk/javascript/group-kick-ban-members) | [Change Scope](/sdk/javascript/group-change-member-scope) - **Update/Delete** → [Update Group](/sdk/javascript/update-group) | [Delete Group](/sdk/javascript/delete-group) - + Groups help your users to converse together in a single space. You can have three types of groups- private, public and password protected. diff --git a/sdk/javascript/interactive-messages.mdx b/sdk/javascript/interactive-messages.mdx index 2f66ee123..87c261f1b 100644 --- a/sdk/javascript/interactive-messages.mdx +++ b/sdk/javascript/interactive-messages.mdx @@ -4,8 +4,7 @@ description: "Learn how to send and receive interactive messages with embedded f --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Send an interactive message @@ -20,7 +19,7 @@ CometChat.addMessageListener("interactive", new CometChat.MessageListener({ onInteractionGoalCompleted: (receipt) => { } })); ``` - + An InteractiveMessage is a specialised object that encapsulates an interactive unit within a chat message, such as an embedded form that users can fill out directly within the chat interface. This enhances user engagement by making the chat experience more interactive and responsive to user input. diff --git a/sdk/javascript/join-group.mdx b/sdk/javascript/join-group.mdx index e6858239c..01cfee325 100644 --- a/sdk/javascript/join-group.mdx +++ b/sdk/javascript/join-group.mdx @@ -4,8 +4,7 @@ description: "Learn how to join public, password-protected, and private groups, --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Join a public group @@ -19,7 +18,7 @@ CometChat.addGroupListener("listener", new CometChat.GroupListener({ onGroupMemberJoined: (message, joinedUser, joinedGroup) => { } })); ``` - + You can join groups to start participating in group conversations and receive real-time events when other members join. diff --git a/sdk/javascript/key-concepts.mdx b/sdk/javascript/key-concepts.mdx index dcb2b1c3c..490bb9dcc 100644 --- a/sdk/javascript/key-concepts.mdx +++ b/sdk/javascript/key-concepts.mdx @@ -4,8 +4,7 @@ description: "Understand the core concepts of CometChat including users, groups, --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + Key identifiers: - **UID** — Unique User Identifier (alphanumeric, underscore, hyphen) @@ -17,7 +16,7 @@ Key identifiers: Group types: `Public` | `Password` | `Private` Member scopes: `Admin` | `Moderator` | `Participant` Message categories: `message` | `custom` | `action` | `call` - + ### CometChat Dashboard diff --git a/sdk/javascript/leave-group.mdx b/sdk/javascript/leave-group.mdx index 573bb236c..51cf4af8e 100644 --- a/sdk/javascript/leave-group.mdx +++ b/sdk/javascript/leave-group.mdx @@ -4,8 +4,7 @@ description: "Learn how to leave a group and receive real-time events when membe --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Leave a group @@ -16,7 +15,7 @@ CometChat.addGroupListener("listener", new CometChat.GroupListener({ onGroupMemberLeft: (message, leavingUser, group) => { } })); ``` - + You can leave a group to stop receiving updates and messages from that group conversation. diff --git a/sdk/javascript/login-listener.mdx b/sdk/javascript/login-listener.mdx index b58b9dd97..4176ff6a4 100644 --- a/sdk/javascript/login-listener.mdx +++ b/sdk/javascript/login-listener.mdx @@ -4,8 +4,7 @@ description: "Listen for real-time login and logout events using the CometChat J --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Add login listener @@ -19,7 +18,7 @@ CometChat.addLoginListener("LISTENER_ID", new CometChat.LoginListener({ // Remove login listener CometChat.removeLoginListener("LISTENER_ID"); ``` - + The CometChat SDK provides you with real-time updates for the `login` and `logout` events. This can be achieved using the `LoginListener` class provided. LoginListener consists of 4 events that can be triggered. These are as follows: diff --git a/sdk/javascript/managing-web-sockets-connections-manually.mdx b/sdk/javascript/managing-web-sockets-connections-manually.mdx index 38189663a..3c4ee94de 100644 --- a/sdk/javascript/managing-web-sockets-connections-manually.mdx +++ b/sdk/javascript/managing-web-sockets-connections-manually.mdx @@ -4,8 +4,7 @@ description: "Learn how to manually manage WebSocket connections for real-time m --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Disable auto WebSocket connection during init @@ -19,7 +18,7 @@ await CometChat.init("APP_ID", appSettings); CometChat.connect(); CometChat.disconnect(); ``` - + ## Default SDK behaviour on login diff --git a/sdk/javascript/mentions.mdx b/sdk/javascript/mentions.mdx index 98cbce7c5..395723bfd 100644 --- a/sdk/javascript/mentions.mdx +++ b/sdk/javascript/mentions.mdx @@ -5,8 +5,7 @@ description: "Learn how to send messages with user mentions, retrieve mentioned {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Send a message with a mention (use <@uid:UID> format) @@ -21,7 +20,7 @@ const request = new CometChat.MessagesRequestBuilder() .setUID("UID").setLimit(30).mentionsWithTagInfo(true).build(); const messages = await request.fetchPrevious(); ``` - + diff --git a/sdk/javascript/message-structure-and-hierarchy.mdx b/sdk/javascript/message-structure-and-hierarchy.mdx index 389707975..90c6829dd 100644 --- a/sdk/javascript/message-structure-and-hierarchy.mdx +++ b/sdk/javascript/message-structure-and-hierarchy.mdx @@ -5,8 +5,7 @@ description: "Understand the message categories, types, and hierarchy in the Com --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + Message categories and types: - **message** → `text`, `image`, `video`, `audio`, `file` @@ -14,7 +13,7 @@ Message categories and types: - **interactive** → `form`, `card`, `customInteractive` - **action** → `groupMember` (joined/left/kicked/banned), `message` (edited/deleted) - **call** → `audio`, `video` - + The below diagram helps you better understand the various message categories and types that a CometChat message can belong to. diff --git a/sdk/javascript/messaging-overview.mdx b/sdk/javascript/messaging-overview.mdx index bb3a05a95..4914e383e 100644 --- a/sdk/javascript/messaging-overview.mdx +++ b/sdk/javascript/messaging-overview.mdx @@ -5,15 +5,14 @@ description: "Overview of messaging capabilities in the CometChat JavaScript SDK --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + Choose your path: - **Send Messages** → [Send Message](/sdk/javascript/send-message) - Text, media, custom - **Receive Messages** → [Receive Message](/sdk/javascript/receive-message) - Real-time listeners - **Edit/Delete** → [Edit](/sdk/javascript/edit-message) | [Delete](/sdk/javascript/delete-message) - **Advanced** → [Threads](/sdk/javascript/threaded-messages) | [Reactions](/sdk/javascript/reactions) | [Mentions](/sdk/javascript/mentions) - + Messaging is one of the core features of CometChat. We've thoughtfully created methods to help you send, receive and fetch message history. diff --git a/sdk/javascript/presenter-mode.mdx b/sdk/javascript/presenter-mode.mdx index d7f94aa34..f4c869a07 100644 --- a/sdk/javascript/presenter-mode.mdx +++ b/sdk/javascript/presenter-mode.mdx @@ -4,8 +4,7 @@ description: "Learn how to implement Presenter Mode for webinars, keynotes, and --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Start a presentation session @@ -20,7 +19,7 @@ CometChatCalls.joinPresentation(callToken, settings, htmlElement); - **Presenter** (max 5): Can share video, audio, and screen - **Viewer** (up to 100 total): Passive consumers, no outgoing streams - + ## Overview diff --git a/sdk/javascript/rate-limits.mdx b/sdk/javascript/rate-limits.mdx index 9c970fd4c..7d5cd0324 100644 --- a/sdk/javascript/rate-limits.mdx +++ b/sdk/javascript/rate-limits.mdx @@ -4,14 +4,13 @@ description: "Understand CometChat REST API rate limits, response headers, and h --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + - Core Operations (login, create/delete user, create/join group): `10,000` requests/min cumulative - Standard Operations (all other): `20,000` requests/min cumulative - Rate-limited responses return HTTP `429` with `Retry-After` and `X-Rate-Limit-Reset` headers - Monitor usage via `X-Rate-Limit` and `X-Rate-Limit-Remaining` response headers - + ### CometChat REST API Rate Limits diff --git a/sdk/javascript/reactions.mdx b/sdk/javascript/reactions.mdx index 2cf0b44c0..c61c438c8 100644 --- a/sdk/javascript/reactions.mdx +++ b/sdk/javascript/reactions.mdx @@ -4,8 +4,7 @@ description: "Add, remove, and fetch message reactions in real-time using the Co --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Add a reaction @@ -25,7 +24,7 @@ CometChat.addMessageListener("LISTENER_ID", { onMessageReactionRemoved: (reaction) => {} }); ``` - + Enhance user engagement in your chat application with message reactions. Users can express their emotions using reactions to messages. This feature allows users to add or remove reactions, and to fetch all reactions on a message. You can also listen to reaction events in real-time. Let's see how to work with reactions in CometChat's SDK. diff --git a/sdk/javascript/receive-message.mdx b/sdk/javascript/receive-message.mdx index 40e73a06d..d1cad6e87 100644 --- a/sdk/javascript/receive-message.mdx +++ b/sdk/javascript/receive-message.mdx @@ -4,8 +4,7 @@ description: "Receive real-time messages, fetch missed and unread messages, retr --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Listen for real-time messages @@ -29,7 +28,7 @@ const messages = await request.fetchPrevious(); // Get unread message count const counts = await CometChat.getUnreadMessageCount(); ``` - + Receiving messages with CometChat has two parts: diff --git a/sdk/javascript/recording.mdx b/sdk/javascript/recording.mdx index 68beb23af..73cfa98d3 100644 --- a/sdk/javascript/recording.mdx +++ b/sdk/javascript/recording.mdx @@ -4,8 +4,7 @@ description: "Implement call recording for voice and video calls using the Comet --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Start recording @@ -22,7 +21,7 @@ const callListener = new CometChatCalls.OngoingCallListener({ ``` **Recordings are available on the [CometChat Dashboard](https://app.cometchat.com) → Calls section.** - + This section will guide you to implement call recording feature for the voice and video calls. diff --git a/sdk/javascript/resources-overview.mdx b/sdk/javascript/resources-overview.mdx index fce2b674a..d2610212a 100644 --- a/sdk/javascript/resources-overview.mdx +++ b/sdk/javascript/resources-overview.mdx @@ -5,13 +5,12 @@ description: "Access CometChat JavaScript SDK resources including real-time list --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + - [All Real-Time Listeners](/sdk/javascript/all-real-time-listeners) — Complete listener reference - [Upgrading from v3](/sdk/javascript/upgrading-from-v3) — Migration guide - [Rate Limits](/sdk/javascript/rate-limits) — API rate limit details - + We have a number of resources that will help you while integrating CometChat in your app. diff --git a/sdk/javascript/retrieve-conversations.mdx b/sdk/javascript/retrieve-conversations.mdx index 0ca12a8af..98f99a84b 100644 --- a/sdk/javascript/retrieve-conversations.mdx +++ b/sdk/javascript/retrieve-conversations.mdx @@ -4,8 +4,7 @@ description: "Fetch, filter, tag, and search conversations using the CometChat J --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Fetch conversations list @@ -22,7 +21,7 @@ await CometChat.tagConversation("UID", "user", ["archived"]); // Convert message to conversation const conversation = await CometChat.CometChatHelper.getConversationFromMessage(message); ``` - + Conversations provide the last messages for every one-on-one and group conversation the logged-in user is a part of. This makes it easy for you to build a **Recent Chat** list. diff --git a/sdk/javascript/retrieve-group-members.mdx b/sdk/javascript/retrieve-group-members.mdx index 5a95ea3e5..e410c6e51 100644 --- a/sdk/javascript/retrieve-group-members.mdx +++ b/sdk/javascript/retrieve-group-members.mdx @@ -4,8 +4,7 @@ description: "Fetch and filter group members by scope, status, and search keywor --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Fetch group members @@ -21,7 +20,7 @@ const request = new CometChat.GroupMembersRequestBuilder("GUID") const request = new CometChat.GroupMembersRequestBuilder("GUID") .setLimit(30).setSearchKeyword("john").build(); ``` - + ## Retrieve the List of Group Members diff --git a/sdk/javascript/retrieve-groups.mdx b/sdk/javascript/retrieve-groups.mdx index 67280feb4..6b8fa0efc 100644 --- a/sdk/javascript/retrieve-groups.mdx +++ b/sdk/javascript/retrieve-groups.mdx @@ -4,8 +4,7 @@ description: "Fetch, filter, and search groups using the CometChat JavaScript SD --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Fetch groups list @@ -23,7 +22,7 @@ const request = new CometChat.GroupsRequestBuilder() // Get online member count const count = await CometChat.getOnlineGroupMemberCount(["GUID"]); ``` - + ## Retrieve List of Groups diff --git a/sdk/javascript/retrieve-users.mdx b/sdk/javascript/retrieve-users.mdx index d298cb519..3679aaeb0 100644 --- a/sdk/javascript/retrieve-users.mdx +++ b/sdk/javascript/retrieve-users.mdx @@ -4,8 +4,7 @@ description: "Fetch, filter, search, and sort users using the CometChat JavaScri --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Fetch users list @@ -22,7 +21,7 @@ const me = await CometChat.getLoggedinUser(); // Get online user count const count = await CometChat.getOnlineUserCount(); ``` - + ## Retrieve Logged In User Details diff --git a/sdk/javascript/send-message.mdx b/sdk/javascript/send-message.mdx index a46b65f4a..885698891 100644 --- a/sdk/javascript/send-message.mdx +++ b/sdk/javascript/send-message.mdx @@ -4,8 +4,7 @@ description: "Send text, media, and custom messages to users and groups using th --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Send text message to user @@ -24,7 +23,7 @@ await CometChat.sendMediaMessage(msg); const msg = new CometChat.CustomMessage("UID", CometChat.RECEIVER_TYPE.USER, "customType", { key: "value" }); await CometChat.sendCustomMessage(msg); ``` - + Using CometChat, you can send three types of messages: diff --git a/sdk/javascript/session-timeout.mdx b/sdk/javascript/session-timeout.mdx index f07d8414a..d5829e490 100644 --- a/sdk/javascript/session-timeout.mdx +++ b/sdk/javascript/session-timeout.mdx @@ -4,15 +4,14 @@ description: "Handle idle session timeouts in CometChat calls, including automat --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + - Default idle timeout: 180 seconds (3 minutes) alone in a session - Warning dialog appears at 120 seconds with stay/leave options - Auto-terminates after 60 more seconds if no action taken - Listen for `onSessionTimeout` event to handle auto-termination - Customize timeout with `setIdleTimeoutPeriod(seconds)` in CallSettings (v4.1.0+) - + Available since v4.1.0 diff --git a/sdk/javascript/standalone-calling.mdx b/sdk/javascript/standalone-calling.mdx index d576f9f0b..f16a67aaa 100644 --- a/sdk/javascript/standalone-calling.mdx +++ b/sdk/javascript/standalone-calling.mdx @@ -4,8 +4,7 @@ description: "Implement video and audio calling using only the CometChat Calls S --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Generate call token (requires user auth token from REST API) @@ -22,7 +21,7 @@ CometChatCalls.startSession(callToken.token, callSettings, htmlElement); // End session CometChatCalls.endSession(); ``` - + ## Overview This section demonstrates how to implement calling functionality using only the CometChat Calls SDK, without requiring the Chat SDK. This is ideal for applications that need video/audio calling capabilities without the full chat infrastructure. diff --git a/sdk/javascript/threaded-messages.mdx b/sdk/javascript/threaded-messages.mdx index 542fe6921..a1379e661 100644 --- a/sdk/javascript/threaded-messages.mdx +++ b/sdk/javascript/threaded-messages.mdx @@ -4,8 +4,7 @@ description: "Send, receive, and fetch threaded messages using the CometChat Jav --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Send message in a thread @@ -22,7 +21,7 @@ const messages = await request.fetchPrevious(); const request = new CometChat.MessagesRequestBuilder() .setUID("UID").setLimit(30).hideReplies(true).build(); ``` - + Messages that are started from a particular message are called Threaded messages or simply threads. Each Thread is attached to a message which is the Parent message for that thread. diff --git a/sdk/javascript/transfer-group-ownership.mdx b/sdk/javascript/transfer-group-ownership.mdx index 8c6512cb0..ba6b7ac88 100644 --- a/sdk/javascript/transfer-group-ownership.mdx +++ b/sdk/javascript/transfer-group-ownership.mdx @@ -4,8 +4,7 @@ description: "Transfer ownership of a CometChat group to another member using th --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Transfer group ownership @@ -13,7 +12,7 @@ await CometChat.transferGroupOwnership("GUID", "NEW_OWNER_UID"); ``` **Note:** Only the current group owner can transfer ownership. The owner must transfer ownership before leaving the group. - + *In other words, as a logged-in user, how do I transfer the ownership of any group if I am the owner of the group?* diff --git a/sdk/javascript/transient-messages.mdx b/sdk/javascript/transient-messages.mdx index 67c424a0c..363a70f37 100644 --- a/sdk/javascript/transient-messages.mdx +++ b/sdk/javascript/transient-messages.mdx @@ -4,8 +4,7 @@ description: "Send and receive ephemeral real-time messages that are not stored --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Send transient message to user @@ -17,7 +16,7 @@ CometChat.addMessageListener("LISTENER_ID", new CometChat.MessageListener({ onTransientMessageReceived: (msg) => console.log("Transient:", msg) })); ``` - + Transient messages are messages that are sent in real-time only and are not saved or tracked anywhere. The receiver of the message will only receive the message if he is online and these messages cannot be retrieved later. diff --git a/sdk/javascript/typing-indicators.mdx b/sdk/javascript/typing-indicators.mdx index bcb414758..279d3c874 100644 --- a/sdk/javascript/typing-indicators.mdx +++ b/sdk/javascript/typing-indicators.mdx @@ -4,8 +4,7 @@ description: "Send and receive real-time typing indicators for users and groups --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Start typing indicator @@ -21,7 +20,7 @@ CometChat.addMessageListener("LISTENER_ID", new CometChat.MessageListener({ onTypingEnded: (indicator) => console.log("Typing ended:", indicator) })); ``` - + ## Send a Typing Indicator diff --git a/sdk/javascript/update-group.mdx b/sdk/javascript/update-group.mdx index 6696ce0e3..b060a6a7e 100644 --- a/sdk/javascript/update-group.mdx +++ b/sdk/javascript/update-group.mdx @@ -4,15 +4,14 @@ description: "Update group details such as name, type, icon, and description usi --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Update group details const group = new CometChat.Group("GUID", "New Name", CometChat.GROUP_TYPE.PUBLIC); const updated = await CometChat.updateGroup(group); ``` - + ## Update Group diff --git a/sdk/javascript/upgrading-from-v3.mdx b/sdk/javascript/upgrading-from-v3.mdx index c5d1aff1c..6017ea9d0 100644 --- a/sdk/javascript/upgrading-from-v3.mdx +++ b/sdk/javascript/upgrading-from-v3.mdx @@ -4,15 +4,14 @@ description: "Migrate your CometChat JavaScript SDK integration from v3 to v4 wi --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + Key changes from v3 to v4: - Chat SDK: `npm i @cometchat/chat-sdk-javascript` - Calls SDK: `npm i @cometchat/calls-sdk-javascript` - Import: `import { CometChat } from '@cometchat/chat-sdk-javascript'` - Import Calls: `import { CometChatCalls } from '@cometchat/calls-sdk-javascript'` - + ## Upgrading From v3 Upgrading from v3.x to v4 is fairly simple. Below are the major changes that are released as a part of CometChat v4: diff --git a/sdk/javascript/user-management.mdx b/sdk/javascript/user-management.mdx index 64c491a24..9e53be1db 100644 --- a/sdk/javascript/user-management.mdx +++ b/sdk/javascript/user-management.mdx @@ -4,8 +4,7 @@ description: "Create, update, and manage CometChat users programmatically using --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Create a user @@ -22,7 +21,7 @@ await CometChat.updateCurrentUserDetails(user); ``` **Note:** User creation/deletion should ideally happen on your backend via the [REST API](https://api-explorer.cometchat.com). - + When a user logs into your app, you need to programmatically login the user into CometChat. But before you log in the user to CometChat, you need to create the user. diff --git a/sdk/javascript/user-presence.mdx b/sdk/javascript/user-presence.mdx index 27641e140..2fb11d6ed 100644 --- a/sdk/javascript/user-presence.mdx +++ b/sdk/javascript/user-presence.mdx @@ -5,8 +5,7 @@ description: "Track real-time user online/offline status and configure presence --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript // Subscribe to presence during init @@ -23,7 +22,7 @@ CometChat.addUserListener("LISTENER_ID", new CometChat.UserListener({ // Remove listener CometChat.removeUserListener("LISTENER_ID"); ``` - + User Presence helps us understand if a user is available to chat or not. diff --git a/sdk/javascript/users-overview.mdx b/sdk/javascript/users-overview.mdx index 98246d430..625648e58 100644 --- a/sdk/javascript/users-overview.mdx +++ b/sdk/javascript/users-overview.mdx @@ -5,14 +5,13 @@ description: "Overview of CometChat user functionality including user management --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + - [User Management](/sdk/javascript/user-management) — Create and update users - [Retrieve Users](/sdk/javascript/retrieve-users) — Fetch and filter user lists - [User Presence](/sdk/javascript/user-presence) — Track online/offline status - [Block Users](/sdk/javascript/block-users) — Block and unblock users - + The primary aim for our Users functionality is to allow you to quickly retrieve and add users to CometChat. From 201bfdeeb8c8177752e71c18eff1ae1dff6708d6 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 18 Mar 2026 08:52:09 +0530 Subject: [PATCH 15/43] fixes --- sdk/javascript/groups-overview.mdx | 17 ++++++++------- sdk/javascript/receive-message.mdx | 33 +++++++++--------------------- sdk/javascript/send-message.mdx | 26 ++++++++--------------- 3 files changed, 29 insertions(+), 47 deletions(-) diff --git a/sdk/javascript/groups-overview.mdx b/sdk/javascript/groups-overview.mdx index a28cc9af5..5e19c26da 100644 --- a/sdk/javascript/groups-overview.mdx +++ b/sdk/javascript/groups-overview.mdx @@ -4,15 +4,18 @@ sidebarTitle: "Overview" description: "Overview of group management in the CometChat JavaScript SDK including group types, member roles, and available operations." --- -{/* TL;DR for Agents and Quick Reference */} -Choose your path: -- **Create a Group** → [Create Group](/sdk/javascript/create-group) -- **Join a Group** → [Join Group](/sdk/javascript/join-group) -- **Retrieve Groups** → [Retrieve Groups](/sdk/javascript/retrieve-groups) -- **Manage Members** → [Add](/sdk/javascript/group-add-members) | [Kick/Ban](/sdk/javascript/group-kick-ban-members) | [Change Scope](/sdk/javascript/group-change-member-scope) -- **Update/Delete** → [Update Group](/sdk/javascript/update-group) | [Delete Group](/sdk/javascript/delete-group) +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-javascript` | +| Key Classes | `CometChat.Group` | +| Group Types | `PUBLIC`, `PRIVATE`, `PASSWORD` | +| Member Roles | `owner`, `admin`, `moderator`, `participant` | +| Key Methods | `createGroup()`, `joinGroup()`, `leaveGroup()`, `deleteGroup()` | +| Prerequisites | SDK initialized, user logged in | +| Related | [Create Group](/sdk/javascript/create-group), [Join Group](/sdk/javascript/join-group), [Retrieve Groups](/sdk/javascript/retrieve-groups) | + Groups help your users to converse together in a single space. You can have three types of groups- private, public and password protected. diff --git a/sdk/javascript/receive-message.mdx b/sdk/javascript/receive-message.mdx index d1cad6e87..09eab272f 100644 --- a/sdk/javascript/receive-message.mdx +++ b/sdk/javascript/receive-message.mdx @@ -3,31 +3,18 @@ title: "Receive A Message" description: "Receive real-time messages, fetch missed and unread messages, retrieve message history, search messages, and get unread counts using the CometChat JavaScript SDK." --- -{/* TL;DR for Agents and Quick Reference */} -```javascript -// Listen for real-time messages -CometChat.addMessageListener("LISTENER_ID", new CometChat.MessageListener({ - onTextMessageReceived: (msg) => {}, - onMediaMessageReceived: (msg) => {}, - onCustomMessageReceived: (msg) => {} -})); - -// Fetch missed messages (while app was offline) -const latestId = await CometChat.getLastDeliveredMessageId(); -const request = new CometChat.MessagesRequestBuilder() - .setUID("UID").setMessageId(latestId).setLimit(30).build(); -const messages = await request.fetchNext(); - -// Fetch message history -const request = new CometChat.MessagesRequestBuilder() - .setUID("UID").setLimit(30).build(); -const messages = await request.fetchPrevious(); - -// Get unread message count -const counts = await CometChat.getUnreadMessageCount(); -``` +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-javascript` | +| Key Classes | `CometChat.MessageListener`, `CometChat.MessagesRequestBuilder` | +| Listener Events | `onTextMessageReceived`, `onMediaMessageReceived`, `onCustomMessageReceived` | +| Key Methods | `addMessageListener()`, `fetchPrevious()`, `fetchNext()`, `getUnreadMessageCount()` | +| Prerequisites | SDK initialized, user logged in, listener registered | +| Related | [Send Message](/sdk/javascript/send-message), [Delivery & Read Receipts](/sdk/javascript/delivery-read-receipts) | + + Receiving messages with CometChat has two parts: diff --git a/sdk/javascript/send-message.mdx b/sdk/javascript/send-message.mdx index 885698891..4a43fa3dd 100644 --- a/sdk/javascript/send-message.mdx +++ b/sdk/javascript/send-message.mdx @@ -3,26 +3,18 @@ title: "Send A Message" description: "Send text, media, and custom messages to users and groups using the CometChat JavaScript SDK. Includes metadata, tags, quoted messages, and multiple attachments." --- -{/* TL;DR for Agents and Quick Reference */} -```javascript -// Send text message to user -const msg = new CometChat.TextMessage("UID", "Hello!", CometChat.RECEIVER_TYPE.USER); -await CometChat.sendMessage(msg); - -// Send text message to group -const msg = new CometChat.TextMessage("GUID", "Hello!", CometChat.RECEIVER_TYPE.GROUP); -await CometChat.sendMessage(msg); +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-javascript` | +| Key Classes | `CometChat.TextMessage`, `CometChat.MediaMessage`, `CometChat.CustomMessage` | +| Key Methods | `CometChat.sendMessage()`, `CometChat.sendMediaMessage()`, `CometChat.sendCustomMessage()` | +| Receiver Types | `CometChat.RECEIVER_TYPE.USER`, `CometChat.RECEIVER_TYPE.GROUP` | +| Message Types | `TEXT`, `IMAGE`, `VIDEO`, `AUDIO`, `FILE`, `CUSTOM` | +| Prerequisites | SDK initialized, user logged in | +| Related | [Receive Message](/sdk/javascript/receive-message), [Edit Message](/sdk/javascript/edit-message), [Delete Message](/sdk/javascript/delete-message) | -// Send media message -const msg = new CometChat.MediaMessage("UID", file, CometChat.MESSAGE_TYPE.IMAGE, CometChat.RECEIVER_TYPE.USER); -await CometChat.sendMediaMessage(msg); - -// Send custom message -const msg = new CometChat.CustomMessage("UID", CometChat.RECEIVER_TYPE.USER, "customType", { key: "value" }); -await CometChat.sendCustomMessage(msg); -``` Using CometChat, you can send three types of messages: From 053a3a0ee94b8b042e114546902ea8b9bdb43cec Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 18 Mar 2026 12:03:18 +0530 Subject: [PATCH 16/43] deletes extra files --- node_modules/.package-lock.json | 13 ------------- node_modules/22/README.md | 1 - node_modules/22/package.json | 11 ----------- package-lock.json | 18 ------------------ package.json | 5 ----- 5 files changed, 48 deletions(-) delete mode 100644 node_modules/.package-lock.json delete mode 100644 node_modules/22/README.md delete mode 100644 node_modules/22/package.json delete mode 100644 package-lock.json delete mode 100644 package.json diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json deleted file mode 100644 index b9f3c6ed9..000000000 --- a/node_modules/.package-lock.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "docs", - "lockfileVersion": 3, - "requires": true, - "packages": { - "node_modules/22": { - "version": "0.0.0", - "resolved": "https://registry.npmjs.org/22/-/22-0.0.0.tgz", - "integrity": "sha512-MdBPNDaCFY4fZVpp14n3Mt4isZ2yS1DrIiOig/iMLljr4zDa0g/583xf/lFXNPwhxCfGKYvyWJSrYyS8jNk2mQ==", - "license": "MIT" - } - } -} diff --git a/node_modules/22/README.md b/node_modules/22/README.md deleted file mode 100644 index 311c8dd06..000000000 --- a/node_modules/22/README.md +++ /dev/null @@ -1 +0,0 @@ -PLACEHOLDER \ No newline at end of file diff --git a/node_modules/22/package.json b/node_modules/22/package.json deleted file mode 100644 index f3cf8f650..000000000 --- a/node_modules/22/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "22", - "version": "0.0.0", - "description": "PLACEHOLDER", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "author": "Houfeng", - "license": "MIT" -} diff --git a/package-lock.json b/package-lock.json deleted file mode 100644 index e374029e1..000000000 --- a/package-lock.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "docs", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "dependencies": { - "22": "^0.0.0" - } - }, - "node_modules/22": { - "version": "0.0.0", - "resolved": "https://registry.npmjs.org/22/-/22-0.0.0.tgz", - "integrity": "sha512-MdBPNDaCFY4fZVpp14n3Mt4isZ2yS1DrIiOig/iMLljr4zDa0g/583xf/lFXNPwhxCfGKYvyWJSrYyS8jNk2mQ==", - "license": "MIT" - } - } -} diff --git a/package.json b/package.json deleted file mode 100644 index 08836e674..000000000 --- a/package.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "dependencies": { - "22": "^0.0.0" - } -} From b0e8a6e6262756fbb6b090a1fb36cc37995fcd79 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 18 Mar 2026 14:11:55 +0530 Subject: [PATCH 17/43] SDK intialisation and Overview pages --- docs.json | 7 +- sdk/javascript/initialization.mdx | 195 +++++++ sdk/javascript/installation.mdx | 59 +++ sdk/javascript/overview.mdx | 725 +++------------------------ sdk/javascript/setup-sdk.mdx | 280 +++-------- sdk/javascript/ssr-compatibility.mdx | 293 +++++++++++ 6 files changed, 681 insertions(+), 878 deletions(-) create mode 100644 sdk/javascript/initialization.mdx create mode 100644 sdk/javascript/installation.mdx create mode 100644 sdk/javascript/ssr-compatibility.mdx diff --git a/docs.json b/docs.json index 6a9b2ec95..53ac6f904 100644 --- a/docs.json +++ b/docs.json @@ -2500,7 +2500,12 @@ }, { "group": "Setup", - "pages": ["sdk/javascript/setup-sdk"] + "pages": [ + "sdk/javascript/setup-sdk", + "sdk/javascript/installation", + "sdk/javascript/initialization", + "sdk/javascript/ssr-compatibility" + ] }, { "group": "Authentication", diff --git a/sdk/javascript/initialization.mdx b/sdk/javascript/initialization.mdx new file mode 100644 index 000000000..4508c205a --- /dev/null +++ b/sdk/javascript/initialization.mdx @@ -0,0 +1,195 @@ +--- +title: "Initialization" +description: "Configure and initialize the CometChat JavaScript SDK with your App ID and settings." +--- + +The `init()` method initializes the SDK and must be called before any other CometChat method. Call it once at app startup, typically in your entry file (`index.js`, `main.js`, or `App.js`). + +## Basic Initialization + + + +```javascript +let appID = "APP_ID"; +let region = "APP_REGION"; + +let appSetting = new CometChat.AppSettingsBuilder() + .subscribePresenceForAllUsers() + .setRegion(region) + .autoEstablishSocketConnection(true) + .build(); + +CometChat.init(appID, appSetting).then( + () => { + console.log("Initialization completed successfully"); + }, + (error) => { + console.log("Initialization failed with error:", error); + } +); +``` + + + + +```typescript +let appID: string = "APP_ID"; +let region: string = "APP_REGION"; + +let appSetting: CometChat.AppSettings = new CometChat.AppSettingsBuilder() + .subscribePresenceForAllUsers() + .setRegion(region) + .autoEstablishSocketConnection(true) + .build(); + +CometChat.init(appID, appSetting).then( + (initialized: boolean) => { + console.log("Initialization completed successfully", initialized); + }, + (error: CometChat.CometChatException) => { + console.log("Initialization failed with error:", error); + } +); +``` + + + + +```javascript +let appID = "APP_ID"; +let region = "APP_REGION"; + +let appSetting = new CometChat.AppSettingsBuilder() + .subscribePresenceForAllUsers() + .setRegion(region) + .autoEstablishSocketConnection(true) + .build(); + +try { + await CometChat.init(appID, appSetting); + console.log("Initialization completed successfully"); +} catch (error) { + console.log("Initialization failed with error:", error); +} +``` + + + + + +Replace `APP_ID` with your CometChat App ID and `APP_REGION` with your Region from the [Dashboard](https://app.cometchat.com). + + +`CometChat.init()` must be called before any other SDK method. Calling `login()`, `sendMessage()`, or registering listeners before `init()` will fail. + + +## Parameters + +| Parameter | Type | Description | +|-----------|------|-------------| +| appID | string | Your CometChat App ID | +| appSetting | AppSettings | Configuration object built with AppSettingsBuilder | + +## AppSettings Options + +| Method | Description | Default | +|--------|-------------|---------| +| `setRegion(region)` | Region where your app was created (`us`, `eu`, `in`, `in-private`) | Required | +| `subscribePresenceForAllUsers()` | Subscribe to presence events for all users | — | +| `subscribePresenceForRoles(roles)` | Subscribe to presence for specific roles | — | +| `subscribePresenceForFriends()` | Subscribe to presence for friends only | — | +| `autoEstablishSocketConnection(bool)` | Let SDK manage WebSocket connections | `true` | +| `overrideAdminHost(adminHost)` | Custom admin URL (dedicated deployment) | — | +| `overrideClientHost(clientHost)` | Custom client URL (dedicated deployment) | — | +| `setStorageMode(storageMode)` | Local storage mode (`CometChat.StorageMode.SESSION` for session storage) | — | + +### Presence Subscription + +Choose how to subscribe to user presence (online/offline status): + +```javascript +// All users +new CometChat.AppSettingsBuilder() + .subscribePresenceForAllUsers() + .setRegion(region) + .build(); + +// Specific roles +new CometChat.AppSettingsBuilder() + .subscribePresenceForRoles(["admin", "moderator"]) + .setRegion(region) + .build(); + +// Friends only +new CometChat.AppSettingsBuilder() + .subscribePresenceForFriends() + .setRegion(region) + .build(); +``` + +See [User Presence](/sdk/javascript/user-presence) for more details. + +### WebSocket Connection + +By default, the SDK manages WebSocket connections automatically. To manage them manually: + +```javascript +let appSetting = new CometChat.AppSettingsBuilder() + .setRegion(region) + .autoEstablishSocketConnection(false) + .build(); +``` + +See [Managing WebSocket Connections](/sdk/javascript/managing-web-sockets-connections-manually) for manual control. + +### Session Storage + +Use session storage instead of local storage (data clears when browser closes): + +```javascript +let appSetting = new CometChat.AppSettingsBuilder() + .setRegion(region) + .setStorageMode(CometChat.StorageMode.SESSION) + .build(); +``` + +## Best Practices + + + + Call `CometChat.init()` as early as possible in your application lifecycle. It only needs to be called once per session. + + + After initialization, use `CometChat.getLoggedinUser()` to check if a session exists before calling `login()`. + + + Store App ID, Region, and Auth Key in environment variables rather than hardcoding them. + + + +## Troubleshooting + + + + Verify your App ID matches the one in your [CometChat Dashboard](https://app.cometchat.com). Check that you're using the correct region. + + + Ensure `init()` completes successfully before calling other SDK methods. Wait for the Promise to resolve. + + + Corporate firewalls may block WebSocket connections. Check your network configuration or try [manual WebSocket management](/sdk/javascript/managing-web-sockets-connections-manually). + + + +--- + +## Next Steps + + + + Log in users with Auth Key or Auth Token + + + Setup for Next.js, Nuxt, and Ionic + + diff --git a/sdk/javascript/installation.mdx b/sdk/javascript/installation.mdx new file mode 100644 index 000000000..c0ece3d34 --- /dev/null +++ b/sdk/javascript/installation.mdx @@ -0,0 +1,59 @@ +--- +title: "Installation" +description: "Add the CometChat JavaScript SDK to your project using npm or CDN." +--- + +## Package Manager + +Install the SDK using npm: + +```bash +npm install @cometchat/chat-sdk-javascript +``` + +Then import the `CometChat` object wherever you need it: + +```javascript +import { CometChat } from "@cometchat/chat-sdk-javascript"; +``` + +## CDN + +Include the CometChat JavaScript library directly in your HTML: + +```html + +``` + +When using the CDN, `CometChat` is available as a global variable. + +## Get Your Credentials + +Before initializing the SDK, get your credentials from the [CometChat Dashboard](https://app.cometchat.com): + +1. Sign up or log in +2. Create a new app (or use an existing one) +3. Go to **API & Auth Keys** and note your: + - App ID + - Region + - Auth Key + + +**Auth Key** is for development/testing only. In production, generate **Auth Tokens** on your server using the REST API. Never expose Auth Keys in production client code. + + +--- + +## Next Steps + + + + Configure and initialize the SDK + + + Setup for Next.js, Nuxt, and Ionic + + diff --git a/sdk/javascript/overview.mdx b/sdk/javascript/overview.mdx index 8a0cecc1a..b0059c9eb 100644 --- a/sdk/javascript/overview.mdx +++ b/sdk/javascript/overview.mdx @@ -1,683 +1,96 @@ --- -title: "Overview" -description: "Get started with the CometChat JavaScript SDK — install, initialize, create users, log in, and integrate UI Kits or Chat Widget." +title: "JavaScript SDK" +sidebarTitle: "Overview" +description: "Add real-time chat, voice, and video to your JavaScript application with the CometChat SDK." --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Setup Reference** +The CometChat JavaScript SDK enables you to add real-time messaging, voice, and video calling capabilities to any JavaScript application — whether it's a web app built with React, Angular, Vue, or vanilla JavaScript. -```bash -# Install -npm install @cometchat/chat-sdk-javascript -``` +## What You Can Build -```javascript -// Initialize (run once at app start) -const appSettings = new CometChat.AppSettingsBuilder().setRegion("REGION").subscribePresenceForAllUsers().build(); -await CometChat.init("APP_ID", appSettings); +- One-on-one and group messaging +- Voice and video calling +- Typing indicators and read receipts +- User presence (online/offline status) +- Message reactions and threads +- File and media sharing +- Push notifications -// Login -await CometChat.login("UID", "AUTH_KEY"); // Dev only -await CometChat.login(AUTH_TOKEN); // Production -``` +## Requirements -**Required Credentials:** App ID, Region, Auth Key (dev) or Auth Token (prod) -**Get from:** [CometChat Dashboard](https://app.cometchat.com) → Your App → API & Auth Keys - +| Requirement | Version | +|-------------|---------| +| npm | 8.x or above | +| Node.js | 16 or above | -This guide demonstrates how to add chat to a JavaScript application using CometChat. Before you begin, we strongly recommend you read the [Key Concepts](/sdk/javascript/key-concepts) guide. +The SDK works in all modern browsers (Chrome, Firefox, Safari, Edge) and can be used with SSR frameworks like Next.js and Nuxt. -#### I want to integrate with my app +## Getting Started -1. [Get your application keys](overview#get-your-application-keys) -2. [Add the CometChat dependency](overview#add-the-cometchat-dependency) -3. [Initialize CometChat](overview#initialize-cometchat) -4. [Register and Login your user](overview#register-and-login-your-user) -5. [Integrate our UI Kits](overview#integrate-our-ui-kits) -6. [Integrate our Chat Widget](overview#integrate-our-chat-widget) + + + [Sign up for CometChat](https://app.cometchat.com) and create an app. Note your App ID, Region, and Auth Key from the Dashboard. + + + Add the SDK to your project and initialize it with your credentials. See [Setup SDK](/sdk/javascript/setup-sdk). + + + Log in users with Auth Key (development) or Auth Token (production). See [Authentication](/sdk/javascript/authentication-overview). + + + Send and receive messages in real-time. See [Send Messages](/sdk/javascript/send-message). + + -#### I want to explore a sample app (includes UI) +## Sample Apps -Open the app folder in your favorite code editor and follow the steps mentioned in the `README.md` file. +Explore working examples with full source code: -[React Sample App](https://github.com/cometchat-pro/javascript-react-chat-app) - -[Angular Sample App](https://github.com/cometchat-pro/javascript-angular-chat-app) - -[Vue Sample App](https://github.com/cometchat-pro/javascript-vue-chat-app) - -### Get your Application Keys - -[Signup for CometChat](https://app.cometchat.com) and then: - -1. Create a new app -2. Head over to the **API & Auth Keys** section and note the **Auth Key**, **App ID** & **Region** - -## Add the CometChat Dependency - -### NPM - - - -```js - npm install @cometchat/chat-sdk-javascript -``` - - - - - -Then, import the `CometChat` object wherever you want to use CometChat. - - - -```js - import { CometChat } from "@cometchat/chat-sdk-javascript"; -``` - - - - - -### HTML (via CDN) - -Include the CometChat JavaScript library in your HTML code - - - -```html - -``` - - - - - -### Server Side Rendering (SSR) Compatibility - - -**Server-Side Rendering (SSR):** CometChat SDK requires browser APIs (`window`, `WebSocket`). For Next.js, Nuxt, or other SSR frameworks, initialize the SDK only on the client side using dynamic imports or `useEffect`. See the examples below. - - -You can use CometChat with SSR frameworks such as [Next.js](https://nextjs.org/) or [NuxtJS](https://nuxtjs.org/) by importing it dynamically on the client side. - -#### Next.js - -You need to import the CometChat SDK dynamically in the `useEffect` React Hook or `componentDidMount()` lifecycle method. - - - -```javascript -import React from "react"; -import Chat from "./Chat"; - -export default function Home() { - let [libraryImported, setLibraryImported] = React.useState(false); - - React.useEffect(() => { - window.CometChat = require("@cometchat/chat-sdk-javascript").CometChat; - setLibraryImported(true); - }); - - return libraryImported ? :

Loading....

; -} -``` - -
- - -```javascript -import React from 'react'; -import Chat from './Chat'; - -export default class Home extends React.Component { - -constructor(props) { - super(props); - this.state = { - libraryImported: false - }; -} - -componentDidMount(){ - CometChat = require("@cometchat/chat-sdk-javascript").CometChat; - this.setState({libraryImported: true}); -} - -return( - this.state.libraryImported ? :

Loading....

-) - -} -``` - -
- - -```javascript -import React, { Component } from "react"; - -import { COMETCHAT_CONSTANTS } from "./CONSTS"; - -export default class Chat extends Component { - constructor(props) { - super(props); - this.state = { - user: undefined, - }; - } - - componentDidMount() { - this.init(); - } - - init() { - CometChat.init( - COMETCHAT_CONSTANTS.APP_ID, - new CometChat.AppSettingsBuilder() - .setRegion(COMETCHAT_CONSTANTS.REGION) - .subscribePresenceForAllUsers() - .build() - ).then( - () => { - this.login(); - }, - (error) => { - console.log("Init failed with exception:", error); - } - ); - } - - login() { - let UID = "UID"; - CometChat.login(UID, COMETCHAT_CONSTANTS.AUTH_KEY).then( - (user) => { - this.setState({ user }); - }, - (error) => { - console.log("Login failed with exception:", error); - } - ); - } - - render() { - return this.state.user ? ( -
User logged in
- ) : ( -
User not logged in
- ); - } -} -``` - -
- - -```javascript -export const COMETCHAT_CONSTANTS = { - APP_ID: "APP_ID", - REGION: "REGION", - AUTH_KEY: "AUTH_KEY", -}; -``` - - - -
- -#### NuxtJS - -You need to import the CometChat SDK dynamically in the `mounted` lifecycle hook. - - - -```javascript - - - -``` - - - - -```javascript - - - -``` - - - - -```javascript -module.exports = { - APP_ID: "APP_ID", - REGION: "REGION", - AUTH_KEY: "AUTH_KEY", -}; -``` - - - - - -#### Ionic/Cordova - -For Ionic and Cordova applications, you can use the JavaScript SDK directly. Import the CometChat SDK in your component or service: - - - -```typescript -import { Component, OnInit } from '@angular/core'; -import { CometChat } from '@cometchat/chat-sdk-javascript'; - -@Component({ - selector: 'app-root', - templateUrl: 'app.component.html', -}) -export class AppComponent implements OnInit { - - ngOnInit() { - this.initCometChat(); - } - - initCometChat() { - const appID = 'APP_ID'; - const region = 'APP_REGION'; - - const appSetting = new CometChat.AppSettingsBuilder() - .subscribePresenceForAllUsers() - .setRegion(region) - .autoEstablishSocketConnection(true) - .build(); - - CometChat.init(appID, appSetting).then( - () => { - console.log('CometChat initialized successfully'); - }, - (error) => { - console.log('CometChat initialization failed:', error); - } - ); - } -} -``` - - - - - - - -The dedicated Ionic Cordova SDK has been deprecated. For new Ionic/Cordova applications, use the JavaScript SDK as shown above. Existing users of the Ionic SDK can refer to the [legacy documentation](/sdk/ionic-legacy/overview) for reference. - - - -## Initialize CometChat - -The `init()` method initializes the settings required for CometChat. The `init()` method takes the below parameters: - -1. appID - Your CometChat App ID -2. appSettings - An object of the AppSettings class can be created using the AppSettingsBuilder class. The region field is mandatory and can be set using the `setRegion()` method. - -The `AppSettings` class allows you to configure the following settings: - -* **Region**: The region where your app was created. -* [Presence Subscription](/sdk/javascript/user-presence): Represents the subscription type for user presence (real-time online/offline status) -* **autoEstablishSocketConnection(boolean value)**: This property takes a boolean value which when set to `true` informs the SDK to manage the web-socket connection internally. If set to `false`, it informs the SDK that the web-socket connection will be managed manually. The default value for this parameter is true. For more information on this, please check the [Managing Web-Socket connections manually](/sdk/javascript/managing-web-sockets-connections-manually) section. The default value for this property is **true.** -* **overrideAdminHost(adminHost: string)**: This method takes the admin URL as input and uses this admin URL instead of the default admin URL. This can be used in case of dedicated deployment of CometChat. -* **overrideClientHost(clientHost: string)**: This method takes the client URL as input and uses this client URL instead of the default client URL. This can be used in case of dedicated deployment of CometChat. -* **setStorageMode(storageMode)**: This method allows you to configure how CometChat stores data locally. The storageMode parameter can be set to `CometChat.StorageMode.SESSION` to use session storage, which persists data only for the current browser session, or other available storage modes for different persistence behaviors. - -You need to call `init()` before calling any other method from CometChat. We suggest you call the `init()` method on app startup, preferably in the `index.js` file. - - - -```js -let appID = "APP_ID"; -let region = "APP_REGION"; -let appSetting = new CometChat.AppSettingsBuilder() - .subscribePresenceForAllUsers() - .setRegion(region) - .autoEstablishSocketConnection(true) - .setStorageMode(CometChat.StorageMode.SESSION) - .build(); -CometChat.init(appID, appSetting).then( - () => { - console.log("Initialization completed successfully"); - }, - (error) => { - console.log("Initialization failed with error:", error); - } -); -``` - - - - -```typescript -let appID: string = "APP_ID", - region: string = "APP_REGION", - appSetting: CometChat.AppSettings = new CometChat.AppSettingsBuilder() - .subscribePresenceForAllUsers() - .setRegion(region) - .autoEstablishSocketConnection(true) - .setStorageMode(CometChat.StorageMode.SESSION) - .build(); -CometChat.init(appID, appSetting).then( - (initialized: boolean) => { - console.log("Initialization completed successfully", initialized); - }, (error: CometChat.CometChatException) => { - console.log("Initialization failed with error:", error); - } -); -``` - - - - -```javascript -let appID = "APP_ID"; -let region = "APP_REGION"; -let appSetting = new CometChat.AppSettingsBuilder() - .subscribePresenceForAllUsers() - .setRegion(region) - .autoEstablishSocketConnection(true) - .setStorageMode(CometChat.StorageMode.SESSION) - .build(); - -try { - await CometChat.init(appID, appSetting); - console.log("Initialization completed successfully"); -} catch (error) { - console.log("Initialization failed with error:", error); -} -``` - - - - - -Make sure you replace the `APP_ID` with your CometChat **App ID** and `APP_REGION` with your **App Region** in the above code. - - -`CometChat.init()` must be called before any other SDK method. Calling `login()`, `sendMessage()`, or registering listeners before `init()` will fail. - - - -**Auth Key** is for development/testing only. In production, generate **Auth Tokens** on your server using the REST API and pass them to the client. Never expose Auth Keys in production client code. - - -## Register and Login your user - -Once initialization is successful, you will need to create a user. To create users on the fly, you can use the `createUser()` method. This method takes a `User` object and the `Auth Key` as input parameters and returns the created `User` object if the request is successful. - - - -```js -const authKey = "AUTH_KEY"; -const UID = "user1"; -const name = "Kevin"; - -const user = new CometChat.User(UID); - -user.setName(name); - -CometChat.createUser(user, authKey).then( - (user) => { - console.log("user created", user); - }, - (error) => { - console.log("error", error); - } -); -``` - - - - -```typescript -let authKey: string = "AUTH_KEY", - UID: string = "user1", - name: string = "Kevin"; - -const user = new CometChat.User(UID); - -user.setName(name); - -CometChat.createUser(user, authKey).then( - (user: CometChat.User) => { - console.log("user created", user); - }, - (error: CometChat.CometChatException) => { - console.log("error", error); - } -); -``` - - - - -```javascript -const authKey = "AUTH_KEY"; -const UID = "user1"; -const name = "Kevin"; - -const user = new CometChat.User(UID); -user.setName(name); - -try { - const createdUser = await CometChat.createUser(user, authKey); - console.log("user created", createdUser); -} catch (error) { - console.log("error", error); -} -``` - - - - - -Make sure that `UID` and `name` are specified as these are mandatory fields to create a user. - -Once you have created the user successfully, you will need to log the user into CometChat using the `login()` method. - -We recommend you call the CometChat `login()` method once your user logs into your app. The `login()` method needs to be called only once. - - - -This straightforward authentication method is ideal for proof-of-concept (POC) development or during the early stages of application development. For production environments, however, we strongly recommend using an [Auth Token](/sdk/javascript/authentication-overview#login-using-auth-token) instead of an Auth Key to ensure enhanced security. - - - - - -```js -const UID = "cometchat-uid-1"; -const authKey = "AUTH_KEY"; - -CometChat.getLoggedinUser().then( - (user) => { - if (!user) { - CometChat.login(UID, authKey).then( - (user) => { - console.log("Login Successful:", { user }); - }, - (error) => { - console.log("Login failed with exception:", { error }); - } - ); - } - }, - (error) => { - console.log("Some Error Occured", { error }); - } -); -``` - - - - -```typescript -const UID: string = "cometchat-uid-1"; -const authKey: string = "AUTH_KEY"; - -CometChat.getLoggedinUser().then( - (user: CometChat.User) => { - if (!user) { - CometChat.login(UID, authKey).then( - (user: CometChat.User) => { - console.log("Login Successful:", { user }); - }, - (error: CometChat.CometChatException) => { - console.log("Login failed with exception:", { error }); - } - ); - } - }, - (error: CometChat.CometChatException) => { - console.log("Some Error Occured", { error }); - } -); -``` - - - - -```javascript -const UID = "cometchat-uid-1"; -const authKey = "AUTH_KEY"; - -try { - const loggedInUser = await CometChat.getLoggedinUser(); - if (!loggedInUser) { - const user = await CometChat.login(UID, authKey); - console.log("Login Successful:", { user }); - } -} catch (error) { - console.log("Login failed with exception:", { error }); -} -``` - - - - - -Make sure you replace the `AUTH_KEY` with your CometChat **AuthKey** in the above code. - - -Sample Users - -We have set up 5 users for testing having UIDs: `cometchat-uid-1`, `cometchat-uid-2`, `cometchat-uid-3`, `cometchat-uid-4` and `cometchat-uid-5`. - - - -The `login()` method returns the `User` object on `Promise` resolved containing all the information of the logged-in user. - - - -UID can be alphanumeric with an underscore and hyphen. Spaces, punctuation and other special characters are not allowed. - - - -## Integrate our UI Kits - -* Please refer to the section to integrate [React UI Kit](/ui-kit/react/overview) into your website. -* Please refer to the section to integrate [Angular UI Kit](/ui-kit/angular/overview) into your website. -* Please refer to the section to integrate [Vue UI Kit](/ui-kit/vue/overview) into your website. - -## Integrate our Chat Widget + + + React sample app + + + Angular sample app + + + Vue sample app + + -* Please refer to the section to integrate [Chat Widget](/widget/html-bootstrap-jquery) into your Website. +## UI Kits - -- **Initialize once at app start** — Call `CometChat.init()` only once, preferably in your app's entry point (index.js, App.js, or main.ts) -- **Check login state first** — Always call `getLoggedinUser()` before `login()` to avoid unnecessary login attempts -- **Use Auth Tokens in production** — Never expose Auth Keys in production client code. Generate Auth Tokens on your server. -- **Handle SSR correctly** — For Next.js, Nuxt, or other SSR frameworks, initialize CometChat only on the client side using dynamic imports or `useEffect` -- **Store credentials securely** — Keep App ID, Region, and Auth Keys in environment variables, not hardcoded in source code - +Skip the UI work and use our pre-built components: - -- **"SDK not initialized" error** — Ensure `CometChat.init()` is called and completes successfully before any other SDK method -- **Login fails with invalid credentials** — Verify your App ID, Region, and Auth Key match your CometChat Dashboard settings -- **SSR hydration errors** — CometChat requires browser APIs. Use dynamic imports or `useEffect` to initialize only on the client side -- **User not found on login** — The UID must exist. Create the user first with `createUser()` or via the Dashboard/REST API -- **WebSocket connection issues** — Check if `autoEstablishSocketConnection` is set correctly. For manual control, see [Managing WebSocket Connections](/sdk/javascript/managing-web-sockets-connections-manually) + + + Ready-to-use React components + + + Ready-to-use Angular components + + + Ready-to-use Vue components + + -For more issues, see the [Troubleshooting Guide](/sdk/javascript/troubleshooting). - +## Chat Widget ---- +For the fastest integration, embed our [Chat Widget](/widget/html-bootstrap-jquery) with just a few lines of code — no SDK knowledge required. -## Next Steps +## Resources - Understand UIDs, GUIDs, auth tokens, and more + Understand UIDs, GUIDs, auth tokens, and core concepts - - Learn about login methods and auth token generation + + See what's new in the latest SDK version - - Send your first text or media message + + Migration guide for V3 users - - Listen for incoming messages in real time + + Common issues and solutions diff --git a/sdk/javascript/setup-sdk.mdx b/sdk/javascript/setup-sdk.mdx index 342b8f4b3..b9a70607b 100644 --- a/sdk/javascript/setup-sdk.mdx +++ b/sdk/javascript/setup-sdk.mdx @@ -1,254 +1,92 @@ --- title: "Setup" sidebarTitle: "Overview" -description: "Install, configure, and initialize the CometChat JavaScript SDK in your application using npm or CDN." +description: "Install, configure, and initialize the CometChat JavaScript SDK in your application." --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Setup Reference** +This section covers everything you need to get the CometChat JavaScript SDK running in your application. -```bash -# Install -npm install @cometchat/chat-sdk-javascript -``` - -```javascript -import { CometChat } from "@cometchat/chat-sdk-javascript"; - -// Initialize (run once at app start) -const appSettings = new CometChat.AppSettingsBuilder() - .subscribePresenceForAllUsers() - .setRegion("REGION") - .autoEstablishSocketConnection(true) - .build(); -await CometChat.init("APP_ID", appSettings); -``` +## Prerequisites -**Required:** App ID, Region from [CometChat Dashboard](https://app.cometchat.com) → API & Auth Keys - - -Migrating app version from v3 to v4 ? +| Requirement | Version | +|-------------|---------| +| npm | 8.x or above | +| Node.js | 16 or above | -Skip the create new app step. Your existing v3 app can be migrated to v4. +You'll also need your credentials from the [CometChat Dashboard](https://app.cometchat.com): +- App ID +- Region +- Auth Key (for development) -Follow steps mentioned in **Add the CometChat dependency** section below to upgrade to latest version of v4 +## Setup Steps - + + + Add the CometChat SDK to your project via npm or CDN. See [Installation](/sdk/javascript/installation). + + + Configure and initialize the SDK with your App ID and Region. See [Initialization](/sdk/javascript/initialization). + + + Log in users to start sending and receiving messages. See [Authentication](/sdk/javascript/authentication-overview). + + -## Get your Application Keys +## Framework Guides -[Signup for CometChat](https://app.cometchat.com) and then: +Using an SSR framework? The SDK requires browser APIs and needs client-side initialization: -1. Create a new app -2. Head over to the **API & Auth Keys** section and note the **Auth Key**, **App ID** & **Region** + + + Dynamic imports with useEffect + + + Client-side mounted hook + + + Direct SDK usage + + -## Add the CometChat Dependency + +Migrating from V3 to V4? Your existing app can be migrated — no need to create a new one. See [Upgrading from V3](/sdk/javascript/upgrading-from-v3). + -### Package Manager +## Quick Reference - - ```bash +# Install npm install @cometchat/chat-sdk-javascript ``` - - - - -Then, import the `CometChat` object wherever you want to use CometChat. - - - -```js +```javascript import { CometChat } from "@cometchat/chat-sdk-javascript"; -``` - - - - - -### HTML (via CDN) - -Include the CometChat JavaScript library in your HTML code. - - - -``` - -``` - - - - -## Initialize CometChat - -The `init()` method initialises the settings required for CometChat. The `init()` method takes the below parameters: - -1. appID - You CometChat App ID -2. appSettings - An object of the AppSettings class can be created using the AppSettingsBuilder class. The region field is mandatory and can be set using the `setRegion()` method. - -The `AppSettings` class allows you to configure two settings: - -* **Region**: The region where you app was created. -* [Presence Subscription](/sdk/javascript/user-presence)**:** Represents the subscription type for user presence (real-time online/offline status) -* **autoEstablishSocketConnection(boolean value)**: This property takes a boolean value which when set to `true` informs the SDK to manage the web-socket connection internally. If set to `false` , it informs the SDK that the web-socket connection will be managed manually. The default value for this parameter is true. For more information on this, please check the [Managing Web-Socket connections manually](/sdk/javascript/managing-web-sockets-connections-manually) section. The default value for this property is **true.** -* **overrideAdminHost(adminHost: string)**: This method takes the admin URL as input and uses this admin URL instead of the default admin URL. This can be used in case of dedicated deployment of CometChat. -* **overrideClientHost(clientHost: string)**: This method takes the client URL as input and uses this client URL instead of the default client URL. This can be used in case of dedicated deployment of CometChat. - -You need to call `init()` before calling any other method from CometChat. We suggest you call the `init()` method on app startup, preferably in the `index.js` file. - - - -```js -let appID = "APP_ID"; -let region = "APP_REGION"; -let appSetting = new CometChat.AppSettingsBuilder() +// Initialize +const appSettings = new CometChat.AppSettingsBuilder() + .setRegion("REGION") .subscribePresenceForAllUsers() - .setRegion(region) - .autoEstablishSocketConnection(true) .build(); -CometChat.init(appID, appSetting).then( - () => { - console.log("Initialization completed successfully"); - }, - (error) => { - console.log("Initialization failed with error:", error); - } -); -``` - - - - -```typescript -let appID: string = "APP_ID", - region: string = "APP_REGION", - appSetting: CometChat.AppSettings = new CometChat.AppSettingsBuilder() - .subscribePresenceForAllUsers() - .setRegion(region) - .autoEstablishSocketConnection(true) - .build(); -CometChat.init(appID, appSetting).then( - (initialized: boolean) => { - console.log("Initialization completed successfully", initialized); - }, - (error: CometChat.CometChatException) => { - console.log("Initialization failed with error:", error); - } -); -``` - - - -```javascript -let appID = "APP_ID"; -let region = "APP_REGION"; -let appSetting = new CometChat.AppSettingsBuilder() - .subscribePresenceForAllUsers() - .setRegion(region) - .autoEstablishSocketConnection(true) - .build(); +await CometChat.init("APP_ID", appSettings); -try { - await CometChat.init(appID, appSetting); - console.log("Initialization completed successfully"); -} catch (error) { - console.log("Initialization failed with error:", error); -} +// Login +await CometChat.login("UID", "AUTH_KEY"); ``` - - - - -Make sure you replace the `APP_ID` with your CometChat **App ID** and `APP_REGION` with your **App Region** in the above code. - - -`CometChat.init()` must be called before any other SDK method. Calling `login()`, `sendMessage()`, or registering listeners before `init()` will fail. - - - -**Auth Key** is for development/testing only. In production, generate **Auth Tokens** on your server using the REST API and pass them to the client. Never expose Auth Keys in production client code. - - -| Parameter | Description | -| ---------- | ----------------------------------- | -| appID | CometChat App ID | -| appSetting | An object of the AppSettings class. | - -### AppSettings Configuration Options - -| Method | Description | Default | -| --- | --- | --- | -| `setRegion(region)` | The region where your app was created (`us`, `eu`, `in`, `in-private`) | Required | -| `subscribePresenceForAllUsers()` | Subscribe to presence events for all users | — | -| `subscribePresenceForRoles(roles)` | Subscribe to presence events for specific roles | — | -| `subscribePresenceForFriends()` | Subscribe to presence events for friends only | — | -| `autoEstablishSocketConnection(bool)` | Let the SDK manage WebSocket connections internally | `true` | -| `overrideAdminHost(adminHost)` | Use a custom admin URL (dedicated deployment) | — | -| `overrideClientHost(clientHost)` | Use a custom client URL (dedicated deployment) | — | -| `setStorageMode(storageMode)` | Configure local storage mode (`CometChat.StorageMode.SESSION` for session storage) | — | - - -**Server-Side Rendering (SSR):** CometChat SDK requires browser APIs (`window`, `WebSocket`). For Next.js, Nuxt, or other SSR frameworks, initialize the SDK only on the client side using dynamic imports or `useEffect`. See the [Overview page](/sdk/javascript/overview#server-side-rendering-ssr-compatibility) for framework-specific examples. - - -After initialization, `CometChat.login()` returns a [`User`](/sdk/reference/entities#user) object representing the logged-in user. Access the response data using getter methods: - -| Field | Getter | Return Type | Description | -|-------|--------|-------------|-------------| -| uid | `getUid()` | `string` | Unique user ID | -| name | `getName()` | `string` | Display name of the user | -| avatar | `getAvatar()` | `string` | URL of the user's avatar | -| authToken | `getAuthToken()` | `string` | Auth token for the session | -| status | `getStatus()` | `string` | Online status (`"online"` or `"offline"`) | - -See the [Authentication](/sdk/javascript/authentication-overview) page for full login details. - -## Best Practices - - - - Call `CometChat.init()` as early as possible in your application lifecycle — typically in your entry file (`index.js`, `main.js`, or `App.js`). It only needs to be called once per app session. - - - Use `CometChat.getLoggedinUser()` to check if a user session already exists before calling `login()`. This avoids unnecessary login calls and improves app startup time. - - - Store your App ID, Region, and Auth Key in environment variables rather than hardcoding them. This makes it easier to switch between development and production environments. - - - -## Troubleshooting - - - - Verify your App ID is correct and matches the one in your [CometChat Dashboard](https://app.cometchat.com). Ensure you're using the right region (`us`, `eu`, `in`, or `in-private`). - - - This means `init()` was not called or hasn't completed before other SDK methods were invoked. Ensure `init()` resolves successfully before calling `login()`, `sendMessage()`, or registering listeners. - - - If you're behind a corporate firewall or proxy, WebSocket connections may be blocked. Check your network configuration. You can also manage WebSocket connections manually — see [Managing WebSocket Connections](/sdk/javascript/managing-web-sockets-connections-manually). - - - ---- - -## Next Steps +## Pages in This Section - - Log in users with Auth Key or Auth Token + + Add the SDK via npm or CDN + + + Configure and initialize the SDK - - Send your first text, media, or custom message + + Next.js, Nuxt, and Ionic setup + + + Log in users with Auth Key or Token diff --git a/sdk/javascript/ssr-compatibility.mdx b/sdk/javascript/ssr-compatibility.mdx new file mode 100644 index 000000000..fc2b710ba --- /dev/null +++ b/sdk/javascript/ssr-compatibility.mdx @@ -0,0 +1,293 @@ +--- +title: "SSR Compatibility" +description: "Set up the CometChat JavaScript SDK with Next.js, NuxtJS, Ionic, and other server-side rendering frameworks." +--- + +The CometChat SDK requires browser APIs (`window`, `WebSocket`) and cannot run on the server. For SSR frameworks, initialize the SDK only on the client side. + +## Next.js + +Import the SDK dynamically in `useEffect` (functional components) or `componentDidMount` (class components). + + + +```javascript +import React from "react"; +import Chat from "./Chat"; + +export default function Home() { + let [libraryImported, setLibraryImported] = React.useState(false); + + React.useEffect(() => { + window.CometChat = require("@cometchat/chat-sdk-javascript").CometChat; + setLibraryImported(true); + }, []); + + return libraryImported ? :

Loading....

; +} +``` + +
+ + +```javascript +import React from 'react'; +import Chat from './Chat'; + +export default class Home extends React.Component { + constructor(props) { + super(props); + this.state = { + libraryImported: false + }; + } + + componentDidMount() { + window.CometChat = require("@cometchat/chat-sdk-javascript").CometChat; + this.setState({ libraryImported: true }); + } + + render() { + return this.state.libraryImported ? :

Loading....

; + } +} +``` + +
+ + +```javascript +import React, { Component } from "react"; +import { COMETCHAT_CONSTANTS } from "./CONSTS"; + +export default class Chat extends Component { + constructor(props) { + super(props); + this.state = { + user: undefined, + }; + } + + componentDidMount() { + this.init(); + } + + init() { + CometChat.init( + COMETCHAT_CONSTANTS.APP_ID, + new CometChat.AppSettingsBuilder() + .setRegion(COMETCHAT_CONSTANTS.REGION) + .subscribePresenceForAllUsers() + .build() + ).then( + () => { + this.login(); + }, + (error) => { + console.log("Init failed with exception:", error); + } + ); + } + + login() { + let UID = "UID"; + CometChat.login(UID, COMETCHAT_CONSTANTS.AUTH_KEY).then( + (user) => { + this.setState({ user }); + }, + (error) => { + console.log("Login failed with exception:", error); + } + ); + } + + render() { + return this.state.user ? ( +
User logged in
+ ) : ( +
User not logged in
+ ); + } +} +``` + +
+ + +```javascript +export const COMETCHAT_CONSTANTS = { + APP_ID: "APP_ID", + REGION: "REGION", + AUTH_KEY: "AUTH_KEY", +}; +``` + + + +
+ +## NuxtJS + +Import the SDK dynamically in the `mounted` lifecycle hook. + + + +```javascript + + + +``` + + + + +```javascript + + + +``` + + + + +```javascript +module.exports = { + APP_ID: "APP_ID", + REGION: "REGION", + AUTH_KEY: "AUTH_KEY", +}; +``` + + + + + +## Ionic/Cordova + +For Ionic and Cordova applications, use the JavaScript SDK directly. Import and initialize in your root component: + +```typescript +import { Component, OnInit } from '@angular/core'; +import { CometChat } from '@cometchat/chat-sdk-javascript'; + +@Component({ + selector: 'app-root', + templateUrl: 'app.component.html', +}) +export class AppComponent implements OnInit { + + ngOnInit() { + this.initCometChat(); + } + + initCometChat() { + const appID = 'APP_ID'; + const region = 'APP_REGION'; + + const appSetting = new CometChat.AppSettingsBuilder() + .subscribePresenceForAllUsers() + .setRegion(region) + .autoEstablishSocketConnection(true) + .build(); + + CometChat.init(appID, appSetting).then( + () => { + console.log('CometChat initialized successfully'); + }, + (error) => { + console.log('CometChat initialization failed:', error); + } + ); + } +} +``` + + +The dedicated Ionic Cordova SDK has been deprecated. For new Ionic/Cordova applications, use the JavaScript SDK as shown above. Existing users can refer to the [legacy documentation](/sdk/ionic-legacy/overview). + + +## Troubleshooting + + + + The SDK is being imported on the server. Use dynamic imports inside `useEffect`, `componentDidMount`, or `mounted` hooks to ensure client-side only execution. + + + Ensure the loading state renders the same content on server and client. Use a simple loading indicator until the SDK is ready. + + + When using `require()`, assign to `window.CometChat` to make it globally available. Then access it as `CometChat` (without window prefix) in child components. + + + +--- + +## Next Steps + + + + Log in users with Auth Key or Auth Token + + + Send your first message + + From ec00ff09631f9b1a83eb0268ef4ece9343d71947 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 18 Mar 2026 14:19:12 +0530 Subject: [PATCH 18/43] Troubleshooting and Best Practices --- docs.json | 5 +- sdk/javascript/authentication-overview.mdx | 34 --------- sdk/javascript/best-practices.mdx | 86 ++++++++++++++++++++++ sdk/javascript/initialization.mdx | 28 ------- sdk/javascript/login-listener.mdx | 14 ---- sdk/javascript/rate-limits.mdx | 14 ---- sdk/javascript/ssr-compatibility.mdx | 14 ---- 7 files changed, 89 insertions(+), 106 deletions(-) create mode 100644 sdk/javascript/best-practices.mdx diff --git a/docs.json b/docs.json index 53ac6f904..fb3d74c42 100644 --- a/docs.json +++ b/docs.json @@ -2495,7 +2495,9 @@ "sdk/javascript/overview", "sdk/javascript/key-concepts", "sdk/javascript/message-structure-and-hierarchy", - "sdk/javascript/rate-limits" + "sdk/javascript/rate-limits", + "sdk/javascript/best-practices", + "sdk/javascript/troubleshooting" ] }, { @@ -2589,7 +2591,6 @@ "group": "Resources", "pages": [ "sdk/javascript/resources-overview", - "sdk/javascript/troubleshooting", "sdk/javascript/all-real-time-listeners", "sdk/javascript/upgrading-from-v3" ] diff --git a/sdk/javascript/authentication-overview.mdx b/sdk/javascript/authentication-overview.mdx index 5a6eff608..03756f7db 100644 --- a/sdk/javascript/authentication-overview.mdx +++ b/sdk/javascript/authentication-overview.mdx @@ -287,40 +287,6 @@ try { -## Best Practices - - - - Before calling `login()`, use `CometChat.getLoggedinUser()` to check if a session already exists. This avoids unnecessary login calls and prevents session conflicts. - - - Auth Keys are convenient for development but expose your app to security risks in production. Always generate Auth Tokens server-side using the [REST API](https://api-explorer.cometchat.com/reference/create-authtoken) and pass them to the client. - - - Auth Tokens can expire. Implement a mechanism to detect login failures due to expired tokens and re-generate them from your server. Use the [Login Listener](/sdk/javascript/login-listener) to detect session changes. - - - Always call `CometChat.logout()` when your user signs out of your app. This clears the SDK session and stops real-time event delivery, preventing stale data and memory leaks. - - - -## Troubleshooting - - - - The user must be created in CometChat before they can log in. Create the user via the [Dashboard](https://app.cometchat.com) (testing) or [REST API](https://api-explorer.cometchat.com/reference/creates-user) (production) first. - - - Verify your Auth Key matches the one in your [CometChat Dashboard](https://app.cometchat.com) → API & Auth Keys. Ensure you haven't accidentally used the REST API Key instead. - - - Ensure `CometChat.init()` has been called and completed successfully before calling `login()`. Verify your App ID and Region are correct. - - - This can happen if the SDK session was not persisted. Ensure `init()` is called on every app load before checking `getLoggedinUser()`. The SDK stores session data in the browser — clearing browser storage will clear the session. - - - --- ## Next Steps diff --git a/sdk/javascript/best-practices.mdx b/sdk/javascript/best-practices.mdx new file mode 100644 index 000000000..5721b89ed --- /dev/null +++ b/sdk/javascript/best-practices.mdx @@ -0,0 +1,86 @@ +--- +title: "Best Practices" +description: "Recommended patterns and practices for building with the CometChat JavaScript SDK." +--- + +Follow these best practices to build reliable, performant, and secure applications with the CometChat JavaScript SDK. + +## Initialization + + + + Call `CometChat.init()` as early as possible in your application lifecycle — typically in your entry file (`index.js`, `main.js`, or `App.js`). It only needs to be called once per session. + + + Store App ID, Region, and Auth Key in environment variables rather than hardcoding them. This makes it easier to switch between development and production environments. + + + +## Authentication + + + + Before calling `login()`, use `CometChat.getLoggedinUser()` to check if a session already exists. This avoids unnecessary login calls and prevents session conflicts. + + + Auth Keys are convenient for development but expose your app to security risks in production. Always generate Auth Tokens server-side using the [REST API](https://api-explorer.cometchat.com/reference/create-authtoken) and pass them to the client. + + + Auth Tokens can expire. Implement a mechanism to detect login failures due to expired tokens and re-generate them from your server. Use the [Login Listener](/sdk/javascript/login-listener) to detect session changes. + + + Always call `CometChat.logout()` when your user signs out of your app. This clears the SDK session and stops real-time event delivery, preventing stale data and memory leaks. + + + +## Listeners + + + + Each listener must have a unique ID string. If you register a new listener with the same ID, it will replace the previous one. Use descriptive IDs like `"LOGIN_LISTENER_MAIN"` or `"MESSAGE_LISTENER_CHAT_SCREEN"` to avoid accidental overwrites. + + + Register listeners as early as possible in your app lifecycle (e.g., right after `login()`). Remove them when the component or page that registered them is destroyed to prevent memory leaks. + + + Use the `logoutSuccess` callback to clear your app's local state, redirect to the login screen, and clean up any other SDK listeners. This ensures a clean state when the user logs out. + + + +## Rate Limits + + + + If you need to perform many operations (e.g., sending messages to multiple users), space them out over time rather than firing them all at once. Use a queue or throttle mechanism to stay within the per-minute limits. + + + Check the `X-Rate-Limit-Remaining` header in REST API responses to proactively slow down before hitting the limit. This is more efficient than waiting for `429` errors. + + + Core operations (login, create/delete user, create/join group) share a lower cumulative limit of 10,000/min. Standard operations have a higher 20,000/min limit. Plan your architecture accordingly — avoid frequent login/logout cycles. + + + +## SSR Frameworks + + + + CometChat SDK requires browser APIs (`window`, `WebSocket`). For Next.js, Nuxt, or other SSR frameworks, use dynamic imports or `useEffect` to ensure the SDK loads only on the client. + + + Show a loading indicator while the SDK initializes on the client. This prevents hydration mismatches and provides a better user experience. + + + +--- + +## Next Steps + + + + Common issues and solutions + + + Installation and initialization guide + + diff --git a/sdk/javascript/initialization.mdx b/sdk/javascript/initialization.mdx index 4508c205a..bc918d41a 100644 --- a/sdk/javascript/initialization.mdx +++ b/sdk/javascript/initialization.mdx @@ -153,34 +153,6 @@ let appSetting = new CometChat.AppSettingsBuilder() .build(); ``` -## Best Practices - - - - Call `CometChat.init()` as early as possible in your application lifecycle. It only needs to be called once per session. - - - After initialization, use `CometChat.getLoggedinUser()` to check if a session exists before calling `login()`. - - - Store App ID, Region, and Auth Key in environment variables rather than hardcoding them. - - - -## Troubleshooting - - - - Verify your App ID matches the one in your [CometChat Dashboard](https://app.cometchat.com). Check that you're using the correct region. - - - Ensure `init()` completes successfully before calling other SDK methods. Wait for the Promise to resolve. - - - Corporate firewalls may block WebSocket connections. Check your network configuration or try [manual WebSocket management](/sdk/javascript/managing-web-sockets-connections-manually). - - - --- ## Next Steps diff --git a/sdk/javascript/login-listener.mdx b/sdk/javascript/login-listener.mdx index 4176ff6a4..5a103fd20 100644 --- a/sdk/javascript/login-listener.mdx +++ b/sdk/javascript/login-listener.mdx @@ -181,20 +181,6 @@ In order to stop receiving events related to login and logout you need to use th Always remove login listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling.
-## Best Practices - - - - Each listener must have a unique ID string. If you register a new listener with the same ID, it will replace the previous one. Use descriptive IDs like `"LOGIN_LISTENER_MAIN"` or `"LOGIN_LISTENER_AUTH_SCREEN"` to avoid accidental overwrites. - - - Use the `logoutSuccess` callback to clear your app's local state, redirect to the login screen, and clean up any other SDK listeners. This ensures a clean state when the user logs out. - - - Register login listeners as early as possible in your app lifecycle (e.g., right after `init()`). Remove them only when the component or page that registered them is destroyed. - - - --- ## Next Steps diff --git a/sdk/javascript/rate-limits.mdx b/sdk/javascript/rate-limits.mdx index 7d5cd0324..9b9aa1332 100644 --- a/sdk/javascript/rate-limits.mdx +++ b/sdk/javascript/rate-limits.mdx @@ -97,20 +97,6 @@ const users: CometChat.User[] = await callWithRetry(() => -## Best Practices - - - - If you need to perform many operations (e.g., sending messages to multiple users), space them out over time rather than firing them all at once. Use a queue or throttle mechanism to stay within the per-minute limits. - - - Check the `X-Rate-Limit-Remaining` header in REST API responses to proactively slow down before hitting the limit. This is more efficient than waiting for `429` errors. - - - Core operations (login, create/delete user, create/join group) share a lower cumulative limit of 10,000/min. Standard operations have a higher 20,000/min limit. Plan your architecture accordingly — avoid frequent login/logout cycles. - - - --- ## Next Steps diff --git a/sdk/javascript/ssr-compatibility.mdx b/sdk/javascript/ssr-compatibility.mdx index fc2b710ba..a4b362c12 100644 --- a/sdk/javascript/ssr-compatibility.mdx +++ b/sdk/javascript/ssr-compatibility.mdx @@ -265,20 +265,6 @@ export class AppComponent implements OnInit { The dedicated Ionic Cordova SDK has been deprecated. For new Ionic/Cordova applications, use the JavaScript SDK as shown above. Existing users can refer to the [legacy documentation](/sdk/ionic-legacy/overview). -## Troubleshooting - - - - The SDK is being imported on the server. Use dynamic imports inside `useEffect`, `componentDidMount`, or `mounted` hooks to ensure client-side only execution. - - - Ensure the loading state renders the same content on server and client. Use a simple loading indicator until the SDK is ready. - - - When using `require()`, assign to `window.CometChat` to make it globally available. Then access it as `CometChat` (without window prefix) in child components. - - - --- ## Next Steps From 65137dc4d7805d9a979876dd8dbfe46a31fbc2a9 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 18 Mar 2026 14:23:40 +0530 Subject: [PATCH 19/43] Best Practices and Troubleshooting --- sdk/javascript/best-practices.mdx | 63 +++++++++++++++++++++ sdk/javascript/block-users.mdx | 19 ------- sdk/javascript/call-logs.mdx | 19 ------- sdk/javascript/calling-overview.mdx | 19 ------- sdk/javascript/calling-setup.mdx | 19 ------- sdk/javascript/create-group.mdx | 19 ------- sdk/javascript/default-call.mdx | 19 ------- sdk/javascript/delete-group.mdx | 17 ------ sdk/javascript/direct-call.mdx | 20 ------- sdk/javascript/join-group.mdx | 19 ------- sdk/javascript/leave-group.mdx | 19 ------- sdk/javascript/recording.mdx | 19 ------- sdk/javascript/retrieve-users.mdx | 19 ------- sdk/javascript/session-timeout.mdx | 17 ------ sdk/javascript/standalone-calling.mdx | 19 ------- sdk/javascript/update-group.mdx | 17 ------ sdk/javascript/user-management.mdx | 15 ----- sdk/javascript/user-presence.mdx | 15 ----- sdk/javascript/video-view-customisation.mdx | 21 ------- sdk/javascript/virtual-background.mdx | 24 -------- 20 files changed, 63 insertions(+), 355 deletions(-) diff --git a/sdk/javascript/best-practices.mdx b/sdk/javascript/best-practices.mdx index 5721b89ed..4c86315cd 100644 --- a/sdk/javascript/best-practices.mdx +++ b/sdk/javascript/best-practices.mdx @@ -72,6 +72,69 @@ Follow these best practices to build reliable, performant, and secure applicatio +## Users + + + + Use `setLimit()` with reasonable values (30-50) and call `fetchNext()` for subsequent pages. Don't fetch all users at once. + + + Call `fetchNext()` on the same `UsersRequest` instance for pagination. Creating a new object resets the cursor. + + + Store frequently accessed user objects locally to reduce API calls, especially for `getUser()`. + + + Enable this in user lists to respect block relationships and provide a cleaner experience. + + + Always create and update users from your backend server using the REST API to keep your Auth Key secure. + + + +## Groups + + + + Choose descriptive, unique GUIDs (e.g., `"project-alpha-team"`) that are easy to reference in your codebase. + + + Group type cannot be changed after creation. Choose between PUBLIC, PASSWORD, and PRIVATE based on your use case. + + + Use `createGroupWithMembers()` to add initial members in a single API call instead of creating the group and adding members separately. + + + Before calling `joinGroup()`, check the group's `hasJoined` property to avoid unnecessary API calls. + + + Show a confirmation dialog before leaving or deleting a group, especially for groups with important conversations. + + + +## Calling + + + + Unless using Standalone Calling, always initialize the Chat SDK (`CometChat.init()`) before the Calls SDK (`CometChatCalls.init()`). + + + Save the session ID from `initiateCall()` response immediately. You'll need it for accept, reject, cancel, and starting the session. + + + Implement handlers for all listener events (accepted, rejected, cancelled, busy, ended) to provide a complete user experience. + + + Generate call tokens immediately before starting a session rather than caching them, as tokens may expire. + + + Always call `CometChatCalls.endSession()` in both `onCallEnded` and `onCallEndButtonPressed` callbacks to release media resources. + + + Always notify participants when recording starts. This is often a legal requirement in many jurisdictions. + + + --- ## Next Steps diff --git a/sdk/javascript/block-users.mdx b/sdk/javascript/block-users.mdx index 480e1856b..dad8bface 100644 --- a/sdk/javascript/block-users.mdx +++ b/sdk/javascript/block-users.mdx @@ -290,25 +290,6 @@ blockedUsersRequest.fetchNext().then( --- - - - - **Block in batches** — You can block multiple users in a single call by passing an array of UIDs. This is more efficient than blocking one at a time. - - **Update UI immediately** — After blocking/unblocking, update your user list and conversation list to reflect the change. - - **Use direction filters** — Use `BLOCKED_BY_ME` to show users you've blocked, `HAS_BLOCKED_ME` to detect who blocked you, or `BOTH` for the full picture. - - **Hide blocked users in lists** — Use `hideBlockedUsers(true)` in `UsersRequestBuilder` to automatically exclude blocked users from user lists. - - **Handle block status in messaging** — Messages from blocked users won't be delivered. Inform users that blocking prevents all communication. - - - - **Block operation returns "fail" for a UID** — The UID may not exist or may already be blocked. Verify the UID is correct. - - **Still receiving messages after blocking** — Ensure the block operation completed successfully. Check the response object for "success" status on each UID. - - **Blocked user list empty** — Verify the direction filter. Default is `BOTH`, but if you set `HAS_BLOCKED_ME` and no one has blocked you, the list will be empty. - - **Unblock not working** — Ensure you're passing the correct UIDs. The unblock operation only works on users you've blocked (`BLOCKED_BY_ME`). - - **Blocked user still appears in user list** — Use `hideBlockedUsers(true)` in your `UsersRequestBuilder` to filter them out automatically. - - - ---- - ## Next Steps diff --git a/sdk/javascript/call-logs.mdx b/sdk/javascript/call-logs.mdx index d08f3a85b..064066a55 100644 --- a/sdk/javascript/call-logs.mdx +++ b/sdk/javascript/call-logs.mdx @@ -156,25 +156,6 @@ Note: Replace `"SESSION_ID"` with the ID of the session you are interested in. --- - - - - **Paginate results** — Use `setLimit()` with reasonable values (30-50) and implement pagination with `fetchNext()` / `fetchPrevious()` for large call histories. - - **Filter by category** — Use `setCallCategory("call")` or `setCallCategory("meet")` to separate regular calls from meetings. - - **Cache auth tokens** — Store the user's auth token rather than fetching it repeatedly for each call log request. - - **Handle empty results** — Always check if the returned array is empty before processing call logs. - - **Use appropriate filters** — Combine filters like `setCallDirection()`, `setCallStatus()`, and `setHasRecording()` to narrow down results efficiently. - - - - **Empty call logs returned** — Verify the auth token is valid and belongs to a user who has participated in calls. Check that filters aren't too restrictive. - - **Auth token errors** — Ensure you're using `loggedInUser.getAuthToken()` and that the user is logged in before fetching call logs. - - **Missing recordings** — Use `setHasRecording(true)` to filter only calls with recordings. Recordings may take time to process after a call ends. - - **Pagination not working** — Make sure you're reusing the same `CallLogRequestBuilder` instance for `fetchNext()` / `fetchPrevious()` calls. - - **Session ID not found** — The session ID must match an existing call session. Verify the session ID is correct and the call has completed. - - - ---- - ## Next Steps diff --git a/sdk/javascript/calling-overview.mdx b/sdk/javascript/calling-overview.mdx index 7d7e5f99c..a1c0adc69 100644 --- a/sdk/javascript/calling-overview.mdx +++ b/sdk/javascript/calling-overview.mdx @@ -116,25 +116,6 @@ Use this when you want: --- - - - - **Choose the right approach** — Use Ringing for full call experience with notifications, Call Session for custom UI, and Standalone for minimal SDK footprint. - - **Initialize both SDKs** — For Ringing and Call Session flows, ensure both Chat SDK and Calls SDK are initialized before starting calls. - - **Handle all call states** — Implement handlers for accepted, rejected, cancelled, busy, and ended states to provide a complete user experience. - - **Clean up resources** — Always call `CometChatCalls.endSession()` when leaving a call to release camera, microphone, and network resources. - - **Test on multiple devices** — Voice and video calling behavior can vary across browsers and devices. Test thoroughly on your target platforms. - - - - **No audio/video** — Check browser permissions for camera and microphone. Ensure the user granted access when prompted. - - **Call not connecting** — Verify both participants have initialized the Calls SDK and are using the same session ID. - - **One-way audio** — This often indicates a firewall or NAT issue. CometChat uses TURN servers, but corporate networks may block WebRTC traffic. - - **Poor call quality** — Check network bandwidth. Video calls require stable connections. Consider offering audio-only fallback for poor connections. - - **Calls SDK not found** — Ensure `@cometchat/calls-sdk-javascript` is installed and imported correctly. - - - ---- - ## Next Steps diff --git a/sdk/javascript/calling-setup.mdx b/sdk/javascript/calling-setup.mdx index 2ca0ea53f..710dd6a8f 100644 --- a/sdk/javascript/calling-setup.mdx +++ b/sdk/javascript/calling-setup.mdx @@ -143,25 +143,6 @@ Make sure you replace the `APP_ID` with your CometChat **App ID** and `REGION` w --- - - - - **Initialize once** — Call `CometChatCalls.init()` only once at app startup, typically in your main entry file (index.js, App.js). - - **Initialize Chat SDK first** — Unless using [Standalone Calling](/sdk/javascript/standalone-calling), always initialize the Chat SDK (`CometChat.init()`) before the Calls SDK. - - **Handle initialization errors** — Always implement error handling for the init promise to catch configuration issues early. - - **Use environment variables** — Store App ID and Region in environment variables rather than hardcoding them. - - **Verify initialization** — Before making any Calls SDK method calls, ensure initialization completed successfully. - - - - **"CometChatCalls is not initialized"** — Ensure `CometChatCalls.init()` completed successfully before calling other methods. Check that the promise resolved without errors. - - **Invalid App ID or Region** — Verify your App ID and Region match exactly what's shown in the [CometChat Dashboard](https://app.cometchat.com). Region is case-sensitive (e.g., "us", "eu"). - - **CORS errors** — If using a custom host, ensure your domain is whitelisted in the CometChat Dashboard under App Settings. - - **Module not found** — Verify the package is installed correctly with `npm list @cometchat/calls-sdk-javascript`. Try removing node_modules and reinstalling. - - **Chat SDK not initialized** — If you see errors about missing user context, ensure `CometChat.init()` and `CometChat.login()` completed before initializing the Calls SDK. - - - ---- - ## Next Steps diff --git a/sdk/javascript/create-group.mdx b/sdk/javascript/create-group.mdx index b11d8b991..8e866e7e2 100644 --- a/sdk/javascript/create-group.mdx +++ b/sdk/javascript/create-group.mdx @@ -242,25 +242,6 @@ This method returns an Object which has two keys: `group` & `members` . The grou | tags | Yes | A list of tags to identify specific groups. | ---- - - - - - **Use meaningful GUIDs** — Choose descriptive, unique GUIDs (e.g., `"project-alpha-team"`) that are easy to reference in your codebase. - - **Set group type carefully** — Group type cannot be changed after creation. Choose between PUBLIC, PASSWORD, and PRIVATE based on your use case. - - **Add members at creation** — Use `createGroupWithMembers()` to add initial members in a single API call instead of creating the group and adding members separately. - - **Store metadata** — Use the `metadata` field to store custom data (e.g., project ID, department) rather than encoding it in the group name. - - **Handle GUID conflicts** — If a GUID already exists, creation will fail. Check for existing groups or use unique identifiers. - - - - **"GUID already exists" error** — A group with that GUID already exists. Use a different GUID or retrieve the existing group. - - **"User not authorized" error** — The logged-in user may not have permission to create groups. Check your app's role settings in the Dashboard. - - **Members not added during creation** — Check the response object's `members` key. Individual member additions can fail (e.g., invalid UID) while the group creation succeeds. - - **Password group not requiring password** — Ensure `groupType` is set to `CometChat.GROUP_TYPE.PASSWORD` and a non-empty password is provided. - - **GUID validation error** — GUIDs can only contain alphanumeric characters, underscores, and hyphens. No spaces or special characters. - - - --- ## Next Steps diff --git a/sdk/javascript/default-call.mdx b/sdk/javascript/default-call.mdx index d04a568d8..42df01e3d 100644 --- a/sdk/javascript/default-call.mdx +++ b/sdk/javascript/default-call.mdx @@ -573,25 +573,6 @@ Always remove call listeners when they're no longer needed (e.g., on component u --- - - - - **Store session ID** — Save the session ID from `initiateCall()` response immediately. You'll need it for accept, reject, cancel, and starting the session. - - **Handle all call states** — Implement handlers for all listener events (accepted, rejected, cancelled, busy, ended) to provide a complete user experience. - - **Show appropriate UI** — Display outgoing call UI after `initiateCall()`, incoming call UI in `onIncomingCallReceived()`, and dismiss UI in rejection/cancellation callbacks. - - **Clean up on unmount** — Remove call listeners when the component unmounts or when navigating away from the call screen. - - **Handle busy state** — Check if the user is already on a call before accepting a new one. Use `CALL_STATUS.BUSY` to inform the caller. - - - - **Call not received** — Verify the receiver is logged in and has registered the call listener. Check that the receiver UID/GUID is correct. - - **Duplicate call events** — Ensure you're using unique listener IDs and removing listeners when no longer needed. Multiple registrations with the same ID replace the previous listener. - - **Session not starting after accept** — After `acceptCall()` succeeds, you must generate a call token and call `startSession()`. The accept only signals intent, it doesn't start the media session. - - **Call stuck in ringing state** — Implement timeout logic to auto-cancel calls that aren't answered within a reasonable time (e.g., 30-60 seconds). - - **"Call already in progress" error** — Use `CometChat.getActiveCall()` to check for existing calls before initiating a new one. - - - ---- - ## Next Steps diff --git a/sdk/javascript/delete-group.mdx b/sdk/javascript/delete-group.mdx index dad4a602c..0cfc50412 100644 --- a/sdk/javascript/delete-group.mdx +++ b/sdk/javascript/delete-group.mdx @@ -78,23 +78,6 @@ The `deleteGroup()` method takes the following parameters: On success, the method resolves with a success message string confirming the operation. ---- - - - - - **Confirm before deleting** — Always show a confirmation dialog. Group deletion is irreversible and removes all messages and member associations. - - **Verify admin status** — Only group admins can delete groups. Check the user's scope before showing the delete option in your UI. - - **Notify members** — Consider sending a final message or notification before deleting so members are aware. - - **Clean up local state** — After deletion, remove the group from local caches, conversation lists, and any UI references. - - - - **"Not authorized" error** — Only admins can delete groups. Verify the logged-in user's scope is `ADMIN` for this group. - - **Group not found** — The GUID may be incorrect or the group was already deleted. Verify the GUID exists. - - **Members still see the group** — Other members will receive a group deletion event via `GroupListener`. Ensure they handle `onGroupMemberLeft` or similar cleanup. - - **Deletion seems to hang** — Check network connectivity. The operation requires a server round-trip. - - - --- ## Next Steps diff --git a/sdk/javascript/direct-call.mdx b/sdk/javascript/direct-call.mdx index 11088163d..33d1f1d09 100644 --- a/sdk/javascript/direct-call.mdx +++ b/sdk/javascript/direct-call.mdx @@ -745,26 +745,6 @@ CometChatCalls.removeCallEventListener("UNIQUE_LISTENER_ID"); --- - - - - **Generate tokens just-in-time** — Generate call tokens immediately before starting a session rather than caching them, as tokens may expire. - - **Handle all listener events** — Implement handlers for all `OngoingCallListener` events to provide a complete user experience and proper resource cleanup. - - **Clean up on session end** — Always call `CometChatCalls.endSession()` in both `onCallEnded` and `onCallEndButtonPressed` callbacks to release media resources. - - **Use unique listener IDs** — Use descriptive, unique listener IDs to prevent accidental overwrites and enable targeted removal. - - **Provide a container element** — Ensure the HTML element passed to `startSession()` exists in the DOM and has appropriate dimensions for the call UI. - - - - **Black video screen** — Check that the HTML container element has explicit width and height. The call UI needs dimensions to render properly. - - **Token generation fails** — Verify the auth token is valid and the user is logged in. Ensure the session ID is a non-empty string. - - **No audio/video after joining** — Check browser permissions for camera and microphone. The user must grant access when prompted. - - **onCallEnded not firing** — This event only fires for 1:1 calls with exactly 2 participants. For group calls, use `onUserLeft` to track participants. - - **Duplicate event callbacks** — Ensure you're not registering the same listener multiple times. Use unique listener IDs and remove listeners when done. - - **Session timeout unexpected** — The default idle timeout is 180 seconds. Use `setIdleTimeoutPeriod()` to customize or disable (set to 0) if needed. - - - ---- - ## Next Steps diff --git a/sdk/javascript/join-group.mdx b/sdk/javascript/join-group.mdx index 01cfee325..bb11a4a14 100644 --- a/sdk/javascript/join-group.mdx +++ b/sdk/javascript/join-group.mdx @@ -145,25 +145,6 @@ For the group member joined event, in the `Action` object received, the followin --- - - - - **Check `hasJoined` first** — Before calling `joinGroup()`, check the group's `hasJoined` property to avoid unnecessary API calls. - - **Handle password groups** — For password-protected groups, prompt the user for the password before calling `joinGroup()`. - - **Update UI on join** — After successfully joining, update your group list and enable messaging for that group. - - **Listen for join events** — Register `GroupListener` to receive real-time notifications when other members join. - - **Clean up listeners** — Remove group listeners when leaving the screen or component to prevent memory leaks. - - - - **"Already a member" error** — The user has already joined this group. Check `hasJoined` before attempting to join. - - **"Invalid password" error** — The password provided doesn't match. Ensure the password is correct for password-protected groups. - - **Can't join private group** — Private groups require an invitation. Users must be added by an admin using `addMembersToGroup()`. - - **Join events not received** — Ensure `addGroupListener()` is called before the join event occurs. Verify the listener ID is unique. - - **Group not found** — The GUID may be incorrect or the group may have been deleted. Verify the GUID exists. - - - ---- - ## Next Steps diff --git a/sdk/javascript/leave-group.mdx b/sdk/javascript/leave-group.mdx index 51cf4af8e..8d7d8a8aa 100644 --- a/sdk/javascript/leave-group.mdx +++ b/sdk/javascript/leave-group.mdx @@ -123,25 +123,6 @@ For the group member left event, in the `Action` object received, the following --- - - - - **Confirm before leaving** — Show a confirmation dialog before leaving a group, especially for groups with important conversations. - - **Update UI immediately** — Remove the group from the active list and disable messaging after successfully leaving. - - **Handle owner leaving** — If the group owner leaves, ownership should be transferred first using [Transfer Group Ownership](/sdk/javascript/transfer-group-ownership). - - **Clean up listeners** — Remove any group-specific listeners after leaving to prevent memory leaks and stale event handling. - - **Check missed events** — When re-joining a group, fetch missed messages and action events to stay up to date. - - - - **"Not a member" error** — The user is not a member of this group. Verify the GUID and check `hasJoined` status. - - **Owner can't leave** — Group owners must transfer ownership before leaving. Use `transferGroupOwnership()` first. - - **Leave events not received** — Ensure `addGroupListener()` is registered before the leave event occurs. Check listener IDs are unique. - - **Still receiving group messages** — Ensure `leaveGroup()` completed successfully. Check the promise resolved without errors. - - **Group still in conversation list** — Refresh the conversation list after leaving. The group may still appear until the list is re-fetched. - - - ---- - ## Next Steps diff --git a/sdk/javascript/recording.mdx b/sdk/javascript/recording.mdx index 73cfa98d3..19f4fc682 100644 --- a/sdk/javascript/recording.mdx +++ b/sdk/javascript/recording.mdx @@ -163,25 +163,6 @@ Currently, the call recordings are available on the [CometChat Dashboard](https: --- - - - - **Inform users about recording** — Always notify participants when recording starts. This is often a legal requirement in many jurisdictions. - - **Use auto-start for compliance** — If all calls must be recorded for compliance, use `startRecordingOnCallStart(true)` to ensure no calls are missed. - - **Handle recording events** — Implement `onRecordingStarted` and `onRecordingStopped` listeners to update UI and inform users of recording status. - - **Check recording availability** — Recording is a premium feature. Verify it's enabled for your CometChat plan before implementing. - - **Plan for storage** — Recordings consume storage. Implement a retention policy and regularly download/archive recordings from the Dashboard. - - - - **Recording button not visible** — Ensure `showRecordingButton(true)` is set in CallSettings. The button is hidden by default. - - **Recording not starting** — Verify recording is enabled for your CometChat app in the Dashboard. Check that the call session is active before calling `startRecording()`. - - **Recording not appearing in Dashboard** — Recordings may take several minutes to process after a call ends. Check back later or filter by date range. - - **onRecordingStarted not firing** — Ensure the recording listener is registered before starting the session. Check that you're using the correct listener format. - - **Recording quality issues** — Recording quality depends on the source video/audio quality. Ensure participants have stable connections and good lighting for video. - - - ---- - ## Next Steps diff --git a/sdk/javascript/retrieve-users.mdx b/sdk/javascript/retrieve-users.mdx index 3679aaeb0..c20501ebb 100644 --- a/sdk/javascript/retrieve-users.mdx +++ b/sdk/javascript/retrieve-users.mdx @@ -590,25 +590,6 @@ This method returns the total online user count for your app. --- - - - - **Paginate results** — Use `setLimit()` with reasonable values (30-50) and call `fetchNext()` for subsequent pages. Don't fetch all users at once. - - **Reuse the request object** — Call `fetchNext()` on the same `UsersRequest` instance for pagination. Creating a new object resets the cursor. - - **Filter strategically** — Combine `setStatus()`, `setRoles()`, and `setTags()` to narrow results efficiently rather than filtering client-side. - - **Cache user details** — Store frequently accessed user objects locally to reduce API calls, especially for `getUser()`. - - **Use `hideBlockedUsers(true)`** — Enable this in user lists to respect block relationships and provide a cleaner experience. - - - - **Empty user list returned** — Check that users exist in your CometChat app. Verify filters aren't too restrictive by removing them one at a time. - - **Pagination not working** — Ensure you're reusing the same `UsersRequest` object for `fetchNext()` calls. Creating a new builder resets pagination. - - **`getUser()` returns error** — Verify the UID exists and is spelled correctly. UIDs are case-sensitive. - - **Online count seems wrong** — `getOnlineUserCount()` returns the total across your app, not just the current user's contacts. Users must have an active connection. - - **Search not finding users** — By default, search checks both UID and name. Use `searchIn()` to limit search scope if needed. - - - ---- - ## Next Steps diff --git a/sdk/javascript/session-timeout.mdx b/sdk/javascript/session-timeout.mdx index d5829e490..cec093cef 100644 --- a/sdk/javascript/session-timeout.mdx +++ b/sdk/javascript/session-timeout.mdx @@ -44,23 +44,6 @@ The `onSessionTimeout` event is triggered when the call automatically terminates --- - - - - **Customize timeout for your use case** — Use `setIdleTimeoutPeriod()` to adjust the timeout based on your application's needs. Longer timeouts for waiting rooms, shorter for quick calls. - - **Handle the warning dialog** — The 60-second warning gives users time to decide. Ensure your UI doesn't block or hide this dialog. - - **Implement onSessionTimeout** — Always handle the `onSessionTimeout` event to properly clean up resources and update your UI when auto-termination occurs. - - **Consider disabling for specific scenarios** — For use cases like webinars or waiting rooms where users may be alone for extended periods, consider increasing or disabling the timeout. - - - - **Timeout happening too quickly** — The default is 180 seconds (3 minutes). Use `setIdleTimeoutPeriod()` to increase if needed. - - **Warning dialog not appearing** — The dialog appears at 120 seconds of being alone. If using a custom layout (`enableDefaultLayout(false)`), you need to implement your own warning UI. - - **onSessionTimeout not firing** — Ensure you've registered the listener before starting the session. This event only fires on auto-termination, not manual end. - - **Timeout not resetting** — The timer resets when another participant joins. If it's not resetting, verify the other participant successfully joined the session. - - - ---- - ## Next Steps diff --git a/sdk/javascript/standalone-calling.mdx b/sdk/javascript/standalone-calling.mdx index f16a67aaa..499a06a2e 100644 --- a/sdk/javascript/standalone-calling.mdx +++ b/sdk/javascript/standalone-calling.mdx @@ -674,25 +674,6 @@ CometChatCalls.endSession(); --- - - - - **Secure auth token handling** — Never expose auth tokens in client-side code. Generate them server-side and pass securely to the client. - - **Use consistent session IDs** — For participants to join the same call, they must use the same session ID. Generate a unique ID and share it through your backend. - - **Implement proper cleanup** — Always call `endSession()` when leaving a call to release camera, microphone, and network resources. - - **Handle all listener events** — Implement handlers for all `OngoingCallListener` events to provide a complete user experience. - - **Test without Chat SDK** — Standalone calling doesn't require Chat SDK initialization. Verify your implementation works independently. - - - - **Invalid auth token** — Auth tokens obtained from REST API may expire. Implement token refresh logic or generate new tokens as needed. - - **Participants can't join same call** — Ensure all participants are using the exact same session ID. Session IDs are case-sensitive. - - **No user context** — Unlike the Chat SDK flow, standalone calling doesn't have automatic user context. User information comes from the auth token. - - **Call not connecting** — Verify the Calls SDK is initialized with correct App ID and Region. Check that both participants have valid call tokens. - - **Missing user info in callbacks** — User details in callbacks come from the auth token. Ensure the token was generated for a user with complete profile information. - - - ---- - ## Next Steps diff --git a/sdk/javascript/update-group.mdx b/sdk/javascript/update-group.mdx index b060a6a7e..6055c6023 100644 --- a/sdk/javascript/update-group.mdx +++ b/sdk/javascript/update-group.mdx @@ -83,23 +83,6 @@ For more information on the `Group` class, please check [here](/sdk/javascript/c --- - - - - **Only update changed fields** — Set only the fields you want to change on the Group object. Unchanged fields retain their current values. - - **Validate before updating** — Check that the user has admin or moderator scope before showing update options in your UI. - - **Update metadata carefully** — When updating metadata, merge with existing data rather than replacing it entirely to avoid losing other fields. - - **Refresh after update** — After a successful update, refresh the group details in your UI to reflect the changes. - - - - **"Not authorized" error** — Only admins and moderators can update group details. Check the user's scope. - - **Group type not changing** — Group type cannot be changed after creation. This is by design. - - **Update not reflected** — Ensure the update promise resolved successfully. Other members receive the update via `GroupListener`. - - **Metadata overwritten** — When updating metadata, the entire metadata object is replaced. Merge with existing metadata before updating. - - - ---- - ## Next Steps diff --git a/sdk/javascript/user-management.mdx b/sdk/javascript/user-management.mdx index 9e53be1db..21bbcf75b 100644 --- a/sdk/javascript/user-management.mdx +++ b/sdk/javascript/user-management.mdx @@ -227,21 +227,6 @@ Deleting a user can only be achieved via the Restful APIs. For more information | blockedByMe | No | A boolean that determines if the logged in user has blocked the user | | tags | Yes | A list of tags to identify specific users | - - -- **Backend user creation** — Always create and update users from your backend server using the REST API to keep your `Auth Key` secure. -- **UID format** — Use alphanumeric characters, underscores, and hyphens only. Avoid spaces and special characters. -- **Metadata usage** — Store additional user info (e.g., department, preferences) in the `metadata` JSON field rather than creating custom fields. -- **Sync on registration** — Create the CometChat user immediately when a user registers in your app to avoid login failures. - - -- **`createUser()` fails with "Auth Key not found"** — Invalid or missing Auth Key. Verify the Auth Key from your [CometChat Dashboard](https://app.cometchat.com). -- **`createUser()` fails with "UID already exists"** — A user with that UID was already created. Use `updateUser()` instead, or choose a different UID. -- **`updateCurrentUserDetails()` doesn't update role** — Role cannot be changed for the logged-in user. Use `updateUser()` with Auth Key from your backend to change roles. -- **User not appearing in user list** — The user was created but not yet indexed. Wait a moment and retry. Ensure `createUser()` resolved successfully. - - - ## Next Steps diff --git a/sdk/javascript/user-presence.mdx b/sdk/javascript/user-presence.mdx index 2fb11d6ed..f2f82082e 100644 --- a/sdk/javascript/user-presence.mdx +++ b/sdk/javascript/user-presence.mdx @@ -140,21 +140,6 @@ When you fetch the list of users, in the [User](/sdk/javascript/user-management# 2. `lastActiveAt` - in case the user is offline, this field holds the timestamp of the time when the user was last online. This can be used to display the Last seen of the user if need be. - - -- **Choose the right subscription** — Use `subscribePresenceForFriends()` or `subscribePresenceForRoles()` instead of `subscribePresenceForAllUsers()` in apps with many users to reduce unnecessary events. -- **Use unique listener IDs** — Use unique, descriptive listener IDs (e.g., `"chat-screen-presence"`) to avoid accidentally overwriting other listeners. -- **Cleanup on unmount** — Always call `removeUserListener()` when the component/view is destroyed. -- **Combine with user list** — Use the `status` field from `UsersRequest` results for initial state, then update via `UserListener` for real-time changes. - - -- **No presence events received** — Presence subscription not configured in `AppSettings`. Add `subscribePresenceForAllUsers()`, `subscribePresenceForRoles()`, or `subscribePresenceForFriends()` to your `AppSettingsBuilder`. -- **Presence events stop after navigation** — The listener was removed or the component unmounted. Re-register the listener when the component mounts again. -- **Duplicate presence events** — Multiple listeners registered with the same or different IDs. Ensure you remove old listeners before adding new ones. -- **`lastActiveAt` is `0` or `null`** — The user has never been online or data is not yet available. Handle this in your UI with a fallback like "Never active". - - - ## Next Steps diff --git a/sdk/javascript/video-view-customisation.mdx b/sdk/javascript/video-view-customisation.mdx index 5e3880224..a8bf033ae 100644 --- a/sdk/javascript/video-view-customisation.mdx +++ b/sdk/javascript/video-view-customisation.mdx @@ -56,27 +56,6 @@ videoSettings.setNetworkLabelParams(CometChat.CallSettings.POSITION_BOTTOM_RIGHT - - - -| Practice | Details | -| --- | --- | -| Aspect ratio choice | Use `ASPECT_RATIO_CONTAIN` to show the full video without cropping; use `ASPECT_RATIO_COVER` for a full-bleed look that may crop edges | -| Label positioning | Avoid placing the name label and network label in the same corner to prevent overlap | -| Full screen button | Keep the full screen button visible for better UX; only hide it if your app provides its own full screen toggle | - - - - -| Symptom | Cause | Fix | -| --- | --- | --- | -| Video settings not applied | `setMainVideoContainerSetting()` not called on `CallSettingsBuilder` | Pass the `MainVideoContainerSetting` object to `CallSettingsBuilder.setMainVideoContainerSetting()` before calling `startCall()` | -| Labels overlapping | Multiple labels positioned in the same corner | Assign different position constants to each label | -| Full screen button missing | Visibility set to `false` | Set the second parameter of `setFullScreenButtonParams()` to `true` | - - - - ## Next Steps diff --git a/sdk/javascript/virtual-background.mdx b/sdk/javascript/virtual-background.mdx index 0879041c1..0af81739a 100644 --- a/sdk/javascript/virtual-background.mdx +++ b/sdk/javascript/virtual-background.mdx @@ -111,30 +111,6 @@ The `VirtualBackground` Class is the required in case you want to change how the | `enforceBackgroundBlur(enforceBackgroundBlur: number)` | This method starts the call with background blurred. To blur the background you need to pass an integer value between 1-99 which decides the blur level. **Default = 0** | | `enforceBackgroundImage(enforceBackgroundImage: string)` | This methods starts the call with the provided background image. | - - - -| Practice | Details | -| --- | --- | -| Blur level range | Use values between 1-99 for `enforceBackgroundBlur()`. Higher values produce stronger blur. A value of 0 disables blur | -| Image hosting | Host background images on a CDN for fast loading. Large images may cause lag when applied | -| Enforce vs allow | Use `enforceBackgroundBlur()` or `enforceBackgroundImage()` when you want a mandatory background (e.g., for privacy). Use `allowBackgroundBlur()` and `allowUserImages()` to let users choose | -| Custom buttons | Use `CallController` methods (`setBackgroundBlur`, `setBackgroundImage`, `openVirtualBackground`) when building a custom UI instead of the default CometChat menu | - - - - -| Symptom | Cause | Fix | -| --- | --- | --- | -| Virtual background option not visible | `showVirtualBackgroundSetting(false)` was set | Set `showVirtualBackgroundSetting(true)` in `CallSettingsBuilder` | -| Background blur not applied on call start | `enforceBackgroundBlur()` not set or set to 0 | Pass a value between 1-99 to `enforceBackgroundBlur()` | -| Custom images not appearing | `setImages()` not called or empty array passed | Pass a non-empty array of valid image URLs to `setImages()` | -| `CallController.getInstance()` returns null | Called before the call has started | Only use `CallController` methods after `startCall()` has been invoked | -| User can't upload their own images | `allowUserImages(false)` was set | Set `allowUserImages(true)` in the `VirtualBackground` configuration | - - - - ## Next Steps From 01ea580fbfe11c1f985b67e09fea0fe73161ab9a Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 18 Mar 2026 14:31:57 +0530 Subject: [PATCH 20/43] Troubleshooting and error guides --- .../additional-message-filtering.mdx | 17 - sdk/javascript/ai-agents.mdx | 16 - sdk/javascript/ai-moderation.mdx | 16 - sdk/javascript/all-real-time-listeners.mdx | 16 - sdk/javascript/best-practices.mdx | 377 ++++++++++++++++++ sdk/javascript/connection-status.mdx | 16 - sdk/javascript/custom-css.mdx | 17 - sdk/javascript/delete-conversation.mdx | 14 - sdk/javascript/delivery-read-receipts.mdx | 15 - sdk/javascript/group-add-members.mdx | 16 - sdk/javascript/group-change-member-scope.mdx | 16 - sdk/javascript/group-kick-ban-members.mdx | 16 - sdk/javascript/groups-overview.mdx | 16 - ...aging-web-sockets-connections-manually.mdx | 16 - sdk/javascript/mentions.mdx | 15 - sdk/javascript/presenter-mode.mdx | 16 - sdk/javascript/reactions.mdx | 15 - sdk/javascript/receive-message.mdx | 17 - sdk/javascript/retrieve-group-members.mdx | 16 - sdk/javascript/retrieve-groups.mdx | 16 - sdk/javascript/send-message.mdx | 17 - sdk/javascript/threaded-messages.mdx | 15 - sdk/javascript/transfer-group-ownership.mdx | 14 - sdk/javascript/troubleshooting.mdx | 142 +++++++ sdk/javascript/typing-indicators.mdx | 15 - sdk/javascript/upgrading-from-v3.mdx | 14 - 26 files changed, 519 insertions(+), 377 deletions(-) diff --git a/sdk/javascript/additional-message-filtering.mdx b/sdk/javascript/additional-message-filtering.mdx index 1334b05bd..1a9f13782 100644 --- a/sdk/javascript/additional-message-filtering.mdx +++ b/sdk/javascript/additional-message-filtering.mdx @@ -1520,23 +1520,6 @@ let GUID: string = "GUID", The response will contain a list of media message objects filtered to only the specified attachment types (e.g., image and video). Each message includes an `attachments` array with file details and thumbnail generation metadata. - -- **Combine filters strategically**: Use `setCategories()` with `setTypes()` for precise filtering -- **Set reasonable limits**: Use 30-50 messages per fetch for optimal performance -- **Use timestamps for sync**: `setUpdatedAfter()` helps sync local cache with server -- **Hide deleted messages in UI**: Use `hideDeletedMessages(true)` for cleaner message lists -- **Filter blocked users**: Use `hideMessagesFromBlockedUsers(true)` to respect user preferences -- **Reuse MessagesRequest**: Call `fetchPrevious()`/`fetchNext()` on the same object for pagination - - - -- **No messages returned** — Conflicting filters may cancel each other out. Simplify filters and add them one at a time to isolate the issue. -- **Missing message types** — Ensure the category matches the type (e.g., category `"message"` for type `"text"`). -- **Pagination not working** — Reuse the same `MessagesRequest` object for `fetchPrevious()` / `fetchNext()` calls. Creating a new object resets pagination. -- **Thread replies included** — Add `.hideReplies(true)` to exclude thread messages from the main conversation. -- **Deleted messages showing** — Add `.hideDeletedMessages(true)` to filter them out. This is not enabled by default. - - --- ## Next Steps diff --git a/sdk/javascript/ai-agents.mdx b/sdk/javascript/ai-agents.mdx index 7c2a7d495..736fff274 100644 --- a/sdk/javascript/ai-agents.mdx +++ b/sdk/javascript/ai-agents.mdx @@ -163,22 +163,6 @@ These events are received via the **`MessageListener`** after the run completes. Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling.
- -- **Register both listeners** — Use `AIAssistantListener` for real-time streaming events and `MessageListener` for persisted agentic messages. Both are needed for a complete experience. -- **Handle streaming progressively** — Use `Text Message Content` events to render the assistant's reply token-by-token for a responsive UI, rather than waiting for the full reply. -- **Track run lifecycle** — Use `Run Start` and `Run Finished` events to show loading indicators and know when the agent is done processing. -- **Remove listeners on cleanup** — Always call both `removeAIAssistantListener()` and `removeMessageListener()` when the component unmounts. -- **Handle tool calls gracefully** — Tool call events may occur multiple times in a single run. Display appropriate UI feedback for each tool invocation. - - - -- **No events received** — Ensure the AI Agent is configured in the CometChat Dashboard and the user is sending text messages (agents only respond to text). -- **`onAIAssistantEventReceived` not firing** — Verify the `AIAssistantListener` is registered after successful `CometChat.init()` and `login()`. -- **Agentic messages not arriving** — These come via `MessageListener` after the run completes. Make sure you've registered `onAIAssistantMessageReceived`, `onAIToolResultReceived`, and `onAIToolArgumentsReceived`. -- **Duplicate events** — Check that you're not registering multiple listeners with different IDs. Remove old listeners before adding new ones. -- **Streaming events arrive but no final message** — The run may have failed. Check for error events in the `onAIAssistantEventReceived` callback. - - --- ## Next Steps diff --git a/sdk/javascript/ai-moderation.mdx b/sdk/javascript/ai-moderation.mdx index a2eb995cb..82bf9f876 100644 --- a/sdk/javascript/ai-moderation.mdx +++ b/sdk/javascript/ai-moderation.mdx @@ -328,22 +328,6 @@ Here's a complete implementation showing the full moderation flow: Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling.
- -- **Show pending state in UI** — When `getModerationStatus()` returns `PENDING`, display a visual indicator (spinner, dimmed message) so users know the message is being reviewed. -- **Handle disapproved messages gracefully** — Don't just hide blocked messages silently. Show a placeholder or notification so the sender understands what happened. -- **Register the listener early** — Add the `onMessageModerated` listener before sending messages so you don't miss any moderation results. -- **Track pending messages** — Maintain a local map of pending message IDs so you can update the UI when moderation results arrive. -- **Test with moderation rules** — Configure moderation rules in the Dashboard before testing. Without rules, messages won't be moderated. - - - -- **`onMessageModerated` never fires** — Ensure moderation is enabled in the CometChat Dashboard and rules are configured under Moderation > Rules. -- **All messages show `PENDING` but never resolve** — Check that your moderation rules are properly configured and the moderation service is active in your plan. -- **Custom messages not being moderated** — AI Moderation only supports Text, Image, and Video messages. Custom messages are not subject to moderation. -- **Moderation status is `undefined`** — You may be using an older SDK version that doesn't support moderation. Update to the latest version. -- **Disapproved messages still visible to recipients** — The SDK handles this automatically. If recipients still see blocked messages, verify your `onMessageModerated` handler is updating the UI correctly. - - ## Next Steps diff --git a/sdk/javascript/all-real-time-listeners.mdx b/sdk/javascript/all-real-time-listeners.mdx index f9323f14c..a33575498 100644 --- a/sdk/javascript/all-real-time-listeners.mdx +++ b/sdk/javascript/all-real-time-listeners.mdx @@ -567,22 +567,6 @@ CometChat.removeCallListener(listenerID); - -- **Use unique listener IDs** — Each listener must have a unique ID. Using the same ID for multiple listeners will overwrite the previous one, causing missed events. -- **Register listeners early** — Add listeners right after `CometChat.init()` and `login()` succeed so you don't miss any events. -- **Always clean up** — Remove all listeners when they're no longer needed (component unmount, page navigation, logout) to prevent memory leaks and duplicate callbacks. -- **Keep listener callbacks lightweight** — Avoid heavy processing inside listener callbacks. Dispatch events to your state management layer and process asynchronously. -- **Use specific listeners** — Only register the listener types you need. Don't register a `GroupListener` if your page only handles messages. - - - -- **Events not firing** — Ensure listeners are registered after a successful `CometChat.init()` and `login()`. Listeners registered before init have no effect. -- **Duplicate events received** — You likely have multiple listeners registered with the same or different IDs. Check that you're removing old listeners before adding new ones. -- **Missing events after page navigation** — Listeners are removed when the component unmounts. Re-register them when the new component mounts. -- **`onMessagesDelivered` / `onMessagesRead` not triggering** — Delivery and read receipts must be explicitly sent by the recipient using `markAsDelivered()` / `markAsRead()`. -- **Call events not received** — Ensure you've registered a `CallListener` and that the CometChat Calling SDK is properly initialized. - - --- ## Next Steps diff --git a/sdk/javascript/best-practices.mdx b/sdk/javascript/best-practices.mdx index 4c86315cd..5205156f2 100644 --- a/sdk/javascript/best-practices.mdx +++ b/sdk/javascript/best-practices.mdx @@ -45,6 +45,12 @@ Follow these best practices to build reliable, performant, and secure applicatio Use the `logoutSuccess` callback to clear your app's local state, redirect to the login screen, and clean up any other SDK listeners. This ensures a clean state when the user logs out. + + Avoid heavy processing inside listener callbacks. Dispatch events to your state management layer and process asynchronously. + + + Only register the listener types you need. Don't register a `GroupListener` if your page only handles messages. + ## Rate Limits @@ -92,6 +98,167 @@ Follow these best practices to build reliable, performant, and secure applicatio +## Messaging + + + + Choose text, media, or custom messages based on your content. + + + Use `setMetadata()` to attach location, device info, or other contextual data. + + + Use `setTags()` to mark messages for easy filtering (e.g., "starred", "important"). + + + Always implement error callbacks to handle network issues or invalid parameters. + + + Before sending media messages, verify the file type matches the message type (IMAGE, VIDEO, AUDIO, FILE). + + + Always call `removeMessageListener()` when components unmount to prevent memory leaks. + + + Use `setLimit()` with reasonable values (30-50) and call `fetchPrevious()` for more. + + + Use `setCategories()` and `setTypes()` to fetch only relevant messages. + + + Use `setCategories()` with `setTypes()` for precise filtering. + + + `setUpdatedAfter()` helps sync local cache with server. + + + Use `hideDeletedMessages(true)` for cleaner message lists. + + + Use `hideMessagesFromBlockedUsers(true)` to respect user preferences. + + + Call `fetchPrevious()`/`fetchNext()` on the same object for pagination. + + + +## Threaded Messages + + + + Store the current thread's `parentMessageId` to filter incoming messages. + + + Exclude thread replies from main conversation to avoid clutter. + + + Use `setLimit()` and `fetchPrevious()` for large threads. + + + Clean up message listeners when user exits a thread view. + + + Display the number of replies on parent messages to indicate thread activity. + + + +## Reactions + + + + Show the reaction immediately, then sync with server response. + + + Keep message objects in sync with real-time events. + + + Provide a curated set of emojis for better UX. + + + Display aggregated counts with `getReactions()` for each message. + + + Check `getReactedByMe()` before allowing users to add the same reaction. + + + +## Mentions + + + + Always use `<@uid:UID>` format for mentions in message text. + + + Ensure mentioned UIDs exist before sending. + + + Parse message text and style mentions differently. + + + Use `mentionsWithTagInfo(true)` to get user tags for mentioned users. + + + Use `mentionsWithBlockedInfo(true)` to check blocked relationships. + + + +## Typing Indicators + + + + Don't call `startTyping()` on every keystroke - debounce to ~300ms intervals. + + + Call `endTyping()` after a period of inactivity (e.g., 3-5 seconds). + + + Always call `endTyping()` when the user sends a message. + + + Prevent duplicate events by using component-specific listener IDs. + + + Clean up listeners when leaving a conversation view. + + + +## Delivery & Read Receipts + + + + Call `markAsDelivered()` when messages are fetched and displayed. + + + Call `markAsRead()` when the user actually views/scrolls to a message. + + + Prefer passing the full message object to `markAsDelivered()`/`markAsRead()` for simplicity. + + + Mark the last message in a batch - all previous messages are automatically marked. + + + Receipts are queued and sent when the user comes back online. + + + +## Conversations + + + + Always show a confirmation dialog before deleting conversations. + + + Remove the conversation from the list optimistically, then handle errors. + + + If deletion fails, restore the conversation in the UI. + + + If you cache conversations locally, remove them after successful deletion. + + + ## Groups @@ -110,6 +277,103 @@ Follow these best practices to build reliable, performant, and secure applicatio Show a confirmation dialog before leaving or deleting a group, especially for groups with important conversations. + + Use public for open communities, private for invite-only teams, password for semi-restricted access. + + + Give admin/moderator roles only to trusted users who need management capabilities. + + + Owners must transfer ownership to another member before they can leave the group. + + + When fetching group members, use `GroupMembersRequestBuilder` with reasonable limits (30-50). + + + Register `GroupListener` to receive real-time updates for member changes, scope changes, and group updates. + + + When building a sidebar or group list, filter to joined groups so users only see groups they belong to. + + + If you call `getGroup()` frequently for the same GUID, cache the result locally to reduce API calls. + + + Fetching tags adds payload size. Only enable it when your UI displays or filters by tags. + + + +## Group Members + + + + Add multiple members in a single `addMembersToGroup()` call rather than calling it once per user. + + + Assign `PARTICIPANT` by default. Only use `ADMIN` or `MODERATOR` when the user genuinely needs elevated permissions. + + + The response array contains per-user results. Check each entry for `"success"` or an error message to handle failures gracefully. + + + Ensure the UIDs exist and are not already members to avoid unnecessary API calls and confusing error responses. + + + Always use `fetchNext()` in a loop or on-scroll. Set a reasonable limit (10–30) per request to avoid large payloads. + + + Create the `GroupMembersRequest` once and call `fetchNext()` repeatedly. Creating a new builder each time resets pagination. + + + Use `setScopes(["admin", "moderator"])` when building admin views to show only privileged members. + + + Filter by `CometChat.USER_STATUS.ONLINE` to show active members in real-time collaboration features. + + + You can chain `setSearchKeyword()`, `setScopes()`, and `setStatus()` on the same builder for precise results. + + + The logged-in user must be the group admin to change another member's scope. Moderators cannot change scopes. + + + Promoting a user to admin gives them full control over the group. Add a confirmation dialog in your UI. + + + Always use `CometChat.GROUP_MEMBER_SCOPE.ADMIN`, `CometChat.GROUP_MEMBER_SCOPE.MODERATOR`, or `CometChat.GROUP_MEMBER_SCOPE.PARTICIPANT` instead of raw strings. + + + Refresh the member list or update the local state after a successful scope change to reflect the new role immediately. + + + Use kick when you want the user to be able to rejoin. Use ban when the user should be permanently removed until explicitly unbanned. + + + Banning is a stronger action than kicking. Add a confirmation dialog in your UI before calling `banGroupMember()`. + + + Use `BannedMembersRequestBuilder` with a reasonable limit (10–30) and call `fetchNext()` in a loop for large banned lists. + + + Only admins and moderators can kick/ban. Check the user's scope before showing these actions in the UI. + + + +## Group Ownership + + + + The owner cannot leave a group without first transferring ownership. Always call `transferGroupOwnership()` before `leaveGroup()`. + + + Transfer ownership to an active admin or moderator who can manage the group responsibly. + + + Ownership transfer is irreversible. Add a confirmation dialog before calling the method. + + + After a successful transfer, update your local group data to reflect the new owner. + ## Calling @@ -133,6 +397,119 @@ Follow these best practices to build reliable, performant, and secure applicatio Always notify participants when recording starts. This is often a legal requirement in many jurisdictions. + + Always generate a new call token using `generateToken()` before starting a presentation. Reusing expired tokens will fail. + + + Use `setIsPresenter(true)` for presenters and `setIsPresenter(false)` for viewers. The default is viewer. + + + The maximum number of presenters is 5. Additional users should join as viewers. + + + These are different events. `onCallEnded` fires when the call ends server-side, while `onCallEndButtonPressed` fires when the user clicks the end button locally. + + + +## Custom CSS (Calling) + + + + Applying styles to undocumented internal classes may break with SDK updates. Stick to the classes listed in the documentation. + + + Altering the grid container dimensions can break the layout. Only customize colors, borders, and visibility. + + + Some SDK styles may need `!important` to override, but overusing it makes maintenance harder. + + + CSS changes may look different in `DEFAULT`, `TILE`, and `SPOTLIGHT` modes. Test all three. + + + When customizing button dimensions, ensure they remain large enough for easy interaction (minimum 44x44px for touch targets). + + + +## Connection & WebSocket + + + + Add the connection listener right after `CometChat.init()` succeeds, ideally in your app's entry point, so you catch all connection state changes. + + + Display a banner or indicator when the connection is `"disconnected"` or `"connecting"` so users know messages may be delayed. + + + If the connection drops, queue user actions (like sending messages) and retry once `onConnected` fires. + + + Use the listener-based approach instead. Polling adds unnecessary overhead when the SDK already pushes state changes. + + + The default auto-connect behavior works well for most apps. Only manage connections manually if you need fine-grained control (e.g., background/foreground transitions, battery optimization). + + + Always verify the user is logged in with `CometChat.getLoggedInUser()` before calling `CometChat.connect()`. + + + Use `CometChat.addConnectionListener()` alongside manual connection management to track the actual connection state. + + + If you disconnect when the app goes to background, call `CometChat.connect()` when the app returns to foreground. + + + Allow time for the connection to establish or close before toggling again. + + + +## AI Features + + + + Use `AIAssistantListener` for real-time streaming events and `MessageListener` for persisted agentic messages. Both are needed for a complete experience. + + + Use `Text Message Content` events to render the assistant's reply token-by-token for a responsive UI, rather than waiting for the full reply. + + + Use `Run Start` and `Run Finished` events to show loading indicators and know when the agent is done processing. + + + Tool call events may occur multiple times in a single run. Display appropriate UI feedback for each tool invocation. + + + When `getModerationStatus()` returns `PENDING`, display a visual indicator (spinner, dimmed message) so users know the message is being reviewed. + + + Don't just hide blocked messages silently. Show a placeholder or notification so the sender understands what happened. + + + Add the `onMessageModerated` listener before sending messages so you don't miss any moderation results. + + + Maintain a local map of pending message IDs so you can update the UI when moderation results arrive. + + + Configure moderation rules in the Dashboard before testing. Without rules, messages won't be moderated. + + + +## Upgrading from V3 + + + + Complete the v4 [setup instructions](/sdk/javascript/setup-sdk) before changing imports, so you have the latest SDK version installed. + + + Use find-and-replace across your project to change all `@cometchat-pro/chat` imports to `@cometchat/chat-sdk-javascript` in one pass. + + + After updating dependencies and imports, test each feature area (messaging, calling, groups) individually to catch any breaking changes. + + + After migration, uninstall the v3 packages (`npm uninstall @cometchat-pro/chat`) to avoid conflicts. + --- diff --git a/sdk/javascript/connection-status.mdx b/sdk/javascript/connection-status.mdx index afcdbbee7..20ecaad73 100644 --- a/sdk/javascript/connection-status.mdx +++ b/sdk/javascript/connection-status.mdx @@ -126,22 +126,6 @@ The connection listener callbacks and `getConnectionStatus()` return string enum Always remove connection listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling.
- -- **Register early** — Add the connection listener right after `CometChat.init()` succeeds, ideally in your app's entry point, so you catch all connection state changes. -- **Show connection status in UI** — Display a banner or indicator when the connection is `"disconnected"` or `"connecting"` so users know messages may be delayed. -- **Queue actions during disconnection** — If the connection drops, queue user actions (like sending messages) and retry once `onConnected` fires. -- **Remove listeners on cleanup** — Always call `CometChat.removeConnectionListener()` when the component unmounts or the app shuts down. -- **Don't poll `getConnectionStatus()`** — Use the listener-based approach instead. Polling adds unnecessary overhead when the SDK already pushes state changes. - - - -- **Listener never fires** — Ensure you register the listener after a successful `CometChat.init()` call. Registering before init has no effect. -- **Stuck in "connecting" state** — Check your network connection and firewall settings. Also verify your `appId` and `region` are correct in the init configuration. -- **Frequent disconnections** — This usually indicates network instability. The SDK automatically reconnects, but if it persists, check for WebSocket-blocking proxies or VPNs. -- **`getConnectionStatus()` returns `undefined`** — The SDK hasn't been initialized yet. Call `CometChat.init()` first. -- **Multiple `onConnected` callbacks** — You likely have multiple listeners registered with different IDs. Remove old listeners before adding new ones. - - --- ## Next Steps diff --git a/sdk/javascript/custom-css.mdx b/sdk/javascript/custom-css.mdx index fd0692626..bdcfd44c0 100644 --- a/sdk/javascript/custom-css.mdx +++ b/sdk/javascript/custom-css.mdx @@ -188,23 +188,6 @@ The above example results in the below output:- By following these recommendations, you can maintain a stable and visually consistent grid layout. - -- **Only use documented CSS classes** — Applying styles to undocumented internal classes may break with SDK updates. Stick to the classes listed in this guide. -- **Don't resize the grid container** — Altering the grid container dimensions can break the layout. Only customize colors, borders, and visibility. -- **Use `!important` sparingly** — Some SDK styles may need `!important` to override, but overusing it makes maintenance harder. -- **Test across modes** — CSS changes may look different in `DEFAULT`, `TILE`, and `SPOTLIGHT` modes. Test all three. -- **Keep button sizes accessible** — When customizing button dimensions, ensure they remain large enough for easy interaction (minimum 44x44px for touch targets). - - - -- **CSS changes not applying** — The SDK may use inline styles or higher-specificity selectors. Try adding `!important` to your rules. -- **Layout breaks after customization** — You may have resized the grid container or applied conflicting `display` or `position` properties. Revert and apply changes incrementally. -- **Styles only work in one mode** — Some CSS classes are mode-specific. Test in `DEFAULT`, `TILE`, and `SPOTLIGHT` modes to ensure consistency. -- **Muted button styles not showing** — Use the `-muted` variant classes (e.g., `cc-audio-icon-container-muted`) for muted state styling. -- **Custom styles disappear on SDK update** — If the SDK updates internal class names, your custom CSS may stop working. Pin your SDK version and test after updates. - - - --- ## Next Steps diff --git a/sdk/javascript/delete-conversation.mdx b/sdk/javascript/delete-conversation.mdx index 253f5607e..6815524c7 100644 --- a/sdk/javascript/delete-conversation.mdx +++ b/sdk/javascript/delete-conversation.mdx @@ -99,20 +99,6 @@ The `deleteConversation()` method takes the following parameters: On success, the `deleteConversation()` method resolves with a success message string confirming the operation. - -- **Confirm before deleting**: Always show a confirmation dialog before deleting conversations -- **Update UI immediately**: Remove the conversation from the list optimistically, then handle errors -- **Handle errors gracefully**: If deletion fails, restore the conversation in the UI -- **Clear local cache**: If you cache conversations locally, remove them after successful deletion - - - -- **Conversation still visible after deletion** — Refresh the conversation list after deletion. Update your UI immediately on success. -- **Delete fails** — Verify the UID or GUID exists and is correct. -- **Other user still sees messages** — The SDK deletes for the logged-in user only. Use the REST API to delete for all participants. -- **"Conversation not found" error** — The conversation may already be deleted, or the `conversationType` doesn't match. Ensure it's `user` or `group` as appropriate. - - --- ## Next Steps diff --git a/sdk/javascript/delivery-read-receipts.mdx b/sdk/javascript/delivery-read-receipts.mdx index 0d34a52c4..b575093fd 100644 --- a/sdk/javascript/delivery-read-receipts.mdx +++ b/sdk/javascript/delivery-read-receipts.mdx @@ -840,21 +840,6 @@ CometChat.removeMessageListener("UNIQUE_LISTENER_ID"); ```
- -- **Mark as delivered on fetch**: Call `markAsDelivered()` when messages are fetched and displayed -- **Mark as read on view**: Call `markAsRead()` when the user actually views/scrolls to a message -- **Use message objects**: Prefer passing the full message object to `markAsDelivered()`/`markAsRead()` for simplicity -- **Batch receipts**: Mark the last message in a batch - all previous messages are automatically marked -- **Handle offline scenarios**: Receipts are queued and sent when the user comes back online - - - -- **Receipts not updating** — Verify `addMessageListener()` includes receipt handlers (`onMessagesDelivered`, `onMessagesRead`). -- **Double-tick not showing** — Call `markAsDelivered()` on message fetch and real-time receive. It won't happen automatically. -- **Read status not syncing** — Use the message object overload for `markAsRead()` for simpler implementation and fewer parameter errors. -- **Group receipts missing** — Enable "Enhanced Messaging Status" in the [CometChat Dashboard](https://app.cometchat.com) for group read receipts. - - --- ## Next Steps diff --git a/sdk/javascript/group-add-members.mdx b/sdk/javascript/group-add-members.mdx index 75ad5f504..98b218791 100644 --- a/sdk/javascript/group-add-members.mdx +++ b/sdk/javascript/group-add-members.mdx @@ -162,22 +162,6 @@ For the group member added event, in the `Action` object received, the following 3. `actionBy` - User object containing the details of the user who added the member to the group 4. `actionFor` - Group object containing the details of the group to which the member was added - -- **Batch member additions** — Add multiple members in a single `addMembersToGroup()` call rather than calling it once per user. -- **Set appropriate scopes** — Assign `PARTICIPANT` by default. Only use `ADMIN` or `MODERATOR` when the user genuinely needs elevated permissions. -- **Handle partial failures** — The response array contains per-user results. Check each entry for `"success"` or an error message to handle failures gracefully. -- **Remove listeners on cleanup** — Always call `CometChat.removeGroupListener()` when the component unmounts or the page navigates away. -- **Validate UIDs before adding** — Ensure the UIDs exist and are not already members to avoid unnecessary API calls and confusing error responses. - - - -- **"ERR_NOT_A_MEMBER" error** — Only admins or moderators can add members. Verify the logged-in user has the correct scope in the group. -- **Some members fail while others succeed** — `addMembersToGroup()` returns per-user results. Check the response object for individual error messages (e.g., user already a member, invalid UID). -- **`onMemberAddedToGroup` not firing** — Ensure the group listener is registered before the add operation. Also verify the listener ID is unique and not being overwritten. -- **Duplicate events received** — You likely have multiple listeners registered with different IDs. Remove old listeners before adding new ones. -- **Banned members can't be added** — A banned user must be unbanned first before they can be added back to the group. - - --- ## Next Steps diff --git a/sdk/javascript/group-change-member-scope.mdx b/sdk/javascript/group-change-member-scope.mdx index a179f6d91..369d19f30 100644 --- a/sdk/javascript/group-change-member-scope.mdx +++ b/sdk/javascript/group-change-member-scope.mdx @@ -136,22 +136,6 @@ For the group member scope changed event, in the `Action` object received, the f 5. `oldScope` - The original scope of the member 6. `newScope` - The updated scope of the member - -- **Only admins can change scope** — The logged-in user must be the group admin to change another member's scope. Moderators cannot change scopes. -- **Confirm before promoting** — Promoting a user to admin gives them full control over the group. Add a confirmation dialog in your UI. -- **Remove listeners on cleanup** — Always call `CometChat.removeGroupListener()` when the component unmounts or the page navigates away. -- **Use scope constants** — Always use `CometChat.GROUP_MEMBER_SCOPE.ADMIN`, `CometChat.GROUP_MEMBER_SCOPE.MODERATOR`, or `CometChat.GROUP_MEMBER_SCOPE.PARTICIPANT` instead of raw strings. -- **Update UI after scope change** — Refresh the member list or update the local state after a successful scope change to reflect the new role immediately. - - - -- **"ERR_NOT_A_MEMBER" or permission error** — Only the group admin can change member scopes. Verify the logged-in user is the admin. -- **Cannot demote another admin** — Only the group owner can demote admins. Regular admins can only change scope of moderators and participants. -- **`onGroupMemberScopeChanged` not firing** — Ensure the group listener is registered before the scope change and the listener ID is unique. -- **Scope change succeeds but UI doesn't update** — The API call returns a boolean. You need to manually update your local member list or re-fetch members after the change. -- **Invalid scope value error** — Use the SDK constants (`CometChat.GROUP_MEMBER_SCOPE.ADMIN`, etc.) rather than raw strings like `"admin"`. - - --- ## Next Steps diff --git a/sdk/javascript/group-kick-ban-members.mdx b/sdk/javascript/group-kick-ban-members.mdx index 6641dce2a..69ec90449 100644 --- a/sdk/javascript/group-kick-ban-members.mdx +++ b/sdk/javascript/group-kick-ban-members.mdx @@ -386,22 +386,6 @@ For group member unbanned event, the details can be obtained using the below fie 3. `actionOn` - User object containing the details of the member that has been unbanned 4. `actionFor` - Group object containing the details of the Group from which the member was unbanned - -- **Kick vs. Ban** — Use kick when you want the user to be able to rejoin. Use ban when the user should be permanently removed until explicitly unbanned. -- **Confirm before banning** — Banning is a stronger action than kicking. Add a confirmation dialog in your UI before calling `banGroupMember()`. -- **Remove listeners on cleanup** — Always call `CometChat.removeGroupListener()` when the component unmounts or the page navigates away. -- **Paginate banned members** — Use `BannedMembersRequestBuilder` with a reasonable limit (10–30) and call `fetchNext()` in a loop for large banned lists. -- **Handle permissions gracefully** — Only admins and moderators can kick/ban. Check the user's scope before showing these actions in the UI. - - - -- **"ERR_NOT_A_MEMBER" or permission error** — Only admins or moderators can kick/ban members. Verify the logged-in user's scope in the group. -- **Kicked user can still see the group** — Kicking removes the user but doesn't prevent rejoining. If you need to block access, use `banGroupMember()` instead. -- **Banned user can rejoin** — This shouldn't happen. Verify you called `banGroupMember()` and not `kickGroupMember()`. Check the banned members list to confirm. -- **`onGroupMemberBanned` not firing** — Ensure the group listener is registered before the ban operation and the listener ID is unique. -- **Unban fails with error** — Verify the user is actually banned in the group. You can confirm by fetching the banned members list first. - - --- ## Next Steps diff --git a/sdk/javascript/groups-overview.mdx b/sdk/javascript/groups-overview.mdx index 5e19c26da..df477b297 100644 --- a/sdk/javascript/groups-overview.mdx +++ b/sdk/javascript/groups-overview.mdx @@ -39,22 +39,6 @@ Each group includes three kinds of users- owner, moderator, member. | **Moderator** | Kick and ban members, moderate content | | **Member** | Send/receive messages, leave group | - -- **Choose the right group type** — Use public for open communities, private for invite-only teams, password for semi-restricted access -- **Assign appropriate roles** — Give admin/moderator roles only to trusted users who need management capabilities -- **Transfer ownership before leaving** — Owners must transfer ownership to another member before they can leave the group -- **Use pagination for large groups** — When fetching group members, use `GroupMembersRequestBuilder` with reasonable limits (30-50) -- **Handle group events** — Register `GroupListener` to receive real-time updates for member changes, scope changes, and group updates - - - -- **Can't join private group** — Private groups require an admin to add you. Use `joinGroup()` only for public or password-protected groups. -- **Owner can't leave group** — Transfer ownership first using `transferGroupOwnership()`, then call `leaveGroup()`. -- **Group not appearing in list** — Verify you're a member of the group. Use `getJoinedGroups()` to fetch only groups you've joined. -- **Permission denied errors** — Check the user's scope in the group. Only admins/moderators can perform management actions. -- **Password group join fails** — Ensure the password is correct and passed as the second parameter to `joinGroup()`. - - --- ## Next Steps diff --git a/sdk/javascript/managing-web-sockets-connections-manually.mdx b/sdk/javascript/managing-web-sockets-connections-manually.mdx index 3c4ee94de..6cd7a7380 100644 --- a/sdk/javascript/managing-web-sockets-connections-manually.mdx +++ b/sdk/javascript/managing-web-sockets-connections-manually.mdx @@ -115,22 +115,6 @@ CometChat.disconnect(); - -- **Only disable auto-connect when needed** — The default auto-connect behavior works well for most apps. Only manage connections manually if you need fine-grained control (e.g., background/foreground transitions, battery optimization). -- **Check login status before connecting** — Always verify the user is logged in with `CometChat.getLoggedInUser()` before calling `CometChat.connect()`. -- **Pair with Connection Listener** — Use `CometChat.addConnectionListener()` alongside manual connection management to track the actual connection state. -- **Reconnect on app foreground** — If you disconnect when the app goes to background, call `CometChat.connect()` when the app returns to foreground. -- **Don't call connect/disconnect rapidly** — Allow time for the connection to establish or close before toggling again. - - - -- **No real-time events after login** — If you set `autoEstablishSocketConnection(false)`, you must call `CometChat.connect()` manually after login. -- **`connect()` doesn't seem to work** — Ensure the user is logged in first. `connect()` requires an authenticated session. -- **Events stop after calling `disconnect()`** — This is expected. Call `CometChat.connect()` to resume receiving events. -- **Connection drops intermittently** — This is usually a network issue. The SDK auto-reconnects by default, but if you're managing connections manually, you need to handle reconnection logic yourself. -- **`autoEstablishSocketConnection(false)` not taking effect** — Make sure you're passing it to the `AppSettingsBuilder` before calling `CometChat.init()`. It cannot be changed after initialization. - - --- ## Next Steps diff --git a/sdk/javascript/mentions.mdx b/sdk/javascript/mentions.mdx index 395723bfd..097193e83 100644 --- a/sdk/javascript/mentions.mdx +++ b/sdk/javascript/mentions.mdx @@ -394,21 +394,6 @@ Messages containing mentions are returned as [`BaseMessage`](/sdk/reference/mess | mentionedUsers | `getMentionedUsers()` | [`User[]`](/sdk/reference/entities#user) | Array of users mentioned in the message | | hasMentionedMe | `hasMentionedMe()` | `boolean` | Whether the logged-in user is mentioned in the message | - -- **Use correct format**: Always use `<@uid:UID>` format for mentions in message text -- **Validate UIDs**: Ensure mentioned UIDs exist before sending -- **Highlight mentions in UI**: Parse message text and style mentions differently -- **Fetch tag info when needed**: Use `mentionsWithTagInfo(true)` to get user tags for mentioned users -- **Handle blocked users**: Use `mentionsWithBlockedInfo(true)` to check blocked relationships - - - -- **Mention not parsed** — Use the `<@uid:UID>` format exactly. Any deviation will prevent parsing. -- **`getMentionedUsers()` returns empty** — This only works on messages received from the server, not locally constructed messages. -- **Missing user tags** — Add `mentionsWithTagInfo(true)` to your request builder to include tag information. -- **Blocked info missing** — Add `mentionsWithBlockedInfo(true)` to your request builder to include blocked relationship data. - - --- ## Next Steps diff --git a/sdk/javascript/presenter-mode.mdx b/sdk/javascript/presenter-mode.mdx index f4c869a07..2500f850a 100644 --- a/sdk/javascript/presenter-mode.mdx +++ b/sdk/javascript/presenter-mode.mdx @@ -171,22 +171,6 @@ CometChatCalls.removeCallEventListener("UNIQUE_ID"); ``` - -- **Generate a fresh call token** — Always generate a new call token using `generateToken()` before starting a presentation. Reusing expired tokens will fail. -- **Set presenter role explicitly** — Use `setIsPresenter(true)` for presenters and `setIsPresenter(false)` for viewers. The default is viewer. -- **Limit presenters to 5** — The maximum number of presenters is 5. Additional users should join as viewers. -- **Remove listeners on cleanup** — Always call `CometChatCalls.removeCallEventListener()` when the component unmounts or the presentation ends. -- **Handle `onCallEnded` and `onCallEndButtonPressed`** — These are different events. `onCallEnded` fires when the call ends server-side, while `onCallEndButtonPressed` fires when the user clicks the end button locally. - - - -- **Presentation doesn't start** — Ensure you've generated a valid call token and the HTML element exists in the DOM before calling `joinPresentation()`. -- **Viewer can send audio/video** — Verify `setIsPresenter(false)` is set for viewers. Viewers should not have outgoing streams. -- **`onUserJoined` not firing** — Ensure the call event listener is registered before joining the presentation. -- **Black screen after joining** — Check that the HTML element passed to `joinPresentation()` is visible and has proper dimensions (width/height). -- **More than 5 presenters needed** — Presenter Mode supports a maximum of 5 presenters. Consider using a standard group call for more active participants. - - --- ## Next Steps diff --git a/sdk/javascript/reactions.mdx b/sdk/javascript/reactions.mdx index c61c438c8..f36a62be9 100644 --- a/sdk/javascript/reactions.mdx +++ b/sdk/javascript/reactions.mdx @@ -405,21 +405,6 @@ action After calling this method, the message instance's reactions are updated. You can then use message.getReactions() to get the latest reactions and refresh your UI accordingly. - -- **Update UI optimistically**: Show the reaction immediately, then sync with server response -- **Use `updateMessageWithReactionInfo()`**: Keep message objects in sync with real-time events -- **Limit reaction options**: Provide a curated set of emojis for better UX -- **Show reaction counts**: Display aggregated counts with `getReactions()` for each message -- **Handle duplicates**: Check `getReactedByMe()` before allowing users to add the same reaction - - - -- **Reaction not appearing** — Call `updateMessageWithReactionInfo()` on real-time events to keep the UI in sync. -- **Duplicate reactions** — Use `getReactedByMe()` to check if the user already reacted before adding. -- **Reactions out of sync** — Ensure `onMessageReactionAdded` and `onMessageReactionRemoved` handlers are registered. -- **Can't remove reaction** — Use the exact same emoji string that was used when adding the reaction. - - --- ## Next Steps diff --git a/sdk/javascript/receive-message.mdx b/sdk/javascript/receive-message.mdx index 09eab272f..c3af814b2 100644 --- a/sdk/javascript/receive-message.mdx +++ b/sdk/javascript/receive-message.mdx @@ -1005,23 +1005,6 @@ CometChat.getUnreadMessageCountForAllGroups().then( It returns an object which will contain the GUID as the key and the unread message count as the value. - -- **Remove listeners on cleanup**: Always call `removeMessageListener()` when components unmount to prevent memory leaks -- **Use unique listener IDs**: Generate unique IDs per component/screen to avoid conflicts -- **Handle all message types**: Implement handlers for text, media, and custom messages -- **Fetch missed messages on app resume**: Call `getLastDeliveredMessageId()` and fetch messages since that ID -- **Paginate message history**: Use `setLimit()` with reasonable values (30-50) and call `fetchPrevious()` for more -- **Filter by category/type**: Use `setCategories()` and `setTypes()` to fetch only relevant messages - - - -- **Not receiving messages** — Verify `addMessageListener()` was called with the correct listener ID before messages are sent. -- **Duplicate messages** — Ensure only one listener per ID is registered. Remove listeners on component unmount. -- **Missing messages after reconnect** — Use `getLastDeliveredMessageId()` + `fetchNext()` to fetch messages missed while offline. -- **Wrong message count** — Blocked users may be included. Use `hideMessagesFromBlockedUsers` parameter to exclude them. -- **History not loading** — Use `fetchPrevious()` for message history and `fetchNext()` for missed messages. Don't mix them up. - - --- ## Next Steps diff --git a/sdk/javascript/retrieve-group-members.mdx b/sdk/javascript/retrieve-group-members.mdx index e410c6e51..ba27d0679 100644 --- a/sdk/javascript/retrieve-group-members.mdx +++ b/sdk/javascript/retrieve-group-members.mdx @@ -216,22 +216,6 @@ The `fetchNext()` method returns an array of [`GroupMember`](/sdk/reference/enti | joinedAt | `getJoinedAt()` | `number` | Timestamp when the member joined the group | | guid | `getGuid()` | `string` | GUID of the group this member belongs to | - -- **Paginate results** — Always use `fetchNext()` in a loop or on-scroll. Set a reasonable limit (10–30) per request to avoid large payloads. -- **Reuse the request object** — Create the `GroupMembersRequest` once and call `fetchNext()` repeatedly. Creating a new builder each time resets pagination. -- **Filter by scope for admin panels** — Use `setScopes(["admin", "moderator"])` when building admin views to show only privileged members. -- **Use status filter for presence** — Filter by `CometChat.USER_STATUS.ONLINE` to show active members in real-time collaboration features. -- **Combine filters** — You can chain `setSearchKeyword()`, `setScopes()`, and `setStatus()` on the same builder for precise results. - - - -- **Empty member list returned** — Verify the GUID is correct and the logged-in user is a member of the group. Non-members cannot fetch member lists. -- **`fetchNext()` returns the same results** — You're likely creating a new `GroupMembersRequest` each time. Reuse the same instance for pagination. -- **Search not finding members** — `setSearchKeyword()` matches against member names. Ensure the keyword is correct and partially matches. -- **Scope filter returns no results** — Double-check the scope strings. Valid values are `"admin"`, `"moderator"`, and `"participant"`. -- **Status filter not working** — Use `CometChat.USER_STATUS.ONLINE` or `CometChat.USER_STATUS.OFFLINE` constants, not raw strings. - - --- ## Next Steps diff --git a/sdk/javascript/retrieve-groups.mdx b/sdk/javascript/retrieve-groups.mdx index 6b8fa0efc..c7dbd2afd 100644 --- a/sdk/javascript/retrieve-groups.mdx +++ b/sdk/javascript/retrieve-groups.mdx @@ -326,22 +326,6 @@ CometChat.getOnlineGroupMemberCount(guids).then( This method returns a JSON Object with the GUID as the key and the online member count for that group as the value. - -- **Use pagination** — Always call `fetchNext()` in a loop or on-scroll rather than fetching all groups at once. Set a reasonable limit (10–30) per page. -- **Cache group details** — If you call `getGroup()` frequently for the same GUID, cache the result locally to reduce API calls. -- **Use `joinedOnly(true)` for navigation** — When building a sidebar or group list, filter to joined groups so users only see groups they belong to. -- **Combine filters wisely** — You can chain `setSearchKeyword()`, `setTags()`, and `joinedOnly()` on the same builder for precise results. -- **Use `withTags(true)` only when needed** — Fetching tags adds payload size. Only enable it when your UI displays or filters by tags. - - - -- **Empty group list returned** — Ensure the logged-in user has the correct permissions. Private groups only appear if the user is a member. -- **`fetchNext()` returns the same results** — You're likely creating a new `GroupsRequest` object each time. Reuse the same instance across pagination calls. -- **`getGroup()` fails with "Group not found"** — Verify the GUID is correct and the group hasn't been deleted. Password/private groups require membership. -- **Online member count returns 0** — The user must be a member of the group. Also confirm the GUIDs array is not empty. -- **Search not returning expected results** — `setSearchKeyword()` matches against the group name. Ensure the keyword is spelled correctly and is at least partially matching. - - --- ## Next Steps diff --git a/sdk/javascript/send-message.mdx b/sdk/javascript/send-message.mdx index 4a43fa3dd..5aa4a540b 100644 --- a/sdk/javascript/send-message.mdx +++ b/sdk/javascript/send-message.mdx @@ -1758,23 +1758,6 @@ It is also possible to send interactive messages from CometChat, to know more [c - -- **Use appropriate message types**: Choose text, media, or custom messages based on your content -- **Add metadata for context**: Use `setMetadata()` to attach location, device info, or other contextual data -- **Tag important messages**: Use `setTags()` to mark messages for easy filtering (e.g., "starred", "important") -- **Handle errors gracefully**: Always implement error callbacks to handle network issues or invalid parameters -- **Use async/await for cleaner code**: Modern JavaScript syntax makes message sending code more readable -- **Validate file types**: Before sending media messages, verify the file type matches the message type (IMAGE, VIDEO, AUDIO, FILE) - - - -- **Message not sent** — Ensure `CometChat.login()` succeeded before sending. The user must be logged in. -- **Media upload fails** — Check file size limits in your CometChat plan. Verify the file type matches the message type. -- **Custom message not received** — Ensure the receiver has an `onCustomMessageReceived` handler registered. -- **Metadata not appearing** — Use `setMetadata()` before calling the send method, not after. -- **Quoted message fails** — Verify the quoted message ID exists and belongs to the same conversation. - - --- ## Next Steps diff --git a/sdk/javascript/threaded-messages.mdx b/sdk/javascript/threaded-messages.mdx index a1379e661..cbde9a1b7 100644 --- a/sdk/javascript/threaded-messages.mdx +++ b/sdk/javascript/threaded-messages.mdx @@ -306,21 +306,6 @@ messagesRequest.fetchPrevious().then( The above snippet will return messages between the logged in user and `cometchat-uid-1` excluding all the threaded messages belonging to the same conversation. - -- **Track active thread ID**: Store the current thread's `parentMessageId` to filter incoming messages -- **Use `hideReplies(true)`**: Exclude thread replies from main conversation to avoid clutter -- **Paginate thread messages**: Use `setLimit()` and `fetchPrevious()` for large threads -- **Remove listeners on thread close**: Clean up message listeners when user exits a thread view -- **Show reply count**: Display the number of replies on parent messages to indicate thread activity - - - -- **Thread replies appearing in main chat** — Add `.hideReplies(true)` to your `MessagesRequestBuilder` to exclude thread replies from the main conversation. -- **Missing thread messages** — Verify `setParentMessageId()` uses the correct parent message ID. -- **Real-time messages not filtered** — Compare `getParentMessageId()` with the active thread ID to filter incoming messages. -- **Empty thread** — The parent message may have been deleted. Handle this case gracefully in your UI. - - --- ## Next Steps diff --git a/sdk/javascript/transfer-group-ownership.mdx b/sdk/javascript/transfer-group-ownership.mdx index ba6b7ac88..fae911602 100644 --- a/sdk/javascript/transfer-group-ownership.mdx +++ b/sdk/javascript/transfer-group-ownership.mdx @@ -55,20 +55,6 @@ CometChat.transferGroupOwnership(GUID, UID).then( On success, the method resolves with a success message string confirming the operation. - -- **Transfer before leaving** — The owner cannot leave a group without first transferring ownership. Always call `transferGroupOwnership()` before `leaveGroup()`. -- **Choose a trusted member** — Transfer ownership to an active admin or moderator who can manage the group responsibly. -- **Confirm in UI** — Ownership transfer is irreversible. Add a confirmation dialog before calling the method. -- **Update local state** — After a successful transfer, update your local group data to reflect the new owner. - - - -- **"ERR_NOT_A_MEMBER" or permission error** — Only the current group owner can transfer ownership. Verify the logged-in user is the owner. -- **Transfer fails with "User not found"** — The target UID must be an existing member of the group. Verify the UID and their membership status. -- **Owner still can't leave after transfer** — Ensure the `transferGroupOwnership()` promise resolved successfully before calling `leaveGroup()`. -- **New owner doesn't have admin privileges** — After ownership transfer, the new owner automatically gets the owner role. If the UI doesn't reflect this, re-fetch the group details. - - --- ## Next Steps diff --git a/sdk/javascript/troubleshooting.mdx b/sdk/javascript/troubleshooting.mdx index 61b2454e9..e3f2b2023 100644 --- a/sdk/javascript/troubleshooting.mdx +++ b/sdk/javascript/troubleshooting.mdx @@ -63,6 +63,17 @@ description: "Common failure modes and fixes for the CometChat JavaScript SDK." | Messages not appearing in conversation | Wrong receiver type | Use `CometChat.RECEIVER_TYPE.USER` for 1:1 and `CometChat.RECEIVER_TYPE.GROUP` for groups | | Media message upload fails | File too large or unsupported format | Check file size limits. Supported formats: images (PNG, JPG, GIF), videos (MP4), audio (MP3, WAV) | | `onTextMessageReceived` not firing | Listener registered after message sent | Register listeners immediately after `login()` completes | +| Custom message not received | Missing handler | Ensure the receiver has an `onCustomMessageReceived` handler registered | +| Metadata not appearing | Set after send | Use `setMetadata()` before calling the send method, not after | +| Quoted message fails | Invalid message ID | Verify the quoted message ID exists and belongs to the same conversation | +| No messages returned from filter | Conflicting filters | Simplify filters and add them one at a time to isolate the issue | +| Missing message types | Category mismatch | Ensure the category matches the type (e.g., category `"message"` for type `"text"`) | +| Pagination not working | New request object | Reuse the same `MessagesRequest` object for `fetchPrevious()` / `fetchNext()` calls | +| Thread replies included | Missing filter | Add `.hideReplies(true)` to exclude thread messages from the main conversation | +| Deleted messages showing | Missing filter | Add `.hideDeletedMessages(true)` to filter them out | +| Thread replies appearing in main chat | Missing filter | Add `.hideReplies(true)` to your `MessagesRequestBuilder` | +| Missing thread messages | Wrong parent ID | Verify `setParentMessageId()` uses the correct parent message ID | +| Empty thread | Deleted parent | The parent message may have been deleted. Handle this case gracefully in your UI | --- @@ -75,6 +86,32 @@ description: "Common failure modes and fixes for the CometChat JavaScript SDK." | Group members not loading | Insufficient permissions | Only group members can fetch member list. Ensure user has joined | | Cannot kick/ban members | User lacks admin/moderator scope | Only admins and moderators can kick/ban. Check user's scope in the group | | Group creation fails | Missing required fields | Ensure GUID, name, and group type are provided | +| Can't join private group | Requires admin invite | Private groups require an admin to add you. Use `joinGroup()` only for public or password-protected groups | +| Owner can't leave group | Ownership not transferred | Transfer ownership first using `transferGroupOwnership()`, then call `leaveGroup()` | +| Group not appearing in list | Not a member | Verify you're a member of the group. Use `getJoinedGroups()` to fetch only groups you've joined | +| Password group join fails | Wrong password | Ensure the password is correct and passed as the second parameter to `joinGroup()` | +| Empty group list returned | Permission issue | Ensure the logged-in user has the correct permissions. Private groups only appear if the user is a member | +| `fetchNext()` returns same results | New request object | You're likely creating a new `GroupsRequest` object each time. Reuse the same instance | +| `getGroup()` fails with "Group not found" | Invalid GUID or deleted | Verify the GUID is correct and the group hasn't been deleted. Password/private groups require membership | +| Online member count returns 0 | Not a member | The user must be a member of the group. Also confirm the GUIDs array is not empty | +| Search not returning expected results | Partial match issue | `setSearchKeyword()` matches against the group name. Ensure the keyword is spelled correctly | +| Empty member list returned | Not a member | Verify the GUID is correct and the logged-in user is a member of the group | +| Scope filter returns no results | Invalid scope strings | Valid values are `"admin"`, `"moderator"`, and `"participant"` | +| Status filter not working | Wrong constant | Use `CometChat.USER_STATUS.ONLINE` or `CometChat.USER_STATUS.OFFLINE` constants, not raw strings | +| "ERR_NOT_A_MEMBER" when adding members | Insufficient permissions | Only admins or moderators can add members. Verify the logged-in user has the correct scope | +| Some members fail while others succeed | Per-user errors | `addMembersToGroup()` returns per-user results. Check the response object for individual error messages | +| `onMemberAddedToGroup` not firing | Listener not registered | Ensure the group listener is registered before the add operation | +| Cannot demote another admin | Not owner | Only the group owner can demote admins. Regular admins can only change scope of moderators and participants | +| `onGroupMemberScopeChanged` not firing | Listener not registered | Ensure the group listener is registered before the scope change | +| Scope change succeeds but UI doesn't update | Manual update needed | The API call returns a boolean. You need to manually update your local member list | +| Invalid scope value error | Raw strings used | Use the SDK constants (`CometChat.GROUP_MEMBER_SCOPE.ADMIN`, etc.) rather than raw strings | +| Kicked user can still see the group | Kick vs ban | Kicking removes the user but doesn't prevent rejoining. Use `banGroupMember()` instead | +| Banned user can rejoin | Wrong method used | Verify you called `banGroupMember()` and not `kickGroupMember()` | +| `onGroupMemberBanned` not firing | Listener not registered | Ensure the group listener is registered before the ban operation | +| Unban fails with error | User not banned | Verify the user is actually banned in the group by fetching the banned members list | +| Transfer fails with "User not found" | Invalid UID | The target UID must be an existing member of the group | +| Owner still can't leave after transfer | Transfer not complete | Ensure the `transferGroupOwnership()` promise resolved successfully before calling `leaveGroup()` | +| New owner doesn't have admin privileges | UI not updated | After ownership transfer, the new owner automatically gets the owner role. Re-fetch the group details | --- @@ -89,6 +126,16 @@ description: "Common failure modes and fixes for the CometChat JavaScript SDK." | Poor call quality | Network bandwidth issues | Check connection stability. Consider audio-only fallback for poor connections | | Call buttons not appearing | Calls SDK not detected | Ensure `@cometchat/calls-sdk-javascript` is installed — UI Kit auto-detects it | | Incoming call not showing | Call listener not registered | Register `CometChat.addCallListener()` at app root level | +| Presentation doesn't start | Invalid token or missing element | Ensure you've generated a valid call token and the HTML element exists in the DOM before calling `joinPresentation()` | +| Viewer can send audio/video | Wrong role | Verify `setIsPresenter(false)` is set for viewers. Viewers should not have outgoing streams | +| `onUserJoined` not firing | Listener not registered | Ensure the call event listener is registered before joining the presentation | +| Black screen after joining | Element not visible | Check that the HTML element passed to `joinPresentation()` is visible and has proper dimensions | +| More than 5 presenters needed | Limit reached | Presenter Mode supports a maximum of 5 presenters. Consider using a standard group call | +| CSS changes not applying | Specificity issue | The SDK may use inline styles or higher-specificity selectors. Try adding `!important` | +| Layout breaks after customization | Container resized | You may have resized the grid container or applied conflicting `display` or `position` properties | +| Styles only work in one mode | Mode-specific classes | Some CSS classes are mode-specific. Test in `DEFAULT`, `TILE`, and `SPOTLIGHT` modes | +| Muted button styles not showing | Wrong class | Use the `-muted` variant classes (e.g., `cc-audio-icon-container-muted`) for muted state styling | +| Custom styles disappear on SDK update | Class names changed | If the SDK updates internal class names, your custom CSS may stop working. Pin your SDK version | --- @@ -101,6 +148,15 @@ description: "Common failure modes and fixes for the CometChat JavaScript SDK." | Connection drops frequently | Network instability | Implement reconnection logic. Use `CometChat.addConnectionListener()` to monitor status | | Events delayed or batched | Network latency | This is expected on slow connections. Events are delivered in order | | `autoEstablishSocketConnection` not working | Set to `false` in AppSettings | If managing connections manually, call `CometChat.connect()` explicitly | +| Listener never fires | Registered before init | Ensure you register the listener after a successful `CometChat.init()` call | +| Stuck in "connecting" state | Network or config issue | Check your network connection and firewall settings. Verify `appId` and `region` are correct | +| Frequent disconnections | Network instability | The SDK automatically reconnects, but check for WebSocket-blocking proxies or VPNs | +| `getConnectionStatus()` returns `undefined` | SDK not initialized | The SDK hasn't been initialized yet. Call `CometChat.init()` first | +| Multiple `onConnected` callbacks | Multiple listeners | You likely have multiple listeners registered with different IDs. Remove old listeners | +| No real-time events after login | Auto-connect disabled | If you set `autoEstablishSocketConnection(false)`, you must call `CometChat.connect()` manually | +| `connect()` doesn't seem to work | Not logged in | Ensure the user is logged in first. `connect()` requires an authenticated session | +| Events stop after calling `disconnect()` | Expected behavior | Call `CometChat.connect()` to resume receiving events | +| `autoEstablishSocketConnection(false)` not taking effect | Set after init | Make sure you're passing it to the `AppSettingsBuilder` before calling `CometChat.init()` | --- @@ -114,6 +170,14 @@ description: "Common failure modes and fixes for the CometChat JavaScript SDK." | Moderation status always PENDING | Moderation rules not configured | Configure moderation rules in Dashboard → Moderation → Rules | | Extension feature not appearing | Extension not activated | Enable the extension from [Dashboard](https://app.cometchat.com) → Extensions | | Stickers/Polls not showing | Extension not enabled | Activate Stickers or Polls extension in Dashboard | +| `onMessageModerated` never fires | Moderation not enabled | Ensure moderation is enabled in the CometChat Dashboard and rules are configured | +| All messages show `PENDING` but never resolve | Rules not configured | Check that your moderation rules are properly configured and the moderation service is active | +| Custom messages not being moderated | Unsupported type | AI Moderation only supports Text, Image, and Video messages. Custom messages are not moderated | +| Moderation status is `undefined` | Old SDK version | You may be using an older SDK version. Update to the latest version | +| Disapproved messages still visible | UI not updated | Verify your `onMessageModerated` handler is updating the UI correctly | +| Agentic messages not arriving | Wrong listener | These come via `MessageListener` after the run completes. Register `onAIAssistantMessageReceived` | +| Duplicate AI events | Multiple listeners | Check that you're not registering multiple listeners with different IDs | +| Streaming events arrive but no final message | Run failed | The run may have failed. Check for error events in the `onAIAssistantEventReceived` callback | --- @@ -129,6 +193,84 @@ description: "Common failure modes and fixes for the CometChat JavaScript SDK." --- +## Listeners + +| Symptom | Cause | Fix | +| --- | --- | --- | +| Events not firing | Listeners registered before init | Ensure listeners are registered after a successful `CometChat.init()` and `login()` | +| Duplicate events received | Multiple listeners | You likely have multiple listeners registered with the same or different IDs. Remove old listeners | +| Missing events after page navigation | Listeners removed | Listeners are removed when the component unmounts. Re-register them when the new component mounts | +| `onMessagesDelivered` / `onMessagesRead` not triggering | Receipts not sent | Delivery and read receipts must be explicitly sent by the recipient using `markAsDelivered()` / `markAsRead()` | +| Call events not received | Call listener not registered | Ensure you've registered a `CallListener` and that the CometChat Calling SDK is properly initialized | + +--- + +## Typing Indicators + +| Symptom | Cause | Fix | +| --- | --- | --- | +| Typing indicator not showing | Listener not registered | Verify `addMessageListener()` is called before typing starts | +| Indicator stuck on "typing" | `endTyping()` not called | Ensure `endTyping()` is called on message send, input blur, or after a timeout (3-5 seconds) | +| Multiple typing events firing | Duplicate listeners | Use unique listener IDs and remove listeners on component unmount | +| Wrong user shown typing | Wrong receiver ID | Verify the `receiverId` matches the current conversation's UID or GUID | + +--- + +## Delivery & Read Receipts + +| Symptom | Cause | Fix | +| --- | --- | --- | +| Receipts not updating | Missing handlers | Verify `addMessageListener()` includes receipt handlers (`onMessagesDelivered`, `onMessagesRead`) | +| Double-tick not showing | `markAsDelivered()` not called | Call `markAsDelivered()` on message fetch and real-time receive. It won't happen automatically | +| Read status not syncing | Parameter errors | Use the message object overload for `markAsRead()` for simpler implementation | +| Group receipts missing | Feature not enabled | Enable "Enhanced Messaging Status" in the [CometChat Dashboard](https://app.cometchat.com) | + +--- + +## Reactions + +| Symptom | Cause | Fix | +| --- | --- | --- | +| Reaction not appearing | UI not synced | Call `updateMessageWithReactionInfo()` on real-time events to keep the UI in sync | +| Duplicate reactions | No check before adding | Use `getReactedByMe()` to check if the user already reacted before adding | +| Reactions out of sync | Missing handlers | Ensure `onMessageReactionAdded` and `onMessageReactionRemoved` handlers are registered | +| Can't remove reaction | Wrong emoji string | Use the exact same emoji string that was used when adding the reaction | + +--- + +## Mentions + +| Symptom | Cause | Fix | +| --- | --- | --- | +| Mention not parsed | Wrong format | Use the `<@uid:UID>` format exactly. Any deviation will prevent parsing | +| `getMentionedUsers()` returns empty | Local message | This only works on messages received from the server, not locally constructed messages | +| Missing user tags | Not requested | Add `mentionsWithTagInfo(true)` to your request builder | +| Blocked info missing | Not requested | Add `mentionsWithBlockedInfo(true)` to your request builder | + +--- + +## Conversations + +| Symptom | Cause | Fix | +| --- | --- | --- | +| Conversation still visible after deletion | UI not updated | Refresh the conversation list after deletion. Update your UI immediately on success | +| Delete fails | Invalid ID | Verify the UID or GUID exists and is correct | +| Other user still sees messages | Local deletion only | The SDK deletes for the logged-in user only. Use the REST API to delete for all participants | +| "Conversation not found" error | Already deleted or wrong type | The conversation may already be deleted, or the `conversationType` doesn't match | + +--- + +## Upgrading from V3 + +| Symptom | Cause | Fix | +| --- | --- | --- | +| "Module not found" errors after upgrade | Old import paths | Search your project for `@cometchat-pro/chat` and replace with `@cometchat/chat-sdk-javascript` | +| Calls SDK not working | Wrong package name | The calls SDK package name also changed. Use `@cometchat/calls-sdk-javascript` | +| TypeScript type errors | Type definitions changed | Some type definitions may have changed. Check the [changelog](https://github.com/cometchat/chat-sdk-javascript/releases) | +| Both v3 and v4 installed | Package conflict | Having both versions can cause conflicts. Remove the v3 package completely before installing v4 | + +--- + ## Common Error Codes | Error Code | Description | Resolution | diff --git a/sdk/javascript/typing-indicators.mdx b/sdk/javascript/typing-indicators.mdx index 279d3c874..7bd7d6e60 100644 --- a/sdk/javascript/typing-indicators.mdx +++ b/sdk/javascript/typing-indicators.mdx @@ -204,21 +204,6 @@ The `onTypingStarted` and `onTypingEnded` listener callbacks receive a [`TypingI | sender | `getSender()` | `User` | The user who is typing | | metadata | `getMetadata()` | `Object` | Additional custom data sent with the indicator | - -- **Debounce typing events**: Don't call `startTyping()` on every keystroke - debounce to ~300ms intervals -- **Auto-stop typing**: Call `endTyping()` after a period of inactivity (e.g., 3-5 seconds) -- **Stop on send**: Always call `endTyping()` when the user sends a message -- **Use unique listener IDs**: Prevent duplicate events by using component-specific listener IDs -- **Remove listeners on unmount**: Clean up listeners when leaving a conversation view - - - -- **Typing indicator not showing** — Verify `addMessageListener()` is called before typing starts. The listener must be registered first. -- **Indicator stuck on "typing"** — Ensure `endTyping()` is called on message send, input blur, or after a timeout (3-5 seconds of inactivity). -- **Multiple typing events firing** — Use unique listener IDs and remove listeners on component unmount to prevent duplicates. -- **Wrong user shown typing** — Verify the `receiverId` matches the current conversation's UID or GUID. - - --- ## Next Steps diff --git a/sdk/javascript/upgrading-from-v3.mdx b/sdk/javascript/upgrading-from-v3.mdx index 6017ea9d0..51d7e1b01 100644 --- a/sdk/javascript/upgrading-from-v3.mdx +++ b/sdk/javascript/upgrading-from-v3.mdx @@ -72,20 +72,6 @@ import {CometChatCalls} from '@cometchat/calls-sdk-javascript'; - -- **Follow the setup guide first** — Complete the v4 [setup instructions](/sdk/javascript/setup-sdk) before changing imports, so you have the latest SDK version installed. -- **Update all imports at once** — Use find-and-replace across your project to change all `@cometchat-pro/chat` imports to `@cometchat/chat-sdk-javascript` in one pass. -- **Test incrementally** — After updating dependencies and imports, test each feature area (messaging, calling, groups) individually to catch any breaking changes. -- **Remove old packages** — After migration, uninstall the v3 packages (`npm uninstall @cometchat-pro/chat`) to avoid conflicts. - - - -- **"Module not found" errors after upgrade** — You likely have old import paths. Search your project for `@cometchat-pro/chat` and replace with `@cometchat/chat-sdk-javascript`. -- **Calls SDK not working** — The calls SDK package name also changed. Use `@cometchat/calls-sdk-javascript` instead of the v3 package. -- **TypeScript type errors** — Some type definitions may have changed between v3 and v4. Check the [changelog](https://github.com/cometchat/chat-sdk-javascript/releases) for breaking type changes. -- **Both v3 and v4 installed** — Having both versions can cause conflicts. Remove the v3 package completely before installing v4. - - --- ## Next Steps From 34dfb3aa742e92486841655ce66fbac854cea395 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 18 Mar 2026 14:33:42 +0530 Subject: [PATCH 21/43] Update docs.json --- docs.json | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs.json b/docs.json index fb3d74c42..df5363a19 100644 --- a/docs.json +++ b/docs.json @@ -2495,9 +2495,7 @@ "sdk/javascript/overview", "sdk/javascript/key-concepts", "sdk/javascript/message-structure-and-hierarchy", - "sdk/javascript/rate-limits", - "sdk/javascript/best-practices", - "sdk/javascript/troubleshooting" + "sdk/javascript/rate-limits" ] }, { @@ -2617,6 +2615,9 @@ "sdk/javascript/angular-overview" ] }, + + "sdk/javascript/best-practices", + "sdk/javascript/troubleshooting", "sdk/javascript/extensions-overview", "sdk/javascript/ai-user-copilot-overview", "sdk/javascript/ai-chatbots-overview", From 17ee844d4e1ac59a539014fb290bf3ce2f13c4d4 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 18 Mar 2026 14:40:43 +0530 Subject: [PATCH 22/43] frame these pages better --- sdk/javascript/key-concepts.mdx | 149 +++++++---------- .../message-structure-and-hierarchy.mdx | 154 +++++++++--------- sdk/javascript/rate-limits.mdx | 58 ++++--- 3 files changed, 170 insertions(+), 191 deletions(-) diff --git a/sdk/javascript/key-concepts.mdx b/sdk/javascript/key-concepts.mdx index 490bb9dcc..138c523c9 100644 --- a/sdk/javascript/key-concepts.mdx +++ b/sdk/javascript/key-concepts.mdx @@ -3,7 +3,6 @@ title: "Key Concepts" description: "Understand the core concepts of CometChat including users, groups, messaging categories, authentication, and member roles." --- -{/* TL;DR for Agents and Quick Reference */} Key identifiers: @@ -18,129 +17,101 @@ Member scopes: `Admin` | `Moderator` | `Participant` Message categories: `message` | `custom` | `action` | `call` -### CometChat Dashboard +This guide covers the fundamental concepts you need to understand when building with CometChat. -The CometChat Dashboard enables you to create new apps (projects) and manage your existing apps. +## CometChat Dashboard - -How many apps to create? - -Ideally, you should create two apps- one for development and one for production. And you should use a single app irrespective of the number of platforms. +The [CometChat Dashboard](https://app.cometchat.com) enables you to create new apps (projects) and manage your existing apps. -Do not create separate apps for every platform; if you do, your users on different platforms will not be able to communicate with each other! +- For every app, a unique App ID is generated. This App ID is required when integrating CometChat within your app. +- Along with the App ID, you will need to create an Auth Key (from the Dashboard) which can be used for user authentication. + +Ideally, create two apps — one for development and one for production. Use a single app regardless of the number of platforms. Do not create separate apps for every platform; if you do, your users on different platforms will not be able to communicate with each other. -* For every app, a unique App ID is generated. This App ID will be required when integrating CometChat within your app. -* Along with the App ID, you will need to create an Auth Key (from the Dashboard) which can be used for user authentication. - -### Auth & Rest API Keys - -You can generate two types of keys from the dashboard. - -| Type | Privileges | Recommended Use | -| ------------ | ---------------------------------------------------------------- | --------------------------------------------- | -| Auth Key | The Auth Key can be used to create & login users. | In your client side code (during development) | -| Rest API Key | The Rest API Key can be used to perform any CometChat operation. | In your server side code | +## API Keys -### Users +You can generate two types of keys from the dashboard: -A user is anyone who uses CometChat. - -### UID - -* Each user is uniquely identified using UID. -* The UID is typically the primary ID of the user from your database. +| Type | Privileges | Recommended Use | +| --- | --- | --- | +| Auth Key | Create & login users | Client-side code (development only) | +| REST API Key | Perform any CometChat operation | Server-side code only | - -UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. - +Never expose your REST API Key in client-side code. Use Auth Tokens for production authentication. -### Auth Token - -* A single user can have multiple auth tokens. The auth tokens should be per user per device. -* It should be generated by API call ideally, via server to server call. The auth token should then be given to CometChat for login. -* An Auth Token can only be deleted via dashboard or using REST API. +## Users -### Authentication +A user is anyone who uses CometChat. Each user is uniquely identified using a UID (Unique User Identifier). -To allow a user to use CometChat, the user must log in to CometChat. +- The UID is typically the primary ID of the user from your database +- UID can be alphanumeric with underscore and hyphen only — spaces, punctuation, and other special characters are not allowed -**CometChat does not handle user management.** You must handle user registration and login at your end. Once the user is logged into your app/site, you can log in the user to CometChat **programmatically**. So the user does not ever directly login to CometChat. +## Auth Tokens -**CometChat does not handle friends management.** If you want to associate friends with your users, you must handle friends management in your app. Once two users are friends (i.e. they have accepted each other as friends), then you can associate them as friends in CometChat. +Auth Tokens are secure, per-user credentials for production use: -### Typical Workflow +- A single user can have multiple auth tokens (one per device) +- Generate tokens server-side via the [REST API](https://api-explorer.cometchat.com/reference/create-authtoken) +- Tokens can only be deleted via the Dashboard or REST API -| Your App | Your Server | CometChat | -| ----------------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | -| User registers in your app | You store the user information in your database (e.g. ID, name, email, phone, location etc. in `users` table) | You add the user to CometChat (only ID & name) using the Rest API | -| User logs in to your app | You verify the credentials, login the user and retrieve the user ID | You log in the user to CometChat using the same user ID programmatically | -| User sends a friend request | You display the request to the potential friend | No action required | -| User accepts a friend request | You display the users as friends | You add both the users as friends using the Rest API | +## Authentication Flow -### User Roles +CometChat does not handle user management or friends management. You handle registration and login in your app, then log users into CometChat programmatically. -A role is a category for a group of similar users. For example, you may want to group your premium users using the role "Premium". You then use this to filter users or enable/disable features by writing conditional code. - -### User List - -* The User List can be used to build the **Contacts** or **Who's Online** view in your app. -* The list of users can be different based on the logged-in user. - -### Groups - -A group can be used for multiple users to communicate with each other on a particular topic/interest. - -### GUID - -* Each group is uniquely identified using GUID. -* The GUID is typically the primary ID of the group from your database. If you do not store group information in your database, you can generate a random string for use as GUID. +| Your App | Your Server | CometChat | +| --- | --- | --- | +| User registers | Store user info in your database | Create user via REST API (UID & name) | +| User logs in | Verify credentials, retrieve user ID | Log in user programmatically with UID | +| User sends friend request | Display request to potential friend | No action required | +| User accepts friend request | Display users as friends | Add both users as friends via REST API | - +## User Roles -GUID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. +A role is a category for grouping similar users. For example, group premium users with the role "Premium" to filter users or enable/disable features conditionally. - +## Groups -### Types +A group enables multiple users to communicate on a particular topic or interest. Each group is uniquely identified using a GUID (Group Unique Identifier). -CometChat supports three different types of groups: +- The GUID is typically the primary ID of the group from your database +- GUID can be alphanumeric with underscore and hyphen only -| Type | Visibility | Participation | -| -------- | ---------------------------- | ------------------------------------------------- | -| Public | All users | Any user can choose to join | -| Password | All users | Any user with a valid password can choose to join | -| Private | Only users part of the group | Invited users will be auto-joined | +## Group Types -### Members +| Type | Visibility | Participation | +| --- | --- | --- | +| Public | All users | Any user can join | +| Password | All users | Users with valid password can join | +| Private | Members only | Users must be invited (auto-joined) | -Once a participant joins a group, they become a member of the group. Members are part of the group indefinitely i.e. they will keep receiving messages, calls & notifications. To stop, the participant must either be kicked, banned or intentionally leave the group. +## Member Scopes -CometChat supports three different types of member scopes in a group: +Once a user joins a group, they become a member with one of three scopes: -| Member | Default | Privileges | -| ----------- | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Admin | Group creator is assigned Admin scope | - Change scope of Group Members to admin, moderator or participant. - Can add members to a group. - Kick & Ban Participants/Moderators/Admins - Send & Receive Messages & Calls - Update group - Delete group | -| Moderator | - | - Change scope of moderator or participant. - Update group - Kick & Ban Participants - Send & Receive Messages & Calls | -| Participant | Any other user is assigned Participant scope | - Send & Receive Messages & Calls | +| Scope | Default | Privileges | +| --- | --- | --- | +| Admin | Group creator | Full control: manage members, change scopes, kick/ban anyone, update/delete group | +| Moderator | — | Moderate: change participant scopes, kick/ban participants, update group | +| Participant | All other members | Basic: send & receive messages and calls | -### Messaging +## Message Categories -Any message in CometChat can belong to either one of the below categories +Every message belongs to one of these categories: -| Category | Description | -| -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| message | Any message belonging to the category `message` can belong to either one of the below types: 1. text 2. image 3. video 4. audio 5. file | -| custom | Custom messages are an option available for developers to send custom data across to users/groups. To send any additional data that does not fit in the default categories and types provided by CometChat, you can use the custom messages. | -| action | Action messages are system-generated messages. These can belong to either of the below types: 1. groupMember - when the action is performed on a group member 2. message - when the action is performed on a message | -| call | These are call-related messages. These can belong to either one of the two types: 1. audio 2. video | +| Category | Types | Description | +| --- | --- | --- | +| `message` | `text`, `image`, `video`, `audio`, `file` | Standard messages | +| `custom` | Developer-defined | Custom data (e.g., location, polls) | +| `action` | `groupMember`, `message` | System-generated (joins, edits, deletes) | +| `call` | `audio`, `video` | Call-related messages | -For more information, you can refer to the [Message structure and hierarchy guide](/sdk/javascript/message-structure-and-hierarchy). +For more details, see the [Message Structure and Hierarchy](/sdk/javascript/message-structure-and-hierarchy) guide. -### Glossary Quick Lookup +## Glossary | Term | Definition | Learn More | | --- | --- | --- | diff --git a/sdk/javascript/message-structure-and-hierarchy.mdx b/sdk/javascript/message-structure-and-hierarchy.mdx index 90c6829dd..1f93fc379 100644 --- a/sdk/javascript/message-structure-and-hierarchy.mdx +++ b/sdk/javascript/message-structure-and-hierarchy.mdx @@ -1,10 +1,9 @@ --- -title: "Message" -sidebarTitle: "Message Structure And Hierarchy" +title: "Message Structure and Hierarchy" +sidebarTitle: "Message Structure" description: "Understand the message categories, types, and hierarchy in the CometChat JavaScript SDK including text, media, custom, action, interactive, and call messages." --- -{/* TL;DR for Agents and Quick Reference */} Message categories and types: @@ -15,36 +14,44 @@ Message categories and types: - **call** → `audio`, `video` -The below diagram helps you better understand the various message categories and types that a CometChat message can belong to. +Every message in CometChat belongs to a category and has a specific type. Understanding this hierarchy helps you handle different message types correctly in your application. + +## Message Hierarchy -### Checking Message Category and Type +## Categories Overview + +| Category | Types | Description | +| --- | --- | --- | +| `message` | `text`, `image`, `video`, `audio`, `file` | Standard user messages | +| `custom` | Developer-defined | Custom data (location, polls, etc.) | +| `interactive` | `form`, `card`, `customInteractive` | Messages with actionable UI elements | +| `action` | `groupMember`, `message` | System-generated events | +| `call` | `audio`, `video` | Call-related messages | -You can determine the category and type of any received message using the following methods: +## Checking Message Category and Type + +Use `getCategory()` and `getType()` to determine how to handle a received message: ```javascript -// Check message category -const category = message.getCategory(); // "message", "custom", "action", "call", "interactive" - -// Check message type -const type = message.getType(); // "text", "image", "video", "audio", "file", etc. +const category = message.getCategory(); +const type = message.getType(); -// Example: Handle different message categories switch (category) { case CometChat.CATEGORY_MESSAGE: if (type === CometChat.MESSAGE_TYPE.TEXT) { - console.log("Text message:", message.getText()); + console.log("Text:", message.getText()); } else if (type === CometChat.MESSAGE_TYPE.IMAGE) { console.log("Image URL:", message.getData().url); } break; case CometChat.CATEGORY_CUSTOM: - console.log("Custom message type:", type, "data:", message.getData()); + console.log("Custom type:", type, "data:", message.getData()); break; case CometChat.CATEGORY_ACTION: console.log("Action:", message.getAction()); @@ -57,16 +64,14 @@ switch (category) { ```typescript -// Check message category const category: string = message.getCategory(); const type: string = message.getType(); -// Example: Handle different message categories switch (category) { case CometChat.CATEGORY_MESSAGE: if (type === CometChat.MESSAGE_TYPE.TEXT) { const textMsg = message as CometChat.TextMessage; - console.log("Text message:", textMsg.getText()); + console.log("Text:", textMsg.getText()); } else if (type === CometChat.MESSAGE_TYPE.IMAGE) { const mediaMsg = message as CometChat.MediaMessage; console.log("Image URL:", mediaMsg.getData().url); @@ -74,7 +79,7 @@ switch (category) { break; case CometChat.CATEGORY_CUSTOM: const customMsg = message as CometChat.CustomMessage; - console.log("Custom message type:", type, "data:", customMsg.getData()); + console.log("Custom type:", type, "data:", customMsg.getData()); break; case CometChat.CATEGORY_ACTION: const actionMsg = message as CometChat.Action; @@ -89,83 +94,78 @@ switch (category) { -As you can see in the above diagram, every message belongs to a particular category. A message can belong to either one of the 4 categories - -1. Message -2. Custom -3. Action -4. Call - -Each category can be further be classified into types. - -A message belonging to the category `message` can be classified into either 1 of the below types: +## Message Category -1. text - A plain text message -2. image- An image message -3. video- A video message -4. audio- An audio message -5. file- A file message +Messages with category `message` are standard user-sent messages: -## Custom +| Type | Description | +| --- | --- | +| `text` | Plain text message | +| `image` | Image attachment | +| `video` | Video attachment | +| `audio` | Audio attachment | +| `file` | File attachment | -In the case of messages that belong to the `custom` category, there are no predefined types. Custom messages can be used by developers to send messages that do not fit in the default category and types provided by CometChat. For messages with the category `custom`, the developers can set their own type to uniquely identify the custom message. A very good example of a custom message would be the sharing of location co-ordinates. In this case, the developer can decide to use the custom message with type set to `location`. +## Custom Category -For sending custom messages, see [Send Message → Custom Messages](/sdk/javascript/send-message#custom-message). +Custom messages allow you to send data that doesn't fit the default categories. You define your own type to identify the message (e.g., `location`, `poll`, `sticker`). -## Interactive - -An InteractiveMessage is a specialized object that encapsulates an interactive unit within a chat message, such as an embedded form that users can fill out directly within the chat interface. Messages belonging to the interactive category can further be classified into one of the below types: - -1. form- for interactive form -2. card- for interactive card -3. customInteractive- for custom interaction messages - - - -to know about Interactive messages please [click here](/sdk/javascript/interactive-messages) - - +```javascript +// Example: Sending a location as a custom message +const customMessage = new CometChat.CustomMessage( + receiverID, + CometChat.RECEIVER_TYPE.USER, + "location", + { latitude: 37.7749, longitude: -122.4194 } +); +``` -## Action +See [Send Message → Custom Messages](/sdk/javascript/send-message#custom-message) for details. -Action messages are system-generated messages. Messages belonging to the `action` category can further be classified into one of the below types: +## Interactive Category -1. groupMember - action performed on a group member. -2. message - action performed on a message. +Interactive messages contain actionable UI elements that users can interact with directly in the chat: -Action messages hold another property called `action` which actually determine the action that has been performed For the type `groupMember` the action can be either one of the below: +| Type | Description | +| --- | --- | +| `form` | Embedded form with input fields | +| `card` | Card with buttons and actions | +| `customInteractive` | Custom interactive elements | -1. joined - when a group member joins a group -2. left - when a group member leaves a group -3. kicked - when a group member is kicked from the group -4. banned - when a group member is banned from the group -5. unbanned - when a group member is unbanned from the group -6. added - when a user is added to the group -7. scopeChanged - When the scope of a group member is changed. +See [Interactive Messages](/sdk/javascript/interactive-messages) for implementation details. -For the type `message`, the action can be either one of the below: +## Action Category -1. edited - when a message is edited. -2. deleted - when a message is deleted. +Action messages are system-generated events. They have a `type` and an `action` property: -## Call +**Type: `groupMember`** — Actions on group members: +- `joined` — Member joined the group +- `left` — Member left the group +- `kicked` — Member was kicked +- `banned` — Member was banned +- `unbanned` — Member was unbanned +- `added` — Member was added +- `scopeChanged` — Member's scope was changed -Messages with the category `call` are Calling related messages. These can belong to either one of the 2 types +**Type: `message`** — Actions on messages: +- `edited` — Message was edited +- `deleted` — Message was deleted -1. audio -2. video +## Call Category -For implementing calling, see [Default Calling](/sdk/javascript/default-call) or [Direct Calling](/sdk/javascript/direct-call). +Call messages track call events with types `audio` or `video`. The `status` property indicates the call state: -The call messages have a property called status that helps you figure out the status of the call. The status can be either one of the below values: +| Status | Description | +| --- | --- | +| `initiated` | Call started | +| `ongoing` | Call accepted and in progress | +| `canceled` | Caller canceled | +| `rejected` | Receiver rejected | +| `unanswered` | No answer | +| `busy` | Receiver on another call | +| `ended` | Call completed | -1. initiated - when a is initiated to a user/group -2. ongoing - when the receiver of the call has accepted the call -3. canceled - when the call has been canceled by the initiator of the call -4. rejected - when the call has been rejected by the receiver of the call -5. unanswered - when the call was not answered by the receiver. -6. busy - when the receiver of the call was busy on another call. -7. ended - when the call was successfully completed and ended by either the initiator or receiver. +See [Default Calling](/sdk/javascript/default-call) or [Direct Calling](/sdk/javascript/direct-call) for implementation. --- diff --git a/sdk/javascript/rate-limits.mdx b/sdk/javascript/rate-limits.mdx index 9b9aa1332..1d8a4a86c 100644 --- a/sdk/javascript/rate-limits.mdx +++ b/sdk/javascript/rate-limits.mdx @@ -3,7 +3,6 @@ title: "Rate Limits" description: "Understand CometChat REST API rate limits, response headers, and how to handle rate-limited requests in your JavaScript application." --- -{/* TL;DR for Agents and Quick Reference */} - Core Operations (login, create/delete user, create/join group): `10,000` requests/min cumulative @@ -12,38 +11,33 @@ description: "Understand CometChat REST API rate limits, response headers, and h - Monitor usage via `X-Rate-Limit` and `X-Rate-Limit-Remaining` response headers -### CometChat REST API Rate Limits +CometChat applies rate limits to ensure fair usage and platform stability. Understanding these limits helps you build applications that handle high traffic gracefully. - +## Rate Limit Tiers -The rate limits below are for general applications. Rate limits can be adjusted on a per need basis, depending on your use-case and plan. The rate limits are cumulative. For example: If the rate limit for core operations is 100 requests per minute, then you can either login a user, add user to a group, remove a user from a group, etc for total 100 requests per minute. +| Operation Type | Limit | Examples | +| --- | --- | --- | +| Core Operations | 10,000 requests/min | Login, create/delete user, create/join group | +| Standard Operations | 20,000 requests/min | All other operations | + +Rate limits are cumulative within each tier. For example, if you make 5,000 login requests and 5,000 create user requests in one minute, you've hit the 10,000 core operations limit. -1. **Core Operations:** Core operations are rate limited to `10,000` requests per minute. Core operations include user login, create/delete user, create/join group cumulatively. -2. **Standard Operations:** Standard operations are rate limited to `20,000` requests per minute. Standard operations include all other operations cumulatively. - -## What happens when rate limit is reached ? - -The request isn't processed and a response is sent containing a 429 response code. Along with the response code there will be couple of headers sent which specifies the time in seconds that you must wait before you can try request again. - -`Retry-After: 15` - -`X-Rate-Limit-Reset: 1625143246` - -## Is there any endpoint that returns rate limit of all resources ? +## Response Headers -No, we don't provide a rate-limit endpoint. +CometChat includes rate limit information in response headers: -However, we do provide the following response headers that you can use to confirm the app's current rate limit and monitor the number of requests remaining in the current minute: +| Header | Description | +| --- | --- | +| `X-Rate-Limit` | Your current rate limit | +| `X-Rate-Limit-Remaining` | Requests remaining in current window | +| `Retry-After` | Seconds to wait before retrying (on 429) | +| `X-Rate-Limit-Reset` | Unix timestamp when limit resets (on 429) | -`X-Rate-Limit: 700` +## Handling Rate Limits -`X-Rate-Limit-Remaining: 699` - -## Handling Rate-Limited Responses - -When your application receives a `429` response, you should wait before retrying. Here's a recommended approach using exponential backoff: +When you exceed the rate limit, CometChat returns HTTP `429 Too Many Requests`. Implement exponential backoff to handle this gracefully: @@ -72,7 +66,10 @@ const users = await callWithRetry(() => ```typescript -async function callWithRetry(apiCall: () => Promise, maxRetries: number = 3): Promise { +async function callWithRetry( + apiCall: () => Promise, + maxRetries: number = 3 +): Promise { for (let attempt = 0; attempt < maxRetries; attempt++) { try { return await apiCall(); @@ -97,6 +94,17 @@ const users: CometChat.User[] = await callWithRetry(() => +## Tips for Staying Within Limits + +- **Batch operations** — Space out bulk operations over time instead of firing all at once +- **Monitor headers** — Check `X-Rate-Limit-Remaining` to proactively slow down before hitting limits +- **Avoid frequent login/logout** — Core operations share a lower limit; minimize login cycles +- **Use pagination** — Fetch data in reasonable page sizes (30-50 items) rather than requesting everything at once + + +Rate limits can be adjusted based on your use case and plan. Contact CometChat support if you need higher limits. + + --- ## Next Steps From 8e797c1323c96145279220d7d15f4e9508558e4c Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 18 Mar 2026 14:43:39 +0530 Subject: [PATCH 23/43] Update send-message.mdx --- sdk/javascript/send-message.mdx | 1815 ++++--------------------------- 1 file changed, 190 insertions(+), 1625 deletions(-) diff --git a/sdk/javascript/send-message.mdx b/sdk/javascript/send-message.mdx index 5aa4a540b..529b8371e 100644 --- a/sdk/javascript/send-message.mdx +++ b/sdk/javascript/send-message.mdx @@ -1,1762 +1,321 @@ --- -title: "Send A Message" -description: "Send text, media, and custom messages to users and groups using the CometChat JavaScript SDK. Includes metadata, tags, quoted messages, and multiple attachments." +title: "Send Messages" +sidebarTitle: "Send Messages" +description: "Send text, media, and custom messages to users and groups using the CometChat JavaScript SDK." --- | Field | Value | | --- | --- | -| Package | `@cometchat/chat-sdk-javascript` | -| Key Classes | `CometChat.TextMessage`, `CometChat.MediaMessage`, `CometChat.CustomMessage` | -| Key Methods | `CometChat.sendMessage()`, `CometChat.sendMediaMessage()`, `CometChat.sendCustomMessage()` | +| Key Classes | `TextMessage`, `MediaMessage`, `CustomMessage` | +| Key Methods | `sendMessage()`, `sendMediaMessage()`, `sendCustomMessage()` | | Receiver Types | `CometChat.RECEIVER_TYPE.USER`, `CometChat.RECEIVER_TYPE.GROUP` | | Message Types | `TEXT`, `IMAGE`, `VIDEO`, `AUDIO`, `FILE`, `CUSTOM` | | Prerequisites | SDK initialized, user logged in | -| Related | [Receive Message](/sdk/javascript/receive-message), [Edit Message](/sdk/javascript/edit-message), [Delete Message](/sdk/javascript/delete-message) | -Using CometChat, you can send three types of messages: +CometChat supports three types of messages: -1. [Text Message](/sdk/javascript/send-message#text-message) is the most common and standard message type. -2. [Media Message](/sdk/javascript/send-message#media-message) for sending photos, videos and files. -3. [Custom Message](/sdk/javascript/send-message#custom-message), for sending completely custom data using JSON structures. -4. [Interactive Messages](/sdk/javascript/interactive-messages), for sending end-user interactive messages of type form, card and custom Interactive +| Type | Method | Use Case | +| --- | --- | --- | +| [Text](#text-message) | `sendMessage()` | Plain text messages | +| [Media](#media-message) | `sendMediaMessage()` | Images, videos, audio, files | +| [Custom](#custom-message) | `sendCustomMessage()` | Location, polls, or any JSON data | -You can also send metadata along with a text, media or custom message. Think, for example, if you'd want to share the user's location with every message, you can use the metadata field +You can also send [Interactive Messages](/sdk/javascript/interactive-messages) for forms, cards, and custom UI elements. ## Text Message -*In other words, as a sender, how do I send a text message?* +Send a text message using `CometChat.sendMessage()` with a `TextMessage` object. -To send a text message to a single user or group, you need to use the `sendMessage()` method and pass a `TextMessage` object to it. - -### Add Metadata - -To send custom data along with a text message, you can use the `setMetadata` method and pass a `JSON Object` to it. - - - -```javascript -let metadata = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", -}; - -textMessage.setMetadata(metadata); -``` - - - - -```typescript -let metadata: Object = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", -}; - -textMessage.setMetadata(metadata); -``` - - - - - -### Add Tags - -To add a tag to a message you can use the `setTags()` method of the TextMessage Class. The `setTags()` method accepts a list of tags. - - - -```javascript -let tags = ["starredMessage"]; - -textMessage.setTags(tags); -``` - - - - -```typescript -let tags: Array = ["starredMessage"]; - -textMessage.setTags(tags); -``` - - - - - -Once the text message object is ready, you need to use the `sendMessage()` method to send the text message to the recipient. - - - -```javascript -let receiverID = "UID"; -let messageText = "Hello world!"; -let receiverType = CometChat.RECEIVER_TYPE.USER; -let textMessage = new CometChat.TextMessage( - receiverID, - messageText, - receiverType -); - -CometChat.sendMessage(textMessage).then( - (message) => { - console.log("Message sent successfully:", message); - }, - (error) => { - console.log("Message sending failed with error:", error); - } -); -``` - - - - -```javascript -let receiverID = "GUID"; -let messageText = "Hello world!"; -let receiverType = CometChat.RECEIVER_TYPE.GROUP; -let textMessage = new CometChat.TextMessage( - receiverID, - messageText, - receiverType -); - -CometChat.sendMessage(textMessage).then( - (message) => { - console.log("Message sent successfully:", message); - }, - (error) => { - console.log("Message sending failed with error:", error); - } -); -``` - - - - -```typescript -let receiverID: string = "UID", - messageText: string = "Hello world!", - receiverType: string = CometChat.RECEIVER_TYPE.USER, - textMessage: CometChat.TextMessage = new CometChat.TextMessage( - receiverID, - messageText, - receiverType - ); - -CometChat.sendMessage(textMessage).then( - (message: CometChat.TextMessage) => { - console.log("Message sent successfully:", message); - }, - (error: CometChat.CometChatException) => { - console.log("Message sending failed with error:", error); - } -); -``` - - - - -```typescript -let receiverID: string = "GUID", - messageText: string = "Hello world!", - receiverType: string = CometChat.RECEIVER_TYPE.GROUP, - textMessage: CometChat.TextMessage = new CometChat.TextMessage( - receiverID, - messageText, - receiverType - ); - -CometChat.sendMessage(textMessage).then( - (message: CometChat.TextMessage) => { - console.log("Message sent successfully:", message); - }, - (error: CometChat.CometChatException) => { - console.log("Message sending failed with error:", error); - } -); -``` - - - - -```javascript -try { - const receiverID = "UID"; - const messageText = "Hello world!"; - const receiverType = CometChat.RECEIVER_TYPE.USER; - const textMessage = new CometChat.TextMessage( - receiverID, - messageText, - receiverType - ); - - const message = await CometChat.sendMessage(textMessage); - console.log("Message sent successfully:", message); -} catch (error) { - console.log("Message sending failed with error:", error); -} -``` - - - - - -### Set Quoted Message Id - -To set a quoted message ID for a message, use the `setQuotedMessageId()` method of the TextMessage class. This method accepts the ID of the message to be quoted. - - - -```javascript -textMessage.setQuotedMessageId(10); -``` - - - - -```typescript -textMessage.setQuotedMessageId(10); -``` - - - - - -Once the text message object is ready, you need to use the `sendMessage()` method to send the text message to the recipient. - - - -```javascript -let receiverID = "UID"; -let messageText = "Hello world!"; -let receiverType = CometChat.RECEIVER_TYPE.USER; -let textMessage = new CometChat.TextMessage( - receiverID, - messageText, - receiverType -); - -CometChat.sendMessage(textMessage).then( - (message) => { - console.log("Message sent successfully:", message); - }, - (error) => { - console.log("Message sending failed with error:", error); - } -); -``` - - - - -```javascript -let receiverID = "GUID"; -let messageText = "Hello world!"; -let receiverType = CometChat.RECEIVER_TYPE.GROUP; -let textMessage = new CometChat.TextMessage( - receiverID, - messageText, - receiverType -); - -CometChat.sendMessage(textMessage).then( - (message) => { - console.log("Message sent successfully:", message); - }, - (error) => { - console.log("Message sending failed with error:", error); - } -); -``` - - - - -```typescript -let receiverID: string = "UID", - messageText: string = "Hello world!", - receiverType: string = CometChat.RECEIVER_TYPE.USER, - textMessage: CometChat.TextMessage = new CometChat.TextMessage( - receiverID, - messageText, - receiverType - ); - -CometChat.sendMessage(textMessage).then( - (message: CometChat.TextMessage) => { - console.log("Message sent successfully:", message); - }, - (error: CometChat.CometChatException) => { - console.log("Message sending failed with error:", error); - } -); -``` - - - - -```typescript -let receiverID: string = "GUID", - messageText: string = "Hello world!", - receiverType: string = CometChat.RECEIVER_TYPE.GROUP, - textMessage: CometChat.TextMessage = new CometChat.TextMessage( - receiverID, - messageText, - receiverType - ); - -CometChat.sendMessage(textMessage).then( - (message: CometChat.TextMessage) => { - console.log("Message sent successfully:", message); - }, - (error: CometChat.CometChatException) => { - console.log("Message sending failed with error:", error); - } -); -``` - - - - - -The `TextMessage` class constructor takes the following parameters: - -| Parameter | Description | | -| ---------------- | -------------------------------------------------------------------------------------------- | -------- | -| **receiverID** | `UID` of the user or `GUID` of the group receiving the message | Required | -| **messageText** | The text message | Required | -| **receiverType** | The type of the receiver - `CometChat.RECEIVER_TYPE.USER` or `CometChat.RECEIVER_TYPE.GROUP` | Required | - -When a text message is sent successfully, the response will include a `TextMessage` object which includes all information related to the sent message. -## Media Message - -*In other words, as a sender, how do I send a media message like photos, videos & files?* - -To send a media message to any user or group, you need to use the `sendMediaMessage()` method and pass a `MediaMessage` object to it. - -### Add Metadata - -To send custom data along with a media message, you can use the `setMetadata` method and pass a `JSON Object` to it. - - - -```javascript -let metadata = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", -}; - -mediaMessage.setMetadata(metadata); -``` - - - - -```typescript -let metadata: Object = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", -}; - -mediaMessage.setMetadata(metadata); -``` - - - - - -### Add Caption(Text along with Media Message) - -To send a caption with a media message, you can use the `setCaption` method and pass text to it. - - - -```javascript -let caption = "Random Caption"; - -mediaMessage.setCaption(caption); -``` - - - - -```typescript -let caption: string = "Random Caption"; - -mediaMessage.setCaption(caption); -``` - - - - - -### Add Tags - -To add a tag to a message you can use the `setTags()` method of the MediaMessage Class. The `setTags()` method accepts a list of tags. - - - -```javascript -let tags = ["starredMessage"]; - -mediaMessage.setTags(tags); -``` - - - - -```typescript -let tags: Array = ["starredMessage"]; - -mediaMessage.setTags(tags); -``` - - - - - -There are 2 ways you can send Media Messages using the CometChat SDK: - -1. **By providing the File:** You can directly share the file object while creating an object of the MediaMessage class. When the media message is sent using the `sendMediaMessage()` method, this file is then uploaded to CometChat servers and the URL of the file is sent in the success response of the `sendMediaMessage()` function. - -Getting file Object: - - - -```html - - - - - - -``` - - - - - - - -```javascript -let receiverID = "UID"; -let messageType = CometChat.MESSAGE_TYPE.FILE; -let receiverType = CometChat.RECEIVER_TYPE.USER; -let mediaMessage = new CometChat.MediaMessage( - receiverID, - "INPUT FILE OBJECT", - messageType, - receiverType -); - -CometChat.sendMediaMessage(mediaMessage).then( - (message) => { - console.log("Media message sent successfully", message); - }, - (error) => { - console.log("Media message sending failed with error", error); - } -); -``` - - - - -```javascript -let receiverID = "GUID"; -let messageType = CometChat.MESSAGE_TYPE.FILE; -let receiverType = CometChat.RECEIVER_TYPE.GROUP; -let mediaMessage = new CometChat.MediaMessage( - receiverID, - `INPUT FILE OBJECT`, - messageType, - receiverType -); - -CometChat.sendMediaMessage(mediaMessage).then( - (message) => { - console.log("Media message sent successfully", message); - }, - (error) => { - console.log("Media message sending failed with error", error); - } -); -``` - - - - -```typescript -let receiverID: string = "UID", - messageType: string = CometChat.MESSAGE_TYPE.FILE, - receiverType: string = CometChat.RECEIVER_TYPE.USER, - mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( - receiverID, - "INPUT FILE OBJECT", - messageType, - receiverType - ); - -CometChat.sendMediaMessage(mediaMessage).then( - (message: CometChat.MediaMessage) => { - console.log("Media message sent successfully", message); - }, - (error: CometChat.CometChatException) => { - console.log("Media message sending failed with error", error); - } -); -``` - - - - -```typescript -let receiverID: string = "GUID", - messageType: string = CometChat.MESSAGE_TYPE.FILE, - receiverType: string = CometChat.RECEIVER_TYPE.GROUP, - mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( - receiverID, - "INPUT FILE OBJECT", - messageType, - receiverType - ); - -CometChat.sendMediaMessage(mediaMessage).then( - (message: CometChat.MediaMessage) => { - console.log("Media message sent successfully", message); - }, - (error: CometChat.CometChatException) => { - console.log("Media message sending failed with error", error); - } -); -``` - - - - - -### Set Quoted Message Id - -To set a quoted message ID for a message, use the `setQuotedMessageId()` method of the MediaMessage class. This method accepts the ID of the message to be quoted. - - - -```javascript -mediaMessage.setQuotedMessageId(10); -``` - - - - -```typescript -mediaMessage.setQuotedMessageId(10); -``` - - - - - -There are 2 ways you can send Media Messages using the CometChat SDK: - -1. **By providing the File:** You can directly share the file object while creating an object of the MediaMessage class. When the media message is sent using the `sendMediaMessage()` method, this file is then uploaded to CometChat servers and the URL of the file is sent in the success response of the `sendMediaMessage()` function. - -Getting file Object: - - - -```html - - - - - - -``` - - - - - - - -```javascript -let receiverID = "UID"; -let messageType = CometChat.MESSAGE_TYPE.FILE; -let receiverType = CometChat.RECEIVER_TYPE.USER; -let mediaMessage = new CometChat.MediaMessage( - receiverID, - "INPUT FILE OBJECT", - messageType, - receiverType -); - -CometChat.sendMediaMessage(mediaMessage).then( - (message) => { - console.log("Media message sent successfully", message); - }, - (error) => { - console.log("Media message sending failed with error", error); - } -); -``` - - - - -```javascript -let receiverID = "GUID"; -let messageType = CometChat.MESSAGE_TYPE.FILE; -let receiverType = CometChat.RECEIVER_TYPE.GROUP; -let mediaMessage = new CometChat.MediaMessage( - receiverID, - `INPUT FILE OBJECT`, - messageType, - receiverType -); - -CometChat.sendMediaMessage(mediaMessage).then( - (message) => { - console.log("Media message sent successfully", message); - }, - (error) => { - console.log("Media message sending failed with error", error); - } -); -``` - - - - -```typescript -let receiverID: string = "UID", - messageType: string = CometChat.MESSAGE_TYPE.FILE, - receiverType: string = CometChat.RECEIVER_TYPE.USER, - mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( - receiverID, - "INPUT FILE OBJECT", - messageType, - receiverType - ); - -CometChat.sendMediaMessage(mediaMessage).then( - (message: CometChat.MediaMessage) => { - console.log("Media message sent successfully", message); - }, - (error: CometChat.CometChatException) => { - console.log("Media message sending failed with error", error); - } -); -``` - - - - -```typescript -let receiverID: string = "GUID", - messageType: string = CometChat.MESSAGE_TYPE.FILE, - receiverType: string = CometChat.RECEIVER_TYPE.GROUP, - mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( - receiverID, - "INPUT FILE OBJECT", - messageType, - receiverType - ); - -CometChat.sendMediaMessage(mediaMessage).then( - (message: CometChat.MediaMessage) => { - console.log("Media message sent successfully", message); - }, - (error: CometChat.CometChatException) => { - console.log("Media message sending failed with error", error); - } -); -``` - - - - - -The `MediaMessage` class constructor takes the following parameters: - -| Parameter | Description | | -| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | -| **receiverId** | The `UID` or `GUID` of the recipient. | Required | -| **file** | The file object to be sent | Required | -| **messageType** | The type of the message that needs to be sent which in this case can be:
1.`CometChat.MESSAGE_TYPE.IMAGE`
2.`CometChat.MESSAGE_TYPE.VIDEO`
3.`CometChat.MESSAGE_TYPE.AUDIO`
4.`CometChat.MESSAGE_TYPE.FILE` | Required | -| **receiverType** | The type of the receiver to whom the message is to be sent.
`1. CometChat.RECEIVER_TYPE.USER`
`2. CometChat.RECEIVER_TYPE.GROUP` | Required | - -2. **By providing the URL of the File:** The second way to send media messages using the CometChat SDK is to provide the SDK with the URL of any file that is hosted on your servers or any cloud storage. To achieve this you will have to make use of the Attachment class. For more information, you can refer to the below code snippet: - - - -```javascript -let receiverID = "cometchat-uid-2"; -let messageType = CometChat.MESSAGE_TYPE.IMAGE; -let receiverType = CometChat.RECEIVER_TYPE.USER; -let mediaMessage = new CometChat.MediaMessage( - receiverID, - "", - messageType, - receiverType -); - -let file = { - name: "mario", - extension: "png", - mimeType: "image/png", - url: "https://pngimg.com/uploads/mario/mario_PNG125.png", -}; - -let attachment = new CometChat.Attachment(file); - -mediaMessage.setAttachment(attachment); - -CometChat.sendMediaMessage(mediaMessage).then( - (mediaMessage) => { - console.log("message", mediaMessage); - }, - (error) => { - console.log("error in sending message", error); - } -); -``` - - - - -```javascript -let receiverID = "cometchat-guid-1"; -let messageType = CometChat.MESSAGE_TYPE.IMAGE; -let receiverType = CometChat.RECEIVER_TYPE.GROUP; -let mediaMessage = new CometChat.MediaMessage( - receiverID, - "", - messageType, - receiverType -); - -let file = { - name: "mario", - extension: "png", - mimeType: "image/png", - url: "https://pngimg.com/uploads/mario/mario_PNG125.png", -}; - -let attachment = new CometChat.Attachment(file); - -mediaMessage.setAttachment(attachment); - -CometChat.sendMediaMessage(mediaMessage).then( - (mediaMessage) => { - console.log("message", mediaMessage); - }, - (error) => { - console.log("error in sending message", error); - } -); -``` - - - - -```typescript -let receiverID: string = "cometchat-uid-2", - messageType: string = CometChat.MESSAGE_TYPE.IMAGE, - receiverType: string = CometChat.RECEIVER_TYPE.USER, - mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( - receiverID, - "", - messageType, - receiverType - ); - -let file: Object = { - name: "mario", - extension: "png", - mimeType: "image/png", - url: "https://pngimg.com/uploads/mario/mario_PNG125.png", -}; - -let attachment: CometChat.Attachment = new CometChat.Attachment(file); - -mediaMessage.setAttachment(attachment); - -CometChat.sendMediaMessage(mediaMessage).then( - (mediaMessage: CometChat.MediaMessage) => { - console.log("message", mediaMessage); - }, - (error: CometChat.CometChatException) => { - console.log("error in sending message", error); - } -); -``` - - - - -```typescript -let receiverID: string = "cometchat-guid-1", - messageType: string = CometChat.MESSAGE_TYPE.IMAGE, - receiverType: string = CometChat.RECEIVER_TYPE.GROUP, - mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( - receiverID, - "", - messageType, - receiverType - ); - -let file: Object = { - name: "mario", - extension: "png", - mimeType: "image/png", - url: "https://pngimg.com/uploads/mario/mario_PNG125.png", -}; - -let attachment: CometChat.Attachment = new CometChat.Attachment(file); - -mediaMessage.setAttachment(attachment); - -CometChat.sendMediaMessage(mediaMessage).then( - (mediaMessage: CometChat.MediaMessage) => { - console.log("message", mediaMessage); - }, - (error: CometChat.CometChatException) => { - console.log("error in sending message", error); - } -); -``` - - - - - -When a media message is sent successfully, the response will include a `MediaMessage` object which includes all information related to the sent message. -## Multiple Attachments in a Media Message - -Starting version 3.0.9 & above the SDK supports sending multiple attachments in a single media message. As in the case of a single attachment in a media message, there are two ways you can send Media Messages using the CometChat SDK: - -1. **By providing an array of files:** You can now share an array of files while creating an object of the MediaMessage class. When the media message is sent using the `sendMediaMessage()` method, the files are uploaded to the CometChat servers & the URL of the files is sent in the success response of the `sendMediaMessage()` method. - -Getting files: - - - -```html - - - - - - -``` - - - - - - - -```javascript -let receiverID = "UID"; -let messageType = CometChat.MESSAGE_TYPE.FILE; -let receiverType = CometChat.RECEIVER_TYPE.USER; -let mediaMessage = new CometChat.MediaMessage( - receiverID, - files, - messageType, - receiverType -); - -CometChat.sendMediaMessage(mediaMessage).then( - (message) => { - console.log("Media message sent successfully", message); - }, - (error) => { - console.log("Media message sending failed with error", error); - } -); -``` - - - - -```typescript -let receiverID: string = "UID", - messageType: string = CometChat.MESSAGE_TYPE.FILE, - receiverType: string = CometChat.RECEIVER_TYPE.USER, - mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( - receiverID, - files, - messageType, - receiverType - ); - -CometChat.sendMediaMessage(mediaMessage).then( - (message: CometChat.MediaMessage) => { - console.log("Media message sent successfully", message); - }, - (error: CometChat.CometChatException) => { - console.log("Media message sending failed with error", error); - } -); -``` - - - - -```javascript -let receiverID = "GUID"; -let messageType = CometChat.MESSAGE_TYPE.FILE; -let receiverType = CometChat.RECEIVER_TYPE.GROUP; -let mediaMessage = new CometChat.MediaMessage( - receiverID, - files, - messageType, - receiverType -); - -CometChat.sendMediaMessage(mediaMessage).then( - (message) => { - console.log("Media message sent successfully", message); - }, - (error) => { - console.log("Media message sending failed with error", error); - } -); -``` - - - - -```typescript -let receiverID: string = "GUID", - messageType: string = CometChat.MESSAGE_TYPE.FILE, - receiverType: string = CometChat.RECEIVER_TYPE.GROUP, - mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( - receiverID, - files, - messageType, - receiverType - ); - -CometChat.sendMediaMessage(mediaMessage).then( - (message: CometChat.MediaMessage) => { - console.log("Media message sent successfully", message); - }, - (error: CometChat.CometChatException) => { - console.log("Media message sending failed with error", error); - } -); -``` - - - - - -The `MediaMessage` class constructor takes the following parameters: - -| Parameter | Description | -| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **receiverId** | The `UID` or `GUID` of the recipient. | -| **files** | An array of files. | -| **messageType** | The type of the message that needs to be sent which in this case can be:
1. `CometChat.MESSAGE_TYPE.IMAGE`
2. `CometChat.MESSAGE_TYPE.VIDEO`
3. `CometChat.MESSAGE_TYPE.AUDIO`
4. `CometChat.MESSAGE_TYPE.FILE` | -| **receiverType** | The type of the receiver to whom the message is to be sent.
`1. CometChat.RECEIVER_TYPE.USER`
`2. CometChat.RECEIVER_TYPE.GROUP` | - -2. **By providing the URL of the multiple files:** The second way to send multiple attachments in a single media message using the CometChat SDK is to provide the SDK with the URL of multiple files that are hosted on your servers or any cloud storage. To achieve this you will have to make use of the Attachment class. For more information, you can refer to the below code snippet: - - - -```javascript -let receiverID = "cometchat-uid-2"; -let messageType = CometChat.MESSAGE_TYPE.IMAGE; -let receiverType = CometChat.RECEIVER_TYPE.USER; -let mediaMessage = new CometChat.MediaMessage( - receiverID, - "", - messageType, - receiverType -); - -let attachment1 = { - name: "mario", - extension: "png", - mimeType: "image/png", - url: "https://pngimg.com/uploads/mario/mario_PNG125.png", -}; - -let attachment2 = { - name: "jaguar", - extension: "png", - mimeType: "image/png", - url: "https://pngimg.com/uploads/jaguar/jaguar_PNG20759.png", -}; - -let attachments = []; -attachments.push(new CometChat.Attachment(attachment1)); -attachments.push(new CometChat.Attachment(attachment2)); - -mediaMessage.setAttachments(attachments); - -CometChat.sendMediaMessage(mediaMessage).then( - (mediaMessage) => { - console.log("message", mediaMessage); - }, - (error) => { - console.log("error in sending message", error); - } -); -``` - - - - -```typescript -let receiverID: string = "cometchat-uid-2", - messageType: string = CometChat.MESSAGE_TYPE.IMAGE, - receiverType: string = CometChat.RECEIVER_TYPE.USER, - mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( - receiverID, - "", - messageType, - receiverType - ); - -let attachment1: Object = { - name: "mario", - extension: "png", - mimeType: "image/png", - url: "https://pngimg.com/uploads/mario/mario_PNG125.png", -}; - -let attachment2: Object = { - name: "jaguar", - extension: "png", - mimeType: "image/png", - url: "https://pngimg.com/uploads/jaguar/jaguar_PNG20759.png", -}; - -let attachments: Array = []; -attachments.push(new CometChat.Attachment(attachment1)); -attachments.push(new CometChat.Attachment(attachment2)); - -mediaMessage.setAttachments(attachments); - -CometChat.sendMediaMessage(mediaMessage).then( - (mediaMessage: CometChat.MediaMessage) => { - console.log("message", mediaMessage); - }, - (error: CometChat.CometChatException) => { - console.log("error in sending message", error); - } -); -``` - - - - + + ```javascript -let receiverID = "cometchat-guid-1"; -let messageType = CometChat.MESSAGE_TYPE.IMAGE; -let receiverType = CometChat.RECEIVER_TYPE.GROUP; -let mediaMessage = new CometChat.MediaMessage( - receiverID, - "", - messageType, - receiverType -); +const receiverID = "UID"; // or GUID for groups +const receiverType = CometChat.RECEIVER_TYPE.USER; // or GROUP +const textMessage = new CometChat.TextMessage(receiverID, "Hello!", receiverType); -let attachment1 = { - name: "mario", - extension: "png", - mimeType: "image/png", - url: "https://pngimg.com/uploads/mario/mario_PNG125.png", -}; - -let attachment2 = { - name: "jaguar", - extension: "png", - mimeType: "image/png", - url: "https://pngimg.com/uploads/jaguar/jaguar_PNG20759.png", -}; - -let attachments = []; -attachments.push(new CometChat.Attachment(attachment1)); -attachments.push(new CometChat.Attachment(attachment2)); - -mediaMessage.setAttachments(attachments); - -CometChat.sendMediaMessage(mediaMessage).then( - (mediaMessage) => { - console.log("message", mediaMessage); - }, - (error) => { - console.log("error in sending message", error); - } +CometChat.sendMessage(textMessage).then( + message => console.log("Message sent:", message), + error => console.log("Error:", error) ); ``` - - - + ```typescript -let receiverID: string = "cometchat-guid-1", - messageType: string = CometChat.MESSAGE_TYPE.IMAGE, - receiverType: string = CometChat.RECEIVER_TYPE.GROUP, - mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( - receiverID, - "", - messageType, - receiverType - ); - -let attachment1: Object = { - name: "mario", - extension: "png", - mimeType: "image/png", - url: "https://pngimg.com/uploads/mario/mario_PNG125.png", -}; - -let attachment1: Object = { - name: "jaguar", - extension: "png", - mimeType: "image/png", - url: "https://pngimg.com/uploads/jaguar/jaguar_PNG20759.png", -}; - -let attachments: Array = []; -attachments.push(new CometChat.Attachment(attachment1)); -attachments.push(new CometChat.Attachment(attachment2)); +const receiverID: string = "UID"; +const receiverType: string = CometChat.RECEIVER_TYPE.USER; +const textMessage = new CometChat.TextMessage(receiverID, "Hello!", receiverType); -mediaMessage.setAttachments(attachments); - -CometChat.sendMediaMessage(mediaMessage).then( - (mediaMessage: CometChat.MediaMessage) => { - console.log("message", mediaMessage); - }, - (error: CometChat.CometChatException) => { - console.log("error in sending message", error); - } +CometChat.sendMessage(textMessage).then( + (message: CometChat.TextMessage) => console.log("Message sent:", message), + (error: CometChat.CometChatException) => console.log("Error:", error) ); ``` - - -When a media message is sent successfully, the response will include a `MediaMessage` object which includes all information related to the sent message. - -You can use the `setMetadata()`, `setCaption()` & `setTags()` methods to add metadata, caption and tags respectively in exactly the same way as it is done while sending a single file or attachment in a Media Message. -## Custom Message - -*In other words, as a sender, how do I send a custom message like location coordinates?* - -CometChat allows you to send custom messages which are neither text nor media messages. +### TextMessage Parameters -In order to send a custom message, you need to use the `sendCustomMessage()` method. +| Parameter | Type | Description | +| --- | --- | --- | +| `receiverID` | `string` | UID of user or GUID of group | +| `messageText` | `string` | The text content | +| `receiverType` | `string` | `CometChat.RECEIVER_TYPE.USER` or `GROUP` | -The `sendCustomMessage()` method takes an object of the `CustomMessage` which can be obtained using the below constructor. - - - -```js -let customMessage = new CometChat.CustomMessage( - receiverID, - receiverType, - customType, - customData -); -``` +### Optional: Add Metadata - +Attach custom JSON data to any message: - -```typescript -let customMessage: CometChat.CustomMessage = new CometChat.CustomMessage( - receiverID, - receiverType, - customType, - customData -); +```javascript +textMessage.setMetadata({ + latitude: "50.6192171633316", + longitude: "-72.68182268750002" +}); ``` - - - - -The above constructor, helps you create a custom message with the message type set to whatever is passed to the constructor and the category set to `custom`. - -The parameters involved are: - -1. `receiverId` - The unique ID of the user or group to which the message is to be sent. -2. `receiverType` - Type of the receiver i.e user or group -3. `customType` - custom message type that you need to set -4. `customData` - The data to be passed as the message in the form of a JSON Object. - -You can also use the subType field of the `CustomMessage` class to set a specific type for the custom message. This can be achieved using the `setSubtype()` method. +### Optional: Add Tags -### Add Tags +Tag messages for filtering: -To add a tag to a message you can use the `setTags()` method of the CustomMessage Class. The `setTags()` method accepts a list of tags. - - - ```javascript -let tags = ["starredMessage"]; - -customMessage.setTags(tags); +textMessage.setTags(["starred", "important"]); ``` - +### Optional: Quote a Message - -```typescript -let tags: Array = ["starredMessage"]; +Reply to a specific message: -customMessage.setTags(tags); +```javascript +textMessage.setQuotedMessageId(123); // ID of message to quote ``` - +## Media Message - +Send images, videos, audio, or files using `CometChat.sendMediaMessage()`. -Once the object of `CustomMessage` class is ready you can send the custom message using the `sendCustomMessage()` method. +### Option 1: Upload a File + +Pass a file object directly — CometChat uploads it automatically: - + ```javascript -let receiverID = "UID"; -let customData = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", -}; -let customType = "location"; -let receiverType = CometChat.RECEIVER_TYPE.USER; -let customMessage = new CometChat.CustomMessage( - receiverID, - receiverType, - customType, - customData -); - -CometChat.sendCustomMessage(customMessage).then( - (message) => { - console.log("custom message sent successfully", message); - }, - (error) => { - console.log("custom message sending failed with error", error); - } -); -``` +// Get file from input element +const file = document.getElementById("fileInput").files[0]; - +const receiverID = "UID"; +const messageType = CometChat.MESSAGE_TYPE.IMAGE; // or VIDEO, AUDIO, FILE +const receiverType = CometChat.RECEIVER_TYPE.USER; - -```javascript -let receiverID = "GUID"; -let customData = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", -}; -let customType = "location"; -let receiverType = CometChat.RECEIVER_TYPE.GROUP; -let customMessage = new CometChat.CustomMessage( +const mediaMessage = new CometChat.MediaMessage( receiverID, - receiverType, - customType, - customData + file, + messageType, + receiverType ); -CometChat.sendCustomMessage(customMessage).then( - (message) => { - console.log("custom message sent successfully", message); - }, - (error) => { - console.log("custom message sending failed with error", error); - } +CometChat.sendMediaMessage(mediaMessage).then( + message => console.log("Media sent:", message), + error => console.log("Error:", error) ); ``` - - - + ```typescript -let receiverID: string = "UID", - customData: Object = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", - }, - customType: string = "location", - receiverType: string = CometChat.RECEIVER_TYPE.USER, - customMessage: CometChat.CustomMessage = new CometChat.CustomMessage( - receiverID, - receiverType, - customType, - customData - ); +const file: File = (document.getElementById("fileInput") as HTMLInputElement).files![0]; -CometChat.sendCustomMessage(customMessage).then( - (message: CometChat.CustomMessage) => { - console.log("custom message sent successfully", message); - }, - (error: CometChat.CometChatException) => { - console.log("custom message sending failed with error", error); - } +const mediaMessage = new CometChat.MediaMessage( + "UID", + file, + CometChat.MESSAGE_TYPE.IMAGE, + CometChat.RECEIVER_TYPE.USER ); -``` - - - - -```typescript -let receiverID: string = "GUID", - customData: Object = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", - }, - customType: string = "location", - receiverType: string = CometChat.RECEIVER_TYPE.GROUP, - customMessage: CometChat.CustomMessage = new CometChat.CustomMessage( - receiverID, - receiverType, - customType, - customData - ); -CometChat.sendCustomMessage(customMessage).then( - (message: CometChat.CustomMessage) => { - console.log("custom message sent successfully", message); - }, - (error: CometChat.CometChatException) => { - console.log("custom message sending failed with error", error); - } +CometChat.sendMediaMessage(mediaMessage).then( + (message: CometChat.MediaMessage) => console.log("Media sent:", message), + (error: CometChat.CometChatException) => console.log("Error:", error) ); ``` - - -### Set Quoted Message Id +### Option 2: Send a URL -To set a quoted message ID for a message, use the `setQuotedMessageId()` method of the CustomMessage class. This method accepts the ID of the message to be quoted. +Send media hosted on your server or cloud storage: - - ```javascript -customMessage.setQuotedMessageId(10); -``` +const mediaMessage = new CometChat.MediaMessage( + "UID", + "", + CometChat.MESSAGE_TYPE.IMAGE, + CometChat.RECEIVER_TYPE.USER +); - +const attachment = new CometChat.Attachment({ + name: "photo", + extension: "png", + mimeType: "image/png", + url: "https://example.com/photo.png" +}); - -```typescript -customMessage.setQuotedMessageId(10); +mediaMessage.setAttachment(attachment); + +CometChat.sendMediaMessage(mediaMessage).then( + message => console.log("Media sent:", message), + error => console.log("Error:", error) +); ``` - +### MediaMessage Parameters - +| Parameter | Type | Description | +| --- | --- | --- | +| `receiverID` | `string` | UID of user or GUID of group | +| `file` | `File` or `string` | File object or empty string (if using URL) | +| `messageType` | `string` | `IMAGE`, `VIDEO`, `AUDIO`, or `FILE` | +| `receiverType` | `string` | `USER` or `GROUP` | -Once the object of `CustomMessage` class is ready you can send the custom message using the `sendCustomMessage()` method. +### Optional: Add Caption - - ```javascript -let receiverID = "UID"; -let customData = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", -}; -let customType = "location"; -let receiverType = CometChat.RECEIVER_TYPE.USER; -let customMessage = new CometChat.CustomMessage( - receiverID, - receiverType, - customType, - customData -); - -CometChat.sendCustomMessage(customMessage).then( - (message) => { - console.log("custom message sent successfully", message); - }, - (error) => { - console.log("custom message sending failed with error", error); - } -); +mediaMessage.setCaption("Check out this photo!"); ``` - +### Multiple Attachments - +Send multiple files in a single message: + + + ```javascript -let receiverID = "GUID"; -let customData = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", -}; -let customType = "location"; -let receiverType = CometChat.RECEIVER_TYPE.GROUP; -let customMessage = new CometChat.CustomMessage( - receiverID, - receiverType, - customType, - customData -); +const files = document.getElementById("fileInput").files; // FileList -CometChat.sendCustomMessage(customMessage).then( - (message) => { - console.log("custom message sent successfully", message); - }, - (error) => { - console.log("custom message sending failed with error", error); - } +const mediaMessage = new CometChat.MediaMessage( + "UID", + files, + CometChat.MESSAGE_TYPE.FILE, + CometChat.RECEIVER_TYPE.USER ); -``` +CometChat.sendMediaMessage(mediaMessage); +``` - - -```typescript -let receiverID: string = "UID", - customData: Object = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", - }, - customType: string = "location", - receiverType: string = CometChat.RECEIVER_TYPE.USER, - customMessage: CometChat.CustomMessage = new CometChat.CustomMessage( - receiverID, - receiverType, - customType, - customData - ); - -CometChat.sendCustomMessage(customMessage).then( - (message: CometChat.CustomMessage) => { - console.log("custom message sent successfully", message); - }, - (error: CometChat.CometChatException) => { - console.log("custom message sending failed with error", error); - } + +```javascript +const mediaMessage = new CometChat.MediaMessage( + "UID", + "", + CometChat.MESSAGE_TYPE.IMAGE, + CometChat.RECEIVER_TYPE.USER ); -``` - +const attachments = [ + new CometChat.Attachment({ name: "img1", extension: "png", mimeType: "image/png", url: "https://example.com/1.png" }), + new CometChat.Attachment({ name: "img2", extension: "png", mimeType: "image/png", url: "https://example.com/2.png" }) +]; - -```typescript -let receiverID: string = "GUID", - customData: Object = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", - }, - customType: string = "location", - receiverType: string = CometChat.RECEIVER_TYPE.GROUP, - customMessage: CometChat.CustomMessage = new CometChat.CustomMessage( - receiverID, - receiverType, - customType, - customData - ); +mediaMessage.setAttachments(attachments); -CometChat.sendCustomMessage(customMessage).then( - (message: CometChat.CustomMessage) => { - console.log("custom message sent successfully", message); - }, - (error: CometChat.CometChatException) => { - console.log("custom message sending failed with error", error); - } -); +CometChat.sendMediaMessage(mediaMessage); ``` - - -The above sample explains how custom messages can be used to share the location with a user. The same can be achieved for groups. - -On success, you will receive an object of the `CustomMessage` class. - -### Update Conversation - -*How can I decide whether the custom message should update the last message of a conversation?* +## Custom Message -By default, a custom message will update the last message of a conversation. If you wish to not update the last message of the conversation when a custom message is sent, please use shouldUpdateConversation(value: boolean) method of the Custom Message. +Send structured data that doesn't fit text or media categories — like location coordinates, polls, or game moves. - + ```javascript -let receiverID = "UID"; -let customData = { +const receiverID = "UID"; +const receiverType = CometChat.RECEIVER_TYPE.USER; +const customType = "location"; +const customData = { latitude: "50.6192171633316", - longitude: "-72.68182268750002", + longitude: "-72.68182268750002" }; -let customType = "location"; -let receiverType = CometChat.RECEIVER_TYPE.USER; -let customMessage = new CometChat.CustomMessage( - receiverID, - receiverType, - customType, - customData -); - -customMessage.shouldUpdateConversation(false); -CometChat.sendCustomMessage(customMessage).then( - (message) => { - console.log("custom message sent successfully", message); - }, - (error) => { - console.log("custom message sending failed with error", error); - } -); -``` - - - -```javascript -let receiverID = "GUID"; -let customData = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", -}; -let customType = "location"; -let receiverType = CometChat.RECEIVER_TYPE.GROUP; -let customMessage = new CometChat.CustomMessage( +const customMessage = new CometChat.CustomMessage( receiverID, receiverType, customType, customData ); -customMessage.shouldUpdateConversation(false); CometChat.sendCustomMessage(customMessage).then( - (message) => { - console.log("custom message sent successfully", message); - }, - (error) => { - console.log("custom message sending failed with error", error); - } + message => console.log("Custom message sent:", message), + error => console.log("Error:", error) ); ``` - - - + ```typescript -let receiverID: string = "UID", - customData: Object = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", - }, - customType: string = "location", - receiverType: string = CometChat.RECEIVER_TYPE.USER, - customMessage: CometChat.CustomMessage = new CometChat.CustomMessage( - receiverID, - receiverType, - customType, - customData - ); - -customMessage.shouldUpdateConversation(false); -CometChat.sendCustomMessage(customMessage).then( - (message: CometChat.CustomMessage) => { - console.log("custom message sent successfully", message); - }, - (error: CometChat.CometChatException) => { - console.log("custom message sending failed with error", error); - } +const customMessage = new CometChat.CustomMessage( + "UID", + CometChat.RECEIVER_TYPE.USER, + "location", + { latitude: "50.6192171633316", longitude: "-72.68182268750002" } ); -``` - - - - -```typescript -let receiverID: string = "GUID", - customData: Object = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", - }, - customType: string = "location", - receiverType: string = CometChat.RECEIVER_TYPE.GROUP, - customMessage: CometChat.CustomMessage = new CometChat.CustomMessage( - receiverID, - receiverType, - customType, - customData - ); -customMessage.shouldUpdateConversation(false); CometChat.sendCustomMessage(customMessage).then( - (message: CometChat.CustomMessage) => { - console.log("custom message sent successfully", message); - }, - (error: CometChat.CometChatException) => { - console.log("custom message sending failed with error", error); - } + (message: CometChat.CustomMessage) => console.log("Custom message sent:", message), + (error: CometChat.CometChatException) => console.log("Error:", error) ); ``` - - -### Custom Notification Body +### CustomMessage Parameters -*How can i customise the notification body of custom message?* - -To add a custom notification body for `Push, Email & SMS` notification of a custom message you can use the `setConversationText(text: string)` method of Custom Message class. - - - -```javascript -let receiverID = "UID"; -let customData = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", -}; -let customType = "location"; -let receiverType = CometChat.RECEIVER_TYPE.USER; -let customMessage = new CometChat.CustomMessage( - receiverID, - receiverType, - customType, - customData -); +| Parameter | Type | Description | +| --- | --- | --- | +| `receiverID` | `string` | UID of user or GUID of group | +| `receiverType` | `string` | `USER` or `GROUP` | +| `customType` | `string` | Your custom type (e.g., `"location"`, `"poll"`) | +| `customData` | `object` | JSON data to send | -customMessage.setConversationText("Custom notification body"); -CometChat.sendCustomMessage(customMessage).then( - (message) => { - console.log("custom message sent successfully", message); - }, - (error) => { - console.log("custom message sending failed with error", error); - } -); -``` +### Optional: Control Conversation Update - +By default, custom messages update the conversation's last message. To prevent this: - ```javascript -let receiverID = "GUID"; -let customData = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", -}; -let customType = "location"; -let receiverType = CometChat.RECEIVER_TYPE.GROUP; -let customMessage = new CometChat.CustomMessage( - receiverID, - receiverType, - customType, - customData -); - -customMessage.setConversationText("Custom notificatoin body"); -CometChat.sendCustomMessage(customMessage).then( - (message) => { - console.log("custom message sent successfully", message); - }, - (error) => { - console.log("custom message sending failed with error", error); - } -); +customMessage.shouldUpdateConversation(false); ``` - - - -```typescript -let receiverID: string = "UID", - customData: Object = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", - }, - customType: string = "location", - receiverType: string = CometChat.RECEIVER_TYPE.USER, - customMessage: CometChat.CustomMessage = new CometChat.CustomMessage( - receiverID, - receiverType, - customType, - customData - ); - -customMessage.setConversationText("Custom notification body"); -CometChat.sendCustomMessage(customMessage).then( - (message: CometChat.CustomMessage) => { - console.log("custom message sent successfully", message); - }, - (error: CometChat.CometChatException) => { - console.log("custom message sending failed with error", error); - } -); -``` +### Optional: Custom Notification Text - +Set custom text for push/email/SMS notifications: - -```typescript -let receiverID: string = "GUID", - customData: Object = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", - }, - customType: string = "location", - receiverType: string = CometChat.RECEIVER_TYPE.GROUP, - customMessage: CometChat.CustomMessage = new CometChat.CustomMessage( - receiverID, - receiverType, - customType, - customData - ); - -customMessage.setConversationText("Custom notification body"); -CometChat.sendCustomMessage(customMessage).then( - (message: CometChat.CustomMessage) => { - console.log("custom message sent successfully", message); - }, - (error: CometChat.CometChatException) => { - console.log("custom message sending failed with error", error); - } -); +```javascript +customMessage.setConversationText("Shared a location"); ``` - +## Common Options - +These methods work on all message types: + +| Method | Description | +| --- | --- | +| `setMetadata(object)` | Attach custom JSON data | +| `setTags(array)` | Add string tags for filtering | +| `setQuotedMessageId(id)` | Reply to a specific message | -When a custom message is sent successfully, the response will include a `CustomMessage` object which includes all information related to the sent message. - +## Response -It is also possible to send interactive messages from CometChat, to know more [click here](/sdk/javascript/interactive-messages) +All send methods return a Promise that resolves with the sent message object containing: - +| Property | Description | +| --- | --- | +| `getId()` | Unique message ID | +| `getSender()` | User object of the sender | +| `getReceiverId()` | UID or GUID of the recipient | +| `getSentAt()` | Timestamp when sent | +| `getMetadata()` | Custom metadata (if set) | +| `getTags()` | Tags array (if set) | --- @@ -1764,9 +323,15 @@ It is also possible to send interactive messages from CometChat, to know more [c - Listen for incoming messages in real-time and fetch missed messages + Listen for incoming messages in real-time - Edit previously sent text and custom messages + Edit previously sent messages + + + Delete sent messages + + + Send forms, cards, and custom UI elements From aa7442cba30e08b77d7c988c1db1dfcd069e79b9 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 18 Mar 2026 14:46:45 +0530 Subject: [PATCH 24/43] Update send-message.mdx --- sdk/javascript/send-message.mdx | 876 +++++++++++++++++++++++++++----- 1 file changed, 743 insertions(+), 133 deletions(-) diff --git a/sdk/javascript/send-message.mdx b/sdk/javascript/send-message.mdx index 529b8371e..c81e2a940 100644 --- a/sdk/javascript/send-message.mdx +++ b/sdk/javascript/send-message.mdx @@ -31,86 +31,233 @@ You can also send [Interactive Messages](/sdk/javascript/interactive-messages) f Send a text message using `CometChat.sendMessage()` with a `TextMessage` object. - + ```javascript -const receiverID = "UID"; // or GUID for groups -const receiverType = CometChat.RECEIVER_TYPE.USER; // or GROUP -const textMessage = new CometChat.TextMessage(receiverID, "Hello!", receiverType); +let receiverID = "UID"; +let messageText = "Hello world!"; +let receiverType = CometChat.RECEIVER_TYPE.USER; +let textMessage = new CometChat.TextMessage( + receiverID, + messageText, + receiverType +); CometChat.sendMessage(textMessage).then( - message => console.log("Message sent:", message), - error => console.log("Error:", error) + (message) => { + console.log("Message sent successfully:", message); + }, + (error) => { + console.log("Message sending failed with error:", error); + } ); ``` - + +```javascript +let receiverID = "GUID"; +let messageText = "Hello world!"; +let receiverType = CometChat.RECEIVER_TYPE.GROUP; +let textMessage = new CometChat.TextMessage( + receiverID, + messageText, + receiverType +); + +CometChat.sendMessage(textMessage).then( + (message) => { + console.log("Message sent successfully:", message); + }, + (error) => { + console.log("Message sending failed with error:", error); + } +); +``` + + ```typescript -const receiverID: string = "UID"; -const receiverType: string = CometChat.RECEIVER_TYPE.USER; -const textMessage = new CometChat.TextMessage(receiverID, "Hello!", receiverType); +let receiverID: string = "UID", + messageText: string = "Hello world!", + receiverType: string = CometChat.RECEIVER_TYPE.USER, + textMessage: CometChat.TextMessage = new CometChat.TextMessage( + receiverID, + messageText, + receiverType + ); CometChat.sendMessage(textMessage).then( - (message: CometChat.TextMessage) => console.log("Message sent:", message), - (error: CometChat.CometChatException) => console.log("Error:", error) + (message: CometChat.TextMessage) => { + console.log("Message sent successfully:", message); + }, + (error: CometChat.CometChatException) => { + console.log("Message sending failed with error:", error); + } ); ``` + +```typescript +let receiverID: string = "GUID", + messageText: string = "Hello world!", + receiverType: string = CometChat.RECEIVER_TYPE.GROUP, + textMessage: CometChat.TextMessage = new CometChat.TextMessage( + receiverID, + messageText, + receiverType + ); + +CometChat.sendMessage(textMessage).then( + (message: CometChat.TextMessage) => { + console.log("Message sent successfully:", message); + }, + (error: CometChat.CometChatException) => { + console.log("Message sending failed with error:", error); + } +); +``` + + +```javascript +try { + const receiverID = "UID"; + const messageText = "Hello world!"; + const receiverType = CometChat.RECEIVER_TYPE.USER; + const textMessage = new CometChat.TextMessage( + receiverID, + messageText, + receiverType + ); + + const message = await CometChat.sendMessage(textMessage); + console.log("Message sent successfully:", message); +} catch (error) { + console.log("Message sending failed with error:", error); +} +``` + -### TextMessage Parameters +The `TextMessage` class constructor takes the following parameters: -| Parameter | Type | Description | +| Parameter | Description | Required | | --- | --- | --- | -| `receiverID` | `string` | UID of user or GUID of group | -| `messageText` | `string` | The text content | -| `receiverType` | `string` | `CometChat.RECEIVER_TYPE.USER` or `GROUP` | +| `receiverID` | UID of the user or GUID of the group receiving the message | Yes | +| `messageText` | The text message content | Yes | +| `receiverType` | `CometChat.RECEIVER_TYPE.USER` or `CometChat.RECEIVER_TYPE.GROUP` | Yes | -### Optional: Add Metadata +### Add Metadata -Attach custom JSON data to any message: +Attach custom JSON data to the message: + + ```javascript -textMessage.setMetadata({ +let metadata = { + latitude: "50.6192171633316", + longitude: "-72.68182268750002", +}; + +textMessage.setMetadata(metadata); +``` + + +```typescript +let metadata: Object = { latitude: "50.6192171633316", - longitude: "-72.68182268750002" -}); + longitude: "-72.68182268750002", +}; + +textMessage.setMetadata(metadata); ``` + + -### Optional: Add Tags +### Add Tags -Tag messages for filtering: +Tag messages for easy filtering later: + + ```javascript -textMessage.setTags(["starred", "important"]); +let tags = ["starredMessage"]; + +textMessage.setTags(tags); +``` + + +```typescript +let tags: Array = ["starredMessage"]; + +textMessage.setTags(tags); ``` + + -### Optional: Quote a Message +### Quote a Message -Reply to a specific message: +Reply to a specific message by setting its ID: + + ```javascript -textMessage.setQuotedMessageId(123); // ID of message to quote +textMessage.setQuotedMessageId(10); +``` + + +```typescript +textMessage.setQuotedMessageId(10); ``` + + ## Media Message Send images, videos, audio, or files using `CometChat.sendMediaMessage()`. -### Option 1: Upload a File +There are two ways to send media messages: +1. **Upload a file** — Pass a file object and CometChat uploads it automatically +2. **Send a URL** — Provide a URL to media hosted on your server or cloud storage -Pass a file object directly — CometChat uploads it automatically: +### Upload a File + +Get the file from an input element and pass it to `MediaMessage`: + +```html + +``` - + ```javascript -// Get file from input element -const file = document.getElementById("fileInput").files[0]; +let receiverID = "UID"; +let messageType = CometChat.MESSAGE_TYPE.IMAGE; +let receiverType = CometChat.RECEIVER_TYPE.USER; +let file = document.getElementById("img_file").files[0]; -const receiverID = "UID"; -const messageType = CometChat.MESSAGE_TYPE.IMAGE; // or VIDEO, AUDIO, FILE -const receiverType = CometChat.RECEIVER_TYPE.USER; +let mediaMessage = new CometChat.MediaMessage( + receiverID, + file, + messageType, + receiverType +); + +CometChat.sendMediaMessage(mediaMessage).then( + (message) => { + console.log("Media message sent successfully", message); + }, + (error) => { + console.log("Media message sending failed with error", error); + } +); +``` + + +```javascript +let receiverID = "GUID"; +let messageType = CometChat.MESSAGE_TYPE.IMAGE; +let receiverType = CometChat.RECEIVER_TYPE.GROUP; +let file = document.getElementById("img_file").files[0]; -const mediaMessage = new CometChat.MediaMessage( +let mediaMessage = new CometChat.MediaMessage( receiverID, file, messageType, @@ -118,108 +265,510 @@ const mediaMessage = new CometChat.MediaMessage( ); CometChat.sendMediaMessage(mediaMessage).then( - message => console.log("Media sent:", message), - error => console.log("Error:", error) + (message) => { + console.log("Media message sent successfully", message); + }, + (error) => { + console.log("Media message sending failed with error", error); + } ); ``` - + +```typescript +let receiverID: string = "UID", + messageType: string = CometChat.MESSAGE_TYPE.IMAGE, + receiverType: string = CometChat.RECEIVER_TYPE.USER, + file: File = (document.getElementById("img_file") as HTMLInputElement).files![0]; + +let mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( + receiverID, + file, + messageType, + receiverType +); + +CometChat.sendMediaMessage(mediaMessage).then( + (message: CometChat.MediaMessage) => { + console.log("Media message sent successfully", message); + }, + (error: CometChat.CometChatException) => { + console.log("Media message sending failed with error", error); + } +); +``` + + ```typescript -const file: File = (document.getElementById("fileInput") as HTMLInputElement).files![0]; +let receiverID: string = "GUID", + messageType: string = CometChat.MESSAGE_TYPE.IMAGE, + receiverType: string = CometChat.RECEIVER_TYPE.GROUP, + file: File = (document.getElementById("img_file") as HTMLInputElement).files![0]; -const mediaMessage = new CometChat.MediaMessage( - "UID", +let mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( + receiverID, file, - CometChat.MESSAGE_TYPE.IMAGE, - CometChat.RECEIVER_TYPE.USER + messageType, + receiverType ); CometChat.sendMediaMessage(mediaMessage).then( - (message: CometChat.MediaMessage) => console.log("Media sent:", message), - (error: CometChat.CometChatException) => console.log("Error:", error) + (message: CometChat.MediaMessage) => { + console.log("Media message sent successfully", message); + }, + (error: CometChat.CometChatException) => { + console.log("Media message sending failed with error", error); + } ); ``` -### Option 2: Send a URL +### Send a URL -Send media hosted on your server or cloud storage: +Send media hosted on your server or cloud storage using the `Attachment` class: + + ```javascript -const mediaMessage = new CometChat.MediaMessage( - "UID", +let receiverID = "UID"; +let messageType = CometChat.MESSAGE_TYPE.IMAGE; +let receiverType = CometChat.RECEIVER_TYPE.USER; +let mediaMessage = new CometChat.MediaMessage( + receiverID, "", - CometChat.MESSAGE_TYPE.IMAGE, - CometChat.RECEIVER_TYPE.USER + messageType, + receiverType +); + +let file = { + name: "mario", + extension: "png", + mimeType: "image/png", + url: "https://pngimg.com/uploads/mario/mario_PNG125.png", +}; + +let attachment = new CometChat.Attachment(file); +mediaMessage.setAttachment(attachment); + +CometChat.sendMediaMessage(mediaMessage).then( + (message) => { + console.log("Media message sent successfully", message); + }, + (error) => { + console.log("Media message sending failed with error", error); + } +); +``` + + +```javascript +let receiverID = "GUID"; +let messageType = CometChat.MESSAGE_TYPE.IMAGE; +let receiverType = CometChat.RECEIVER_TYPE.GROUP; +let mediaMessage = new CometChat.MediaMessage( + receiverID, + "", + messageType, + receiverType +); + +let file = { + name: "mario", + extension: "png", + mimeType: "image/png", + url: "https://pngimg.com/uploads/mario/mario_PNG125.png", +}; + +let attachment = new CometChat.Attachment(file); +mediaMessage.setAttachment(attachment); + +CometChat.sendMediaMessage(mediaMessage).then( + (message) => { + console.log("Media message sent successfully", message); + }, + (error) => { + console.log("Media message sending failed with error", error); + } ); +``` + + +```typescript +let receiverID: string = "UID", + messageType: string = CometChat.MESSAGE_TYPE.IMAGE, + receiverType: string = CometChat.RECEIVER_TYPE.USER, + mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( + receiverID, + "", + messageType, + receiverType + ); + +let file: Object = { + name: "mario", + extension: "png", + mimeType: "image/png", + url: "https://pngimg.com/uploads/mario/mario_PNG125.png", +}; -const attachment = new CometChat.Attachment({ - name: "photo", +let attachment: CometChat.Attachment = new CometChat.Attachment(file); +mediaMessage.setAttachment(attachment); + +CometChat.sendMediaMessage(mediaMessage).then( + (message: CometChat.MediaMessage) => { + console.log("Media message sent successfully", message); + }, + (error: CometChat.CometChatException) => { + console.log("Media message sending failed with error", error); + } +); +``` + + +```typescript +let receiverID: string = "GUID", + messageType: string = CometChat.MESSAGE_TYPE.IMAGE, + receiverType: string = CometChat.RECEIVER_TYPE.GROUP, + mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( + receiverID, + "", + messageType, + receiverType + ); + +let file: Object = { + name: "mario", extension: "png", mimeType: "image/png", - url: "https://example.com/photo.png" -}); + url: "https://pngimg.com/uploads/mario/mario_PNG125.png", +}; +let attachment: CometChat.Attachment = new CometChat.Attachment(file); mediaMessage.setAttachment(attachment); CometChat.sendMediaMessage(mediaMessage).then( - message => console.log("Media sent:", message), - error => console.log("Error:", error) + (message: CometChat.MediaMessage) => { + console.log("Media message sent successfully", message); + }, + (error: CometChat.CometChatException) => { + console.log("Media message sending failed with error", error); + } ); ``` + + -### MediaMessage Parameters +The `MediaMessage` class constructor takes the following parameters: -| Parameter | Type | Description | +| Parameter | Description | Required | | --- | --- | --- | -| `receiverID` | `string` | UID of user or GUID of group | -| `file` | `File` or `string` | File object or empty string (if using URL) | -| `messageType` | `string` | `IMAGE`, `VIDEO`, `AUDIO`, or `FILE` | -| `receiverType` | `string` | `USER` or `GROUP` | +| `receiverID` | UID of the user or GUID of the group | Yes | +| `file` | File object to upload, or empty string if using URL | Yes | +| `messageType` | `CometChat.MESSAGE_TYPE.IMAGE`, `VIDEO`, `AUDIO`, or `FILE` | Yes | +| `receiverType` | `CometChat.RECEIVER_TYPE.USER` or `GROUP` | Yes | + +### Add Caption -### Optional: Add Caption +Add text along with the media: + + ```javascript mediaMessage.setCaption("Check out this photo!"); ``` + + +```typescript +mediaMessage.setCaption("Check out this photo!"); +``` + + + +### Add Metadata and Tags -### Multiple Attachments +Same as text messages: -Send multiple files in a single message: +```javascript +mediaMessage.setMetadata({ location: "Paris" }); +mediaMessage.setTags(["vacation"]); +mediaMessage.setQuotedMessageId(10); +``` + +## Multiple Attachments + +Send multiple files in a single media message. + +### Upload Multiple Files - + ```javascript -const files = document.getElementById("fileInput").files; // FileList +let receiverID = "UID"; +let messageType = CometChat.MESSAGE_TYPE.FILE; +let receiverType = CometChat.RECEIVER_TYPE.USER; +let files = document.getElementById("img_file").files; // FileList -const mediaMessage = new CometChat.MediaMessage( - "UID", +let mediaMessage = new CometChat.MediaMessage( + receiverID, files, - CometChat.MESSAGE_TYPE.FILE, - CometChat.RECEIVER_TYPE.USER + messageType, + receiverType +); + +CometChat.sendMediaMessage(mediaMessage).then( + (message) => { + console.log("Media message sent successfully", message); + }, + (error) => { + console.log("Media message sending failed with error", error); + } +); +``` + + +```javascript +let receiverID = "GUID"; +let messageType = CometChat.MESSAGE_TYPE.FILE; +let receiverType = CometChat.RECEIVER_TYPE.GROUP; +let files = document.getElementById("img_file").files; + +let mediaMessage = new CometChat.MediaMessage( + receiverID, + files, + messageType, + receiverType +); + +CometChat.sendMediaMessage(mediaMessage).then( + (message) => { + console.log("Media message sent successfully", message); + }, + (error) => { + console.log("Media message sending failed with error", error); + } +); +``` + + +```typescript +let receiverID: string = "UID", + messageType: string = CometChat.MESSAGE_TYPE.FILE, + receiverType: string = CometChat.RECEIVER_TYPE.USER, + files: FileList = (document.getElementById("img_file") as HTMLInputElement).files!; + +let mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( + receiverID, + files, + messageType, + receiverType +); + +CometChat.sendMediaMessage(mediaMessage).then( + (message: CometChat.MediaMessage) => { + console.log("Media message sent successfully", message); + }, + (error: CometChat.CometChatException) => { + console.log("Media message sending failed with error", error); + } +); +``` + + +```typescript +let receiverID: string = "GUID", + messageType: string = CometChat.MESSAGE_TYPE.FILE, + receiverType: string = CometChat.RECEIVER_TYPE.GROUP, + files: FileList = (document.getElementById("img_file") as HTMLInputElement).files!; + +let mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( + receiverID, + files, + messageType, + receiverType ); -CometChat.sendMediaMessage(mediaMessage); +CometChat.sendMediaMessage(mediaMessage).then( + (message: CometChat.MediaMessage) => { + console.log("Media message sent successfully", message); + }, + (error: CometChat.CometChatException) => { + console.log("Media message sending failed with error", error); + } +); ``` - + + +### Send Multiple URLs + + + ```javascript -const mediaMessage = new CometChat.MediaMessage( - "UID", +let receiverID = "UID"; +let messageType = CometChat.MESSAGE_TYPE.IMAGE; +let receiverType = CometChat.RECEIVER_TYPE.USER; +let mediaMessage = new CometChat.MediaMessage( + receiverID, "", - CometChat.MESSAGE_TYPE.IMAGE, - CometChat.RECEIVER_TYPE.USER + messageType, + receiverType ); -const attachments = [ - new CometChat.Attachment({ name: "img1", extension: "png", mimeType: "image/png", url: "https://example.com/1.png" }), - new CometChat.Attachment({ name: "img2", extension: "png", mimeType: "image/png", url: "https://example.com/2.png" }) -]; +let attachment1 = { + name: "mario", + extension: "png", + mimeType: "image/png", + url: "https://pngimg.com/uploads/mario/mario_PNG125.png", +}; + +let attachment2 = { + name: "jaguar", + extension: "png", + mimeType: "image/png", + url: "https://pngimg.com/uploads/jaguar/jaguar_PNG20759.png", +}; + +let attachments = []; +attachments.push(new CometChat.Attachment(attachment1)); +attachments.push(new CometChat.Attachment(attachment2)); mediaMessage.setAttachments(attachments); -CometChat.sendMediaMessage(mediaMessage); +CometChat.sendMediaMessage(mediaMessage).then( + (message) => { + console.log("Media message sent successfully", message); + }, + (error) => { + console.log("Media message sending failed with error", error); + } +); +``` + + +```javascript +let receiverID = "GUID"; +let messageType = CometChat.MESSAGE_TYPE.IMAGE; +let receiverType = CometChat.RECEIVER_TYPE.GROUP; +let mediaMessage = new CometChat.MediaMessage( + receiverID, + "", + messageType, + receiverType +); + +let attachment1 = { + name: "mario", + extension: "png", + mimeType: "image/png", + url: "https://pngimg.com/uploads/mario/mario_PNG125.png", +}; + +let attachment2 = { + name: "jaguar", + extension: "png", + mimeType: "image/png", + url: "https://pngimg.com/uploads/jaguar/jaguar_PNG20759.png", +}; + +let attachments = []; +attachments.push(new CometChat.Attachment(attachment1)); +attachments.push(new CometChat.Attachment(attachment2)); + +mediaMessage.setAttachments(attachments); + +CometChat.sendMediaMessage(mediaMessage).then( + (message) => { + console.log("Media message sent successfully", message); + }, + (error) => { + console.log("Media message sending failed with error", error); + } +); +``` + + +```typescript +let receiverID: string = "UID", + messageType: string = CometChat.MESSAGE_TYPE.IMAGE, + receiverType: string = CometChat.RECEIVER_TYPE.USER, + mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( + receiverID, + "", + messageType, + receiverType + ); + +let attachment1: Object = { + name: "mario", + extension: "png", + mimeType: "image/png", + url: "https://pngimg.com/uploads/mario/mario_PNG125.png", +}; + +let attachment2: Object = { + name: "jaguar", + extension: "png", + mimeType: "image/png", + url: "https://pngimg.com/uploads/jaguar/jaguar_PNG20759.png", +}; + +let attachments: Array = []; +attachments.push(new CometChat.Attachment(attachment1)); +attachments.push(new CometChat.Attachment(attachment2)); + +mediaMessage.setAttachments(attachments); + +CometChat.sendMediaMessage(mediaMessage).then( + (message: CometChat.MediaMessage) => { + console.log("Media message sent successfully", message); + }, + (error: CometChat.CometChatException) => { + console.log("Media message sending failed with error", error); + } +); +``` + + +```typescript +let receiverID: string = "GUID", + messageType: string = CometChat.MESSAGE_TYPE.IMAGE, + receiverType: string = CometChat.RECEIVER_TYPE.GROUP, + mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( + receiverID, + "", + messageType, + receiverType + ); + +let attachment1: Object = { + name: "mario", + extension: "png", + mimeType: "image/png", + url: "https://pngimg.com/uploads/mario/mario_PNG125.png", +}; + +let attachment2: Object = { + name: "jaguar", + extension: "png", + mimeType: "image/png", + url: "https://pngimg.com/uploads/jaguar/jaguar_PNG20759.png", +}; + +let attachments: Array = []; +attachments.push(new CometChat.Attachment(attachment1)); +attachments.push(new CometChat.Attachment(attachment2)); + +mediaMessage.setAttachments(attachments); + +CometChat.sendMediaMessage(mediaMessage).then( + (message: CometChat.MediaMessage) => { + console.log("Media message sent successfully", message); + }, + (error: CometChat.CometChatException) => { + console.log("Media message sending failed with error", error); + } +); ``` @@ -229,17 +778,17 @@ CometChat.sendMediaMessage(mediaMessage); Send structured data that doesn't fit text or media categories — like location coordinates, polls, or game moves. - + ```javascript -const receiverID = "UID"; -const receiverType = CometChat.RECEIVER_TYPE.USER; -const customType = "location"; -const customData = { +let receiverID = "UID"; +let customData = { latitude: "50.6192171633316", - longitude: "-72.68182268750002" + longitude: "-72.68182268750002", }; +let customType = "location"; +let receiverType = CometChat.RECEIVER_TYPE.USER; -const customMessage = new CometChat.CustomMessage( +let customMessage = new CometChat.CustomMessage( receiverID, receiverType, customType, @@ -247,75 +796,136 @@ const customMessage = new CometChat.CustomMessage( ); CometChat.sendCustomMessage(customMessage).then( - message => console.log("Custom message sent:", message), - error => console.log("Error:", error) + (message) => { + console.log("Custom message sent successfully", message); + }, + (error) => { + console.log("Custom message sending failed with error", error); + } ); ``` - + +```javascript +let receiverID = "GUID"; +let customData = { + latitude: "50.6192171633316", + longitude: "-72.68182268750002", +}; +let customType = "location"; +let receiverType = CometChat.RECEIVER_TYPE.GROUP; + +let customMessage = new CometChat.CustomMessage( + receiverID, + receiverType, + customType, + customData +); + +CometChat.sendCustomMessage(customMessage).then( + (message) => { + console.log("Custom message sent successfully", message); + }, + (error) => { + console.log("Custom message sending failed with error", error); + } +); +``` + + ```typescript -const customMessage = new CometChat.CustomMessage( - "UID", - CometChat.RECEIVER_TYPE.USER, - "location", - { latitude: "50.6192171633316", longitude: "-72.68182268750002" } +let receiverID: string = "UID", + customData: Object = { + latitude: "50.6192171633316", + longitude: "-72.68182268750002", + }, + customType: string = "location", + receiverType: string = CometChat.RECEIVER_TYPE.USER, + customMessage: CometChat.CustomMessage = new CometChat.CustomMessage( + receiverID, + receiverType, + customType, + customData + ); + +CometChat.sendCustomMessage(customMessage).then( + (message: CometChat.CustomMessage) => { + console.log("Custom message sent successfully", message); + }, + (error: CometChat.CometChatException) => { + console.log("Custom message sending failed with error", error); + } ); +``` + + +```typescript +let receiverID: string = "GUID", + customData: Object = { + latitude: "50.6192171633316", + longitude: "-72.68182268750002", + }, + customType: string = "location", + receiverType: string = CometChat.RECEIVER_TYPE.GROUP, + customMessage: CometChat.CustomMessage = new CometChat.CustomMessage( + receiverID, + receiverType, + customType, + customData + ); CometChat.sendCustomMessage(customMessage).then( - (message: CometChat.CustomMessage) => console.log("Custom message sent:", message), - (error: CometChat.CometChatException) => console.log("Error:", error) + (message: CometChat.CustomMessage) => { + console.log("Custom message sent successfully", message); + }, + (error: CometChat.CometChatException) => { + console.log("Custom message sending failed with error", error); + } ); ``` -### CustomMessage Parameters +The `CustomMessage` class constructor takes the following parameters: -| Parameter | Type | Description | +| Parameter | Description | Required | | --- | --- | --- | -| `receiverID` | `string` | UID of user or GUID of group | -| `receiverType` | `string` | `USER` or `GROUP` | -| `customType` | `string` | Your custom type (e.g., `"location"`, `"poll"`) | -| `customData` | `object` | JSON data to send | +| `receiverID` | UID of the user or GUID of the group | Yes | +| `receiverType` | `CometChat.RECEIVER_TYPE.USER` or `GROUP` | Yes | +| `customType` | Your custom type string (e.g., `"location"`, `"poll"`) | Yes | +| `customData` | JSON object with your custom data | Yes | -### Optional: Control Conversation Update - -By default, custom messages update the conversation's last message. To prevent this: +### Add Tags ```javascript -customMessage.shouldUpdateConversation(false); +customMessage.setTags(["starredMessage"]); ``` -### Optional: Custom Notification Text - -Set custom text for push/email/SMS notifications: +### Quote a Message ```javascript -customMessage.setConversationText("Shared a location"); +customMessage.setQuotedMessageId(10); ``` -## Common Options +### Control Conversation Update + +By default, custom messages update the conversation's last message. To prevent this: -These methods work on all message types: +```javascript +customMessage.shouldUpdateConversation(false); +``` -| Method | Description | -| --- | --- | -| `setMetadata(object)` | Attach custom JSON data | -| `setTags(array)` | Add string tags for filtering | -| `setQuotedMessageId(id)` | Reply to a specific message | +### Custom Notification Text -## Response +Set custom text for push, email, and SMS notifications: -All send methods return a Promise that resolves with the sent message object containing: +```javascript +customMessage.setConversationText("Shared a location"); +``` -| Property | Description | -| --- | --- | -| `getId()` | Unique message ID | -| `getSender()` | User object of the sender | -| `getReceiverId()` | UID or GUID of the recipient | -| `getSentAt()` | Timestamp when sent | -| `getMetadata()` | Custom metadata (if set) | -| `getTags()` | Tags array (if set) | + +You can also send interactive messages with forms, cards, and buttons. See [Interactive Messages](/sdk/javascript/interactive-messages) for details. + --- From 01ed70bc94534dcd27239ab001ad74cf99deabd0 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 18 Mar 2026 15:03:29 +0530 Subject: [PATCH 25/43] Update send-message.mdx --- sdk/javascript/send-message.mdx | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/sdk/javascript/send-message.mdx b/sdk/javascript/send-message.mdx index c81e2a940..1ee100a15 100644 --- a/sdk/javascript/send-message.mdx +++ b/sdk/javascript/send-message.mdx @@ -144,6 +144,8 @@ The `TextMessage` class constructor takes the following parameters: | `messageText` | The text message content | Yes | | `receiverType` | `CometChat.RECEIVER_TYPE.USER` or `CometChat.RECEIVER_TYPE.GROUP` | Yes | +On success, `sendMessage()` returns a [TextMessage](/sdk/reference/messages#textmessage) object. + ### Add Metadata Attach custom JSON data to the message: @@ -468,6 +470,8 @@ The `MediaMessage` class constructor takes the following parameters: | `messageType` | `CometChat.MESSAGE_TYPE.IMAGE`, `VIDEO`, `AUDIO`, or `FILE` | Yes | | `receiverType` | `CometChat.RECEIVER_TYPE.USER` or `GROUP` | Yes | +On success, `sendMediaMessage()` returns a [MediaMessage](/sdk/reference/messages#mediamessage) object. + ### Add Caption Add text along with the media: @@ -895,6 +899,8 @@ The `CustomMessage` class constructor takes the following parameters: | `customType` | Your custom type string (e.g., `"location"`, `"poll"`) | Yes | | `customData` | JSON object with your custom data | Yes | +On success, `sendCustomMessage()` returns a [CustomMessage](/sdk/reference/messages#custommessage) object. + ### Add Tags ```javascript From 90403fdfcbd63067331b30ba7e72cd45b9a126c8 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 18 Mar 2026 15:29:06 +0530 Subject: [PATCH 26/43] Update receive-message.mdx --- sdk/javascript/receive-message.mdx | 112 ++++++++++------------------- 1 file changed, 37 insertions(+), 75 deletions(-) diff --git a/sdk/javascript/receive-message.mdx b/sdk/javascript/receive-message.mdx index c3af814b2..5d7740aad 100644 --- a/sdk/javascript/receive-message.mdx +++ b/sdk/javascript/receive-message.mdx @@ -1,5 +1,6 @@ --- -title: "Receive A Message" +title: "Receive Messages" +sidebarTitle: "Receive Messages" description: "Receive real-time messages, fetch missed and unread messages, retrieve message history, search messages, and get unread counts using the CometChat JavaScript SDK." --- @@ -7,26 +8,21 @@ description: "Receive real-time messages, fetch missed and unread messages, retr | Field | Value | | --- | --- | -| Package | `@cometchat/chat-sdk-javascript` | | Key Classes | `CometChat.MessageListener`, `CometChat.MessagesRequestBuilder` | -| Listener Events | `onTextMessageReceived`, `onMediaMessageReceived`, `onCustomMessageReceived` | | Key Methods | `addMessageListener()`, `fetchPrevious()`, `fetchNext()`, `getUnreadMessageCount()` | -| Prerequisites | SDK initialized, user logged in, listener registered | -| Related | [Send Message](/sdk/javascript/send-message), [Delivery & Read Receipts](/sdk/javascript/delivery-read-receipts) | +| Listener Events | `onTextMessageReceived`, `onMediaMessageReceived`, `onCustomMessageReceived` | +| Prerequisites | SDK initialized, user logged in | - Receiving messages with CometChat has two parts: -1. Adding a listener to receive [real-time messages](/sdk/javascript/receive-message#real-time-messages) when your app is running -2. Calling a method to retrieve [missed messages](/sdk/javascript/receive-message#missed-messages) when your app was not running +1. Adding a listener to receive [real-time messages](#real-time-messages) when your app is running +2. Calling a method to retrieve [missed messages](#missed-messages) when your app was not running ## Real-Time Messages -*In other words, as a recipient, how do I receive messages when my app is running?* - -To receive real-time incoming messages, you need to register the `MessageListener` wherever you wish to receive the incoming messages. You can use the `addMessageListener()` method to do so. +Register the `MessageListener` to receive incoming messages in real-time using `addMessageListener()`. Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. @@ -79,11 +75,11 @@ CometChat.addMessageListener( -| Parameter | Description | -| -------------- | --------------------------------------------- | -| **listenerId** | An ID that uniquely identifies that listener. | +| Parameter | Description | +| --- | --- | +| `listenerID` | An ID that uniquely identifies that listener | -We recommend you remove the listener once you don't want to receive a message for particular listener. +Remove the listener when you no longer need to receive messages: @@ -107,9 +103,7 @@ CometChat.removeMessageListener(listenerID); - As a sender, you will not receive your own message in a real-time message event. However, if a user is logged-in using multiple devices, they will receive an event for their own message in other devices. - Each listener callback receives the specific message subclass — [`TextMessage`](/sdk/reference/messages#textmessage), [`MediaMessage`](/sdk/reference/messages#mediamessage), or [`CustomMessage`](/sdk/reference/messages#custommessage) — depending on the message type. Access the data using getter methods: @@ -125,15 +119,9 @@ Each listener callback receives the specific message subclass — [`TextMessage` ## Missed Messages -*In other words, as a recipient, how do I receive messages that I missed when my app was not running?* +Fetch messages that were sent while your app was offline using `MessagesRequestBuilder` with `setMessageId()` and `fetchNext()`. -For most use cases, you will need to add functionality to load missed messages. If you're building an on-demand or live streaming app, you may choose to skip this and fetch message history instead. - -Using the same `MessagesRequest` class and the filters provided by the `MessagesRequestBuilder` class, you can fetch the message that were sent to the logged-in user but were not delivered to him as he was offline. For this, you will require the id of the last message received. You can either maintain it at your end or use the `getLastDeliveredMessageId()` method provided by the CometChat class. This id needs to be passed to the `setMessageId()` method of the builder class. - -Now using the `fetchNext()` method, you can fetch all the messages that were sent to the user when he/she was offline. - -Calling the `fetchNext()` method on the same object repeatedly allows you to fetch all the offline messages for the logged in user. +Use `getLastDeliveredMessageId()` to get the ID of the last delivered message, then fetch all messages after that point. Call `fetchNext()` repeatedly on the same object to paginate through all missed messages. ### Fetch Missed Messages of a particular one-on-one conversation @@ -253,9 +241,7 @@ The `fetchNext()` method returns an array of [`BaseMessage`](/sdk/reference/mess ## Unread Messages -*In other words, as a logged-in user, how do I fetch the messages I've not read?* - -Using the `MessagesRequest` class described above, you can fetch the unread messages for the logged in user. In order to achieve this, you need to set the `unread` variable in the builder to true using the `setUnread()` method so that only the unread messages are fetched. +Fetch unread messages by setting `setUnread(true)` on the builder. ### Fetch Unread Messages of a particular one-on-one conversation @@ -358,19 +344,16 @@ messagesRequest.fetchPrevious().then( -Base Message - -The list of messages received is in the form of objects of `BaseMessage` class. A BaseMessage can either be an object of the `TextMessage`, `MediaMessage`, `CustomMessage`, `Action` or `Call` class. You can use the `instanceOf` operator to check the type of object. - +The list of messages received is in the form of `BaseMessage` objects. A BaseMessage can either be an object of the `TextMessage`, `MediaMessage`, `CustomMessage`, `Action` or `Call` class. You can use the `instanceof` operator to check the type of object. ## Message History -*In other words, as a logged-in user, how do I fetch the complete message history?* +Fetch the complete conversation history using `MessagesRequestBuilder` with `fetchPrevious()`. Call `fetchPrevious()` repeatedly on the same object to paginate through the entire conversation — useful for implementing upward scrolling. ### Fetch Message History of a particular one-on-one conversation -Using the `MessagesRequest` class and the filters for the `MessagesRequestBuilder` class as shown in the below code snippet, you can fetch the entire conversation between the logged in user and any particular user. For this use case, it is mandatory to set the UID parameter using the `setUID()` method of the builder. This UID is the unique id of the user for which the conversation needs to be fetched. +Set the UID using `setUID()` to fetch the conversation with a specific user. @@ -415,11 +398,9 @@ messagesRequest.fetchPrevious().then( -Calling the `fetchPrevious()` method on the same object repeatedly allows you to fetch the entire conversation between the logged in user and the specified user. This can be implemented with upward scrolling to display the entire conversation. - ### Fetch Message History of a particular group conversation -Using the `MessagesRequest` class and the filters for the `MessagesRequestBuilder` class as shown in the below code snippet, you can fetch the entire conversation for any group provided you have joined the group. For this use case, it is mandatory to set the GUID parameter using the `setGUID()` method of the builder. This GUID is the unique identifier of the Group for which the messages are to be fetched. +Set the GUID using `setGUID()` to fetch messages from a group you've joined. @@ -467,8 +448,6 @@ messagesRequest.fetchPrevious().then( -Calling the `fetchPrevious()` method on the same object repeatedly allows you to fetch the entire conversation for the group. This can be implemented with upward scrolling to display the entire conversation. - The `fetchPrevious()` method returns an array of [`BaseMessage`](/sdk/reference/messages#basemessage) objects (which may be [`TextMessage`](/sdk/reference/messages#textmessage), [`MediaMessage`](/sdk/reference/messages#mediamessage), or other subclasses). Access the data using getter methods: | Field | Getter | Return Type | Description | @@ -481,16 +460,12 @@ The `fetchPrevious()` method returns an array of [`BaseMessage`](/sdk/reference/ ## Search Messages -In other words, as a logged-in user, how do I search a message? - -In order to do this, you can use the `setSearchKeyword()` method. This method accepts string as input. When set, the SDK will fetch messages which match the `searchKeyword`. +Use `setSearchKeyword()` to search for messages matching a keyword. - By default, the searchKey is searched only in message text. However, if you enable `Conversation & Advanced Search`, the searchKey will be searched in message text, file name, mentions & mime type of the file. The `Conversation & Advanced Search` is only available in `Advanced` & `Custom` [plans](https://www.cometchat.com/pricing). If you're already on one of these plans, please enable the `Conversation & Advanced Search` from [CometChat Dashboard](https://app.cometchat.com) (Open your app, navigate to Chats -> Settings -> General Configuration) - | Feature | Basic Search | Advance Search | @@ -606,15 +581,11 @@ messagesRequest.fetchPrevious().then( ## Unread Message Count -*In other words, as a logged-in user, how do I find out the number of unread messages that I have?* +Get the number of unread messages for users, groups, or all conversations. ### Fetch Unread Message Count of a particular one-on-one conversation -*In other words, how do I find out the number of unread messages I have from a particular user?* - -In order to get the unread message count for a particular user, you can use the `getUnreadMessageCountForUser()`. - -This method has the below two variants: +Use `getUnreadMessageCountForUser()` to get the unread count for a specific user. @@ -634,7 +605,7 @@ CometChat.getUnreadMessageCountForUser(UID); -If you wish to ignore the messages from blocked users you can use the below syntax setting the boolean parameter to true: +To ignore messages from blocked users, set the boolean parameter to true: @@ -690,15 +661,11 @@ CometChat.getUnreadMessageCountForUser(UID).then( -It will return an object which will contain the UID as the key and the unread message count as the value. +Returns an object with the UID as key and unread message count as value. ### Fetch Unread Message Count of a particular group conversation -*In other words, how do I find out the number of unread messages I have in a single group?* - -In order to get the unread message count for a particular group, you can use the `getUnreadMessageCountForGroup()`. - -This method has the below two variants: +Use `getUnreadMessageCountForGroup()` to get the unread count for a specific group. @@ -718,7 +685,7 @@ CometChat.getUnreadMessageCountForGroup(GUID); -If you wish to ignore the messages from blocked users you can use the below syntax setting the boolean parameter to true: +To ignore messages from blocked users, set the boolean parameter to true: @@ -774,15 +741,11 @@ CometChat.getUnreadMessageCountForGroup(GUID).then( -It will return an object which will contain the GUID as the key and the unread message count as the value. +Returns an object with the GUID as key and unread message count as value. ### Fetch Unread Message Count of all one-on-one & group conversations -*In other words, how do I find out the number of unread messages for every one-on-one and group conversation?* - -In order to get all the unread message count combined i.e unread message counts for all the users and groups, you can use the `getUnreadMessageCount()` method. - -This method has two variants: +Use `getUnreadMessageCount()` to get unread counts for all users and groups combined. @@ -801,7 +764,7 @@ CometChat.getUnreadMessageCount(); -If you wish to ignore the messages from blocked users you can use the below syntax setting the boolean parameter to true: +To ignore messages from blocked users, set the boolean parameter to true: @@ -852,14 +815,13 @@ CometChat.getUnreadMessageCount().then( -It returns an object having two keys: - -1. users - The value for this key holds another object that holds the UID as key and their corresponding unread message count as value. -2. groups - The value for this key holds another object that holds the GUID as key and their corresponding unread message count as value. +Returns an object with two keys: +- `users` — Object with UIDs as keys and unread counts as values +- `groups` — Object with GUIDs as keys and unread counts as values ### Fetch Unread Message Count of all one-on-one conversations -In order to fetch the unread message counts for just the users, you can use the `getUnreadMessageCountForAllUsers()` method. This method just like others has two variants: +Use `getUnreadMessageCountForAllUsers()` to get unread counts for all user conversations. @@ -878,7 +840,7 @@ CometChat.getUnreadMessageCountForAllUsers(); -If you wish to ignore the messages from blocked users you can use the below syntax setting the boolean parameter to true: +To ignore messages from blocked users, set the boolean parameter to true: @@ -929,11 +891,11 @@ CometChat.getUnreadMessageCountForAllUsers().then( -It returns an object which will contain the UID as the key and the unread message count as the value. +Returns an object with UIDs as keys and unread counts as values. ### Fetch Unread Message Count of all group conversations -In order to fetch the unread message counts for just the groups, you can use the `getUnreadMessageCountForAllGroups()` method. This method just like others has two variants: +Use `getUnreadMessageCountForAllGroups()` to get unread counts for all group conversations. @@ -952,7 +914,7 @@ CometChat.getUnreadMessageCountForAllGroups(); -If you wish to ignore the messages from blocked users you can use the below syntax setting the boolean parameter to true: +To ignore messages from blocked users, set the boolean parameter to true: @@ -1003,7 +965,7 @@ CometChat.getUnreadMessageCountForAllGroups().then( -It returns an object which will contain the GUID as the key and the unread message count as the value. +Returns an object with GUIDs as keys and unread counts as values. --- From 1f3b24822b43deab61488f2417362dcc383292f5 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 18 Mar 2026 15:45:47 +0530 Subject: [PATCH 27/43] frame these better --- .../additional-message-filtering.mdx | 180 +++++++----------- sdk/javascript/delete-conversation.mdx | 23 +-- sdk/javascript/delete-message.mdx | 43 ++--- sdk/javascript/delivery-read-receipts.mdx | 19 +- sdk/javascript/edit-message.mdx | 44 ++--- sdk/javascript/flag-message.mdx | 3 +- sdk/javascript/interactive-messages.mdx | 3 +- sdk/javascript/mentions.mdx | 3 +- sdk/javascript/reactions.mdx | 1 + sdk/javascript/retrieve-conversations.mdx | 156 +++++++-------- sdk/javascript/threaded-messages.mdx | 37 +--- sdk/javascript/transient-messages.mdx | 3 +- sdk/javascript/typing-indicators.mdx | 36 ++-- 13 files changed, 210 insertions(+), 341 deletions(-) diff --git a/sdk/javascript/additional-message-filtering.mdx b/sdk/javascript/additional-message-filtering.mdx index 1a9f13782..7f89e548a 100644 --- a/sdk/javascript/additional-message-filtering.mdx +++ b/sdk/javascript/additional-message-filtering.mdx @@ -1,5 +1,6 @@ --- title: "Additional Message Filtering" +sidebarTitle: "Additional Filtering" description: "Advanced filtering options for fetching messages using MessagesRequestBuilder in the CometChat JavaScript SDK." --- @@ -37,32 +38,24 @@ messagesRequest.fetchNext().then(messages => { }); **Key methods:** `setUID()`, `setGUID()`, `setLimit()`, `setCategories()`, `setTypes()`, `setTags()`, `setUnread()`, `setParentMessageId()`, `setMessageId()`, `setTimestamp()`, `hideReplies()`, `hideDeletedMessages()` -The `MessagesRequest` class as you must be familiar with helps you to fetch messages based on the various parameters provided to it. This document will help you understand better the various options that are available using the `MessagesRequest` class. +The `MessagesRequest` class fetches messages based on various parameters. It uses the Builder design pattern via `MessagesRequestBuilder`. -The `MessagesRequest` class is designed using the `Builder design pattern`. In order to obtain an object of the `MessagesRequest` class, you will have to make use of the `MessagesRequestBuilder` class in the `MessagesRequest` class. +To fetch messages: +1. Create a `MessagesRequestBuilder` object +2. Set your desired parameters +3. Call `build()` to get a `MessagesRequest` object +4. Call `fetchNext()` or `fetchPrevious()` to retrieve messages -The `MessagesRequestBuilder` class allows you to set various parameters to the `MessagesRequest` class based on which the messages are fetched. +| Method | Description | +| --- | --- | +| `fetchNext()` | Returns messages after the specified parameters | +| `fetchPrevious()` | Returns messages before the specified parameters | -Steps to generate an object of the MessagesRequest class: - -1. Create an object of the `MessagesRequestBuilder` class. -2. Set all the parameters you wish to set. -3. Call the `build()` method of the `MessagesRequestBuilder` class to get an object of the `MessagesRequest` class. - -Once you have an object of the `MessagesRequest` class, you can call either the `fetchNext()` method or the `fetchPrevious()` method using the object. - -1. fetchNext() - Calling this method will return the messages after the specified parameters. -2. fetchPrevious() - Calling this method will give you messages before the specified parameters. - -Since messages are obtained in a paginated manner, a `maximum of 100` messages can be pulled in a single iteration. Calling the `fetchPrevious()`/`fetchNext()` method on the same `MessagesRequest` object will get you the next set of messages. - -Now that you are clear how to use the `MessagesRequest` class, below are the various options available: +Messages are paginated with a maximum of 100 per request. Call `fetchPrevious()`/`fetchNext()` repeatedly on the same object to get subsequent pages. ## Number of messages fetched -*In other words, how do I set the number of messages fetched in a single iteration* - -To achieve this, you can use the `setLimit()` method. This method takes an integer value as the input and informs the SDK to fetch the specified number of messages in one iteration. The maximum number of messages that can be fetched in one go is `100`. +Set the number of messages to fetch per request using `setLimit()`. Maximum is 100. @@ -86,9 +79,7 @@ let messagesRequest: CometChat.MessagesRequest = ## Messages for a user conversation -*In other words, how do I fetch messages between me and any user* - -This can be achieved using the `setUID()` method. This method takes the UID of the user with whom the conversation is to be fetched. When a valid UID is passed, the SDK will return all the messages that are a part of the conversation between the logged-in user and the UID that has been specified. +Use `setUID()` to fetch messages between the logged-in user and a specific user. @@ -113,16 +104,15 @@ let messagesRequest: CometChat.MessagesRequest = -When messages are fetched successfully, the response will include an array of message objects containing all information related to each message. +When messages are fetched successfully, the response includes an array of message objects. The examples on this page use a small `setLimit()` value for brevity. In production, use a higher limit (up to 100) for efficient pagination. -## Messages for a group conversation -*In other words, how do I fetch messages for any group conversation* +## Messages for a group conversation -You can achieve this using the `setGUID()` method. This method takes the GUID of a group for which the conversations are to be fetched. Passing a valid GUID to this method will return all the messages that are a part of the group conversation. Please note that the logged-in user must be a member of the group to fetch the messages for that group. +Use `setGUID()` to fetch messages from a group. The logged-in user must be a member of the group. @@ -147,18 +137,15 @@ let messagesRequest: CometChat.MessagesRequest = -When messages are fetched successfully, the response will include an array of message objects containing all information related to each message. - - -If none of the above two methods `setUID()` and `setGUID()` is used, all the messages for the logged-in user will be fetched. This means that messages from all the one-on-one and group conversations which the logged-in user is a part of will be returned.> All the parameters discussed below can be used along with the setUID() or setGUID() or without any of the two to fetch all the messages that the logged-in user is a part of. +When messages are fetched successfully, the response includes an array of message objects. + +If neither `setUID()` nor `setGUID()` is used, all messages for the logged-in user across all conversations will be fetched. All parameters below can be combined with `setUID()` or `setGUID()`. ## Messages before/after a message -*In other words, how do I fetch messages before or after a particular message* - -This can be achieved using the `setMessageId()` method. This method takes the message-id as input and provides messages only after/before the message-id based on if the fetchNext() or fetchPrevious() method is triggered. +Use `setMessageId()` to fetch messages before or after a specific message ID. Use `fetchNext()` to get messages after, or `fetchPrevious()` to get messages before. @@ -221,14 +208,11 @@ let GUID: string = "GUID", -This method can be used along with `setUID()` or `setGUID()` methods to fetch messages after/before any specific message-id for a particular user/group conversation. +This method can be combined with `setUID()` or `setGUID()` to fetch messages around a specific message in a conversation. -When messages are fetched successfully, the response will include an array of message objects containing all information related to each message. ## Messages before/after a given time -*In other words, how do I fetch messages before or after a particular date or time* - -You can easily achieve this using the `setTimestamp()` method. This method takes the Unix timestamp as input and provides messages only after/before the timestamp based on if fetchNext() or fetchPrevious() method is triggered. +Use `setTimestamp()` with a Unix timestamp to fetch messages before or after a specific time. @@ -291,14 +275,11 @@ let GUID: string = "GUID", -This method can be used along with `setUID()` or `setGUID()` methods to fetch messages after/before any specific date or time for a particular user/group conversation. +This method can be combined with `setUID()` or `setGUID()` to fetch messages around a specific time in a conversation. -When messages are fetched successfully, the response will include an array of message objects containing all information related to each message. ## Unread messages -*In other words, how do I fetch unread messages* - -This can easily be achieved using setting the unread flag to true. For this, you need to use the `setUnread()` method. This method takes a boolean value as input. If the value is set to true, the SDK will return just the unread messages. +Use `setUnread(true)` to fetch only unread messages. @@ -357,14 +338,11 @@ let GUID: string = "GUID", -This method along with `setGUID()` or `setUID()` can be used to fetch unread messages for a particular group or user conversation respectively. +Combine with `setGUID()` or `setUID()` to fetch unread messages for a specific conversation. -When messages are fetched successfully, the response will include an array of unread message objects. ## Exclude messages from blocked users -*In other words, how do I fetch messages excluding the messages from the users I have blocked* - -This can be easily achieved using the `hideMessagesFromBlockedUsers()` method. This method accepts a boolean value which determines if the messages from users blocked by the logged-in user need to be a part if the fetched messages. If the value is set to true, the messages will be hidden and won't be a part of the messages fetched. The default value is false i.e if this method is not used, the messages from blocked users will be included in the fetched messages. +Use `hideMessagesFromBlockedUsers(true)` to exclude messages from users you've blocked. Default is `false`. @@ -423,12 +401,11 @@ let GUID: string = "GUID", -This method can be used to hide the messages by users blocked by logged in user in groups that both the members are a part of. -## Updated and received messages +This also works in group conversations where both users are members. -*In other words, how do I fetch messages that have been received or updated after a particular date or time* +## Updated and received messages -This method accepts a Unix timestamp value and will return all the messages that have been updated and the ones that have been sent/received after the specified time. The messages updated could mean the messages that have been marked as read/delivered or if the messages are edited or deleted. +Use `setUpdatedAfter()` with a Unix timestamp to fetch messages that were sent or updated after a specific time. Updated messages include those marked as read/delivered, edited, or deleted. @@ -491,14 +468,11 @@ let GUID: string = "GUID", -This can be useful in finding the messages that have been received or updated after a certain time. Can prove very useful if you are saving the messages locally and would like to know the messages that have been updated or received after the last message available in your local databases. +Useful for syncing messages with a local database — fetch only what's changed since your last sync. -When messages are fetched successfully, the response may include both action messages (for updates like edits, deletes, read/delivered status changes) and regular messages (for newly received messages). ## Updated messages only -*In other words, how do I fetch messages that have been updated after a particular date or time* - -This can be achieved easily by setting the updatesOnly parameter to true. To do so, you can use the updatesOnly() method. This method takes a boolean input and can be used with the `setUpdatedAfter()` method to get jus the updated messages and not the messages sent/received after the specified time. This method cannot be used independently and always needs to be used with the `setUpdatedAfter()` method. +Use `updatesOnly(true)` with `setUpdatedAfter()` to fetch only updated messages (not newly received ones). This method must be used together with `setUpdatedAfter()`. @@ -565,14 +539,11 @@ let GUID: string = "GUID", -When messages are fetched successfully, the response will include only the messages that have been updated (edited, deleted, read/delivered status changed) after the specified timestamp — not newly received messages. -## Messages for multiple categories +When messages are fetched successfully, the response includes only messages that have been updated (edited, deleted, read/delivered status changed) after the specified timestamp. -*In other words, how do I fetch messages belonging to multiple categories* - -We recommend before trying this, you refer to the [Message structure and hierarchy guide](/sdk/javascript/message-structure-and-hierarchy) to get familiar with the various categories of messages. +## Messages for multiple categories -For this, you will have to use the `setCategories()` method. This method accepts a list of categories. This tells the SDK to fetch messages only belonging to these categories. +Use `setCategories()` with an array of category names to filter by message category. See [Message structure and hierarchy](/sdk/javascript/message-structure-and-hierarchy) for available categories. @@ -635,14 +606,11 @@ let GUID: string = "GUID", -The above snippet will help you get only the messages belonging to the `message` and `custom` category. This can also be used to disable certain categories of messages like `call` and `action`. -## Messages for multiple types - -*In other words, how do I fetch messages belonging to multiple types* +The above snippet fetches only messages in the `message` and `custom` categories. Use this to exclude categories like `call` and `action`. -We recommend before trying this, you refer to the [Message structure and hierarchy guide](/sdk/javascript/message-structure-and-hierarchy) to get familiar with the various types of messages. +## Messages for multiple types -This can be easily achieved using the `setTypes()` method. This method accepts a list of types. This tells the SDK to fetch messages only belonging to these types. +Use `setTypes()` with an array of type names to filter by message type. See [Message structure and hierarchy](/sdk/javascript/message-structure-and-hierarchy) for available types. @@ -713,12 +681,11 @@ let GUID: string = "GUID", -Using the above code snippet, you can fetch all the media messages. -## Messages for a specific thread +The above snippet fetches all media messages (image, video, audio, file). -*In other words, how do I fetch messages that are a part of a thread and not directly a user/group conversations* +## Messages for a specific thread -This can be done using the `setParentMessageId()` method. This method needs to be used when you have implemented threaded conversations in your app. This method will return the messages only belonging to the thread with the specified parent Id. +Use `setParentMessageId()` to fetch messages belonging to a specific thread. @@ -781,12 +748,11 @@ let GUID: string = "GUID", -The above code snippet returns the messages that belong to the thread with parent id 100. -## Hide threaded messages in user/group conversations +The above code returns messages belonging to the thread with the specified parent message ID. -*In other words, how do I exclude threaded messages from the normal user/group conversations* +## Hide threaded messages in user/group conversations -In order to do this, you can use the `hideReplies()` method. This method is also related to threaded conversations. This method takes boolean as input. This boolean when set to true will make sure that the messages that belong to threads are not fetched. If set to false, which is also the default value, the messages belong to the threads will also be fetched along with other messages. +Use `hideReplies(true)` to exclude threaded messages from the main conversation. Default is `false`. @@ -846,9 +812,7 @@ let GUID: string = "GUID", ## Hide deleted messages in user/group conversations -*In other words, how do I exclude deleted messages a user/group conversations* - -In order to do this, you can use the `hideDeletedMessages()` method. This method takes boolean as input. This boolean when set to true will make sure that the deleted messages are not fetched. If set to false, which is also the default value, the deleted messages will also be fetched along with other messages. +Use `hideDeletedMessages(true)` to exclude deleted messages. Default is `false`. @@ -908,9 +872,7 @@ let GUID: string = "GUID", ## Hide quoted messages in user/group conversations -*In other words, how do I exclude quoted messages in a user/group conversations* - -In order to do this, you can use the `hideQuotedMessages()` method. This method takes boolean as input. This boolean when set to true will make sure that the quoted messages are not fetched. If set to false, which is also the default value, the quoted messages will also be fetched along with other messages. +Use `hideQuotedMessages(true)` to exclude quoted messages. Default is `false`. @@ -970,9 +932,7 @@ let GUID: string = "GUID", ## Messages by tags -*In other words, how do I fetch messages by tags* - -In order to do this, you can use the `setTags()` method. This method accepts a list of tags. This tells the SDK to fetch messages only belonging to these tags. +Use `setTags()` with an array of tag names to fetch only messages with those tags. @@ -1036,9 +996,7 @@ let GUID: string = "GUID", ## Messages with tags -*In other words, how do I fetch messages with the tags information* - -In order to do this, you can use the `withTags()` method. This method accepts boolean as input. When set to `true` , the SDK will fetch messages along with the tags. When set to `false` , the SDK will not fetch tags associated with messages. The default value for this parameter is `false` . +Use `withTags(true)` to include tag information in the response. Default is `false`. @@ -1096,17 +1054,15 @@ let GUID: string = "GUID", -When `.withTags(true)` is set on the request builder, each message returned will have its `tags` field populated if it has any tags set. The messages are returned as [`BaseMessage`](/sdk/reference/messages#basemessage) objects (which may be [`TextMessage`](/sdk/reference/messages#textmessage) or other subclasses). You can access the tags using `getTags()`. +When `withTags(true)` is set, each message's `tags` field will be populated. Access tags using `getTags()`. | Additional Field | Getter | Return Type | Description | -|-----------------|--------|-------------|-------------| +| --- | --- | --- | --- | | tags | `getTags()` | `string[]` | Tags associated with the message | ## Messages with links -In other words, as a logged-in user, how do I fetch messages that contains links? - -In order to do this, you can use the `hasLinks()` method. This method accepts boolean as input. When set to `true` , the SDK will fetch messages which have links in the text. The default value for this parameter is `false`. +Use `hasLinks(true)` to fetch only messages containing links. Default is `false`. @@ -1172,9 +1128,7 @@ let GUID: string = "GUID", ## Messages with attachments -In other words, as a logged-in user, how do I fetch messages that contains attachments? - -In order to do this, you can use the `hasAttachments()` method. This method accepts boolean as input. When set to `true` , the SDK will fetch messages which have attachments (image, audio, video or file). The default value for this parameter is `false`. +Use `hasAttachments(true)` to fetch only messages with attachments (image, audio, video, or file). Default is `false`. @@ -1239,12 +1193,11 @@ let GUID: string = "GUID", -The response will contain a list of media message objects with attachment details, including file metadata and thumbnail URLs. -## Messages with reactions +The response contains media message objects with attachment details including file metadata and thumbnail URLs. -In other words, as a logged-in user, how do I fetch messages that contains reactions? +## Messages with reactions -In order to do this, you can use the `hasReactions()` method. This method accepts boolean as input. When set to `true` , the SDK will fetch messages which have reactions. The default value for this parameter is `false`. +Use `hasReactions(true)` to fetch only messages that have reactions. Default is `false`. @@ -1309,12 +1262,11 @@ let GUID: string = "GUID", -The response will contain a list of message objects that have reactions. Each message's `data` object includes a `reactions` array with emoji details. -## Messages with mentions +The response contains message objects with reactions. Each message's `data` object includes a `reactions` array. -In other words, as a logged-in user, how do I fetch messages that contains mentions? +## Messages with mentions -In order to do this, you can use the `hasMentions()` method. This method accepts boolean as input. When set to `true` , the SDK will fetch messages which have mentions. The default value for this parameter is `false`. +Use `hasMentions(true)` to fetch only messages that contain mentions. Default is `false`. @@ -1379,12 +1331,11 @@ let GUID: string = "GUID", -The response will contain a list of text message objects that include mentions. Each message has a `mentionedUsers` array, a `mentionedMe` boolean, and a `data.mentions` object keyed by UID. -## Messages with particular user mentions +The response contains text message objects with mentions. Each message has a `mentionedUsers` array, a `mentionedMe` boolean, and a `data.mentions` object. -In other words, as a logged-in user, how do I fetch messages that mentions specific users? +## Messages with particular user mentions -In order to do this, you can use the `setMentionedUIDs()` method. This method accepts an array of UIDs as input. When set, the SDK will fetch messages which have the mentions of the UIDs passed. +Use `setMentionedUIDs()` with an array of UIDs to fetch messages that mention specific users. @@ -1449,12 +1400,11 @@ let GUID: string = "GUID", -The response will contain a list of text message objects that mention the specific user(s) passed in `setMentionedUIDs()`. Each message includes `mentionedUsers`, `mentionedMe`, and `data.mentions` — filtered to only return messages where the specified UIDs are mentioned. -## Messages with specific attachment types +The response contains text message objects that mention the specified users. -In other words, as a logged-in user, how do I fetch messages that contain specific types of attachments? +## Messages with specific attachment types -In order to do this, you can use the `setAttachmentTypes()` method. This method accepts an array of `CometChat.AttachmentType` ENUM values as input. When provided, the SDK will fetch only those messages that include attachments of the specified types (such as image, audio, video, or file). +Use `setAttachmentTypes()` with an array of `CometChat.AttachmentType` values to fetch messages with specific attachment types. @@ -1519,7 +1469,7 @@ let GUID: string = "GUID", -The response will contain a list of media message objects filtered to only the specified attachment types (e.g., image and video). Each message includes an `attachments` array with file details and thumbnail generation metadata. +The response contains media message objects filtered to the specified attachment types. --- ## Next Steps diff --git a/sdk/javascript/delete-conversation.mdx b/sdk/javascript/delete-conversation.mdx index 6815524c7..fafb284dc 100644 --- a/sdk/javascript/delete-conversation.mdx +++ b/sdk/javascript/delete-conversation.mdx @@ -1,6 +1,7 @@ --- -title: "Delete A Conversation" -description: "Delete user or group conversations for the logged-in user using the CometChat JavaScript SDK." +title: "Delete Conversation" +sidebarTitle: "Delete Conversation" +description: "Delete user or group conversations using the CometChat JavaScript SDK." --- {/* TL;DR for Agents and Quick Reference */} @@ -21,9 +22,7 @@ await CometChat.deleteConversation("GUID", "group"); This operation is irreversible. Deleted conversations cannot be recovered for the logged-in user. -In case you want to delete a conversation, you can use the `deleteConversation()` method. - -This method takes two parameters. The unique id (UID/GUID) of the conversation to be deleted & the type (user/group) of conversation to be deleted. +Use `deleteConversation()` to delete a conversation for the logged-in user. @@ -88,16 +87,14 @@ CometChat.deleteConversation(GUID, type).then( -This method deletes the conversation only for the logged-in user. To delete a conversation for all the users of the conversation, please refer to our REST API documentation [here](https://api-explorer.cometchat.com/reference/resets-user-conversation). - -The `deleteConversation()` method takes the following parameters: +This deletes the conversation only for the logged-in user. To delete for all participants, use the [REST API](https://api-explorer.cometchat.com/reference/resets-user-conversation). -| Parameter | Description | Required | -| ---------------- | --------------------------------------------------------------------------------- | -------- | -| conversationWith | `UID` of the user or `GUID` of the group whose conversation you want to delete. | YES | -| conversationType | The type of conversation you want to delete . It can be either `user` or `group`. | YES | +| Parameter | Description | Required | +| --- | --- | --- | +| conversationWith | UID or GUID of the conversation to delete | Yes | +| conversationType | `user` or `group` | Yes | -On success, the `deleteConversation()` method resolves with a success message string confirming the operation. +On success, returns a confirmation message string. --- diff --git a/sdk/javascript/delete-message.mdx b/sdk/javascript/delete-message.mdx index 276b1cbfc..12757717c 100644 --- a/sdk/javascript/delete-message.mdx +++ b/sdk/javascript/delete-message.mdx @@ -1,6 +1,7 @@ --- -title: "Delete A Message" -description: "Delete messages, receive real-time deletion events, and handle missed deletion events using the CometChat JavaScript SDK." +title: "Delete Message" +sidebarTitle: "Delete Message" +description: "Delete messages using the CometChat JavaScript SDK." --- {/* TL;DR for Agents and Quick Reference */} @@ -26,16 +27,14 @@ CometChat.addMessageListener("ID", new CometChat.MessageListener({ This operation is irreversible. Deleted messages cannot be recovered. -While [deleting a message](/sdk/javascript/delete-message#delete-a-message) is straightforward, receiving events for deleted messages with CometChat has two parts: +Deleting a message is straightforward. Receiving delete events has two parts: -1. Adding a listener to receive [real-time message deletes](/sdk/javascript/delete-message#real-time-message-delete-events) when your app is running. -2. Calling a method to retrieve [missed message deletes](/sdk/javascript/delete-message#missed-message-delete-events) when your app was not running. +1. Adding a listener for [real-time deletes](#real-time-message-delete-events) when your app is running +2. Fetching [missed deletes](#missed-message-delete-events) when your app was offline ## Delete a Message -*In other words, as a sender, how do I delete a message?* - -In case you have to delete a message, you can use the `deleteMessage()` method. This method takes the message ID of the message to be deleted. +Use `deleteMessage()` with the message ID. @@ -84,7 +83,7 @@ try { -Once the message is deleted, In the `onSuccess()` callback, you get an object of the `BaseMessage` class, with the `deletedAt` field set with the timestamp of the time the message was deleted. Also, the `deletedBy` field is set. These two fields can be used to identify if the message is deleted while iterating through a list of messages. +The deleted message object is returned with `deletedAt` (timestamp) and `deletedBy` (UID of deleter) fields set. The `deleteMessage()` method returns a [`BaseMessage`](/sdk/reference/messages#basemessage) object. Access the response data using getter methods: @@ -106,9 +105,7 @@ By default, CometChat allows certain roles to delete a message. ## Real-time Message Delete Events -*In other words, as a recipient, how do I know when someone deletes a message when my app is running?* - -In order to receive real-time events for a message being deleted, you need to override the `onMessageDeleted()` method of the `MessageListener` class. +Use `onMessageDeleted` in `MessageListener` to receive real-time delete events. @@ -156,26 +153,20 @@ The `onMessageDeleted` callback receives a [`BaseMessage`](/sdk/reference/messag ## Missed Message Delete Events -*In other words, as a recipient, how do I know if someone deleted a message when my app was not running?* - -When you retrieve the list of previous messages, for the messages that were deleted, the `deletedAt` and the `deletedBy` fields will be set. Also, for example, of the total number of messages for a conversation are 100, and the message with message ID 50 was deleted. Now the message with id 50 will have the `deletedAt` and the `deletedBy` fields set whenever it is pulled from the history. Also, the 101st message will be an Actionc message informing you that the message with id 50 has been deleted. - -For the message deleted event, in the `Action` object received, the following fields can help you get the relevant information- +When fetching message history, deleted messages have `deletedAt` and `deletedBy` fields set. Additionally, an `Action` message is created when a message is deleted. -1. `action` - `deleted` -2. `actionOn` - Updated message object which was deleted. -3. `actionBy` - User object containing the details of the user who has deleted the message. -4. `actionFor` - User/group object having the details of the receiver to which the message was sent. +The `Action` object contains: +- `action` — `deleted` +- `actionOn` — Deleted message object +- `actionBy` — User who deleted the message +- `actionFor` — Receiver (User/Group) - -In order to edit or delete a message you need to be either the sender of the message or the admin/moderator of the group in which the message was sent. - +You must be the message sender or a group admin/moderator to delete a message. - -Always remove message listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. +Always remove message listeners when they're no longer needed to prevent memory leaks. --- diff --git a/sdk/javascript/delivery-read-receipts.mdx b/sdk/javascript/delivery-read-receipts.mdx index b575093fd..a1bd63fba 100644 --- a/sdk/javascript/delivery-read-receipts.mdx +++ b/sdk/javascript/delivery-read-receipts.mdx @@ -1,6 +1,7 @@ --- title: "Delivery & Read Receipts" -description: "Learn how to mark messages as delivered, read, or unread and receive real-time receipt events using the CometChat JavaScript SDK." +sidebarTitle: "Delivery & Read Receipts" +description: "Mark messages as delivered, read, or unread and receive real-time receipt events using the CometChat JavaScript SDK." --- {/* TL;DR for Agents and Quick Reference */} @@ -33,8 +34,6 @@ Delivery and read receipts let you track whether messages have been delivered to ## Mark Messages as Delivered -*In other words, as a recipient, how do I inform the sender that I've received a message?* - You can mark the messages for a particular conversation as read using the `markAsDelivered()` method. This method takes the below parameters as input: | Parameter | Information | @@ -330,8 +329,6 @@ CometChat.markConversationAsDelivered(conversationWith, conversationType).then( ## Mark Messages as Read -*In other words, as a recipient, how do I inform the sender I've read a message?* - You can mark the messages for a particular conversation as read using the `markAsRead()` method. This method takes the below parameters as input: | Parameter | Information | @@ -608,11 +605,7 @@ CometChat.markConversationAsRead(conversationWith, conversationType).then( ## Mark Messages as Unread -The Mark messages as Unread feature allows users to designate specific messages or conversations as unread, even if they have been previously viewed. - -This feature is valuable for users who want to revisit and respond to important messages or conversations later, ensuring they don't forget or overlook them. - -In other words, how I can mark a message as unread? +Mark messages as unread to revisit important messages later, even if they've been previously viewed. You can mark the messages for a particular conversation as unread using the `markMessageAsUnread()` method. This method takes the below parameters as input: @@ -678,11 +671,9 @@ CometChat.markMessageAsUnread(message).then( -Receive Delivery & Read Receipts - -*In other words, as a recipient, how do I know when a message I sent has been delivered or read by someone?* +## Receive Delivery & Read Receipts -### Real-time events +### Real-time Events 1. `onMessagesDelivered()` - This event is triggered when a message is delivered to a user. 2. `onMessagesRead()` - This event is triggered when a message is read by a user. diff --git a/sdk/javascript/edit-message.mdx b/sdk/javascript/edit-message.mdx index c38298d4f..88dfffc3f 100644 --- a/sdk/javascript/edit-message.mdx +++ b/sdk/javascript/edit-message.mdx @@ -1,6 +1,7 @@ --- -title: "Edit A Message" -description: "Learn how to edit text and custom messages, receive real-time edit events, and handle missed edit events using the CometChat JavaScript SDK." +title: "Edit Message" +sidebarTitle: "Edit Message" +description: "Edit text and custom messages using the CometChat JavaScript SDK." --- {/* TL;DR for Agents and Quick Reference */} @@ -19,20 +20,18 @@ CometChat.addMessageListener("edits", new CometChat.MessageListener({ ``` -While [editing a message](/sdk/javascript/edit-message#edit-a-message) is straightforward, receiving events for edited messages with CometChat has two parts: +Editing a message is straightforward. Receiving edit events has two parts: -1. Adding a listener to receive [real-time message edits](/sdk/javascript/edit-message#real-time-message-edit-events) when your app is running -2. Calling a method to retrieve [missed message edits](/sdk/javascript/edit-message#missed-message-edit-events) when your app was not running +1. Adding a listener for [real-time edits](#real-time-message-edit-events) when your app is running +2. Fetching [missed edits](#missed-message-edit-events) when your app was offline ## Edit a Message -*In other words, as a sender, how do I edit a message?* - -In order to edit a message, you can use the `editMessage()` method. This method takes an object of the `BaseMessage` class. At the moment, you are only allowed to edit `TextMessage` and `CustomMessage`. Thus, the `BaseMessage` object must either be a Text or a Custom Message. +Use `editMessage()` with a `TextMessage` or `CustomMessage` object. Set the message ID using `setId()`. ### Add/Update Tags -While editing a message, you can update the tags associated with the Message. You can use the `setTags()` method to do so. The tags added while editing a message will replace the tags set when the message was sent. +Use `setTags()` to update tags when editing. New tags replace existing ones. @@ -73,7 +72,7 @@ customMessage.setTags(tags); -Once the message object is ready, you can use the `editMessage()` method and pass the message object to it. +Once the message object is ready, call `editMessage()`. @@ -140,7 +139,7 @@ try { -The object of the edited message will be returned in the `onSuccess()` callback method of the listener. The message object will contain the `editedAt` field set with the timestamp of the time the message was edited. This will help you identify if the message was edited while iterating through the list of messages. The `editedBy` field is also set to the UID of the user who edited the message. +The edited message object is returned with `editedAt` (timestamp) and `editedBy` (UID of editor) fields set. The `editMessage()` method returns a [`BaseMessage`](/sdk/reference/messages#basemessage) object (or a subclass like [`TextMessage`](/sdk/reference/messages#textmessage)). Access the response data using getter methods: @@ -163,9 +162,7 @@ By default, CometChat allows certain roles to edit a message. ## Real-time Message Edit Events -*In other words, as a recipient, how do I know when someone has edited their message when my app is running?* - -In order to receive real-time events for message being edited, you need to override the `onMessageEdited()` method of the `MessageListener` class. +Use `onMessageEdited` in `MessageListener` to receive real-time edit events. @@ -221,21 +218,16 @@ The `onMessageEdited` callback receives a [`BaseMessage`](/sdk/reference/message ## Missed Message Edit Events -*In other words, as a recipient, how do I know when someone edited their message when my app was not running?* - -When you retrieve the list of previous messages, for the message that was edited, the `editedAt` and the `editedBy` fields will be set. Also, for example, of the total number of messages for a conversation are 100, and the message with message ID 50 was edited. Now the message with id 50 will have the `editedAt` and the `editedBy` fields set whenever it is pulled from the history. Also, the 101st message will be and \[Action] message informing you that the message with id 50 has been edited. +When fetching message history, edited messages have `editedAt` and `editedBy` fields set. Additionally, an `Action` message is created when a message is edited. -For the message edited event, in the `Action` object received, the following fields can help you get the relevant information- - -1. `action` - `edited` -2. `actionOn` - Updated message object with the edited details. -3. `actionBy` - User object containing the details of the user who has edited the message. -4. `actionFor` - User/group object having the details of the receiver to which the message was sent. +The `Action` object contains: +- `action` — `edited` +- `actionOn` — Updated message object +- `actionBy` — User who edited the message +- `actionFor` — Receiver (User/Group) - -In order to edit a message, you need to be either the sender of the message or the admin/moderator of the group in which the message was sent. - +You must be the message sender or a group admin/moderator to edit a message. --- diff --git a/sdk/javascript/flag-message.mdx b/sdk/javascript/flag-message.mdx index f014957ec..3e310ff16 100644 --- a/sdk/javascript/flag-message.mdx +++ b/sdk/javascript/flag-message.mdx @@ -1,6 +1,7 @@ --- title: "Flag Message" -description: "Learn how to flag inappropriate messages for moderation review using the CometChat JavaScript SDK." +sidebarTitle: "Flag Message" +description: "Flag inappropriate messages for moderation review using the CometChat JavaScript SDK." --- {/* TL;DR for Agents and Quick Reference */} diff --git a/sdk/javascript/interactive-messages.mdx b/sdk/javascript/interactive-messages.mdx index 87c261f1b..beb3e8027 100644 --- a/sdk/javascript/interactive-messages.mdx +++ b/sdk/javascript/interactive-messages.mdx @@ -1,6 +1,7 @@ --- title: "Interactive Messages" -description: "Learn how to send and receive interactive messages with embedded forms, buttons, and other UI elements using the CometChat JavaScript SDK." +sidebarTitle: "Interactive Messages" +description: "Send and receive interactive messages with embedded forms, buttons, and other UI elements using the CometChat JavaScript SDK." --- {/* TL;DR for Agents and Quick Reference */} diff --git a/sdk/javascript/mentions.mdx b/sdk/javascript/mentions.mdx index 097193e83..72ce3d6cc 100644 --- a/sdk/javascript/mentions.mdx +++ b/sdk/javascript/mentions.mdx @@ -1,6 +1,7 @@ --- title: "Mentions" -description: "Learn how to send messages with user mentions, retrieve mentioned users, and filter messages by mention metadata using the CometChat JavaScript SDK." +sidebarTitle: "Mentions" +description: "Send messages with user mentions, retrieve mentioned users, and filter messages by mention metadata using the CometChat JavaScript SDK." --- diff --git a/sdk/javascript/reactions.mdx b/sdk/javascript/reactions.mdx index f36a62be9..477e29090 100644 --- a/sdk/javascript/reactions.mdx +++ b/sdk/javascript/reactions.mdx @@ -1,5 +1,6 @@ --- title: "Reactions" +sidebarTitle: "Reactions" description: "Add, remove, and fetch message reactions in real-time using the CometChat JavaScript SDK. Includes listener events and helper methods for updating UI." --- diff --git a/sdk/javascript/retrieve-conversations.mdx b/sdk/javascript/retrieve-conversations.mdx index 98f99a84b..e15cdcf30 100644 --- a/sdk/javascript/retrieve-conversations.mdx +++ b/sdk/javascript/retrieve-conversations.mdx @@ -1,6 +1,7 @@ --- title: "Retrieve Conversations" -description: "Fetch, filter, tag, and search conversations using the CometChat JavaScript SDK. Includes pagination, tag-based filtering, agentic conversation filters, and message-to-conversation conversion." +sidebarTitle: "Retrieve Conversations" +description: "Fetch, filter, tag, and search conversations using the CometChat JavaScript SDK." --- {/* TL;DR for Agents and Quick Reference */} @@ -23,19 +24,15 @@ const conversation = await CometChat.CometChatHelper.getConversationFromMessage( ``` -Conversations provide the last messages for every one-on-one and group conversation the logged-in user is a part of. This makes it easy for you to build a **Recent Chat** list. +Conversations provide the last message for every one-on-one and group conversation the logged-in user is part of. Use this to build a Recent Chats list. ## Retrieve List of Conversations -*In other words, as a logged-in user, how do I retrieve the latest conversations that I've been a part of?* - -To fetch the list of conversations, you can use the `ConversationsRequest` class. To use this class i.e. to create an object of the `ConversationsRequest` class, you need to use the `ConversationsRequestBuilder` class. The `ConversationsRequestBuilder` class allows you to set the parameters based on which the conversations are to be fetched. - -The `ConversationsRequestBuilder` class allows you to set the below parameters: +Use `ConversationsRequestBuilder` to fetch conversations with various filters. ### Set Limit -This method sets the limit i.e. the number of conversations that should be fetched in a single iteration. +Set the number of conversations to fetch per request. @@ -62,12 +59,7 @@ let limit: number = 30, ### Set Conversation Type -This method can be used to fetch user or group conversations specifically. The `conversationType` variable can hold one of the below two values: - -* user - Only fetches user conversation. -* group - Only fetches group conversations. - -If none is set, the list of conversations will include both user and group conversations. +Filter by conversation type: `user` for one-on-one or `group` for group conversations. If not set, both types are returned. @@ -97,13 +89,14 @@ let limit: number = 30, -The default value for `setLimit` is 30 and the max value is 50. +Default limit is 30, maximum is 50. -When conversations are fetched successfully, the response will include an array of `Conversation` objects filtered by the specified type. +When conversations are fetched successfully, the response includes an array of `Conversation` objects filtered by the specified type. + ### With User and Group Tags -This method can be used to fetch the user/group tags in the `Conversation` Object. By default the value is `false`. +Use `withUserAndGroupTags(true)` to include user/group tags in the response. Default is `false`. @@ -130,10 +123,11 @@ let limit: number = 30, -When conversations are fetched successfully, the response will include `tags` arrays on the `conversationWith` objects (user or group). +When conversations are fetched successfully, the response includes `tags` arrays on the `conversationWith` objects. + ### Set User Tags -This method fetches user conversations that have the specified tags. +Fetch user conversations where the user has specific tags. @@ -162,10 +156,11 @@ let limit: number = 30, -When conversations are fetched successfully, the response will include only user conversations where the user has the specified tags. +When conversations are fetched successfully, the response includes only user conversations where the user has the specified tags. + ### Set Group Tags -This method fetches group conversations that have the specified tags. +Fetch group conversations where the group has specific tags. @@ -194,10 +189,11 @@ let limit: number = 30, -When conversations are fetched successfully, the response will include only group conversations where the group has the specified tags. +When conversations are fetched successfully, the response includes only group conversations where the group has the specified tags. + ### With Tags -This method makes sure that the tags associated with the conversations are returned along with the other details of the conversations. The default value for this parameter is `false` +Use `withTags(true)` to include conversation tags in the response. Default is `false`. @@ -225,7 +221,7 @@ conversationRequest: CometChat.ConversationsRequest = new CometChat.Conversation ### Set Tags -This method helps you fetch the conversations based on the specified tags. +Fetch conversations that have specific tags. @@ -255,7 +251,7 @@ let limit: number = 30, ### Include Blocked Users -This method helps you fetch the conversations of users whom the logged-in user has blocked. +Use `setIncludeBlockedUsers(true)` to include conversations with users you've blocked. @@ -282,10 +278,11 @@ let limit: number = 30, -When conversations are fetched successfully, the response will include conversations with blocked users. To also get the blocked info details (`blockedByMe`, `blockedByMeAt`, `blockedAt`), set `withBlockedInfo` to `true` as well. +When conversations are fetched successfully, the response includes conversations with blocked users. To also get blocked info details (`blockedByMe`, `blockedByMeAt`, `blockedAt`), set `withBlockedInfo` to `true`. + ### With Blocked Info -This method can be used to fetch the blocked information of the blocked user in the `ConversationWith` object. +Use `setWithBlockedInfo(true)` to include blocked user information in the response. @@ -313,7 +310,7 @@ let limit: number = 30, ### Search Conversations -This method helps you search a conversation based on User or Group name. +Use `setSearchKeyword()` to search conversations by user or group name. @@ -346,10 +343,11 @@ let limit: number = 30, -When conversations are fetched successfully, the response will include conversations where the user or group name matches the search keyword. +When conversations are fetched successfully, the response includes conversations where the user or group name matches the search keyword. + ### Unread Conversations -This method helps you fetch unread conversations. +Use `setUnread(true)` to fetch only conversations with unread messages. @@ -382,10 +380,11 @@ let limit: number = 30, -When conversations are fetched successfully, the response will include only conversations that have unread messages (where `unreadMessageCount` is greater than 0). +When conversations are fetched successfully, the response includes only conversations with unread messages (`unreadMessageCount` > 0). + ### Hide Agentic Conversations -This method allows you to exclude agent conversations from the conversation list. When set to `true`, conversations with AI agents will be filtered out. +Use `setHideAgentic(true)` to exclude AI agent conversations from the list. @@ -413,7 +412,7 @@ let limit: number = 30, ### Only Agentic Conversations -This method allows you to fetch only agent conversations. When set to `true`, only conversations with AI agents will be returned in the list. +Use `setOnlyAgentic(true)` to fetch only AI agent conversations. @@ -441,17 +440,14 @@ let limit: number = 30, - -The `setHideAgentic()` and `setOnlyAgentic()` methods are mutually exclusive. You should only use one of them in a single request builder instance. - +`setHideAgentic()` and `setOnlyAgentic()` are mutually exclusive — use only one per request. -When conversations are fetched successfully, the response will include only conversations with AI agents. Agent users have `role: "@agentic"` and include agent-specific metadata. -Finally, once all the parameters are set to the builder class, you need to call the `build()` method to get the object of the `ConversationsRequest` class. +When conversations are fetched successfully, the response includes only AI agent conversations. Agent users have `role: "@agentic"`. -Once you have the object of the `ConversationsRequest` class, you need to call the `fetchNext()` method. Calling this method will return a list of `Conversation` objects containing X number of users depending on the limit set. +### Fetch Conversations -A Maximum of only 50 Conversations can be fetched at once. +Call `build()` to create the request, then `fetchNext()` to retrieve conversations. Maximum 50 per request. @@ -494,19 +490,19 @@ conversationsRequest.fetchNext().then( -The `Conversation` Object consists of the following fields: +The `Conversation` object contains: -| Field | Information | -| ------------------ | ----------------------------------------------------------------- | -| conversationId | ID of the conversation. | -| conversationType | Type of conversation. (user/group) | -| lastMessage | Last message the conversation. | -| conversationWith | User or Group object containing the details of the user or group. | -| unreadMessageCount | Unread message count for the conversation. | -| unreadMentionsCount | Count of unread mentions in the conversation. | -| lastReadMessageId | ID of the last read message in the conversation. | -| latestMessageId | ID of the latest message in the conversation. | -| tags | Array of tags associated with the conversation (when using `withTags`). | +| Field | Description | +| --- | --- | +| conversationId | ID of the conversation | +| conversationType | Type of conversation (`user`/`group`) | +| lastMessage | Last message in the conversation | +| conversationWith | User or Group object | +| unreadMessageCount | Unread message count | +| unreadMentionsCount | Count of unread mentions | +| lastReadMessageId | ID of the last read message | +| latestMessageId | ID of the latest message | +| tags | Tags associated with the conversation (when using `withTags`) | The `fetchNext()` method returns an array of [`Conversation`](/sdk/reference/entities#conversation) objects. Access the response data using getter methods: @@ -521,18 +517,13 @@ The `fetchNext()` method returns an array of [`Conversation`](/sdk/reference/ent ## Tag Conversation -*In other words, as a logged-in user, how do I tag a conversation?* - -To tag a specific conversation, you can use the `tagConversation()` method. The `tagConversation()` method accepts three parameters. - -1. `conversationWith`: UID/GUID of the user/group whose conversation you want to fetch. - -2. `conversationType`: The `conversationType` variable can hold one of the below two values: - - 1. user - Only fetches user conversation. - 2. group - Only fetches group conversations. +Use `tagConversation()` to add tags to a conversation. -3. `tags`: The `tags` variable will be a list of tags you want to add to a conversation. +| Parameter | Description | +| --- | --- | +| `conversationWith` | UID or GUID of the user/group | +| `conversationType` | `user` or `group` | +| `tags` | Array of tags to add | @@ -572,24 +563,19 @@ CometChat.tagConversation(conversationWith, conversationType, tags).then( - -The tags for conversations are one-way. This means that if user A tags a conversation with user B, that tag will be applied to that conversation only for user A. - +Conversation tags are one-way. If user A tags a conversation with user B, that tag only applies for user A. -When the conversation is tagged successfully, the response will return a single `Conversation` object (not an array) with the `tags` field included. -## Retrieve Single Conversation - -*In other words, as a logged-in user, how do I retrieve a specific conversation?* - -To fetch a specific conversation, you can use the `getConversation` method. The `getConversation` method accepts two parameters. +When the conversation is tagged successfully, the response returns a `Conversation` object with the `tags` field. -1. `conversationWith`: UID/GUID of the user/group whose conversation you want to fetch. +## Retrieve Single Conversation -2. `conversationType`: The `conversationType` variable can hold one of the below two values: +Use `getConversation()` to fetch a specific conversation. - 1. user - Only fetches user conversation. - 2. group - Only fetches group conversations. +| Parameter | Description | +| --- | --- | +| `conversationWith` | UID or GUID of the user/group | +| `conversationType` | `user` or `group` | @@ -625,21 +611,11 @@ CometChat.getConversation(conversationWith, conversationType).then( -When the conversation is fetched successfully, the response will return a single `Conversation` object (not an array). -The `getConversation()` method returns a single [`Conversation`](/sdk/reference/entities#conversation) object. Access the response data using getter methods: - -| Field | Getter | Return Type | Description | -|-------|--------|-------------|-------------| -| conversationId | `getConversationId()` | `string` | Unique conversation ID | -| conversationType | `getConversationType()` | `string` | Type of conversation (`"user"` or `"group"`) | -| lastMessage | `getLastMessage()` | `BaseMessage` | The last message in the conversation | -| conversationWith | `getConversationWith()` | `User` \| `Group` | The user or group this conversation is with | -| unreadMessageCount | `getUnreadMessageCount()` | `number` | Number of unread messages | -| tags | `getTags()` | `string[]` | Tags associated with the conversation (when using `withTags`) | +When the conversation is fetched successfully, the response returns a single [`Conversation`](/sdk/reference/entities#conversation) object. ## Convert Messages to Conversations -As per our [receive messages](/sdk/javascript/receive-message) guide, for real-time messages, you will always receive `Message` objects and not `Conversation` objects. Thus, you will need a mechanism to convert the Message object to the `Conversation` object. You can use the `getConversationFromMessage(BaseMessage message)` of the `CometChatHelper` class. +Use `CometChatHelper.getConversationFromMessage()` to convert a received message into a `Conversation` object. Useful for updating your Recent Chats list when receiving real-time messages. @@ -673,9 +649,7 @@ CometChat.CometChatHelper.getConversationFromMessage(message).then( - -While converting the `Message` object to the `Conversation` object, the `unreadMessageCount` & `tags` will not be available in the `Conversation` object. The unread message count needs to be managed in your client-side code. - +When converting a message to a conversation, `unreadMessageCount` and `tags` won't be available. Manage unread counts in your client-side code. --- diff --git a/sdk/javascript/threaded-messages.mdx b/sdk/javascript/threaded-messages.mdx index cbde9a1b7..e3d2bcf27 100644 --- a/sdk/javascript/threaded-messages.mdx +++ b/sdk/javascript/threaded-messages.mdx @@ -1,6 +1,7 @@ --- title: "Threaded Messages" -description: "Send, receive, and fetch threaded messages using the CometChat JavaScript SDK. Includes real-time listeners, thread message history, and filtering thread replies." +sidebarTitle: "Threaded Messages" +description: "Send, receive, and fetch threaded messages using the CometChat JavaScript SDK." --- {/* TL;DR for Agents and Quick Reference */} @@ -23,21 +24,11 @@ const request = new CometChat.MessagesRequestBuilder() ``` -Messages that are started from a particular message are called Threaded messages or simply threads. Each Thread is attached to a message which is the Parent message for that thread. +Threaded messages (or threads) are messages started from a particular parent message. Each thread is attached to a parent message. ## Send Message in a Thread -As mentioned in the [Send a Message](/sdk/javascript/send-message) section. You can either send a message to a User or a Group based on the `receiverType` and the UID/GUID specified for the message. A message can belong to either of the below types: - -1. Text Message -2. Media Message -3. Custom Message. - -Any of the above messages can be sent in a thread. As mentioned, a thread is identified based on the Parent message. So while sending a message the `parentMessageId` must be set for the message to indicate that the message to be sent needs to be a part of the thread with the specified `parentMessageId`. - -This can be achieved using the `setParentMessageId()` method provided by the object of the `TextMessage`, `MediaMessage` and `CustomMessage` class. The id specified in the `setParentMessageId()` method maps the message sent to the particular thread. - -**Example to Send a Text Message in a thread in a user conversation.** +Any message type (Text, Media, or Custom) can be sent in a thread. Set the `parentMessageId` using `setParentMessageId()` to indicate which thread the message belongs to. @@ -78,19 +69,11 @@ CometChat.sendMessage(textMessage).then( -The above snippet shows how a message with the text "Hello" can be sent in the thread with `parentMessageId` 100. - -Similarly, using the `setParentMessageId()` method, Media and Custom Messages can be sent in threads too. +The above snippet sends "Hello" in the thread with `parentMessageId` 100. Media and Custom messages can also be sent in threads using `setParentMessageId()`. ### Receiving Real-Time Messages -The procedure to receive real-time messages is exactly the same as mentioned in the [Receive Messages](/sdk/javascript/receive-message). This can be achieved using the `MessageListener` class provided by the SDK. - - -Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. - - -To add a MessageListener, you can use the `addMessageListener()` method of the SDK. The only thing that needs to be checked is if the received message belongs to the active thread. This can be done using the `parentMessageId` field of the message object. +Use `MessageListener` to receive real-time thread messages. Check if the received message belongs to the active thread using `getParentMessageId()`. @@ -155,9 +138,7 @@ CometChat.addMessageListener( ### Fetch all the messages for any particular thread. -You can fetch all the messages belonging to a particular thread by using the `MessagesRequest` class. In order to get an object of the `MessagesRequest` class, you need to use the `MessagesRequestBuilder` class. and use the `setParentMessageId()` method of the `MessagesRequestBuilder` to inform the SDK that you only need the messages belonging to the thread with the specified parentMessageId. - -Once you have the object of the `MessagesRequest` class, you need to call the `fetchPrevious()` method to get the latest messages in the thread. In one integration, a maximum of 100 messages can be fetched. If you wish to fetch the next set of messages, you need to call the `fetchPrevious()` method again on the same object. +Use `MessagesRequestBuilder` with `setParentMessageId()` to fetch messages belonging to a specific thread. Call `fetchPrevious()` to get messages (max 100 per request). @@ -215,7 +196,7 @@ The `fetchPrevious()` method returns an array of [`BaseMessage`](/sdk/reference/ ## Avoid Threaded Messages in User/Group Conversations -While fetching messages for normal user/group conversations using the `MessagesRequest`, the threaded messages by default will be a part of the list of messages received. In order to exclude the threaded messages from the list of user/group messages, you need to use the `hideReplies()` method of the `MessagesRequestBuilder` class. This method takes a boolean argument which when set to true excludes the messages belonging to threads from the list of messages. +Use `hideReplies(true)` to exclude threaded messages when fetching messages for a conversation. @@ -304,7 +285,7 @@ messagesRequest.fetchPrevious().then( -The above snippet will return messages between the logged in user and `cometchat-uid-1` excluding all the threaded messages belonging to the same conversation. +The above snippet returns messages excluding threaded replies. --- diff --git a/sdk/javascript/transient-messages.mdx b/sdk/javascript/transient-messages.mdx index 363a70f37..a20c4358f 100644 --- a/sdk/javascript/transient-messages.mdx +++ b/sdk/javascript/transient-messages.mdx @@ -1,5 +1,6 @@ --- title: "Transient Messages" +sidebarTitle: "Transient Messages" description: "Send and receive ephemeral real-time messages that are not stored on the server using the CometChat JavaScript SDK. Ideal for live reactions and temporary indicators." --- @@ -77,8 +78,6 @@ CometChat.sendTransientMessage(transientMessage); ## Real-time Transient Messages -*In other words, as a recipient, how do I know when someone sends a transient message?* - Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. diff --git a/sdk/javascript/typing-indicators.mdx b/sdk/javascript/typing-indicators.mdx index 7bd7d6e60..acc3daa87 100644 --- a/sdk/javascript/typing-indicators.mdx +++ b/sdk/javascript/typing-indicators.mdx @@ -1,6 +1,7 @@ --- title: "Typing Indicators" -description: "Send and receive real-time typing indicators for users and groups using the CometChat JavaScript SDK." +sidebarTitle: "Typing Indicators" +description: "Send and receive real-time typing indicators using the CometChat JavaScript SDK." --- {/* TL;DR for Agents and Quick Reference */} @@ -24,11 +25,9 @@ CometChat.addMessageListener("LISTENER_ID", new CometChat.MessageListener({ ## Send a Typing Indicator -*In other words, as a sender, how do I let the recipient(s) know that I'm typing?* - ### Start Typing -You can use the `startTyping()` method to inform the receiver that the logged in user has started typing. The receiver will receive this information in the `onTypingStarted()` method of the `MessageListener` class. In order to send the typing indicator, you need to use the `TypingIndicator` class. +Use `startTyping()` with a `TypingIndicator` object to notify the receiver that you're typing. @@ -79,7 +78,7 @@ CometChat.startTyping(typingNotification); ### Stop Typing -You can use the `endTyping()` method to inform the receiver that the logged in user has stopped typing. The receiver will receive this information in the `onTypingEnded()` method of the `MessageListener` class. In order to send the typing indicator, you need to use the `TypingIndicator` class. +Use `endTyping()` to notify the receiver that you've stopped typing. @@ -129,21 +128,12 @@ CometChat.endTyping(typingNotification); -Custom Data - -You can use the `metadata` field of the `TypingIndicator` class to pass additional data along with the typing indicators. The metadata field is a JSONObject and can be set using the `setMetadata()` method of the `TypingIndicator` class. This data will be received at the receiver end and can be obtained using the `getMetadata()` method. - +Use `setMetadata()` on `TypingIndicator` to pass additional custom data. Retrieve it with `getMetadata()` on the receiver side. ## Real-time Typing Indicators -*In other words, as a recipient, how do I know when someone is typing?* - - -Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. - - -You will receive the typing indicators in the `onTypingStarted()` and the `onTypingEnded()` method of the registered `MessageListener` class. +Use `onTypingStarted` and `onTypingEnded` in `MessageListener` to receive typing events. @@ -186,14 +176,14 @@ CometChat.addMessageListener( -The `TypingIndicator` class consists of the below parameters: +The `TypingIndicator` object contains: -| Parameter | Information | -| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **sender** | An object of the `User` class holding all the information. related to the sender of the typing indicator. | -| **receiverId** | Unique Id of the receiver. This can be the Id of the group or the user the typing indicator is sent to. | -| **receiverType** | This parameter indicates if the typing indicator is to be sent to a user or a group. The possible values are: 1. `CometChat.RECEIVER_TYPE.USER` 2. `CometChat.RECEIVER_TYPE.GROUP` | -| **metadata** | A JSONObject to provider additional data. | +| Parameter | Description | +| --- | --- | +| sender | User object of the person typing | +| receiverId | UID or GUID of the receiver | +| receiverType | `CometChat.RECEIVER_TYPE.USER` or `GROUP` | +| metadata | Additional custom data | The `onTypingStarted` and `onTypingEnded` listener callbacks receive a [`TypingIndicator`](/sdk/reference/auxiliary#typingindicator) object. Access the data using getter methods: From 0916208f5ac1bc05ce7c908cc340340ecb67a570 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 18 Mar 2026 15:52:27 +0530 Subject: [PATCH 28/43] Links the references --- sdk/javascript/delivery-read-receipts.mdx | 6 +++--- sdk/javascript/edit-message.mdx | 2 +- sdk/javascript/interactive-messages.mdx | 2 +- sdk/javascript/reactions.mdx | 6 +++--- sdk/javascript/receive-message.mdx | 2 +- sdk/javascript/retrieve-conversations.mdx | 8 ++++---- sdk/javascript/send-message.mdx | 12 ++++++------ sdk/javascript/transient-messages.mdx | 2 +- sdk/javascript/typing-indicators.mdx | 4 ++-- 9 files changed, 22 insertions(+), 22 deletions(-) diff --git a/sdk/javascript/delivery-read-receipts.mdx b/sdk/javascript/delivery-read-receipts.mdx index a1bd63fba..d060ed6fb 100644 --- a/sdk/javascript/delivery-read-receipts.mdx +++ b/sdk/javascript/delivery-read-receipts.mdx @@ -611,7 +611,7 @@ You can mark the messages for a particular conversation as unread using the `mar | Parameter | Information | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| message | To mark a message as unread, pass a non-null `BaseMessage` instance to the `markMessageAsUnread()` function. All messages below that message in the conversation will contribute to the unread messages count. Example: When User B sends User A a total of 10 messages, and User A invokes the `markMessageAsUnread()` method on the fifth message, all messages located below the fifth message within the conversation list will be designated as unread. This results in a notification indicating there are 5 unread messages in the conversation list. | +| message | To mark a message as unread, pass a non-null [`BaseMessage`](/sdk/reference/messages#basemessage) instance to the `markMessageAsUnread()` function. All messages below that message in the conversation will contribute to the unread messages count. Example: When User B sends User A a total of 10 messages, and User A invokes the `markMessageAsUnread()` method on the fifth message, all messages located below the fifth message within the conversation list will be designated as unread. This results in a notification indicating there are 5 unread messages in the conversation list. | You cannot mark your own messages as unread. This method only works for messages received from other users. @@ -635,7 +635,7 @@ CometChat.markMessageAsUnread(message); -In case you would like to be notified of an error if the receipts fail to go through you can use `.then(successCallback, failureCallback).` On success, this method returns an updated `Conversation` object with the updated unread message count and other conversation data. +In case you would like to be notified of an error if the receipts fail to go through you can use `.then(successCallback, failureCallback).` On success, this method returns an updated [`Conversation`](/sdk/reference/entities#conversation) object with the updated unread message count and other conversation data. @@ -809,7 +809,7 @@ CometChat.getMessageReceipts(messageId).then( -You will receive a list of `MessageReceipt` objects. +You will receive a list of [`MessageReceipt`](/sdk/reference/auxiliary#messagereceipt) objects. diff --git a/sdk/javascript/edit-message.mdx b/sdk/javascript/edit-message.mdx index 88dfffc3f..4587506ca 100644 --- a/sdk/javascript/edit-message.mdx +++ b/sdk/javascript/edit-message.mdx @@ -27,7 +27,7 @@ Editing a message is straightforward. Receiving edit events has two parts: ## Edit a Message -Use `editMessage()` with a `TextMessage` or `CustomMessage` object. Set the message ID using `setId()`. +Use `editMessage()` with a [`TextMessage`](/sdk/reference/messages#textmessage) or [`CustomMessage`](/sdk/reference/messages#custommessage) object. Set the message ID using `setId()`. ### Add/Update Tags diff --git a/sdk/javascript/interactive-messages.mdx b/sdk/javascript/interactive-messages.mdx index beb3e8027..564fdde58 100644 --- a/sdk/javascript/interactive-messages.mdx +++ b/sdk/javascript/interactive-messages.mdx @@ -26,7 +26,7 @@ An InteractiveMessage is a specialised object that encapsulates an interactive u ## InteractiveMessage -`InteractiveMessage` is a chat message with embedded interactive content. It can contain various properties: +[`InteractiveMessage`](/sdk/reference/messages#interactivemessage) is a chat message with embedded interactive content. It can contain various properties: | Parameter | Description | Required | | ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------- | diff --git a/sdk/javascript/reactions.mdx b/sdk/javascript/reactions.mdx index 477e29090..e092ac731 100644 --- a/sdk/javascript/reactions.mdx +++ b/sdk/javascript/reactions.mdx @@ -328,7 +328,7 @@ message.getReactions() ## Check if Logged-in User has Reacted on Message -To check if the logged-in user has reacted on a particular message or not, You can use the `getReactedByMe()` method on any `ReactionCount` object instance. This method will return a boolean value, true if the logged-in user has reacted on that message, otherwise false. +To check if the logged-in user has reacted on a particular message or not, You can use the `getReactedByMe()` method on any [`ReactionCount`](/sdk/reference/auxiliary#reactioncount) object instance. This method will return a boolean value, true if the logged-in user has reacted on that message, otherwise false. @@ -357,9 +357,9 @@ reaction.getReactedByMe(); //Return true is logged-in user reacted on that messa When a user adds or removes a reaction, you will receive a real-time event. Once you receive the real time event you would want to update the message with the latest reaction information. To do so you can use the `updateMessageWithReactionInfo()` method. -The `updateMessageWithReactionInfo()` method provides a seamless way to update the reactions on a message instance (`BaseMessage`) in real-time. This method ensures that when a reaction is added or removed from a message, the BaseMessage object's `getReactions()` property reflects this change immediately. +The `updateMessageWithReactionInfo()` method provides a seamless way to update the reactions on a message instance ([`BaseMessage`](/sdk/reference/messages#basemessage)) in real-time. This method ensures that when a reaction is added or removed from a message, the `BaseMessage` object's `getReactions()` property reflects this change immediately. -When you receive a real-time reaction event (`MessageReaction`), call the `updateMessageWithReactionInfo()` method, passing the BaseMessage instance (`message`), event data (`MessageReaction`) and reaction event action type (`CometChat.REACTION_ACTION.REACTION_ADDED` or `CometChat.REACTION_ACTION.REACTION_REMOVED`) that corresponds to the message being reacted to. +When you receive a real-time reaction event ([`MessageReaction`](/sdk/reference/auxiliary#messagereaction)), call the `updateMessageWithReactionInfo()` method, passing the `BaseMessage` instance (`message`), event data (`MessageReaction`) and reaction event action type (`CometChat.REACTION_ACTION.REACTION_ADDED` or `CometChat.REACTION_ACTION.REACTION_REMOVED`) that corresponds to the message being reacted to. diff --git a/sdk/javascript/receive-message.mdx b/sdk/javascript/receive-message.mdx index 5d7740aad..c4ac562d4 100644 --- a/sdk/javascript/receive-message.mdx +++ b/sdk/javascript/receive-message.mdx @@ -344,7 +344,7 @@ messagesRequest.fetchPrevious().then( -The list of messages received is in the form of `BaseMessage` objects. A BaseMessage can either be an object of the `TextMessage`, `MediaMessage`, `CustomMessage`, `Action` or `Call` class. You can use the `instanceof` operator to check the type of object. +The list of messages received is in the form of [`BaseMessage`](/sdk/reference/messages#basemessage) objects. A `BaseMessage` can either be an object of the [`TextMessage`](/sdk/reference/messages#textmessage), [`MediaMessage`](/sdk/reference/messages#mediamessage), [`CustomMessage`](/sdk/reference/messages#custommessage), `Action` or `Call` class. You can use the `instanceof` operator to check the type of object. ## Message History diff --git a/sdk/javascript/retrieve-conversations.mdx b/sdk/javascript/retrieve-conversations.mdx index e15cdcf30..6d1f4ada3 100644 --- a/sdk/javascript/retrieve-conversations.mdx +++ b/sdk/javascript/retrieve-conversations.mdx @@ -92,7 +92,7 @@ let limit: number = 30, Default limit is 30, maximum is 50. -When conversations are fetched successfully, the response includes an array of `Conversation` objects filtered by the specified type. +When conversations are fetched successfully, the response includes an array of [`Conversation`](/sdk/reference/entities#conversation) objects filtered by the specified type. ### With User and Group Tags @@ -490,7 +490,7 @@ conversationsRequest.fetchNext().then( -The `Conversation` object contains: +The [`Conversation`](/sdk/reference/entities#conversation) object contains: | Field | Description | | --- | --- | @@ -566,7 +566,7 @@ CometChat.tagConversation(conversationWith, conversationType, tags).then( Conversation tags are one-way. If user A tags a conversation with user B, that tag only applies for user A. -When the conversation is tagged successfully, the response returns a `Conversation` object with the `tags` field. +When the conversation is tagged successfully, the response returns a [`Conversation`](/sdk/reference/entities#conversation) object with the `tags` field. ## Retrieve Single Conversation @@ -615,7 +615,7 @@ When the conversation is fetched successfully, the response returns a single [`C ## Convert Messages to Conversations -Use `CometChatHelper.getConversationFromMessage()` to convert a received message into a `Conversation` object. Useful for updating your Recent Chats list when receiving real-time messages. +Use `CometChatHelper.getConversationFromMessage()` to convert a received message into a [`Conversation`](/sdk/reference/entities#conversation) object. Useful for updating your Recent Chats list when receiving real-time messages. diff --git a/sdk/javascript/send-message.mdx b/sdk/javascript/send-message.mdx index 1ee100a15..31204b84d 100644 --- a/sdk/javascript/send-message.mdx +++ b/sdk/javascript/send-message.mdx @@ -8,7 +8,7 @@ description: "Send text, media, and custom messages to users and groups using th | Field | Value | | --- | --- | -| Key Classes | `TextMessage`, `MediaMessage`, `CustomMessage` | +| Key Classes | [`TextMessage`](/sdk/reference/messages#textmessage), [`MediaMessage`](/sdk/reference/messages#mediamessage), [`CustomMessage`](/sdk/reference/messages#custommessage) | | Key Methods | `sendMessage()`, `sendMediaMessage()`, `sendCustomMessage()` | | Receiver Types | `CometChat.RECEIVER_TYPE.USER`, `CometChat.RECEIVER_TYPE.GROUP` | | Message Types | `TEXT`, `IMAGE`, `VIDEO`, `AUDIO`, `FILE`, `CUSTOM` | @@ -28,7 +28,7 @@ You can also send [Interactive Messages](/sdk/javascript/interactive-messages) f ## Text Message -Send a text message using `CometChat.sendMessage()` with a `TextMessage` object. +Send a text message using `CometChat.sendMessage()` with a [`TextMessage`](/sdk/reference/messages#textmessage) object. @@ -136,7 +136,7 @@ try { -The `TextMessage` class constructor takes the following parameters: +The [`TextMessage`](/sdk/reference/messages#textmessage) class constructor takes the following parameters: | Parameter | Description | Required | | --- | --- | --- | @@ -221,7 +221,7 @@ There are two ways to send media messages: ### Upload a File -Get the file from an input element and pass it to `MediaMessage`: +Get the file from an input element and pass it to [`MediaMessage`](/sdk/reference/messages#mediamessage): ```html @@ -461,7 +461,7 @@ CometChat.sendMediaMessage(mediaMessage).then( -The `MediaMessage` class constructor takes the following parameters: +The [`MediaMessage`](/sdk/reference/messages#mediamessage) class constructor takes the following parameters: | Parameter | Description | Required | | --- | --- | --- | @@ -890,7 +890,7 @@ CometChat.sendCustomMessage(customMessage).then( -The `CustomMessage` class constructor takes the following parameters: +The [`CustomMessage`](/sdk/reference/messages#custommessage) class constructor takes the following parameters: | Parameter | Description | Required | | --- | --- | --- | diff --git a/sdk/javascript/transient-messages.mdx b/sdk/javascript/transient-messages.mdx index a20c4358f..f80d95bbe 100644 --- a/sdk/javascript/transient-messages.mdx +++ b/sdk/javascript/transient-messages.mdx @@ -119,7 +119,7 @@ CometChat.addMessageListener( -The `TransientMessage` class consists of the below parameters: +The [`TransientMessage`](/sdk/reference/auxiliary#transientmessage) class consists of the below parameters: | Parameter | Information | | ---------------- | -------------------------------------------------------------------------------------------------------- | diff --git a/sdk/javascript/typing-indicators.mdx b/sdk/javascript/typing-indicators.mdx index acc3daa87..1fb3a0cb4 100644 --- a/sdk/javascript/typing-indicators.mdx +++ b/sdk/javascript/typing-indicators.mdx @@ -27,7 +27,7 @@ CometChat.addMessageListener("LISTENER_ID", new CometChat.MessageListener({ ### Start Typing -Use `startTyping()` with a `TypingIndicator` object to notify the receiver that you're typing. +Use `startTyping()` with a [`TypingIndicator`](/sdk/reference/auxiliary#typingindicator) object to notify the receiver that you're typing. @@ -176,7 +176,7 @@ CometChat.addMessageListener( -The `TypingIndicator` object contains: +The [`TypingIndicator`](/sdk/reference/auxiliary#typingindicator) object contains: | Parameter | Description | | --- | --- | From 0fd5d1f0bd55639f17eb75ba2759f77a42097d49 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 18 Mar 2026 15:55:41 +0530 Subject: [PATCH 29/43] Update docs.json --- docs.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs.json b/docs.json index df5363a19..154a6fe0a 100644 --- a/docs.json +++ b/docs.json @@ -2604,7 +2604,9 @@ { "group": "Reference", "pages": [ - "sdk/reference/messages" + "sdk/reference/messages", + "sdk/reference/entities", + "sdk/reference/auxiliary" ] }, { From c3f526ed92f7e4d0b95f07715076c1264493f744 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 18 Mar 2026 16:00:19 +0530 Subject: [PATCH 30/43] Update send-message.mdx --- sdk/javascript/send-message.mdx | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/sdk/javascript/send-message.mdx b/sdk/javascript/send-message.mdx index 31204b84d..0d8458111 100644 --- a/sdk/javascript/send-message.mdx +++ b/sdk/javascript/send-message.mdx @@ -328,7 +328,7 @@ CometChat.sendMediaMessage(mediaMessage).then( ### Send a URL -Send media hosted on your server or cloud storage using the `Attachment` class: +Send media hosted on your server or cloud storage using the [`Attachment`](/sdk/reference/auxiliary#attachment) class: @@ -921,6 +921,14 @@ By default, custom messages update the conversation's last message. To prevent t customMessage.shouldUpdateConversation(false); ``` +{/* ### Control Push Notifications + +By default, custom messages don't trigger push notifications. To enable them: + +```javascript +customMessage.shouldSendNotification(true); +``` */} + ### Custom Notification Text Set custom text for push, email, and SMS notifications: From ef2c022a9e306654eaf472f9b9a6ec5ae904d477 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 18 Mar 2026 16:04:54 +0530 Subject: [PATCH 31/43] updates references --- sdk/javascript/delivery-read-receipts.mdx | 4 ++-- sdk/javascript/interactive-messages.mdx | 6 +++--- sdk/javascript/reactions.mdx | 3 ++- sdk/javascript/retrieve-conversations.mdx | 7 +++++-- 4 files changed, 12 insertions(+), 8 deletions(-) diff --git a/sdk/javascript/delivery-read-receipts.mdx b/sdk/javascript/delivery-read-receipts.mdx index d060ed6fb..4f26435c5 100644 --- a/sdk/javascript/delivery-read-receipts.mdx +++ b/sdk/javascript/delivery-read-receipts.mdx @@ -758,9 +758,9 @@ The listener callbacks receive a [`MessageReceipt`](/sdk/reference/auxiliary#mes | Field | Getter | Return Type | Description | |-------|--------|-------------|-------------| | messageId | `getMessageId()` | `string` | ID of the message this receipt is for | -| sender | `getSender()` | `User` | User who triggered the receipt | +| sender | `getSender()` | [`User`](/sdk/reference/entities#user) | User who triggered the receipt | | receiptType | `getReceiptType()` | `string` | Type of receipt (`"delivery"` or `"read"`) | -| timestamp | `getTimestamp()` | `number` | Timestamp of the receipt event | +| timestamp | `getTimestamp()` | `string` | Timestamp of the receipt event | | deliveredAt | `getDeliveredAt()` | `number` | Timestamp when the message was delivered | | readAt | `getReadAt()` | `number` | Timestamp when the message was read | diff --git a/sdk/javascript/interactive-messages.mdx b/sdk/javascript/interactive-messages.mdx index 564fdde58..c3101a09c 100644 --- a/sdk/javascript/interactive-messages.mdx +++ b/sdk/javascript/interactive-messages.mdx @@ -167,9 +167,9 @@ The `sendInteractiveMessage()` method returns an [`InteractiveMessage`](/sdk/ref | Field | Getter | Return Type | Description | |-------|--------|-------------|-------------| | interactiveData | `getInteractiveData()` | `Object` | The structured JSON data for the interactive element | -| interactionGoal | `getInteractionGoal()` | `InteractionGoal` | The intended outcome of interacting with the message | -| interactions | `getInteractions()` | `Interaction[]` | List of user interactions performed on the message | -| allowSenderInteraction | `getAllowSenderInteraction()` | `boolean` | Whether the sender can interact with the message | +| interactionGoal | `getInteractionGoal()` | [`InteractionGoal`](/sdk/reference/auxiliary#interactiongoal) | The intended outcome of interacting with the message | +| interactions | `getInteractions()` | [`Interaction[]`](/sdk/reference/auxiliary#interaction) | List of user interactions performed on the message | +| allowSenderInteraction | `getIsSenderInteractionAllowed()` | `boolean` | Whether the sender can interact with the message | ## Event Listeners diff --git a/sdk/javascript/reactions.mdx b/sdk/javascript/reactions.mdx index e092ac731..82e226f6e 100644 --- a/sdk/javascript/reactions.mdx +++ b/sdk/javascript/reactions.mdx @@ -275,10 +275,11 @@ Each reaction listener callback receives a [`ReactionEvent`](/sdk/reference/auxi | Field | Getter | Return Type | Description | |-------|--------|-------------|-------------| -| reaction | `getReaction()` | `string` | The emoji reaction that was added or removed | +| reaction | `getReaction()` | [`Reaction`](/sdk/reference/auxiliary#reaction) | The reaction object containing emoji, user, and timestamp | | receiverId | `getReceiverId()` | `string` | UID or GUID of the receiver | | receiverType | `getReceiverType()` | `string` | Type of receiver (`user` or `group`) | | conversationId | `getConversationId()` | `string` | ID of the conversation | +| parentMessageId | `getParentMessageId()` | `string` | ID of the parent message (for threaded messages) | ## Removing a Reaction Listener diff --git a/sdk/javascript/retrieve-conversations.mdx b/sdk/javascript/retrieve-conversations.mdx index 6d1f4ada3..f8be2187d 100644 --- a/sdk/javascript/retrieve-conversations.mdx +++ b/sdk/javascript/retrieve-conversations.mdx @@ -510,9 +510,12 @@ The `fetchNext()` method returns an array of [`Conversation`](/sdk/reference/ent |-------|--------|-------------|-------------| | conversationId | `getConversationId()` | `string` | Unique conversation ID | | conversationType | `getConversationType()` | `string` | Type of conversation (`"user"` or `"group"`) | -| lastMessage | `getLastMessage()` | `BaseMessage` | The last message in the conversation | -| conversationWith | `getConversationWith()` | `User` \| `Group` | The user or group this conversation is with | +| lastMessage | `getLastMessage()` | [`BaseMessage`](/sdk/reference/messages#basemessage) | The last message in the conversation | +| conversationWith | `getConversationWith()` | [`User`](/sdk/reference/entities#user) \| [`Group`](/sdk/reference/entities#group) | The user or group this conversation is with | | unreadMessageCount | `getUnreadMessageCount()` | `number` | Number of unread messages | +| unreadMentionsCount | `getUnreadMentionsCount()` | `number` | Count of unread mentions | +| lastReadMessageId | `getLastReadMessageId()` | `string` | ID of the last read message | +| latestMessageId | `getLatestMessageId()` | `string` | ID of the latest message | | tags | `getTags()` | `string[]` | Tags associated with the conversation (when using `withTags`) | ## Tag Conversation From 5eba105c6485ace998ee3f490338721d5374168d Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 18 Mar 2026 16:11:40 +0530 Subject: [PATCH 32/43] calling docs - frame this better --- sdk/javascript/call-logs.mdx | 17 +++--- sdk/javascript/calling-setup.mdx | 15 +++-- sdk/javascript/custom-css.mdx | 56 ++++++++--------- sdk/javascript/default-call.mdx | 1 + sdk/javascript/direct-call.mdx | 1 + sdk/javascript/presenter-mode.mdx | 66 +++++++-------------- sdk/javascript/recording.mdx | 21 +++---- sdk/javascript/session-timeout.mdx | 29 +++------ sdk/javascript/standalone-calling.mdx | 1 + sdk/javascript/video-view-customisation.mdx | 9 ++- sdk/javascript/virtual-background.mdx | 19 ++---- 11 files changed, 93 insertions(+), 142 deletions(-) diff --git a/sdk/javascript/call-logs.mdx b/sdk/javascript/call-logs.mdx index 064066a55..deeac9afd 100644 --- a/sdk/javascript/call-logs.mdx +++ b/sdk/javascript/call-logs.mdx @@ -1,5 +1,6 @@ --- title: "Call Logs" +sidebarTitle: "Call Logs" description: "Fetch, filter, and retrieve call history including duration, participants, and recording status using the CometChat Calls SDK." --- @@ -25,15 +26,11 @@ let details = await CometChatCalls.getCallDetails("SESSION_ID", authToken); ## Overview -CometChat's Web Call SDK provides a comprehensive way to integrate call logs into your application, enhancing your user experience by allowing users to effortlessly keep track of their communication history. Call logs provide crucial information such as call duration, participants, and more. - -This feature not only allows users to review their past interactions but it also serves as an effective tool to revisit important conversation details. With the flexibility of fetching call logs, filtering them according to specific parameters, and obtaining detailed information of individual calls, application developers can use this feature to build a more robust and interactive communication framework. - -In the following sections, we will guide you through the process of working with call logs, offering a deeper insight into how to optimally use this feature in your Web application. +Retrieve and display call history including duration, participants, status, and recording information. ## Fetching Call Logs -To fetch all call logs in your 23b application, you should use the `CallLogRequestBuilder`, This builder allows you to customize the call logs fetching process according to your needs. +Use `CallLogRequestBuilder` to fetch and filter call logs: ```javascript let callLogRequestBuilder = new CometChatCalls.CallLogRequestBuilder() @@ -43,7 +40,7 @@ let callLogRequestBuilder = new CometChatCalls.CallLogRequestBuilder() .build() ``` -`CallLogRequestBuilder` has the following settings available. +### Builder Settings | Setting | Description | | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ | @@ -59,7 +56,7 @@ let callLogRequestBuilder = new CometChatCalls.CallLogRequestBuilder() ### Fetch Next -The `fetchNext()` method retrieves the next set of call logs. +Retrieves the next set of call logs: ```javascript let callLogRequestBuilder = new CometChatCalls.CallLogRequestBuilder() @@ -79,7 +76,7 @@ callLogRequestBuilder.fetchNext() ### Fetch Previous -The `fetchPrevious()` method retrieves the previous set of call logs. +Retrieves the previous set of call logs: ```javascript let callLogRequestBuilder = new CometChatCalls.CallLogRequestBuilder() @@ -110,7 +107,7 @@ The `fetchNext()` and `fetchPrevious()` methods return an array of [`Call`](/sdk ## Get Call Details -To retrieve the specific details of a call, use the `getCallDetails()` method. This method requires the Auth token of the logged-in user and the session ID along with a callback listener. +Retrieve details for a specific call session using `getCallDetails()`: diff --git a/sdk/javascript/calling-setup.mdx b/sdk/javascript/calling-setup.mdx index 710dd6a8f..96ffa72cb 100644 --- a/sdk/javascript/calling-setup.mdx +++ b/sdk/javascript/calling-setup.mdx @@ -1,5 +1,6 @@ --- title: "Setup" +sidebarTitle: "Setup" description: "Install and initialize the CometChat Calls SDK for JavaScript to enable voice and video calling in your application." --- @@ -78,15 +79,17 @@ import { CometChatCalls } from "@cometchat/calls-sdk-javascript"; ### Initialize CometChatCalls -The `init()` method initialises the settings required for `CometChatCalls`. The `init()` method takes a single paramater, that is the instance of `CallAppSettings` class. +The `init()` method initializes the Calls SDK. It takes a `CallAppSettings` instance as its parameter. -The `CallAppSettingsBuilder` class allows you to configure three settings: +`CallAppSettingsBuilder` accepts three settings: -1. **appID:** You CometChat App ID -2. **region**: The region where your app was created -3. **host:** This method takes the client URL as input and uses this client URL instead of the default client URL. This can be used in case of dedicated deployment of CometChat. +| Setting | Description | +| ------- | ----------- | +| `appID` | Your CometChat App ID | +| `region` | The region where your app was created | +| `host` | (Optional) Custom client URL for dedicated deployments | -You need to call init() before calling any other method from `CometChatCalls`. We suggest you call the init() method on app startup, preferably in the index.js file. +Call `init()` before any other `CometChatCalls` method — ideally on app startup. diff --git a/sdk/javascript/custom-css.mdx b/sdk/javascript/custom-css.mdx index bdcfd44c0..e02ba8841 100644 --- a/sdk/javascript/custom-css.mdx +++ b/sdk/javascript/custom-css.mdx @@ -1,5 +1,6 @@ --- title: "Custom CSS" +sidebarTitle: "Custom CSS" description: "Customize the CometChat calling UI with custom CSS classes for buttons, video containers, name labels, and grid layouts." --- @@ -21,36 +22,37 @@ description: "Customize the CometChat calling UI with custom CSS classes for but **Modes:** `DEFAULT` | `TILE` | `SPOTLIGHT` -Passing custom CSS allows you to personalize and enhance the user interface of the call screen. +Style the calling UI with custom CSS to match your application's design. ## Common CSS Classes -There are a few common classes used for different modes in the call screen +These classes are available across all call modes: -1. **cc-main-container** - The outermost component of the calling component is represented by a white border in the screenshots above, indicating that it acts as a container for other components. - -2. **cc-bottom-buttons-container** - The container located at the very bottom of the interface houses various action buttons, such as the mute/unmute audio and video, end call, settings icon, and participants icon, among others. It is represented by the red border in above screenshot. - -3. **cc-name-label** - This class is passed in user name text container in all modes. It is represented by green border in the above screenshots. - -4. **cc-video-container** - This class is passed to the video container in all modes. It is represented by orange border in the above screenshots. +| Class | Description | +| ----- | ----------- | +| `cc-main-container` | Outermost container for the calling component | +| `cc-bottom-buttons-container` | Bottom bar containing action buttons (mute, end call, etc.) | +| `cc-name-label` | User name text container | +| `cc-video-container` | Video feed container | ## Bottom Buttons -1. **cc-bottom-buttons-container** - This is the container of all the buttons in calling. -2. **cc-bottom-buttons-icon-container** - This is the div of every button in the button bar. +| Class | Description | +| ----- | ----------- | +| `cc-bottom-buttons-container` | Container for all action buttons | +| `cc-bottom-buttons-icon-container` | Individual button wrapper | -### Individual bottom buttons CSS classes +### Individual Button Classes -* `cc-audio-icon-container` -* `cc-audio-icon-container-muted` -* `cc-video-icon-container` -* `cc-video-icon-container-muted` -* `cc-screen-share-icon-container` -* `cc-switch-video-icon-container` -* `cc-end-call-icon-container` +- `cc-audio-icon-container` — Audio toggle button +- `cc-audio-icon-container-muted` — Audio button (muted state) +- `cc-video-icon-container` — Video toggle button +- `cc-video-icon-container-muted` — Video button (muted state) +- `cc-screen-share-icon-container` — Screen share button +- `cc-switch-video-icon-container` — Switch camera button +- `cc-end-call-icon-container` — End call button -### **Example** +### Example @@ -175,18 +177,10 @@ The above example results in the below output:- +### Guidelines -### Guidelines for Customizing the Grid Layout - -* **CSS Classes:** - - * Please ensure that you only apply CSS classes specified in this documentation. Introducing CSS classes not covered here may cause unexpected UI issues. - -* **Grid Container Resizing:** - - * Avoid resizing the grid container. Altering the grid container’s dimensions can negatively impact the grid layout, leading to undesirable visual distortions. - -By following these recommendations, you can maintain a stable and visually consistent grid layout. +- Only use CSS classes documented here — custom classes may cause UI issues +- Avoid resizing the grid container to prevent layout distortions --- diff --git a/sdk/javascript/default-call.mdx b/sdk/javascript/default-call.mdx index 42df01e3d..6dff0e20e 100644 --- a/sdk/javascript/default-call.mdx +++ b/sdk/javascript/default-call.mdx @@ -1,5 +1,6 @@ --- title: "Ringing" +sidebarTitle: "Ringing" description: "Implement a complete calling workflow with ringing, incoming/outgoing call UI, accept/reject/cancel functionality, and call session management." --- diff --git a/sdk/javascript/direct-call.mdx b/sdk/javascript/direct-call.mdx index 33d1f1d09..110a9d887 100644 --- a/sdk/javascript/direct-call.mdx +++ b/sdk/javascript/direct-call.mdx @@ -1,5 +1,6 @@ --- title: "Call Session" +sidebarTitle: "Call Session" description: "Learn how to generate call tokens, start and manage call sessions, configure call settings, and handle call events using the CometChat JavaScript Calls SDK." --- diff --git a/sdk/javascript/presenter-mode.mdx b/sdk/javascript/presenter-mode.mdx index 2500f850a..bc995697d 100644 --- a/sdk/javascript/presenter-mode.mdx +++ b/sdk/javascript/presenter-mode.mdx @@ -1,5 +1,6 @@ --- title: "Presenter Mode" +sidebarTitle: "Presenter Mode" description: "Learn how to implement Presenter Mode for webinars, keynotes, and online classes using the CometChat JavaScript Calls SDK." --- @@ -23,36 +24,22 @@ CometChatCalls.joinPresentation(callToken, settings, htmlElement); ## Overview -The Presenter Mode feature allows developers to create a calling service experience in which: +Presenter Mode enables broadcast-style calling experiences where presenters share content with passive viewers. -1. There are one or more users who are presenting their video, audio and/or screen (Maximum 5) -2. Viewers who are consumers of that presentation. (They cannot send their audio, video or screen streams out). -3. The total number of presenters and viewers can go up to 100. -4. Features such as mute/unmute audio, show/hide camera capture, recording, etc. will be enabled only for the Presenter in this mode. -5. Other call participants will not get these features. Hence they act like passive viewers in the call. +| Role | Capabilities | Max Count | +| ---- | ------------ | --------- | +| Presenter | Video, audio, screen sharing, mute controls, recording | 5 | +| Viewer | Watch and listen only (no outgoing streams) | Up to 100 total | -Using this feature developers can create experiences such as: +Use cases: webinars, keynotes, all-hands meetings, online classes, talk shows. -1. All hands calls -2. Keynote speeches -3. Webinars -4. Talk shows -5. Online classes -6. and many more... - -### About this guide - -This guide demonstrates how to start a presentation into an React Native application. Before you begin, we strongly recommend you read the calling setup guide. - -Before starting a call session you have to generate a call token using the generateToken() method of the CometChatCalls SDK as mentioned [here](/sdk/javascript/direct-call#generate-call-token). +Before starting a presentation, generate a call token using `generateToken()` as described in [Call Session](/sdk/javascript/direct-call#generate-call-token). ### Start Presentation Session -The most important class that will be used in the implementation is the `PresentationSettings` class. This class allows you to set the various parameters for the Presentation Mode. In order to set the various parameters of the `PresentationSettings` class, you need to use the `PresentationSettingsBuilder` class. Below are the various options available with the `PresentationSettings` class. +Configure the presentation using `PresentationSettingsBuilder`. Set the user type with `setIsPresenter(true)` for presenters or `setIsPresenter(false)` for viewers. -You will need to set the User Type, There are 2 type of users in Presenter Mode, `Presenter` & `Participant` , You can set this `PresentationSettingsBuilder` by using the following method `setIsPresenter(true/false)` - -A basic example of how to start a Presentation: +Basic example: @@ -75,9 +62,15 @@ CometChatCalls.joinPresentation( -## **Listeners** +## Listeners -Listeners can be added in two ways the first one is to use `.setCallEventListener(listeners : OngoingCallListener)` method in `CallSettingsBuilder` or `PresenterSettingsBuilder` class. The second way is to use `CometChatCalls.addCallEventListener(name: string, callListener: OngoingCallListener)` by this you can add multiple listeners and remove the specific listener by their name `CometChatCalls.removeCallEventListener(name: string)` +Add listeners in two ways: +1. Use `.setCallEventListener()` in `PresentationSettingsBuilder` +2. Use `CometChatCalls.addCallEventListener(name, listener)` for multiple listeners + + +Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + @@ -117,7 +110,7 @@ useEffect(() => { -The `CometChatCallsEventsListener` listener provides you with the below callback methods: +### Events | Callback Method | Description | | ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | @@ -134,14 +127,7 @@ The `CometChatCallsEventsListener` listener provides you with the below callback ## Settings -The `PresentationSettings` class is the most important class when it comes to the implementation of the Calling feature. This is the class that allows you to customize the overall calling experience. The properties for the call/conference can be set using the `PresentationSettingsBuilder` class. This will eventually give you and object of the `PresentationSettings` class which you can pass to the `joinPresentation()` method to start the call. - -The **mandatory** parameters that are required to be present for any call/conference to work are: - -1. Context - context of the activity/application -2. RelativeLayout - A RelativeLayout object in which the calling UI is loaded. - -The options available for customization of calls are: +Configure the presentation experience using `PresentationSettingsBuilder`: | Parameter | Description | | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | @@ -159,17 +145,7 @@ The options available for customization of calls are: | `setDefaultAudioMode(audioMode: string)` | This method can be used if you wish to start the call with a specific audio mode. The available options are 1. CometChatCalls.AUDIO\_MODE.SPEAKER = "SPEAKER" 2. CometChatCalls.AUDIO\_MODE.EARPIECE = "EARPIECE" 3. CometChatCalls.AUDIO\_MODE.BLUETOOTH = "BLUETOOTH" 4. CometChatCalls.AUDIO\_MODE.HEADPHONES = "HEADPHONES" | | `setEventListener(new CometChatCallsEventsListener())` | The `CometChatCallsEventsListener` listener provides you callbacks | -In case you wish to achieve a completely customised UI for the Calling experience, you can do so by embedding default android buttons to the screen as per your requirement and then use the below methods to achieve different functionalities for the embedded buttons. - -For the use case where you wish to align your own custom buttons and not use the default layout provided by CometChat you can embed the buttons in your layout and use the below methods to perform the corresponding operations: - - -Always remove call event listeners when they're no longer needed (e.g., on component unmount or when the presentation screen is closed). Failing to remove listeners can cause memory leaks and duplicate event handling. - -```javascript -CometChatCalls.removeCallEventListener("UNIQUE_ID"); -``` - +For custom UI, embed your own buttons and use the call control methods described in [Call Session Methods](/sdk/javascript/direct-call#methods). --- diff --git a/sdk/javascript/recording.mdx b/sdk/javascript/recording.mdx index 19f4fc682..1f8b119be 100644 --- a/sdk/javascript/recording.mdx +++ b/sdk/javascript/recording.mdx @@ -1,5 +1,6 @@ --- title: "Recording (Beta)" +sidebarTitle: "Recording" description: "Implement call recording for voice and video calls using the CometChat JavaScript SDK, including start/stop controls, listeners, and accessing recordings from the Dashboard." --- @@ -23,15 +24,13 @@ const callListener = new CometChatCalls.OngoingCallListener({ **Recordings are available on the [CometChat Dashboard](https://app.cometchat.com) → Calls section.** -This section will guide you to implement call recording feature for the voice and video calls. +Record voice and video calls for playback, compliance, or archival purposes. ## Implementation -Once you have decided to implement [Default Calling](/sdk/javascript/default-call) or [Direct Calling](/sdk/javascript/direct-call) calling and followed the steps to implement them. Just few additional listeners and methods will help you quickly implement call recording in your app. +After setting up [Ringing](/sdk/javascript/default-call) or [Call Session](/sdk/javascript/direct-call), add recording listeners and methods to your call settings. -You need to make changes in the CometChat.startCall method and add the required listeners for recording. Please make sure your callSettings is configured accordingly for [Default Calling](/sdk/javascript/default-call) or [Direct Calling](/sdk/javascript/direct-call). - -A basic example of how to make changes to implement recording for a direct call/ a default call: +Basic example: Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. @@ -90,18 +89,16 @@ CometChatCalls.startSession(callToken, callSettings, htmlElement); -## Settings for call recording - -The `CallSettings`class allows you to customise the overall calling experience. The properties for the call/conference can be set using the `CallSettingsBuilder` class. This will eventually give you and object of the `CallSettings` class which you can pass to the `startSession()` method to start the call. +## Settings -The options available for recording of calls are: +Configure recording options using `CallSettingsBuilder`: | Setting | Description | | --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `showRecordingButton(showRecordingButton: boolean)` | If set to `true` it displays the Recording button in the button Layout. if set to `false` it hides the Recording button in the button Layout. **Default value = false** | | `startRecordingOnCallStart(startRecordingOnCallStart: boolean)` | If set to `true` call recording will start as soon as the call is started. if set to `false` call recording will not start as soon as the call is started. **Default value = false** | -For the use case where you wish to align your own custom buttons and not use the default layout provided by CometChat, you can embed the buttons in your layout and use the below methods to perform the corresponding operations: +For custom UI without the default layout, use these methods to control recording: ### Start Recording @@ -145,9 +142,9 @@ CometChatCalls.stopRecording(); -## Downloading Recording +## Downloading Recordings -Currently, the call recordings are available on the [CometChat Dashboard](https://app.cometchat.com/signup) under the Calls Section. Recordings can be accessed after clicking on the three dots menu icon to expand the menu and then select "View Recordings". You can refer to the below screenshot. You can refer to the below screenshot. +Call recordings are available on the [CometChat Dashboard](https://app.cometchat.com) under the Calls section. Click the three-dot menu and select "View Recordings". diff --git a/sdk/javascript/session-timeout.mdx b/sdk/javascript/session-timeout.mdx index cec093cef..357ba57e2 100644 --- a/sdk/javascript/session-timeout.mdx +++ b/sdk/javascript/session-timeout.mdx @@ -1,5 +1,6 @@ --- -title: "Session Timeout Flow" +title: "Session Timeout" +sidebarTitle: "Session Timeout" description: "Handle idle session timeouts in CometChat calls, including automatic termination, user prompts, and the onSessionTimeout event." --- @@ -13,34 +14,22 @@ description: "Handle idle session timeouts in CometChat calls, including automat - Customize timeout with `setIdleTimeoutPeriod(seconds)` in CallSettings (v4.1.0+) -Available since v4.1.0 +*Available since v4.1.0* ## Overview -CometChat Calls SDK provides a mechanism to handle session timeouts for idle participants. By default, if a participant is alone in a call session for 180 seconds (3 minutes), the following sequence is triggered: +The Calls SDK automatically handles idle session timeouts to prevent abandoned calls from consuming resources. -1. After 120 seconds of being alone in the session, the participant will see a dialog box +**Default behavior** (participant alone in session for 180 seconds): -2. This dialog provides options to either: +1. At 120 seconds: Warning dialog appears with "Stay" or "Leave" options +2. At 180 seconds: Call auto-terminates if no action taken - * Stay in the call - * Leave immediately - -3. If no action is taken within the next 60 seconds, the call will automatically end - -This feature helps manage inactive call sessions and prevents unnecessary resource usage. The idle timeout period ensures that participants don't accidentally remain in abandoned call sessions. +Customize the timeout period using `setIdleTimeoutPeriod(seconds)` in `CallSettingsBuilder`. ### Session Timeout Flow - - - - - - -The `onSessionTimeout` event is triggered when the call automatically terminates due to session timeout, as illustrated in the diagram above. - - +The `onSessionTimeout` event fires when the call auto-terminates due to inactivity. --- diff --git a/sdk/javascript/standalone-calling.mdx b/sdk/javascript/standalone-calling.mdx index 499a06a2e..54db56dca 100644 --- a/sdk/javascript/standalone-calling.mdx +++ b/sdk/javascript/standalone-calling.mdx @@ -1,5 +1,6 @@ --- title: "Standalone Calling" +sidebarTitle: "Standalone Calling" description: "Implement video and audio calling using only the CometChat Calls SDK without the Chat SDK. Covers authentication, token generation, session management, and call controls." --- diff --git a/sdk/javascript/video-view-customisation.mdx b/sdk/javascript/video-view-customisation.mdx index a8bf033ae..84e242291 100644 --- a/sdk/javascript/video-view-customisation.mdx +++ b/sdk/javascript/video-view-customisation.mdx @@ -1,5 +1,6 @@ --- title: "Video View Customisation" +sidebarTitle: "Video View Customisation" description: "Customize the main video container in CometChat calls — aspect ratio, full screen button, name label, and network label positioning." --- @@ -12,17 +13,15 @@ description: "Customize the main video container in CometChat calls — aspect r - **Requires:** [Default Calling](/sdk/javascript/default-call) or [Direct Calling](/sdk/javascript/direct-call) setup -This section will guide you to customise the main video container. +Customize the main video container layout, including aspect ratio, button positions, and label visibility. ## Implementation -Once you have decided to implement [Default Calling](/sdk/javascript/default-call) or [Direct Calling](/sdk/javascript/direct-call) calling and followed the steps to implement them. Just few additional methods will help you quickly customize the main video container. - -Please make sure your callSettings is configured accordingly for [Default Calling](/sdk/javascript/default-call) or [Direct Calling](/sdk/javascript/direct-call). +After setting up [Ringing](/sdk/javascript/default-call) or [Call Session](/sdk/javascript/direct-call), configure video view options in your call settings. ## Main Video Container Setting -The `MainVideoContainerSetting` Class is the required in case you want to customise the main video view. You need to pass the Object of the `MainVideoContainerSetting` Class in the `setMainVideoContainerSetting()` method of the `CallSettingsBuilder`. +The `MainVideoContainerSetting` class customizes the main video view. Pass a `MainVideoContainerSetting` instance to `setMainVideoContainerSetting()` in `CallSettingsBuilder`. | Setting | Description | | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | diff --git a/sdk/javascript/virtual-background.mdx b/sdk/javascript/virtual-background.mdx index 0af81739a..f3f7a2a74 100644 --- a/sdk/javascript/virtual-background.mdx +++ b/sdk/javascript/virtual-background.mdx @@ -1,5 +1,6 @@ --- title: "Virtual Background" +sidebarTitle: "Virtual Background" description: "Implement virtual background features in CometChat video calls — background blur, custom images, and enforced backgrounds using the JavaScript SDK." --- @@ -12,30 +13,22 @@ description: "Implement virtual background features in CometChat video calls — - **Requires:** [Default Calling](/sdk/javascript/default-call) or [Direct Calling](/sdk/javascript/direct-call) setup -This section will guide you to implement virtual background feature in video calls. +Apply blur or custom image backgrounds during video calls. ## Implementation -Once you have decided to implement [Default Calling](/sdk/javascript/default-call) or [Direct Calling](/sdk/javascript/direct-call) calling and followed the steps to implement them. Just few additional methods will help you quickly implement virtual background. - -Please make sure your callSettings is configured accordingly for [Default Calling](/sdk/javascript/default-call) or [Direct Calling](/sdk/javascript/direct-call). +After setting up [Ringing](/sdk/javascript/default-call) or [Call Session](/sdk/javascript/direct-call), configure virtual background options in your call settings. ## Settings -The `CallSettings`class allows you to customise the overall calling experience. The properties for the call/conference can be set using the `CallSettingsBuilder` class. This will eventually give you and object of the `CallSettings` class which you can pass to the `startCall()` method to start the call. - -The **mandatory** parameters that are required to be present for any call/conference to work are: - -1. sessionId - The unique session Id for the call/conference session. - -The options available for virtual background are: +Configure virtual background using `CallSettingsBuilder`: | Setting | Description | | ---------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | | `showVirtualBackgroundSetting(showVBSettings: boolean)` | This method shows/hides the virtual background settings in the menu bar. **Default value = true** | | `setVirtualBackground(virtualBackground: CometChat.VirtualBackground)` | This method will set the virtual background setting. This methods takes an Object of Virtual Background Class. | -For the use case where you wish to align your own custom buttons and not use the default layout provided by CometChat, you can embed the buttons in your layout and use the below methods to perform the corresponding operations: +For custom UI without the default layout, use these methods to control virtual background: ### Open Virtual Background Setting @@ -100,7 +93,7 @@ callController.setBackgroundImage(imageURL); ## Virtual Background Settings -The `VirtualBackground` Class is the required in case you want to change how the end user can use virtual background features in a video call. You need to pass the Object of the `VirtualBackground` Class in the `setVirtualBackground()` method of the `CallSettingsBuilder`. +The `VirtualBackground` class controls how users interact with virtual background features. Pass a `VirtualBackground` instance to `setVirtualBackground()` in `CallSettingsBuilder`. | Setting | Description | | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | From 7c7c882069ac1a5c56d77e74694a8e4a8f8e9bca Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 18 Mar 2026 16:16:08 +0530 Subject: [PATCH 33/43] updates docs for Users and User Presence --- sdk/javascript/block-users.mdx | 35 +++++++---------- sdk/javascript/retrieve-users.mdx | 61 ++++++++++++++---------------- sdk/javascript/user-management.mdx | 40 ++++++++------------ sdk/javascript/user-presence.mdx | 50 ++++++++++-------------- sdk/javascript/users-overview.mdx | 4 +- 5 files changed, 79 insertions(+), 111 deletions(-) diff --git a/sdk/javascript/block-users.mdx b/sdk/javascript/block-users.mdx index dad8bface..5fd991ef8 100644 --- a/sdk/javascript/block-users.mdx +++ b/sdk/javascript/block-users.mdx @@ -1,5 +1,6 @@ --- title: "Block Users" +sidebarTitle: "Block Users" description: "Block and unblock users, and retrieve the list of blocked users using the CometChat JavaScript SDK." --- @@ -23,9 +24,7 @@ let blockedUsers = await request.fetchNext(); ## Block Users -*In other words, as a logged-in user, how do I block a user from sending me messages?* - -You can block users using the `blockUsers()` method. Once any user is blocked, all the communication to and from the respective user will be completely blocked. You can block multiple users in a single operation. The `blockUsers()` method takes a `Array` as a parameter which holds the list of `UID's` to be blocked. +Block users to prevent all communication with them. Use `blockUsers()` with an array of UIDs. @@ -74,7 +73,7 @@ try { -It returns a Array which contains `UID's` as the keys and "success" or "fail" as the value based on if the block operation for the `UID` was successful or not. +Returns an object with UIDs as keys and `"success"` or `"fail"` as values. The method returns an array of [`User`](/sdk/reference/entities#user) objects with the `blockedByMe` field set to `true`. Access the response data using getter methods: @@ -87,9 +86,7 @@ The method returns an array of [`User`](/sdk/reference/entities#user) objects wi ## Unblock Users -*In other words, as a logged-in user, how do I unblock a user I previously blocked?* - -You can unblock the already blocked users using the `unblockUsers()` method. You can unblock multiple users in a single operation. The `unblockUsers()` method takes a `Array` as a parameter which holds the list of `UID's` to be unblocked. +Unblock previously blocked users using `unblockUsers()` with an array of UIDs. @@ -138,7 +135,7 @@ try { -It returns a Array which contains `UID's` as the keys and `success` or `fail` as the value based on if the unblock operation for the `UID` was successful or not. +Returns an object with UIDs as keys and `"success"` or `"fail"` as values. The method returns an array of [`User`](/sdk/reference/entities#user) objects with the `blockedByMe` field set to `false`. Access the response data using getter methods: @@ -151,15 +148,11 @@ The method returns an array of [`User`](/sdk/reference/entities#user) objects wi ## Get List of Blocked Users -*In other words, as a logged-in user, how do I get a list of all users I've blocked?* - -In order to fetch the list of blocked users, you can use the `BlockedUsersRequest` class. To use this class i.e to create an object of the `BlockedUsersRequest class`, you need to use the `BlockedUsersRequestBuilder` class. The `BlockedUsersRequestBuilder` class allows you to set the parameters based on which the blocked users are to be fetched. - -The `BlockedUsersRequestBuilder` class allows you to set the below parameters: +Use `BlockedUsersRequestBuilder` to fetch blocked users with filtering and pagination. ### Set Limit -This method sets the limit i.e. the number of blocked users that should be fetched in a single iteration. +Sets the number of blocked users to fetch per request. @@ -186,7 +179,7 @@ let blockedUsersRequest: CometChat.BlockedUsersRequest = new CometChat.BlockedUs ### Set Search Keyword -This method allows you to set the search string based on which the blocked users are to be fetched. +Filters blocked users by a search string. @@ -217,9 +210,11 @@ let blockedUsersRequest: CometChat.BlockedUsersRequest = new CometChat.BlockedUs ### Set Direction -* CometChat.BlockedUsersRequest.directions.BLOCKED\_BY\_ME - This will ensure that the list of blocked users only contains the users blocked by the logged in user. -* CometChat.BlockedUsersRequest.directions.HAS\_BLOCKED\_ME - This will ensure that the list of blocked users only contains the users that have blocked the logged in user. -* CometChat.BlockedUsersRequest.directions.BOTH - This will make sure the list of users includes both the above cases. This is the default value for the direction variable if it is not set. +Filters by block direction: + +- `BLOCKED_BY_ME` — Users blocked by the logged-in user +- `HAS_BLOCKED_ME` — Users who have blocked the logged-in user +- `BOTH` — Both directions (default) @@ -246,9 +241,7 @@ let blockedUsersRequest: CometChat.BlockedUsersRequest = new CometChat.BlockedUs -Finally, once all the parameters are set to the builder class, you need to call the build() method to get the object of the `BlockedUsersRequest` class. - -Once you have the object of the `BlockedUsersRequest` class, you need to call the `fetchNext()` method. Calling this method will return a list of `User` objects containing n number of blocked users where N is the limit set in the builder class. +After configuring the builder, call `build()` to get the `BlockedUsersRequest` object, then call `fetchNext()` to retrieve blocked users. diff --git a/sdk/javascript/retrieve-users.mdx b/sdk/javascript/retrieve-users.mdx index c20501ebb..e7f27204a 100644 --- a/sdk/javascript/retrieve-users.mdx +++ b/sdk/javascript/retrieve-users.mdx @@ -1,5 +1,6 @@ --- title: "Retrieve Users" +sidebarTitle: "Retrieve Users" description: "Fetch, filter, search, and sort users using the CometChat JavaScript SDK. Includes pagination, role-based filtering, tag support, and online user counts." --- @@ -25,7 +26,7 @@ const count = await CometChat.getOnlineUserCount(); ## Retrieve Logged In User Details -You can get the details of the logged-in user using the `getLoggedInUser()` method. This method can also be used to check if the user is logged in or not. If the method returns `Promise` with reject callback, it indicates that the user is not logged in and you need to log the user into CometChat SDK. +Use `getLoggedInUser()` to get the current user's details. This method also verifies if a user is logged in — a rejected promise indicates no user is logged in. @@ -56,7 +57,7 @@ CometChat.getLoggedinUser().then( -This method will return a `User` object containing all the information related to the logged-in user. +This method returns a [`User`](/sdk/reference/entities#user) object with the logged-in user's information. The method returns a [`User`](/sdk/reference/entities#user) object. Access the response data using getter methods: @@ -71,13 +72,11 @@ The method returns a [`User`](/sdk/reference/entities#user) object. Access the r ## Retrieve List of Users -In order to fetch the list of users, you can use the `UsersRequest` class. To use this class i.e to create an object of the `UsersRequest` class, you need to use the `UsersRequestBuilder` class. The `UsersRequestBuilder` class allows you to set the parameters based on which the users are to be fetched. - -The `UsersRequestBuilder` class allows you to set the below parameters: +Use `UsersRequestBuilder` to fetch users with filtering, searching, and pagination. ### Set Limit -This method sets the limit i.e. the number of users that should be fetched in a single iteration. +Sets the number of users to fetch per request. @@ -104,7 +103,7 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() ### Set Search Keyword -This method allows you to set the search string based on which the users are to be fetched. +Filters users by a search string. @@ -135,7 +134,7 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() ### Search In -This method allows you to define in which user property should the searchKeyword be searched. This method only works in combination with `setSearchKeyword()`. By default the keyword is searched in both UID & Name. +Specifies which user properties to search. Works with `setSearchKeyword()`. By default, searches both UID and name. @@ -170,12 +169,12 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() ### Set Status -The status based on which the users are to be fetched. The status parameter can contain one of the below two values: +Filters users by online status: -* CometChat.USER\_STATUS.ONLINE - will return the list of only online users. -* CometChat.USER\_STATUS.OFFLINE - will return the list of only offline users. +- `CometChat.USER_STATUS.ONLINE` — Only online users +- `CometChat.USER_STATUS.OFFLINE` — Only offline users -If this parameter is not set, will return all the available users. +If not set, returns all users. @@ -204,7 +203,7 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() ### Hide Blocked Users -This method is used to determine if the blocked users should be returned as a part of the user list. If set to true, the user list will not contain the users blocked by the logged in user. +When `true`, excludes users blocked by the logged-in user from the results. @@ -233,7 +232,7 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() ### Set Roles -This method allows you to fetch the users based on multiple roles. +Filters users by specified roles. @@ -264,7 +263,7 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() ### Friends Only -This property when set to true will return only the friends of the logged-in user. +When `true`, returns only friends of the logged-in user. @@ -293,7 +292,7 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() ### Set Tags -This method accepts a list of tags based on which the list of users is to be fetched. The list fetched will only contain the users that have been tagged with the specified tags. +Filters users by specified tags. @@ -324,7 +323,7 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() ### With Tags -This property when set to true will fetch tags data along with the list of users. +When `true`, includes tag data in the returned user objects. @@ -353,7 +352,7 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() ### Set UIDs -This method accepts a list of UIDs based on which the list of users is fetched. A maximum of `25` users can be fetched. +Fetches specific users by their UIDs. Maximum 25 users per request. @@ -384,7 +383,7 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() ### Sort By -This method allows you to sort the User List by a specific property of User. By default the User List is sorted by `status => name => UID` . If `name` is pass to the `sortBy()` method the user list will be sorted by `name => UID`. +Sorts the user list by a specific property. Default sort order: `status → name → UID`. Pass `"name"` to sort by `name → UID`. @@ -416,7 +415,7 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() ### Sort By Order -This method allows you to sort the User List in a specific order. By default the user list is sorted in ascending order. +Sets the sort order. Default is ascending (`"asc"`). Use `"desc"` for descending. @@ -445,9 +444,7 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() -Finally, once all the parameters are set to the builder class, you need to call the build() method to get the object of the UsersRequest class. - -Once you have the object of the UsersRequest class, you need to call the fetchNext() method. Calling this method will return a list of User objects containing n number of users where n is the limit set in the builder class. +After configuring the builder, call `build()` to get the `UsersRequest` object, then call `fetchNext()` to retrieve users. @@ -501,7 +498,7 @@ The `fetchNext()` method returns an array of [`User`](/sdk/reference/entities#us ## Retrieve Particular User Details -To get the information of a user, you can use the `getUser()` method. +Use `getUser()` to fetch a specific user's details by UID. @@ -534,13 +531,11 @@ CometChat.getUser(UID).then( -The `getUser()` method takes the following parameters: - -| Parameter | Description | -| --------- | ---------------------------------------------------------- | -| UID | The UID of the user for whom the details are to be fetched | +| Parameter | Description | +| --------- | ----------- | +| UID | The UID of the user to fetch | -It returns the `User` object containing the details of the user. +Returns a [`User`](/sdk/reference/entities#user) object with the user's details. The method returns a [`User`](/sdk/reference/entities#user) object. Access the response data using getter methods: @@ -553,9 +548,9 @@ The method returns a [`User`](/sdk/reference/entities#user) object. Access the r | lastActiveAt | `getLastActiveAt()` | `number` | Timestamp when the user was last active | | role | `getRole()` | `string` | Role assigned to the user | -## Get online user count +## Get Online User Count -To get the total count of online users for your app, you can use the `getOnlineUserCount()` method. +Use `getOnlineUserCount()` to get the total number of online users in your app. @@ -586,7 +581,7 @@ CometChat.getOnlineUserCount().then( -This method returns the total online user count for your app. +Returns the total online user count as a number. --- diff --git a/sdk/javascript/user-management.mdx b/sdk/javascript/user-management.mdx index 21bbcf75b..a5625c047 100644 --- a/sdk/javascript/user-management.mdx +++ b/sdk/javascript/user-management.mdx @@ -1,5 +1,6 @@ --- title: "User Management" +sidebarTitle: "User Management" description: "Create, update, and manage CometChat users programmatically using the JavaScript SDK. Includes user creation, profile updates, and the User class reference." --- @@ -23,29 +24,20 @@ await CometChat.updateCurrentUserDetails(user); **Note:** User creation/deletion should ideally happen on your backend via the [REST API](https://api-explorer.cometchat.com). -When a user logs into your app, you need to programmatically login the user into CometChat. But before you log in the user to CometChat, you need to create the user. +Users must exist in CometChat before they can log in. Typically: -Summing up- +1. User registers in your app → Create user in CometChat +2. User logs into your app → [Log user into CometChat](/sdk/javascript/authentication-overview) -**When a user registers in your app** +## Creating a User -1. You add the user details in your database -2. You create a user in CometChat - -**When a user logs into your app** - -1. You log in the user to your app -2. You [log in the user in CometChat](/sdk/javascript/authentication-overview) (programmatically) - -## Creating a user - -Ideally, user creation should take place at your backend. You can refer our Rest API to learn more about [creating a user](https://api-explorer.cometchat.com/reference/creates-user) and use the appropriate code sample based on your backend language. +User creation should ideally happen on your backend via the [REST API](https://api-explorer.cometchat.com/reference/creates-user). **Security:** Never expose your `Auth Key` in client-side production code. User creation and updates using `Auth Key` should ideally happen on your backend server. Use client-side creation only for prototyping or development. -However, if you wish to create users on the fly, you can use the `createUser()` method. This method takes a `User` object and the `Auth Key` as input parameters and returns the created `User` object if the request is successful. +For client-side creation (development only), use `createUser()`: @@ -104,9 +96,11 @@ UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and othe -## Updating a user +## Updating a User + +Like creation, user updates should ideally happen on your backend via the [REST API](https://api-explorer.cometchat.com/reference/update-user). -Updating a user similar to creating a user should ideally be achieved at your backend using the Restful APIs. For more information, you can check the [update a user](https://api-explorer.cometchat.com/reference/update-user) section. However, this can be achieved on the fly as well as using the `updateUser()` method. This method takes a `User` object and the `Auth Key` as inputs and returns the updated `User` object on the successful execution of the request. +For client-side updates (development only), use `updateUser()`: @@ -149,7 +143,7 @@ CometChat.updateUser(user, authKey).then( -Please make sure the `User` object provided to the `updateUser()` method has the `UID` of the user to be updated set. +Ensure the `User` object has the correct `UID` set. The method returns a [`User`](/sdk/reference/entities#user) object. Access the response data using getter methods: @@ -161,9 +155,9 @@ The method returns a [`User`](/sdk/reference/entities#user) object. Access the r | role | `getRole()` | `string` | Role assigned to the user | | metadata | `getMetadata()` | `Object` | Custom metadata attached to the user | -## Updating logged-in user +## Updating Logged-in User -Updating a logged-in user is similar to updating a user. The only difference being this method does not require an AuthKey. This method takes a `User` object as input and returns the updated `User` object on the successful execution of the request. +Use `updateCurrentUserDetails()` to update the current user without an Auth Key. Note: You cannot update the user's role with this method. @@ -204,11 +198,9 @@ CometChat.updateCurrentUserDetails(user).then( -By using the `updateCurrentUserDetails()` method one can only update the logged-in user irrespective of the UID passed. Also, it is not possible to update the role of a logged-in user. - -## Deleting a user +## Deleting a User -Deleting a user can only be achieved via the Restful APIs. For more information please check the [delete a user](https://api-explorer.cometchat.com/reference/delete-user) section. +User deletion is only available via the [REST API](https://api-explorer.cometchat.com/reference/delete-user). ## User Class diff --git a/sdk/javascript/user-presence.mdx b/sdk/javascript/user-presence.mdx index f2f82082e..0b62bf35c 100644 --- a/sdk/javascript/user-presence.mdx +++ b/sdk/javascript/user-presence.mdx @@ -1,6 +1,6 @@ --- title: "User Presence" -sidebarTitle: "Overview" +sidebarTitle: "User Presence" description: "Track real-time user online/offline status and configure presence subscriptions using the CometChat JavaScript SDK." --- @@ -24,29 +24,25 @@ CometChat.removeUserListener("LISTENER_ID"); ``` -User Presence helps us understand if a user is available to chat or not. +Track whether users are online or offline in real-time. ## Real-time Presence -*In other words, as a logged-in user, how do I know if a user is online or offline?* +Configure presence subscription in `AppSettings` during SDK initialization. The `AppSettingsBuilder` provides three subscription options: -Based on the settings provided in the AppSettings class while initialising the SDK using the `init()` method, the logged-in user will receive the presence for the other users in the app. +| Method | Description | +| ------ | ----------- | +| `subscribePresenceForAllUsers()` | Receive presence updates for all users | +| `subscribePresenceForRoles(roles)` | Receive presence updates only for users with specified roles | +| `subscribePresenceForFriends()` | Receive presence updates only for friends | -In the `AppSettings` class, you can set the type of Presence you wish to receive for that particular session of the app. - -For presence subscription, the AppSettingsBuilder provides 3 methods : - -* `subscribePresenceForAllUsers()` - this will inform the logged-in user when any user in the app comes online or goes offline -* `subscribePresenceForRoles(Array roles)` - This will inform the logged-in user, only when the users with the specified roles come online or go offline. -* `subscribePresenceForFriends()` - This will inform the logged-in user, only when either of his friends come online or go offline. - -If none of the above methods are used, no presence will be sent to the logged-in user. +If none of these methods are called, no presence events will be delivered. You must configure presence subscription in `AppSettings` during `CometChat.init()` before any presence events will be delivered. See [Setup SDK](/sdk/javascript/setup-sdk) for details. -You need to register the `UserListener` using the `addUserListener()` method where ever you wish to receive these events in. +Register a `UserListener` to receive presence events: @@ -85,11 +81,11 @@ CometChat.addUserListener( -| Parameter | Description | -| ------------ | --------------------------------------------- | -| `listenerID` | An ID that uniquely identifies that listener. | +| Parameter | Description | +| --------- | ----------- | +| `listenerID` | Unique identifier for the listener | -You will receive an object of the `User` class in the listener methods. +Each callback receives a [`User`](/sdk/reference/entities#user) object with presence information. The listener callbacks provide a [`User`](/sdk/reference/entities#user) object with presence fields populated. Access the response data using getter methods: @@ -100,9 +96,7 @@ The listener callbacks provide a [`User`](/sdk/reference/entities#user) object w | status | `getStatus()` | `string` | Online status of the user (`"online"` or `"offline"`) | | lastActiveAt | `getLastActiveAt()` | `number` | Timestamp when the user was last active | - -**Listener Cleanup:** Always remove the listener when the component or view is unmounted/destroyed to prevent memory leaks and duplicate callbacks. Use `CometChat.removeUserListener(listenerID)` in your cleanup logic. - +Remove the listener when no longer needed: @@ -129,16 +123,12 @@ CometChat.removeUserListener("LISTENER_ID"); ## User List Presence -*In other words, as a logged-in user, when I retrieve the user list, how do I know if a user is online/offline?* - -When you fetch the list of users, in the [User](/sdk/javascript/user-management#user-class) object, you will receive 2 fields - -1. `status` - This will hold either of the two values : - -* online - This indicates that the user is currently online and available to chat. -* offline - This indicates that the user is currently offline and is not available to chat. +When fetching users via `UsersRequest`, each [`User`](/sdk/reference/entities#user) object includes presence fields: -2. `lastActiveAt` - in case the user is offline, this field holds the timestamp of the time when the user was last online. This can be used to display the Last seen of the user if need be. +| Field | Description | +| ----- | ----------- | +| `status` | `"online"` or `"offline"` | +| `lastActiveAt` | Timestamp of last activity (useful for "Last seen" display) | ## Next Steps diff --git a/sdk/javascript/users-overview.mdx b/sdk/javascript/users-overview.mdx index 625648e58..83062c071 100644 --- a/sdk/javascript/users-overview.mdx +++ b/sdk/javascript/users-overview.mdx @@ -13,9 +13,7 @@ description: "Overview of CometChat user functionality including user management - [Block Users](/sdk/javascript/block-users) — Block and unblock users -The primary aim for our Users functionality is to allow you to quickly retrieve and add users to CometChat. - -You can begin with [user management](/sdk/javascript/user-management) to sync your users to CometChat. Once that is done, you can [retrieve users](/sdk/javascript/retrieve-users) and display them in your app. +Sync your users to CometChat with [user management](/sdk/javascript/user-management), then [retrieve users](/sdk/javascript/retrieve-users) to display them in your app. ## Next Steps From b4aecb143faa86a905184bb69fd6815dac454c6f Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 18 Mar 2026 16:21:10 +0530 Subject: [PATCH 34/43] groups - frame this better --- sdk/javascript/create-group.mdx | 59 +++++------- sdk/javascript/delete-group.mdx | 3 +- sdk/javascript/group-add-members.mdx | 37 ++++---- sdk/javascript/group-change-member-scope.mdx | 37 ++++---- sdk/javascript/group-kick-ban-members.mdx | 97 ++++++++++---------- sdk/javascript/join-group.mdx | 40 +++----- sdk/javascript/leave-group.mdx | 22 ++--- sdk/javascript/retrieve-group-members.mdx | 27 +++--- sdk/javascript/retrieve-groups.mdx | 43 ++++----- sdk/javascript/transfer-group-ownership.mdx | 7 +- sdk/javascript/update-group.mdx | 15 ++- 11 files changed, 166 insertions(+), 221 deletions(-) diff --git a/sdk/javascript/create-group.mdx b/sdk/javascript/create-group.mdx index 8e866e7e2..e288bb58b 100644 --- a/sdk/javascript/create-group.mdx +++ b/sdk/javascript/create-group.mdx @@ -1,5 +1,6 @@ --- title: "Create A Group" +sidebarTitle: "Create Group" description: "Create public, private, or password-protected groups and optionally add members during creation using the CometChat JavaScript SDK." --- @@ -22,22 +23,16 @@ let result = await CometChat.createGroupWithMembers(group, members, []); ## Create a Group -*In other words, as a logged-in user, how do I create a public, private or password-protected group?* +Use `createGroup()` to create a new group. Pass a `Group` object with the group details. -You can create a group using `createGroup()` method. This method takes a `Group` object as input. +Group constructors: +- `new Group(GUID, name, groupType, password)` +- `new Group(GUID, name, groupType, password, icon, description)` -To create an object of `Group` class, you can use either of the below two constructors: - -1. `new Group(String GUID, String name, String groupType, String password)` -2. `new Group(String GUID, String name, String groupType, String password, String icon, String description)` - -The `groupType` needs to be either of the below 3 values: - -1.`CometChat.GROUP_TYPE.PUBLIC` - -2.`CometChat.GROUP_TYPE.PASSWORD` - -3.`CometChat.GROUP_TYPE.PRIVATE` +Group types: +- `CometChat.GROUP_TYPE.PUBLIC` +- `CometChat.GROUP_TYPE.PASSWORD` +- `CometChat.GROUP_TYPE.PRIVATE` @@ -101,13 +96,11 @@ try { -The createGroup() method takes the following parameters: +| Parameter | Description | +| --------- | ----------- | +| `group` | An instance of `Group` class | -| Parameter | Description | -| --------- | ---------------------------- | -| `group` | An instance of `Group` class | - -After successful creation of the group, you will receive an instance of `Group` class which contains all the information about the particular group. +On success, returns a [`Group`](/sdk/reference/entities#group) object with the created group's details. The method returns a [`Group`](/sdk/reference/entities#group) object. Access the response data using getter methods: @@ -126,24 +119,16 @@ GUID can be alphanumeric with underscore and hyphen. Spaces, punctuation and oth -## Add members while creating a group - -You can create a group and add members at the same time using the `createGroupWithMembers()` method. This method takes the `Group` Object, Array of `Group Member` Object to be added & Array of `UIDs` to be banned. - -To create an object of `Group` class, you can use either of the below two constructors: - -1. `new Group(String GUID, String name, String groupType, String password)` -2. `new Group(String GUID, String name, String groupType, String password, String icon, String description)` - -The `groupType` needs to be either of the below 3 values: +## Add Members While Creating a Group -1. `CometChat.GROUP_TYPE.PUBLIC` -2. `CometChat.GROUP_TYPE.PASSWORD` -3. `CometChat.GROUP_TYPE.PRIVATE` +Use `createGroupWithMembers()` to create a group and add members in one operation. -To create an object of `Group Member` class, you can use the below constructor: +Parameters: +- `group` — The `Group` object +- `members` — Array of `GroupMember` objects to add +- `bannedMembers` — Array of UIDs to ban (can be empty) -* new CometChat.GroupMember(String UID, String scope) +Create a `GroupMember` with: `new CometChat.GroupMember(UID, scope)` @@ -219,7 +204,9 @@ try { -This method returns an Object which has two keys: `group` & `members` . The group key has the Group Object which contains all the information of the group which is created. The members key has the `UID` of the users and the value will either be `success` or an `error` message describing why the operation to add/ban the user failed. +Returns an object with two keys: +- `group` — The created [`Group`](/sdk/reference/entities#group) object +- `members` — Object with UIDs as keys and `"success"` or error message as values ## Group Class diff --git a/sdk/javascript/delete-group.mdx b/sdk/javascript/delete-group.mdx index 0cfc50412..643324371 100644 --- a/sdk/javascript/delete-group.mdx +++ b/sdk/javascript/delete-group.mdx @@ -1,5 +1,6 @@ --- title: "Delete A Group" +sidebarTitle: "Delete Group" description: "Delete a group permanently using the CometChat JavaScript SDK. Only group admins can perform this operation." --- @@ -20,7 +21,7 @@ This operation is irreversible. Deleted groups and their messages cannot be reco ## Delete a Group -To delete a group you need to use the `deleteGroup()` method. The user must be an `Admin` of the group they are trying to delete. +Use `deleteGroup()` to permanently delete a group. Only group admins can perform this operation. diff --git a/sdk/javascript/group-add-members.mdx b/sdk/javascript/group-add-members.mdx index 98b218791..d12c385ba 100644 --- a/sdk/javascript/group-add-members.mdx +++ b/sdk/javascript/group-add-members.mdx @@ -1,5 +1,6 @@ --- title: "Add Members To A Group" +sidebarTitle: "Add Members" description: "Learn how to add members to a group, receive real-time member added events, and handle missed events using the CometChat JavaScript SDK." --- @@ -24,11 +25,13 @@ You can add members to a group programmatically and listen for real-time events ## Add Members to Group -You can add members to the group using the `addMembersToGroup()` method. This method takes the below parameters: +Use `addMembersToGroup()` to add members to a [Group](/sdk/reference/entities#group). -1. `GUID` - GUID of the group the members are to be added to. -2. `members` - This is a list of `GroupMember` objects. In order to add members, you need to create an object of the `GroupMember` class. The UID and the scope of the `GroupMember` are mandatory. -3. `bannedMembers` - This is the list of `UID's` that need to be banned from the Group. This can be set to `null` if there are no members to be banned. +| Parameter | Description | +|-----------|-------------| +| `GUID` | The group to add members to | +| `members` | Array of [GroupMember](/sdk/reference/entities#groupmember) objects (UID and scope required) | +| `bannedMembers` | Array of UIDs to ban (can be empty) | @@ -75,21 +78,15 @@ CometChat.addMembersToGroup(GUID, membersList, []).then( It will return a Array which will contain the `UID` of the users and the value will either be `success` or an error message describing why the operation to add the user to the group. -The method returns a response object (map) where each key is a `UID` and the value is either `"success"` or an error message describing why the operation failed for that user. +The method returns a response object where each key is a `UID` and the value is either `"success"` or an error message. ## Real-Time Group Member Added Events -*In other words, as a member of a group, how do I know when someone is added to the group when my app is running?* - - When a group member is added by another member, this event is triggered. When a user joins a group on their own, the joined event is triggered. - -To receive real-time events whenever a new member is added to a group, you need to implement the `onMemberAddedToGroup()` methods of the `GroupListener` class. - -`onMemberAddedToGroup()` - This method is triggered when any user is added to the group so that the logged in user is informed of the other members added to the group. +Implement `onMemberAddedToGroup()` in `GroupListener` to receive real-time notifications when members are added. @@ -151,16 +148,14 @@ CometChat.removeGroupListener("UNIQUE_LISTENER_ID"); ## Member Added to Group event in Message History -*In other words, as a member of a group, how do I know when someone is added to the group when my app is not running?* - -When you retrieve the list of previous messages if a member has been added to any group that the logged-in user is a member of, the list of messages will contain an `Action` message. An `Action` message is a sub-class of `BaseMessage` class. - -For the group member added event, in the `Action` object received, the following fields can help you get the relevant information- +When fetching previous messages, member additions appear as [Action](/sdk/reference/messages#action) messages (a subclass of `BaseMessage`). -1. `action` - `added` -2. `actionOn` - User object containing the details of the user who was added to the group -3. `actionBy` - User object containing the details of the user who added the member to the group -4. `actionFor` - Group object containing the details of the group to which the member was added +| Field | Value/Type | Description | +|-------|------------|-------------| +| `action` | `"added"` | The action type | +| `actionOn` | [User](/sdk/reference/entities#user) | The user who was added | +| `actionBy` | [User](/sdk/reference/entities#user) | The user who added the member | +| `actionFor` | [Group](/sdk/reference/entities#group) | The group the member was added to | --- diff --git a/sdk/javascript/group-change-member-scope.mdx b/sdk/javascript/group-change-member-scope.mdx index 369d19f30..da3338c2b 100644 --- a/sdk/javascript/group-change-member-scope.mdx +++ b/sdk/javascript/group-change-member-scope.mdx @@ -1,5 +1,6 @@ --- title: "Change Member Scope" +sidebarTitle: "Change Scope" description: "Learn how to change group member roles (admin, moderator, participant) and receive real-time scope change events using the CometChat JavaScript SDK." --- @@ -21,7 +22,7 @@ You can change the role of a group member between admin, moderator, and particip ## Change Scope of a Group Member -In order to change the scope of a group member, you can use the `changeGroupMemberScope()`. +Use `updateGroupMemberScope()` to change a member's role within a [Group](/sdk/reference/entities#group). @@ -64,19 +65,17 @@ This method takes the below parameters: | Parameter | Description | | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `UID` | The UID of the member whose scope you would like to change | -| `GUID` | The GUID of the group for which the member's scope needs to be changed | -| `scope` | The updated scope of the member. This can be either of the 3 values: 1.`CometChat.SCOPE.ADMIN`2.`CometChat.SCOPE.MODERATOR` 3.`CometChat.SCOPE.PARTICIPANT` | +| `UID` | The UID of the member whose scope you want to change | +| `GUID` | The GUID of the group | +| `scope` | The new scope: `CometChat.SCOPE.ADMIN`, `CometChat.SCOPE.MODERATOR`, or `CometChat.SCOPE.PARTICIPANT` | -The default scope of any member is `participant`. Only the **Admin** of the group can change the scope of any participant in the group. +The default scope is `participant`. Only Admins can change member scopes. -On success, the method resolves with a success message string confirming the operation. +On success, the method resolves with a success message string. ## Real-Time Group Member Scope Changed Events -*In other words, as a member of a group, how do I know when someone's scope is changed when my app is running?* - -In order to receive real-time events for the change member scope event, you will need to override the `onGroupMemberScopeChanged()` method of the `GroupListener` class +Implement `onGroupMemberScopeChanged()` in `GroupListener` to receive real-time notifications when a member's scope changes. @@ -123,18 +122,16 @@ CometChat.removeGroupListener("UNIQUE_LISTENER_ID"); ## Missed Group Member Scope Changed Events -*In other words, as a member of a group, how do I know when someone's scope is changed when my app is not running?* - -When you retrieve the list of previous messages if a member's scope has been changed for any group that the logged-in user is a member of, the list of messages will contain an `Action` message. An `Action` message is a sub-class of `BaseMessage` class. - -For the group member scope changed event, in the `Action` object received, the following fields can help you get the relevant information- +When fetching previous messages, scope changes appear as [Action](/sdk/reference/messages#action) messages (a subclass of `BaseMessage`). -1. `action` - `scopeChanged` -2. `actionOn` - User object containing the details of the user whose scope has been changed -3. `actionBy` - User object containing the details of the user who changed the scope of the member -4. `actionFor` - Group object containing the details of the group in which the member scope was changed -5. `oldScope` - The original scope of the member -6. `newScope` - The updated scope of the member +| Field | Value/Type | Description | +|-------|------------|-------------| +| `action` | `"scopeChanged"` | The action type | +| `actionOn` | [User](/sdk/reference/entities#user) | The user whose scope changed | +| `actionBy` | [User](/sdk/reference/entities#user) | The user who changed the scope | +| `actionFor` | [Group](/sdk/reference/entities#group) | The group | +| `oldScope` | `string` | The previous scope | +| `newScope` | `string` | The new scope | --- diff --git a/sdk/javascript/group-kick-ban-members.mdx b/sdk/javascript/group-kick-ban-members.mdx index 69ec90449..a711f8283 100644 --- a/sdk/javascript/group-kick-ban-members.mdx +++ b/sdk/javascript/group-kick-ban-members.mdx @@ -1,5 +1,6 @@ --- title: "Ban Or Kick Member From A Group" +sidebarTitle: "Kick & Ban Members" description: "Learn how to kick, ban, and unban group members, fetch banned member lists, and receive real-time events using the CometChat JavaScript SDK." --- @@ -29,11 +30,11 @@ There are certain actions that can be performed on the group members: 3. Unban a member from the group 4. Update the scope of the member of the group -All the above actions can only be performed by the **Admin** or the **Moderator** of the group. +Only Admins or Moderators can perform these actions. ## Kick a Group Member -The Admin or Moderator of a group can kick a member out of the group using the `kickGroupMember()` method. +Admins or Moderators can remove a member using `kickGroupMember()`. The kicked user can rejoin the group later. @@ -70,20 +71,18 @@ CometChat.kickGroupMember(GUID, UID).then( -The `kickGroupMember()` takes following parameters +The `kickGroupMember()` method takes the following parameters: | Parameter | Description | | --------- | ----------------------------------------------------- | -| `UID` | The UID of the user to be kicked. | +| `UID` | The UID of the user to be kicked | | `GUID` | The GUID of the group from which user is to be kicked | -The kicked user will be no longer part of the group and can not perform any actions in the group, but the kicked user can rejoin the group. - -On success, the method resolves with a success message string confirming the operation. +On success, the method resolves with a success message string. ## Ban a Group Member -The Admin or Moderator of the group can ban a member from the group using the `banGroupMember()` method. +Admins or Moderators can ban a member using `banGroupMember()`. Unlike kicked users, banned users cannot rejoin until unbanned. @@ -124,16 +123,14 @@ The `banGroupMember()` method takes the following parameters: | Parameter | Description | | --------- | ------------------------------------------------------ | -| `UID` | The UID of the user to be banned. | -| `GUID` | The GUID of the group from which user is to be banned. | - -The banned user will be no longer part of the group and can not perform any actions in the group. A banned user cannot rejoin the same group without being unbanned. +| `UID` | The UID of the user to be banned | +| `GUID` | The GUID of the group from which user is to be banned | -On success, the method resolves with a success message string confirming the operation. +On success, the method resolves with a success message string. ## Unban a Banned Group Member from a Group -Only Admin or Moderators of the group can unban a previously banned member from the group using the `unbanGroupMember()` method. +Admins or Moderators can unban a previously banned member using `unbanGroupMember()`. @@ -174,22 +171,18 @@ The `unbanGroupMember()` method takes the following parameters | Parameter | Description | | --------- | ---------------------------------------------------- | -| `UID` | The UID of the user to be unbanned. | -| `GUID` | The UID of the group from which user is to be banned | +| `UID` | The UID of the user to be unbanned | +| `GUID` | The GUID of the group from which user is to be unbanned | -The unbanned user can now rejoin the group. +Once unbanned, the user can rejoin the group. ## Get List of Banned Members for a Group -In order to fetch the list of banned groups members for a group, you can use the `BannedGroupMembersRequest` class. To use this class i.e to create an object of the BannedGroupMembersRequest class, you need to use the `BannedGroupMembersRequestBuilder` class. The `BannedGroupMembersRequestBuilder` class allows you to set the parameters based on which the banned group members are to be fetched. - -The `BannedGroupMembersRequestBuilder` class allows you to set the below parameters: - -The `GUID` of the group for which the banned members are to be fetched must be specified in the constructor of the `GroupMembersRequestBuilder` class. +Use `BannedMembersRequestBuilder` to fetch banned members of a [Group](/sdk/reference/entities#group). The GUID must be specified in the constructor. ### Set Limit -This method sets the limit i.e. the number of banned members that should be fetched in a single iteration. +Sets the number of banned members to fetch per request. @@ -218,7 +211,7 @@ let bannedGroupMembersRequest: CometChat.BannedMembersRequest = new CometChat.Ba ### Set Search Keyword -This method allows you to set the search string based on which the banned group members are to be fetched. +Filters banned members by a search string. @@ -249,9 +242,7 @@ let bannedGroupMembersRequest: CometChat.BannedMembersRequest = new CometChat.Ba -Finally, once all the parameters are set to the builder class, you need to call the build() method to get the object of the `BannedGroupMembersRequest` class. - -Once you have the object of the `BannedGroupMembersRequest` class, you need to call the `fetchNext()` method. Calling this method will return a list of `GroupMember` objects containing n number of banned members where n is the limit set in the builder class. +Once configured, call `build()` to create the request, then `fetchNext()` to retrieve banned members. @@ -296,13 +287,13 @@ bannedGroupMembersRequest.fetchNext().then( ## Real-Time Group Member Kicked/Banned Events -*In other words, as a member of a group, how do I know when someone is banned/kicked when my app is running?* - -In order to get real-time events for the kick/ban/unban group members you need to override the following methods of the `GroupListener` class. +Implement these `GroupListener` methods to receive real-time notifications: -1. `onGroupMemberKicked()` - triggered when any group member has been kicked. -2. `onGroupMemberBanned()` - triggered when any group member has been banned. -3. `onGroupMemberUnbanned()` - triggered when any group member has been unbanned. +| Method | Triggered When | +|--------|----------------| +| `onGroupMemberKicked()` | A member is kicked | +| `onGroupMemberBanned()` | A member is banned | +| `onGroupMemberUnbanned()` | A member is unbanned | @@ -361,30 +352,34 @@ CometChat.removeGroupListener("UNIQUE_LISTENER_ID"); ## Missed Group Member Kicked/Banned Events -*In other words, as a member of a group, how do I know when someone is banned/kicked when my app is not running?* - -When you retrieve the list of previous messages if a member has been kicked/banned/unbanned from any group that the logged-in user is a member of, the list of messages will contain an `Action` message. An `Action` message is a sub-class of `BaseMessage` class. +When fetching previous messages, kick/ban/unban actions appear as [Action](/sdk/reference/messages#action) messages (a subclass of `BaseMessage`). -For group member kicked event, the details can be obtained using the below fields of the `Action` class- +**Kicked event:** -1. `action` - `kicked` -2. `actionBy` - User object containing the details of the user who has kicked the member -3. `actionOn` - User object containing the details of the member that has been kicked -4. `actionFor` - Group object containing the details of the Group from which the member was kicked +| Field | Value/Type | Description | +|-------|------------|-------------| +| `action` | `"kicked"` | The action type | +| `actionBy` | [User](/sdk/reference/entities#user) | The user who kicked the member | +| `actionOn` | [User](/sdk/reference/entities#user) | The member who was kicked | +| `actionFor` | [Group](/sdk/reference/entities#group) | The group | -For group member banned event, the details can be obtained using the below fields of the `Action` class- +**Banned event:** -1. `action` - `banned` -2. `actionBy` - User object containing the details of the user who has banned the member -3. `actionOn` - User object containing the details of the member that has been banned -4. `actionFor` - Group object containing the details of the Group from which the member was banned +| Field | Value/Type | Description | +|-------|------------|-------------| +| `action` | `"banned"` | The action type | +| `actionBy` | [User](/sdk/reference/entities#user) | The user who banned the member | +| `actionOn` | [User](/sdk/reference/entities#user) | The member who was banned | +| `actionFor` | [Group](/sdk/reference/entities#group) | The group | -For group member unbanned event, the details can be obtained using the below fields of the `Action` class- +**Unbanned event:** -1. `action` - `unbanned` -2. `actionBy` - User object containing the details of the user who has unbanned the member -3. `actionOn` - User object containing the details of the member that has been unbanned -4. `actionFor` - Group object containing the details of the Group from which the member was unbanned +| Field | Value/Type | Description | +|-------|------------|-------------| +| `action` | `"unbanned"` | The action type | +| `actionBy` | [User](/sdk/reference/entities#user) | The user who unbanned the member | +| `actionOn` | [User](/sdk/reference/entities#user) | The member who was unbanned | +| `actionFor` | [Group](/sdk/reference/entities#group) | The group | --- diff --git a/sdk/javascript/join-group.mdx b/sdk/javascript/join-group.mdx index bb11a4a14..20b35ec77 100644 --- a/sdk/javascript/join-group.mdx +++ b/sdk/javascript/join-group.mdx @@ -1,5 +1,6 @@ --- title: "Join A Group" +sidebarTitle: "Join Group" description: "Learn how to join public, password-protected, and private groups, and receive real-time join events using the CometChat JavaScript SDK." --- @@ -20,11 +21,11 @@ CometChat.addGroupListener("listener", new CometChat.GroupListener({ ``` -You can join groups to start participating in group conversations and receive real-time events when other members join. +Join groups to participate in group conversations and receive real-time events when members join. ## Join a Group -In order to start participating in group conversations, you will have to join a group. You can do so using the `joinGroup()` method. +Use `joinGroup()` to join a group. @@ -61,19 +62,13 @@ CometChat.joinGroup(GUID, CometChat.GroupType.Public).then( -The `joinGroup()` method takes the below parameters +| Parameter | Description | +| --------- | ----------- | +| `GUID` | The GUID of the group to join | +| `groupType` | `CometChat.GROUP_TYPE.PUBLIC`, `PASSWORD`, or `PRIVATE` | +| `password` | Required for password-protected groups | -| Parameter | Description | -| ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `GUID` | The GUID of the group you would like to join. | -| `groupType` | Type of the group. CometChat provides 3 types of groups viz. 1. CometChat.GROUP\_TYPE.PUBLIC 2. CometChat.GROUP\_TYPE.PASSWORD 3. CometChats.GROUP\_TYPE.PRIVATE | -| `password` | Password is mandatory in case of a password protected group. | - -Once you have joined a group successfully, you can send and receive messages in that group. - -CometChat keeps a track of the groups joined and you do not need to join the group every time you want to communicate in the group. - -You can identify if a group is joined using the `hasJoined` parameter in the `Group` object. +Once joined, you can send and receive messages in the group. CometChat tracks joined groups — you don't need to rejoin each session. Check `hasJoined` on the `Group` object to verify membership. The method returns a [`Group`](/sdk/reference/entities#group) object with `hasJoined` set to `true`. Access the response data using getter methods: @@ -88,9 +83,7 @@ The method returns a [`Group`](/sdk/reference/entities#group) object with `hasJo ## Real-time Group Member Joined Events -*In other words, as a member of a group, how do I know if someone joins the group when my app is running?* - -If a user joins any group, the members of the group receive a real-time event in the `onGroupMemberJoined()` method of the `GroupListener` class. +Register a `GroupListener` to receive events when members join. @@ -133,15 +126,10 @@ CometChat.removeGroupListener("UNIQUE_LISTNER_ID"); ## Missed Group Member Joined Events -*In other words, as a member of a group, how do I know if someone joins the group when my app is not running?* - -When you retrieve the list of previous messages if a member has joined any group that the logged-in user is a member of, the list of messages will contain an `Action` message. An `Action` message is a sub-class of `BaseMessage` class. - -For the group member joined event, in the `Action` object received, the following fields can help you get the relevant information- - -1. `action` - `joined` -2. `actionBy` - User object containing the details of the user who joined the group -3. `actionFor`- Group object containing the details of the group the user has joined +When fetching message history, join events appear as `Action` messages with: +- `action` — `"joined"` +- `actionBy` — [`User`](/sdk/reference/entities#user) who joined +- `actionFor` — [`Group`](/sdk/reference/entities#group) that was joined --- diff --git a/sdk/javascript/leave-group.mdx b/sdk/javascript/leave-group.mdx index 8d7d8a8aa..18988a705 100644 --- a/sdk/javascript/leave-group.mdx +++ b/sdk/javascript/leave-group.mdx @@ -1,5 +1,6 @@ --- title: "Leave A Group" +sidebarTitle: "Leave Group" description: "Learn how to leave a group and receive real-time events when members leave using the CometChat JavaScript SDK." --- @@ -17,11 +18,11 @@ CometChat.addGroupListener("listener", new CometChat.GroupListener({ ``` -You can leave a group to stop receiving updates and messages from that group conversation. +Leave a group to stop receiving updates and messages from that conversation. ## Leave a Group -In order to stop receiving updates and messages for any particular joined group, you will have to leave the group using the `leaveGroup()` method. +Use `leaveGroup()` to leave a group. @@ -66,9 +67,7 @@ On success, the method resolves with a success message string confirming the ope ## Real-time Group Member Left Events -*In other words, as a member of a group, how do I know if someone has left it?* - -If a user leaves any group, The members of the group receive a real-time event in the `onGroupMemberLeft()` method of the `GroupListener` class. +Register a `GroupListener` to receive events when members leave. @@ -111,15 +110,10 @@ CometChat.removeGroupListener("UNIQUE_LISTENER_ID"); ## Missed Group Member Left Events -*In other words, as a member of a group, how do I know if someone has left it when my app is not running?* - -When you retrieve the list of previous messages if a member has left any group that the logged-in user is a member of, the list of messages will contain an `Action` message. An `Action` message is a sub-class of `BaseMessage` class. - -For the group member left event, in the `Action` object received, the following fields can help you get the relevant information- - -1. `action` - `left` -2. `actionBy` - User object containing the details of the user who left the group -3. `actionFor` - Group object containing the details of the group the user has left +When fetching message history, leave events appear as `Action` messages with: +- `action` — `"left"` +- `actionBy` — [`User`](/sdk/reference/entities#user) who left +- `actionFor` — [`Group`](/sdk/reference/entities#group) that was left --- diff --git a/sdk/javascript/retrieve-group-members.mdx b/sdk/javascript/retrieve-group-members.mdx index ba27d0679..cf916ddff 100644 --- a/sdk/javascript/retrieve-group-members.mdx +++ b/sdk/javascript/retrieve-group-members.mdx @@ -1,5 +1,6 @@ --- title: "Retrieve Group Members" +sidebarTitle: "Retrieve Members" description: "Fetch and filter group members by scope, status, and search keyword using the CometChat JavaScript SDK with pagination support." --- @@ -24,15 +25,11 @@ const request = new CometChat.GroupMembersRequestBuilder("GUID") ## Retrieve the List of Group Members -In order to fetch the list of groups members for a group, you can use the `GroupMembersRequest` class. To use this class i.e to create an object of the GroupMembersRequest class, you need to use the `GroupMembersRequestBuilder` class. The `GroupMembersRequestBuilder` class allows you to set the parameters based on which the groups are to be fetched. - -The `GroupMembersRequestBuilder` class allows you to set the below parameters: - -The GUID of the group for which the members are to be fetched must be specified in the constructor of the `GroupMembersRequestBuilder` class. +Use `GroupMembersRequestBuilder` to fetch members of a [Group](/sdk/reference/entities#group). The GUID must be specified in the constructor. ### Set Limit -This method sets the limit i.e. the number of members that should be fetched in a single iteration. +Sets the number of members to fetch per request. @@ -61,7 +58,7 @@ let groupMembersRequest: CometChat.GroupMembersRequest = new CometChat.GroupMemb ### Set Search Keyword -This method allows you to set the search string based on which the group members are to be fetched. +Filters members by a search string. @@ -94,7 +91,7 @@ let groupMembersRequest: CometChat.GroupMembersRequest = new CometChat.GroupMemb ### Set Scopes -This method allows you to fetch group members based on multiple scopes. +Filters members by one or more scopes (`admin`, `moderator`, `participant`). @@ -127,12 +124,14 @@ let groupMembersRequest: CometChat.GroupMembersRequest = new CometChat.GroupMemb ### Set Status -The status based on which the group members are to be fetched. The status parameter can contain one of the below two values: +Filters members by online status: -* CometChat.USER_STATUS.ONLINE - will return the list of only online group members. -* CometChat.USER_STATUS.OFFLINE - will return the list of only offline group members. +| Value | Description | +|-------|-------------| +| `CometChat.USER_STATUS.ONLINE` | Only online members | +| `CometChat.USER_STATUS.OFFLINE` | Only offline members | -If this parameter is not set, will return all the group members regardless of their status. +If not set, returns all members regardless of status. @@ -161,9 +160,7 @@ let groupMembersRequest: CometChat.GroupMembersRequest = new CometChat.GroupMemb -Finally, once all the parameters are set to the builder class, you need to call the build() method to get the object of the `GroupMembersRequest` class. - -Once you have the object of the `GroupMembersRequest` class, you need to call the `fetchNext()` method. Calling this method will return a list of `GroupMember` objects containing n number of members where n is the limit set in the builder class. +Once configured, call `build()` to create the request, then `fetchNext()` to retrieve members. diff --git a/sdk/javascript/retrieve-groups.mdx b/sdk/javascript/retrieve-groups.mdx index c7dbd2afd..d5bbce763 100644 --- a/sdk/javascript/retrieve-groups.mdx +++ b/sdk/javascript/retrieve-groups.mdx @@ -1,5 +1,6 @@ --- title: "Retrieve Groups" +sidebarTitle: "Retrieve Groups" description: "Fetch, filter, and search groups using the CometChat JavaScript SDK. Includes pagination, tag-based filtering, joined-only groups, and online member counts." --- @@ -26,15 +27,11 @@ const count = await CometChat.getOnlineGroupMemberCount(["GUID"]); ## Retrieve List of Groups -*In other words, as a logged-in user, how do I retrieve the list of groups I've joined and groups that are available?* - -In order to fetch the list of groups, you can use the `GroupsRequest` class. To use this class i.e to create an object of the `GroupsRequest` class, you need to use the `GroupsRequestBuilder` class. The `GroupsRequestBuilder` class allows you to set the parameters based on which the groups are to be fetched. - -The `GroupsRequestBuilder` class allows you to set the below parameters: +Use `GroupsRequestBuilder` to fetch groups with filtering, searching, and pagination. ### Set Limit -This method sets the limit i.e. the number of groups that should be fetched in a single iteration. +Sets the number of groups to fetch per request. @@ -61,7 +58,7 @@ let groupsRequest = new CometChat.GroupsRequestBuilder() ### Set Search Keyword -This method allows you to set the search string based on which the groups are to be fetched. +Filters groups by a search string. @@ -92,7 +89,7 @@ let groupsRequest: CometChat.GroupsRequest = new CometChat.GroupsRequestBuilder( ### Joined Only -This method when used, will ask the SDK to only return the groups that the user has joined or is a part of. +When `true`, returns only groups the logged-in user has joined. @@ -121,7 +118,7 @@ let groupsRequest: CometChat.GroupsRequest = new CometChat.GroupsRequestBuilder( ### Set Tags -This method accepts a list of tags based on which the list of groups is to be fetched. The list fetched will only contain the groups that have been tagged with the specified tags. +Filters groups by specified tags. @@ -152,7 +149,7 @@ let groupsRequest: CometChat.GroupsRequest = new CometChat.GroupsRequestBuilder( ### With Tags -This property when set to true will fetch tags data along with the list of groups. +When `true`, includes tag data in the returned group objects. @@ -179,11 +176,11 @@ let groupsRequest: CometChat.GroupsRequest = new CometChat.GroupsRequestBuilder( -Finally, once all the parameters are set to the builder class, you need to call the build() method to get the object of the `GroupsRequest` class. +After configuring the builder, call `build()` to get the `GroupsRequest` object, then call `fetchNext()` to retrieve groups. -Once you have the object of the `GroupsRequest` class, you need to call the `fetchNext()` method. Calling this method will return a list of `Group` objects containing n number of groups where n is the limit set in the builder class. - -The list of groups fetched will only have the public and password type groups. The private groups will only be available if the user is a member of the group. + +The list only includes public and password-protected groups. Private groups appear only if the user is a member. + @@ -237,9 +234,7 @@ The `fetchNext()` method returns an array of [`Group`](/sdk/reference/entities#g ## Retrieve Particular Group Details -*In other words, as a logged-in user, how do I retrieve information for a specific group?* - -To get the information of a group, you can use the `getGroup()` method. +Use `getGroup()` to fetch a specific group's details by GUID. @@ -272,11 +267,11 @@ CometChat.getGroup(GUID).then( -| Parameter | Description | -| --------- | ------------------------------------------------------------ | -| `GUID` | The GUID of the group for whom the details are to be fetched | +| Parameter | Description | +| --------- | ----------- | +| `GUID` | The GUID of the group to fetch | -It returns `Group` object containing the details of the group. +Returns a [`Group`](/sdk/reference/entities#group) object with the group's details. The method returns a [`Group`](/sdk/reference/entities#group) object. Access the response data using getter methods: @@ -289,9 +284,9 @@ The method returns a [`Group`](/sdk/reference/entities#group) object. Access the | owner | `getOwner()` | `string` | UID of the group owner | | hasJoined | `getHasJoined()` | `boolean` | Whether the logged-in user has joined this group | -## Get online group member count +## Get Online Group Member Count -To get the total count of online users in particular groups, you can use the `getOnlineGroupMemberCount()` method. +Use `getOnlineGroupMemberCount()` to get the number of online members in specified groups. @@ -324,7 +319,7 @@ CometChat.getOnlineGroupMemberCount(guids).then( -This method returns a JSON Object with the GUID as the key and the online member count for that group as the value. +Returns an object with GUIDs as keys and online member counts as values. --- diff --git a/sdk/javascript/transfer-group-ownership.mdx b/sdk/javascript/transfer-group-ownership.mdx index fae911602..1fa9199cb 100644 --- a/sdk/javascript/transfer-group-ownership.mdx +++ b/sdk/javascript/transfer-group-ownership.mdx @@ -1,5 +1,6 @@ --- title: "Transfer Group Ownership" +sidebarTitle: "Transfer Ownership" description: "Transfer ownership of a CometChat group to another member using the JavaScript SDK." --- @@ -14,11 +15,9 @@ await CometChat.transferGroupOwnership("GUID", "NEW_OWNER_UID"); **Note:** Only the current group owner can transfer ownership. The owner must transfer ownership before leaving the group. -*In other words, as a logged-in user, how do I transfer the ownership of any group if I am the owner of the group?* +Only the owner of a [Group](/sdk/reference/entities#group) can transfer ownership. Since owners cannot leave their group, you must transfer ownership first if you want to leave. -In order to transfer the ownership of any group, the first condition is that you must be the owner of the group. In case you are the owner of the group, you can use the `transferGroupOwnership()` method provided by the `CometChat` class. - -This will be helpful as the owner is not allowed to leave the group. In case, you as the owner would like to leave the group, you will have to use this method and transfer your ownership first to any other member of the group and only then you will be allowed to leave the group. +Use `transferGroupOwnership()` to transfer ownership to another member. diff --git a/sdk/javascript/update-group.mdx b/sdk/javascript/update-group.mdx index 6055c6023..16124425c 100644 --- a/sdk/javascript/update-group.mdx +++ b/sdk/javascript/update-group.mdx @@ -1,5 +1,6 @@ --- title: "Update A Group" +sidebarTitle: "Update Group" description: "Update group details such as name, type, icon, and description using the CometChat JavaScript SDK." --- @@ -15,9 +16,7 @@ const updated = await CometChat.updateGroup(group); ## Update Group -*In other words, as a group owner, how can I update the group details?* - -You can update the existing details of the group using the `updateGroup()` method. +Use `updateGroup()` to modify group details. Pass a `Group` object with the updated values. @@ -59,13 +58,11 @@ CometChat.updateGroup(group).then( -This method takes an instance of the `Group` class as a parameter which should contain the data that you wish to update. - -| Parameter | Description | -| --------- | ---------------------------- | -| `group` | an instance of class `Group` | +| Parameter | Description | +| --------- | ----------- | +| `group` | An instance of `Group` class with updated values | -After a successful update of the group, you will receive an instance of `Group` class containing update information of the group. +On success, returns a [`Group`](/sdk/reference/entities#group) object with the updated details. The method returns a [`Group`](/sdk/reference/entities#group) object. Access the response data using getter methods: From 70f602de37885c4be2d83cf51903173939c061df Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 18 Mar 2026 16:35:52 +0530 Subject: [PATCH 35/43] Frame these better --- sdk/javascript/ai-agents.mdx | 73 +++++++++++++++----------------- sdk/javascript/ai-moderation.mdx | 11 +++-- 2 files changed, 38 insertions(+), 46 deletions(-) diff --git a/sdk/javascript/ai-agents.mdx b/sdk/javascript/ai-agents.mdx index 736fff274..d3d998e32 100644 --- a/sdk/javascript/ai-agents.mdx +++ b/sdk/javascript/ai-agents.mdx @@ -1,5 +1,6 @@ --- title: "AI Agents" +sidebarTitle: "AI Agents" description: "Integrate AI Agents into your app to enable intelligent, automated conversations with real-time streaming events and tool invocations." --- @@ -29,37 +30,37 @@ CometChat.removeMessageListener("LISTENER_ID"); # AI Agents Overview -AI Agents enable intelligent, automated interactions within your application. They can process user messages, trigger tools, and respond with contextually relevant information. For a broader introduction, see the [AI Agents section](/ai-agents). +AI Agents enable intelligent, automated interactions within your application. They process user messages, trigger tools, and respond with contextually relevant information. For a broader introduction, see the [AI Agents section](/ai-agents). -> **Note:** -> Currently, an Agent only responds to **Text Messages**. + +Agents only respond to text messages. + ## Agent Run Lifecycle and Message Flow -This section explains how a user’s text message to an Agent becomes a structured "run" which emits real-time events and then produces agentic messages for historical retrieval. -- A user sends a text message to an Agent. -- The platform starts a run and streams real-time events via the **`AIAssistantListener`**. -- After the run completes, persisted Agentic Messages arrive via the **`MessageListener`**. +When a user sends a text message to an Agent: +1. The platform starts a run and streams real-time events via `AIAssistantListener` +2. After the run completes, persisted Agentic Messages arrive via `MessageListener` ### Real-time Events -Events are received via the **`onAIAssistantEventReceived`** method of the **`AIAssistantListener`** class in this general order: - -1. Run Start -2. Zero or more tool call cycles (repeats for each tool invocation): - - Tool Call Start - - Tool Call Arguments - - Tool Call End - - Tool Call Result -3. One or more assistant reply streams: - - Text Message Start - - Text Message Content (multiple times; token/char streaming) - - Text Message End -4. Run Finished - -Notes: -- `Run Start` and `Run Finished` are always emitted. -- `Tool Call` events appear only when a backend or frontend tool is invoked. There can be multiple tool calls in a single run. -- `Text Message` events are always emitted and carry the assistant’s reply incrementally. + +Events arrive via `onAIAssistantEventReceived` in this order: + +| Order | Event | Description | +|-------|-------|-------------| +| 1 | Run Start | A new run has begun | +| 2 | Tool Call Start | Agent decided to invoke a tool | +| 3 | Tool Call Arguments | Arguments being passed to the tool | +| 4 | Tool Call End | Tool execution completed | +| 5 | Tool Call Result | Tool's output is available | +| 6 | Text Message Start | Agent started composing a reply | +| 7 | Text Message Content | Streaming content chunks (multiple) | +| 8 | Text Message End | Agent reply is complete | +| 9 | Run Finished | Run finalized; persisted messages follow | + + +`Run Start` and `Run Finished` are always emitted. Tool Call events only appear when tools are invoked. + @@ -94,23 +95,15 @@ Notes: -#### Event descriptions -- Run Start: A new run has begun for the user’s message. -- Tool Call Start: The agent decided to invoke a tool. -- Tool Call Arguments: Arguments being passed to the tool. -- Tool Call End: Tool execution completed. -- Tool Call Result: Tool’s output is available. -- Text Message Start: The agent started composing a reply. -- Text Message Content: Streaming content chunks for progressive rendering. -- Text Message End: The agent reply is complete. -- Run Finished: The run is finalized; persisted messages will follow. - ### Agentic Messages -These events are received via the **`MessageListener`** after the run completes. -- `AIAssistantMessage`: The full assistant reply. -- `AIToolResultMessage`: The final output of a tool call. -- `AIToolArgumentMessage`: The arguments that were passed to a tool. +After the run completes, these messages arrive via `MessageListener`: + +| Message Type | Description | +|--------------|-------------| +| `AIAssistantMessage` | The full assistant reply | +| `AIToolResultMessage` | The final output of a tool call | +| `AIToolArgumentMessage` | The arguments passed to a tool | diff --git a/sdk/javascript/ai-moderation.mdx b/sdk/javascript/ai-moderation.mdx index 82bf9f876..3222af96a 100644 --- a/sdk/javascript/ai-moderation.mdx +++ b/sdk/javascript/ai-moderation.mdx @@ -1,5 +1,6 @@ --- title: "AI Moderation" +sidebarTitle: "AI Moderation" description: "Automatically moderate chat messages using AI to detect and block inappropriate content in real-time." --- @@ -28,7 +29,7 @@ CometChat.addMessageListener("MOD_LISTENER", new CometChat.MessageListener({ ## Overview -AI Moderation in the CometChat SDK helps ensure that your chat application remains safe and compliant by automatically reviewing messages for inappropriate content. This feature leverages AI to moderate messages in real-time, reducing manual intervention and improving user experience. +AI Moderation automatically reviews messages for inappropriate content in real-time, reducing manual intervention and improving user experience. For a broader understanding of moderation features, configuring rules, and managing flagged messages, see the [Moderation Overview](/moderation/overview). @@ -36,11 +37,9 @@ For a broader understanding of moderation features, configuring rules, and manag ## Prerequisites -Before using AI Moderation, ensure the following: - -1. Moderation is enabled for your app in the [CometChat Dashboard](https://app.cometchat.com) -2. Moderation rules are configured under **Moderation > Rules** -3. You're using CometChat SDK version that supports moderation +1. Moderation enabled in the [CometChat Dashboard](https://app.cometchat.com) +2. Moderation rules configured under **Moderation > Rules** +3. CometChat SDK version that supports moderation ## How It Works From 7387db245df08762eeac92e4388e3af7c4d579cc Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 18 Mar 2026 16:37:40 +0530 Subject: [PATCH 36/43] minor fixes --- sdk/reference/auxiliary.mdx | 1 + sdk/reference/entities.mdx | 1 + sdk/reference/messages.mdx | 1 + 3 files changed, 3 insertions(+) diff --git a/sdk/reference/auxiliary.mdx b/sdk/reference/auxiliary.mdx index 8bf7179f6..da80ef3c5 100644 --- a/sdk/reference/auxiliary.mdx +++ b/sdk/reference/auxiliary.mdx @@ -1,5 +1,6 @@ --- title: "Auxiliary" +sidebarTitle: "Auxiliary" description: "Class reference for auxiliary objects returned by CometChat SDK methods. Covers MessageReceipt, ReactionCount, ReactionEvent, TypingIndicator, TransientMessage, and Attachment." --- diff --git a/sdk/reference/entities.mdx b/sdk/reference/entities.mdx index 7c0fd4e90..2d5588aa8 100644 --- a/sdk/reference/entities.mdx +++ b/sdk/reference/entities.mdx @@ -1,5 +1,6 @@ --- title: "Entities" +sidebarTitle: "Entities" description: "Class reference for entity objects returned by CometChat SDK methods. Covers User, Group, Conversation, and GroupMember." --- diff --git a/sdk/reference/messages.mdx b/sdk/reference/messages.mdx index b789a66e9..93626688f 100644 --- a/sdk/reference/messages.mdx +++ b/sdk/reference/messages.mdx @@ -1,5 +1,6 @@ --- title: "Messages" +sidebarTitle: "Messages" description: "Class reference for message objects returned by CometChat SDK methods. Covers BaseMessage and its subclasses like TextMessage." --- From 31f77c1786b8b7fa6b0f7fa6f17655435da7697b Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 18 Mar 2026 16:40:11 +0530 Subject: [PATCH 37/43] Update best-practices.mdx --- sdk/javascript/best-practices.mdx | 577 ++++++------------------------ 1 file changed, 113 insertions(+), 464 deletions(-) diff --git a/sdk/javascript/best-practices.mdx b/sdk/javascript/best-practices.mdx index 5205156f2..64cdc95a9 100644 --- a/sdk/javascript/best-practices.mdx +++ b/sdk/javascript/best-practices.mdx @@ -1,516 +1,165 @@ --- title: "Best Practices" +sidebarTitle: "Best Practices" description: "Recommended patterns and practices for building with the CometChat JavaScript SDK." --- Follow these best practices to build reliable, performant, and secure applications with the CometChat JavaScript SDK. -## Initialization - - - - Call `CometChat.init()` as early as possible in your application lifecycle — typically in your entry file (`index.js`, `main.js`, or `App.js`). It only needs to be called once per session. - - - Store App ID, Region, and Auth Key in environment variables rather than hardcoding them. This makes it easier to switch between development and production environments. - - - -## Authentication - - - - Before calling `login()`, use `CometChat.getLoggedinUser()` to check if a session already exists. This avoids unnecessary login calls and prevents session conflicts. - - - Auth Keys are convenient for development but expose your app to security risks in production. Always generate Auth Tokens server-side using the [REST API](https://api-explorer.cometchat.com/reference/create-authtoken) and pass them to the client. - - - Auth Tokens can expire. Implement a mechanism to detect login failures due to expired tokens and re-generate them from your server. Use the [Login Listener](/sdk/javascript/login-listener) to detect session changes. - - - Always call `CometChat.logout()` when your user signs out of your app. This clears the SDK session and stops real-time event delivery, preventing stale data and memory leaks. - - +## Initialization & Authentication + +| Practice | Description | +|----------|-------------| +| Initialize once at startup | Call `CometChat.init()` in your entry file (`index.js`, `main.js`, or `App.js`). It only needs to be called once per session. | +| Use environment variables | Store App ID, Region, and Auth Key in environment variables rather than hardcoding them. | +| Check for existing sessions | Before calling `login()`, use `CometChat.getLoggedinUser()` to check if a session already exists. | +| Use Auth Tokens in production | Auth Keys are for development only. Generate Auth Tokens server-side using the [REST API](https://api-explorer.cometchat.com/reference/create-authtoken). | +| Handle token expiry | Implement a mechanism to detect login failures due to expired tokens. Use the [Login Listener](/sdk/javascript/login-listener) to detect session changes. | +| Logout on sign-out | Always call `CometChat.logout()` when your user signs out to clear the SDK session and stop real-time events. | ## Listeners - - - Each listener must have a unique ID string. If you register a new listener with the same ID, it will replace the previous one. Use descriptive IDs like `"LOGIN_LISTENER_MAIN"` or `"MESSAGE_LISTENER_CHAT_SCREEN"` to avoid accidental overwrites. - - - Register listeners as early as possible in your app lifecycle (e.g., right after `login()`). Remove them when the component or page that registered them is destroyed to prevent memory leaks. - - - Use the `logoutSuccess` callback to clear your app's local state, redirect to the login screen, and clean up any other SDK listeners. This ensures a clean state when the user logs out. - - - Avoid heavy processing inside listener callbacks. Dispatch events to your state management layer and process asynchronously. - - - Only register the listener types you need. Don't register a `GroupListener` if your page only handles messages. - - +| Practice | Description | +|----------|-------------| +| Use unique listener IDs | Use descriptive IDs like `"MESSAGE_LISTENER_CHAT_SCREEN"` to avoid accidental overwrites. | +| Register early, remove on cleanup | Register listeners after `login()`. Remove them when the component is destroyed to prevent memory leaks. | +| Keep callbacks lightweight | Avoid heavy processing inside listener callbacks. Dispatch events to your state management layer. | +| Use specific listeners | Only register the listener types you need. Don't register a `GroupListener` if your page only handles messages. | + +## Pagination & Caching + +| Practice | Description | +|----------|-------------| +| Use reasonable limits | Set `setLimit()` to 30-50 for users, messages, and group members. | +| Reuse request objects | Call `fetchNext()`/`fetchPrevious()` on the same request instance. Creating a new object resets the cursor. | +| Cache frequently accessed data | Store user and group objects locally to reduce API calls. | ## Rate Limits - - - If you need to perform many operations (e.g., sending messages to multiple users), space them out over time rather than firing them all at once. Use a queue or throttle mechanism to stay within the per-minute limits. - - - Check the `X-Rate-Limit-Remaining` header in REST API responses to proactively slow down before hitting the limit. This is more efficient than waiting for `429` errors. - - - Core operations (login, create/delete user, create/join group) share a lower cumulative limit of 10,000/min. Standard operations have a higher 20,000/min limit. Plan your architecture accordingly — avoid frequent login/logout cycles. - - +| Practice | Description | +|----------|-------------| +| Batch operations | Space out bulk operations using a queue or throttle mechanism. | +| Monitor rate limit headers | Check `X-Rate-Limit-Remaining` in REST API responses to slow down before hitting limits. | +| Distinguish operation types | Core operations (login, create/delete user) share a 10,000/min limit. Standard operations have 20,000/min. Avoid frequent login/logout cycles. | ## SSR Frameworks - - - CometChat SDK requires browser APIs (`window`, `WebSocket`). For Next.js, Nuxt, or other SSR frameworks, use dynamic imports or `useEffect` to ensure the SDK loads only on the client. - - - Show a loading indicator while the SDK initializes on the client. This prevents hydration mismatches and provides a better user experience. - - - -## Users - - - - Use `setLimit()` with reasonable values (30-50) and call `fetchNext()` for subsequent pages. Don't fetch all users at once. - - - Call `fetchNext()` on the same `UsersRequest` instance for pagination. Creating a new object resets the cursor. - - - Store frequently accessed user objects locally to reduce API calls, especially for `getUser()`. - - - Enable this in user lists to respect block relationships and provide a cleaner experience. - - - Always create and update users from your backend server using the REST API to keep your Auth Key secure. - - +| Practice | Description | +|----------|-------------| +| Initialize client-side only | CometChat requires browser APIs. Use dynamic imports or `useEffect` for Next.js, Nuxt, etc. | +| Use loading states | Show a loading indicator while the SDK initializes to prevent hydration mismatches. | ## Messaging - - - Choose text, media, or custom messages based on your content. - - - Use `setMetadata()` to attach location, device info, or other contextual data. - - - Use `setTags()` to mark messages for easy filtering (e.g., "starred", "important"). - - - Always implement error callbacks to handle network issues or invalid parameters. - - - Before sending media messages, verify the file type matches the message type (IMAGE, VIDEO, AUDIO, FILE). - - - Always call `removeMessageListener()` when components unmount to prevent memory leaks. - - - Use `setLimit()` with reasonable values (30-50) and call `fetchPrevious()` for more. - - - Use `setCategories()` and `setTypes()` to fetch only relevant messages. - - - Use `setCategories()` with `setTypes()` for precise filtering. - - - `setUpdatedAfter()` helps sync local cache with server. - - - Use `hideDeletedMessages(true)` for cleaner message lists. - - - Use `hideMessagesFromBlockedUsers(true)` to respect user preferences. - - - Call `fetchPrevious()`/`fetchNext()` on the same object for pagination. - - +| Practice | Description | +|----------|-------------| +| Use appropriate message types | Choose text, media, or custom messages based on your content. | +| Add metadata for context | Use `setMetadata()` to attach location, device info, or other contextual data. | +| Handle errors gracefully | Always implement error callbacks to handle network issues or invalid parameters. | +| Validate file types | Before sending media messages, verify the file type matches the message type. | +| Hide deleted/blocked content | Use `hideDeletedMessages(true)` and `hideMessagesFromBlockedUsers(true)` for cleaner lists. | ## Threaded Messages - - - Store the current thread's `parentMessageId` to filter incoming messages. - - - Exclude thread replies from main conversation to avoid clutter. - - - Use `setLimit()` and `fetchPrevious()` for large threads. - - - Clean up message listeners when user exits a thread view. - - - Display the number of replies on parent messages to indicate thread activity. - - - -## Reactions - - - - Show the reaction immediately, then sync with server response. - - - Keep message objects in sync with real-time events. - - - Provide a curated set of emojis for better UX. - - - Display aggregated counts with `getReactions()` for each message. - - - Check `getReactedByMe()` before allowing users to add the same reaction. - - - -## Mentions - - - - Always use `<@uid:UID>` format for mentions in message text. - - - Ensure mentioned UIDs exist before sending. - - - Parse message text and style mentions differently. - - - Use `mentionsWithTagInfo(true)` to get user tags for mentioned users. - - - Use `mentionsWithBlockedInfo(true)` to check blocked relationships. - - +| Practice | Description | +|----------|-------------| +| Track active thread ID | Store the current thread's `parentMessageId` to filter incoming messages. | +| Use hideReplies(true) | Exclude thread replies from main conversation to avoid clutter. | +| Show reply count | Display the number of replies on parent messages to indicate thread activity. | + +## Reactions & Mentions + +| Practice | Description | +|----------|-------------| +| Update UI optimistically | Show reactions immediately, then sync with server response. | +| Use correct mention format | Always use `<@uid:UID>` format for mentions in message text. | +| Highlight mentions in UI | Parse message text and style mentions differently. | ## Typing Indicators - - - Don't call `startTyping()` on every keystroke - debounce to ~300ms intervals. - - - Call `endTyping()` after a period of inactivity (e.g., 3-5 seconds). - - - Always call `endTyping()` when the user sends a message. - - - Prevent duplicate events by using component-specific listener IDs. - - - Clean up listeners when leaving a conversation view. - - +| Practice | Description | +|----------|-------------| +| Debounce typing events | Don't call `startTyping()` on every keystroke - debounce to ~300ms intervals. | +| Auto-stop typing | Call `endTyping()` after 3-5 seconds of inactivity or when the user sends a message. | ## Delivery & Read Receipts - - - Call `markAsDelivered()` when messages are fetched and displayed. - - - Call `markAsRead()` when the user actually views/scrolls to a message. - - - Prefer passing the full message object to `markAsDelivered()`/`markAsRead()` for simplicity. - - - Mark the last message in a batch - all previous messages are automatically marked. - - - Receipts are queued and sent when the user comes back online. - - - -## Conversations - - - - Always show a confirmation dialog before deleting conversations. - - - Remove the conversation from the list optimistically, then handle errors. - - - If deletion fails, restore the conversation in the UI. - - - If you cache conversations locally, remove them after successful deletion. - - +| Practice | Description | +|----------|-------------| +| Mark as delivered on fetch | Call `markAsDelivered()` when messages are fetched and displayed. | +| Mark as read on view | Call `markAsRead()` when the user actually views/scrolls to a message. | +| Batch receipts | Mark the last message in a batch - all previous messages are automatically marked. | ## Groups - - - Choose descriptive, unique GUIDs (e.g., `"project-alpha-team"`) that are easy to reference in your codebase. - - - Group type cannot be changed after creation. Choose between PUBLIC, PASSWORD, and PRIVATE based on your use case. - - - Use `createGroupWithMembers()` to add initial members in a single API call instead of creating the group and adding members separately. - - - Before calling `joinGroup()`, check the group's `hasJoined` property to avoid unnecessary API calls. - - - Show a confirmation dialog before leaving or deleting a group, especially for groups with important conversations. - - - Use public for open communities, private for invite-only teams, password for semi-restricted access. - - - Give admin/moderator roles only to trusted users who need management capabilities. - - - Owners must transfer ownership to another member before they can leave the group. - - - When fetching group members, use `GroupMembersRequestBuilder` with reasonable limits (30-50). - - - Register `GroupListener` to receive real-time updates for member changes, scope changes, and group updates. - - - When building a sidebar or group list, filter to joined groups so users only see groups they belong to. - - - If you call `getGroup()` frequently for the same GUID, cache the result locally to reduce API calls. - - - Fetching tags adds payload size. Only enable it when your UI displays or filters by tags. - - +| Practice | Description | +|----------|-------------| +| Use meaningful GUIDs | Choose descriptive, unique GUIDs (e.g., `"project-alpha-team"`). | +| Set group type carefully | Group type cannot be changed after creation. Choose between PUBLIC, PASSWORD, and PRIVATE. | +| Add members at creation | Use `createGroupWithMembers()` to add initial members in a single API call. | +| Check hasJoined before joining | Avoid unnecessary API calls by checking the group's `hasJoined` property first. | +| Transfer ownership before leaving | Owners must transfer ownership to another member before they can leave. | +| Use joinedOnly(true) | Filter to joined groups when building sidebars or group lists. | ## Group Members - - - Add multiple members in a single `addMembersToGroup()` call rather than calling it once per user. - - - Assign `PARTICIPANT` by default. Only use `ADMIN` or `MODERATOR` when the user genuinely needs elevated permissions. - - - The response array contains per-user results. Check each entry for `"success"` or an error message to handle failures gracefully. - - - Ensure the UIDs exist and are not already members to avoid unnecessary API calls and confusing error responses. - - - Always use `fetchNext()` in a loop or on-scroll. Set a reasonable limit (10–30) per request to avoid large payloads. - - - Create the `GroupMembersRequest` once and call `fetchNext()` repeatedly. Creating a new builder each time resets pagination. - - - Use `setScopes(["admin", "moderator"])` when building admin views to show only privileged members. - - - Filter by `CometChat.USER_STATUS.ONLINE` to show active members in real-time collaboration features. - - - You can chain `setSearchKeyword()`, `setScopes()`, and `setStatus()` on the same builder for precise results. - - - The logged-in user must be the group admin to change another member's scope. Moderators cannot change scopes. - - - Promoting a user to admin gives them full control over the group. Add a confirmation dialog in your UI. - - - Always use `CometChat.GROUP_MEMBER_SCOPE.ADMIN`, `CometChat.GROUP_MEMBER_SCOPE.MODERATOR`, or `CometChat.GROUP_MEMBER_SCOPE.PARTICIPANT` instead of raw strings. - - - Refresh the member list or update the local state after a successful scope change to reflect the new role immediately. - - - Use kick when you want the user to be able to rejoin. Use ban when the user should be permanently removed until explicitly unbanned. - - - Banning is a stronger action than kicking. Add a confirmation dialog in your UI before calling `banGroupMember()`. - - - Use `BannedMembersRequestBuilder` with a reasonable limit (10–30) and call `fetchNext()` in a loop for large banned lists. - - - Only admins and moderators can kick/ban. Check the user's scope before showing these actions in the UI. - - - -## Group Ownership - - - - The owner cannot leave a group without first transferring ownership. Always call `transferGroupOwnership()` before `leaveGroup()`. - - - Transfer ownership to an active admin or moderator who can manage the group responsibly. - - - Ownership transfer is irreversible. Add a confirmation dialog before calling the method. - - - After a successful transfer, update your local group data to reflect the new owner. - - +| Practice | Description | +|----------|-------------| +| Batch member additions | Add multiple members in a single `addMembersToGroup()` call. | +| Set appropriate scopes | Assign `PARTICIPANT` by default. Only use `ADMIN` or `MODERATOR` when needed. | +| Handle partial failures | Check each entry in the response array for `"success"` or an error message. | +| Use scope constants | Use `CometChat.GROUP_MEMBER_SCOPE.ADMIN` instead of raw strings. | +| Kick vs. Ban | Use kick when the user can rejoin. Use ban for permanent removal until unbanned. | ## Calling - - - Unless using Standalone Calling, always initialize the Chat SDK (`CometChat.init()`) before the Calls SDK (`CometChatCalls.init()`). - - - Save the session ID from `initiateCall()` response immediately. You'll need it for accept, reject, cancel, and starting the session. - - - Implement handlers for all listener events (accepted, rejected, cancelled, busy, ended) to provide a complete user experience. - - - Generate call tokens immediately before starting a session rather than caching them, as tokens may expire. - - - Always call `CometChatCalls.endSession()` in both `onCallEnded` and `onCallEndButtonPressed` callbacks to release media resources. - - - Always notify participants when recording starts. This is often a legal requirement in many jurisdictions. - - - Always generate a new call token using `generateToken()` before starting a presentation. Reusing expired tokens will fail. - - - Use `setIsPresenter(true)` for presenters and `setIsPresenter(false)` for viewers. The default is viewer. - - - The maximum number of presenters is 5. Additional users should join as viewers. - - - These are different events. `onCallEnded` fires when the call ends server-side, while `onCallEndButtonPressed` fires when the user clicks the end button locally. - - +| Practice | Description | +|----------|-------------| +| Initialize Calls SDK after Chat SDK | Always initialize Chat SDK (`CometChat.init()`) before Calls SDK (`CometChatCalls.init()`). | +| Store session ID immediately | Save the session ID from `initiateCall()` response - you'll need it for accept, reject, cancel. | +| Handle all call states | Implement handlers for all listener events (accepted, rejected, cancelled, busy, ended). | +| Generate tokens just-in-time | Generate call tokens immediately before starting a session rather than caching them. | +| Clean up on session end | Always call `CometChatCalls.endSession()` in both `onCallEnded` and `onCallEndButtonPressed` callbacks. | +| Inform users about recording | Always notify participants when recording starts - this is often a legal requirement. | +| Limit presenters to 5 | Additional users should join as viewers. | ## Custom CSS (Calling) - - - Applying styles to undocumented internal classes may break with SDK updates. Stick to the classes listed in the documentation. - - - Altering the grid container dimensions can break the layout. Only customize colors, borders, and visibility. - - - Some SDK styles may need `!important` to override, but overusing it makes maintenance harder. - - - CSS changes may look different in `DEFAULT`, `TILE`, and `SPOTLIGHT` modes. Test all three. - - - When customizing button dimensions, ensure they remain large enough for easy interaction (minimum 44x44px for touch targets). - - +| Practice | Description | +|----------|-------------| +| Only use documented CSS classes | Undocumented internal classes may break with SDK updates. | +| Don't resize the grid container | Only customize colors, borders, and visibility. | +| Test across modes | CSS changes may look different in `DEFAULT`, `TILE`, and `SPOTLIGHT` modes. | +| Keep button sizes accessible | Minimum 44x44px for touch targets. | ## Connection & WebSocket - - - Add the connection listener right after `CometChat.init()` succeeds, ideally in your app's entry point, so you catch all connection state changes. - - - Display a banner or indicator when the connection is `"disconnected"` or `"connecting"` so users know messages may be delayed. - - - If the connection drops, queue user actions (like sending messages) and retry once `onConnected` fires. - - - Use the listener-based approach instead. Polling adds unnecessary overhead when the SDK already pushes state changes. - - - The default auto-connect behavior works well for most apps. Only manage connections manually if you need fine-grained control (e.g., background/foreground transitions, battery optimization). - - - Always verify the user is logged in with `CometChat.getLoggedInUser()` before calling `CometChat.connect()`. - - - Use `CometChat.addConnectionListener()` alongside manual connection management to track the actual connection state. - - - If you disconnect when the app goes to background, call `CometChat.connect()` when the app returns to foreground. - - - Allow time for the connection to establish or close before toggling again. - - +| Practice | Description | +|----------|-------------| +| Register connection listener early | Add the listener right after `CometChat.init()` succeeds. | +| Show connection status in UI | Display a banner when disconnected so users know messages may be delayed. | +| Queue actions during disconnection | Queue user actions and retry once `onConnected` fires. | +| Don't poll getConnectionStatus() | Use the listener-based approach instead. | +| Reconnect on app foreground | If you disconnect in background, call `CometChat.connect()` when returning to foreground. | ## AI Features - - - Use `AIAssistantListener` for real-time streaming events and `MessageListener` for persisted agentic messages. Both are needed for a complete experience. - - - Use `Text Message Content` events to render the assistant's reply token-by-token for a responsive UI, rather than waiting for the full reply. - - - Use `Run Start` and `Run Finished` events to show loading indicators and know when the agent is done processing. - - - Tool call events may occur multiple times in a single run. Display appropriate UI feedback for each tool invocation. - - - When `getModerationStatus()` returns `PENDING`, display a visual indicator (spinner, dimmed message) so users know the message is being reviewed. - - - Don't just hide blocked messages silently. Show a placeholder or notification so the sender understands what happened. - - - Add the `onMessageModerated` listener before sending messages so you don't miss any moderation results. - - - Maintain a local map of pending message IDs so you can update the UI when moderation results arrive. - - - Configure moderation rules in the Dashboard before testing. Without rules, messages won't be moderated. - - +| Practice | Description | +|----------|-------------| +| Register both listeners for AI Agents | Use `AIAssistantListener` for streaming events and `MessageListener` for persisted messages. | +| Handle streaming progressively | Render the assistant's reply token-by-token using `Text Message Content` events. | +| Show pending state for moderation | Display a visual indicator when `getModerationStatus()` returns `PENDING`. | +| Handle disapproved messages gracefully | Show a placeholder or notification so the sender understands what happened. | +| Track pending messages | Maintain a local map of pending message IDs to update UI when moderation results arrive. | ## Upgrading from V3 - - - Complete the v4 [setup instructions](/sdk/javascript/setup-sdk) before changing imports, so you have the latest SDK version installed. - - - Use find-and-replace across your project to change all `@cometchat-pro/chat` imports to `@cometchat/chat-sdk-javascript` in one pass. - - - After updating dependencies and imports, test each feature area (messaging, calling, groups) individually to catch any breaking changes. - - - After migration, uninstall the v3 packages (`npm uninstall @cometchat-pro/chat`) to avoid conflicts. - - +| Practice | Description | +|----------|-------------| +| Follow the setup guide first | Complete the v4 [setup instructions](/sdk/javascript/setup-sdk) before changing imports. | +| Update all imports at once | Use find-and-replace to change all `@cometchat-pro/chat` imports to `@cometchat/chat-sdk-javascript`. | +| Test incrementally | Test each feature area (messaging, calling, groups) individually after updating. | +| Remove old packages | Uninstall v3 packages (`npm uninstall @cometchat-pro/chat`) to avoid conflicts. | --- From 3481029a078031d6da555e4696657d8bd3192b38 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 18 Mar 2026 16:46:45 +0530 Subject: [PATCH 38/43] frame this better --- .../ai-integration-quick-reference.mdx | 26 ------------------- sdk/javascript/troubleshooting.mdx | 10 ------- 2 files changed, 36 deletions(-) diff --git a/sdk/javascript/ai-integration-quick-reference.mdx b/sdk/javascript/ai-integration-quick-reference.mdx index 7ee657163..3f3af5c23 100644 --- a/sdk/javascript/ai-integration-quick-reference.mdx +++ b/sdk/javascript/ai-integration-quick-reference.mdx @@ -4,32 +4,6 @@ sidebarTitle: "AI Quick Reference" description: "Quick reference for AI features in the CometChat JavaScript SDK: AI Agents, AI Moderation, and AI User Copilot." --- -{/* TL;DR for Agents and Quick Reference */} - - -```javascript -// AI Agents - Listen for real-time streaming events -CometChat.addAIAssistantListener("LISTENER_ID", { - onAIAssistantEventReceived: (event) => console.log("Event:", event) -}); - -// AI Agents - Listen for persisted agentic messages -CometChat.addMessageListener("LISTENER_ID", { - onAIAssistantMessageReceived: (msg) => console.log("Assistant reply:", msg), - onAIToolResultReceived: (msg) => console.log("Tool result:", msg), - onAIToolArgumentsReceived: (msg) => console.log("Tool args:", msg) -}); - -// AI Moderation - Check message status -CometChat.sendMessage(textMessage).then(message => { - const status = message.getModerationStatus(); - // CometChat.ModerationStatus.PENDING | APPROVED | DISAPPROVED -}); -``` - -**Prerequisites:** SDK initialized, user logged in, AI features enabled in [CometChat Dashboard](https://app.cometchat.com) - - | Field | Value | diff --git a/sdk/javascript/troubleshooting.mdx b/sdk/javascript/troubleshooting.mdx index e3f2b2023..7b2c19505 100644 --- a/sdk/javascript/troubleshooting.mdx +++ b/sdk/javascript/troubleshooting.mdx @@ -19,16 +19,6 @@ description: "Common failure modes and fixes for the CometChat JavaScript SDK." **Need help?** [Open a support ticket](https://help.cometchat.com/hc/en-us/requests/new) - - -| Field | Value | -| --- | --- | -| Page type | Troubleshooting reference | -| Scope | All CometChat JavaScript SDK issues — initialization, authentication, messaging, groups, calling, WebSocket, extensions, AI features | -| When to reference | When SDK methods fail, data is missing, real-time events don't fire, or features don't work as expected | - - - ## Initialization and Setup | Symptom | Cause | Fix | From 16f4a36b60e53e4ae603924e9c08fca2fd9ea226 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 18 Mar 2026 19:57:37 +0530 Subject: [PATCH 39/43] Update troubleshooting.mdx --- sdk/javascript/troubleshooting.mdx | 304 +++++++++-------------------- 1 file changed, 97 insertions(+), 207 deletions(-) diff --git a/sdk/javascript/troubleshooting.mdx b/sdk/javascript/troubleshooting.mdx index 7b2c19505..ce02a53ff 100644 --- a/sdk/javascript/troubleshooting.mdx +++ b/sdk/javascript/troubleshooting.mdx @@ -4,275 +4,165 @@ sidebarTitle: "Troubleshooting" description: "Common failure modes and fixes for the CometChat JavaScript SDK." --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Troubleshooting Reference** +Find solutions to common issues when building with the CometChat JavaScript SDK. -| Common Issue | Quick Fix | -| --- | --- | +## Quick Reference + +| Issue | Fix | +|-------|-----| | `init()` fails | Verify App ID and Region from [Dashboard](https://app.cometchat.com) | | Login fails with "UID not found" | Create user via Dashboard or REST API first | | SDK methods fail | Ensure `init()` completes before calling other methods | | No real-time events | Check WebSocket connection, verify listeners registered | | SSR errors | Use dynamic imports or `useEffect` for client-side only | -**Need help?** [Open a support ticket](https://help.cometchat.com/hc/en-us/requests/new) - - -## Initialization and Setup - -| Symptom | Cause | Fix | -| --- | --- | --- | -| `init()` fails with "App ID not found" | Invalid App ID or Region | Verify your App ID and Region match the [CometChat Dashboard](https://app.cometchat.com) → API & Auth Keys | -| `init()` fails silently | Missing or incorrect credentials | Double-check App ID, Region, and ensure they're strings, not undefined | -| SDK methods fail with "CometChat not initialized" | `init()` not called or not awaited | Ensure `init()` resolves successfully before calling `login()`, `sendMessage()`, or registering listeners | -| `init()` works but nothing else does | Wrong SDK version or corrupted install | Run `npm install @cometchat/chat-sdk-javascript@latest` to reinstall | - --- -## Authentication +## Initialization & Authentication | Symptom | Cause | Fix | -| --- | --- | --- | -| Login fails with "UID not found" | User doesn't exist in CometChat | Create the user via [Dashboard](https://app.cometchat.com) (testing) or [REST API](https://api-explorer.cometchat.com/reference/creates-user) (production) first | -| Login fails with "Auth Key is not valid" | Wrong Auth Key | Verify Auth Key matches [Dashboard](https://app.cometchat.com) → API & Auth Keys. Don't confuse with REST API Key | -| Login fails with "App not found" | `init()` not completed or wrong App ID | Ensure `init()` completes before `login()`. Verify App ID and Region | -| `getLoggedinUser()` returns null after refresh | Session not persisted or `init()` not called | Call `init()` on every app load before checking `getLoggedinUser()`. Browser storage clearing also clears sessions | -| Auth Token expired | Token has a limited lifetime | Generate a new Auth Token from your server using the [REST API](https://api-explorer.cometchat.com/reference/create-authtoken) | -| Login works but user appears offline | Presence subscription not configured | Use `subscribePresenceForAllUsers()` or appropriate presence method in `AppSettingsBuilder` | +|---------|-------|-----| +| `init()` fails with "App ID not found" | Invalid App ID or Region | Verify credentials in [Dashboard](https://app.cometchat.com) → API & Auth Keys | +| `init()` fails silently | Missing credentials | Double-check App ID and Region are strings, not undefined | +| "CometChat not initialized" | `init()` not awaited | Ensure `init()` resolves before calling other methods | +| Login fails with "UID not found" | User doesn't exist | Create user via [Dashboard](https://app.cometchat.com) or [REST API](https://api-explorer.cometchat.com/reference/creates-user) | +| Login fails with "Auth Key is not valid" | Wrong Auth Key | Verify Auth Key in Dashboard. Don't confuse with REST API Key | +| `getLoggedinUser()` returns null | Session cleared or `init()` not called | Call `init()` on every app load before checking session | +| Auth Token expired | Token lifetime exceeded | Generate new token via [REST API](https://api-explorer.cometchat.com/reference/create-authtoken) | +| User appears offline after login | Presence not configured | Use `subscribePresenceForAllUsers()` in `AppSettingsBuilder` | --- ## Messaging | Symptom | Cause | Fix | -| --- | --- | --- | -| `sendMessage()` fails | User not logged in or invalid receiver | Ensure `login()` completes before sending. Verify receiver UID/GUID exists | -| Messages sent but not received | Message listener not registered | Register `CometChat.addMessageListener()` with `onTextMessageReceived` callback | -| Duplicate messages received | Multiple listeners with same ID | Use unique listener IDs. Remove old listeners before adding new ones | -| Messages not appearing in conversation | Wrong receiver type | Use `CometChat.RECEIVER_TYPE.USER` for 1:1 and `CometChat.RECEIVER_TYPE.GROUP` for groups | -| Media message upload fails | File too large or unsupported format | Check file size limits. Supported formats: images (PNG, JPG, GIF), videos (MP4), audio (MP3, WAV) | -| `onTextMessageReceived` not firing | Listener registered after message sent | Register listeners immediately after `login()` completes | -| Custom message not received | Missing handler | Ensure the receiver has an `onCustomMessageReceived` handler registered | -| Metadata not appearing | Set after send | Use `setMetadata()` before calling the send method, not after | -| Quoted message fails | Invalid message ID | Verify the quoted message ID exists and belongs to the same conversation | -| No messages returned from filter | Conflicting filters | Simplify filters and add them one at a time to isolate the issue | -| Missing message types | Category mismatch | Ensure the category matches the type (e.g., category `"message"` for type `"text"`) | -| Pagination not working | New request object | Reuse the same `MessagesRequest` object for `fetchPrevious()` / `fetchNext()` calls | -| Thread replies included | Missing filter | Add `.hideReplies(true)` to exclude thread messages from the main conversation | -| Deleted messages showing | Missing filter | Add `.hideDeletedMessages(true)` to filter them out | -| Thread replies appearing in main chat | Missing filter | Add `.hideReplies(true)` to your `MessagesRequestBuilder` | -| Missing thread messages | Wrong parent ID | Verify `setParentMessageId()` uses the correct parent message ID | -| Empty thread | Deleted parent | The parent message may have been deleted. Handle this case gracefully in your UI | +|---------|-------|-----| +| `sendMessage()` fails | Not logged in or invalid receiver | Ensure `login()` completes. Verify receiver UID/GUID exists | +| Messages sent but not received | Listener not registered | Register `addMessageListener()` with `onTextMessageReceived` | +| Duplicate messages | Multiple listeners | Use unique listener IDs. Remove old listeners first | +| Wrong conversation | Wrong receiver type | Use `RECEIVER_TYPE.USER` for 1:1, `RECEIVER_TYPE.GROUP` for groups | +| Media upload fails | File too large or unsupported | Check limits. Supported: PNG, JPG, GIF, MP4, MP3, WAV | +| Metadata not appearing | Set after send | Call `setMetadata()` before the send method | +| Pagination not working | New request object | Reuse the same `MessagesRequest` for `fetchPrevious()`/`fetchNext()` | +| Thread replies in main chat | Missing filter | Add `.hideReplies(true)` to `MessagesRequestBuilder` | +| Deleted messages showing | Missing filter | Add `.hideDeletedMessages(true)` | --- ## Groups | Symptom | Cause | Fix | -| --- | --- | --- | -| Cannot join group | Group doesn't exist or wrong GUID | Verify GUID. Create group first if it doesn't exist | -| Cannot send message to group | User not a member | Join the group first using `CometChat.joinGroup()` | -| Group members not loading | Insufficient permissions | Only group members can fetch member list. Ensure user has joined | -| Cannot kick/ban members | User lacks admin/moderator scope | Only admins and moderators can kick/ban. Check user's scope in the group | -| Group creation fails | Missing required fields | Ensure GUID, name, and group type are provided | -| Can't join private group | Requires admin invite | Private groups require an admin to add you. Use `joinGroup()` only for public or password-protected groups | -| Owner can't leave group | Ownership not transferred | Transfer ownership first using `transferGroupOwnership()`, then call `leaveGroup()` | -| Group not appearing in list | Not a member | Verify you're a member of the group. Use `getJoinedGroups()` to fetch only groups you've joined | -| Password group join fails | Wrong password | Ensure the password is correct and passed as the second parameter to `joinGroup()` | -| Empty group list returned | Permission issue | Ensure the logged-in user has the correct permissions. Private groups only appear if the user is a member | -| `fetchNext()` returns same results | New request object | You're likely creating a new `GroupsRequest` object each time. Reuse the same instance | -| `getGroup()` fails with "Group not found" | Invalid GUID or deleted | Verify the GUID is correct and the group hasn't been deleted. Password/private groups require membership | -| Online member count returns 0 | Not a member | The user must be a member of the group. Also confirm the GUIDs array is not empty | -| Search not returning expected results | Partial match issue | `setSearchKeyword()` matches against the group name. Ensure the keyword is spelled correctly | -| Empty member list returned | Not a member | Verify the GUID is correct and the logged-in user is a member of the group | -| Scope filter returns no results | Invalid scope strings | Valid values are `"admin"`, `"moderator"`, and `"participant"` | -| Status filter not working | Wrong constant | Use `CometChat.USER_STATUS.ONLINE` or `CometChat.USER_STATUS.OFFLINE` constants, not raw strings | -| "ERR_NOT_A_MEMBER" when adding members | Insufficient permissions | Only admins or moderators can add members. Verify the logged-in user has the correct scope | -| Some members fail while others succeed | Per-user errors | `addMembersToGroup()` returns per-user results. Check the response object for individual error messages | -| `onMemberAddedToGroup` not firing | Listener not registered | Ensure the group listener is registered before the add operation | -| Cannot demote another admin | Not owner | Only the group owner can demote admins. Regular admins can only change scope of moderators and participants | -| `onGroupMemberScopeChanged` not firing | Listener not registered | Ensure the group listener is registered before the scope change | -| Scope change succeeds but UI doesn't update | Manual update needed | The API call returns a boolean. You need to manually update your local member list | -| Invalid scope value error | Raw strings used | Use the SDK constants (`CometChat.GROUP_MEMBER_SCOPE.ADMIN`, etc.) rather than raw strings | -| Kicked user can still see the group | Kick vs ban | Kicking removes the user but doesn't prevent rejoining. Use `banGroupMember()` instead | -| Banned user can rejoin | Wrong method used | Verify you called `banGroupMember()` and not `kickGroupMember()` | -| `onGroupMemberBanned` not firing | Listener not registered | Ensure the group listener is registered before the ban operation | -| Unban fails with error | User not banned | Verify the user is actually banned in the group by fetching the banned members list | -| Transfer fails with "User not found" | Invalid UID | The target UID must be an existing member of the group | -| Owner still can't leave after transfer | Transfer not complete | Ensure the `transferGroupOwnership()` promise resolved successfully before calling `leaveGroup()` | -| New owner doesn't have admin privileges | UI not updated | After ownership transfer, the new owner automatically gets the owner role. Re-fetch the group details | +|---------|-------|-----| +| Cannot join group | Invalid GUID | Verify GUID. Create group first if needed | +| Cannot send to group | Not a member | Join group first with `joinGroup()` | +| Cannot kick/ban members | Insufficient scope | Only admins and moderators can kick/ban | +| Can't join private group | Requires invite | Private groups require admin to add you | +| Owner can't leave | Ownership not transferred | Call `transferGroupOwnership()` first | +| Password join fails | Wrong password | Pass correct password as second parameter | +| `fetchNext()` returns same results | New request object | Reuse the same `GroupsRequest` instance | +| Scope filter returns nothing | Invalid strings | Use `"admin"`, `"moderator"`, `"participant"` | +| Status filter not working | Wrong constant | Use `CometChat.USER_STATUS.ONLINE`/`OFFLINE` | +| Cannot demote admin | Not owner | Only group owner can demote admins | +| Kicked user can still see group | Kick vs ban | Use `banGroupMember()` to prevent rejoining | --- ## Calling | Symptom | Cause | Fix | -| --- | --- | --- | -| Calls SDK not found | Package not installed | Run `npm install @cometchat/calls-sdk-javascript` | -| No audio/video | Browser permissions denied | Check browser permissions for camera and microphone. User must grant access | -| Call not connecting | Session ID mismatch or SDK not initialized | Verify both participants use same session ID. Initialize Calls SDK before starting | -| One-way audio | Firewall or NAT blocking WebRTC | CometChat uses TURN servers, but corporate networks may block WebRTC traffic | -| Poor call quality | Network bandwidth issues | Check connection stability. Consider audio-only fallback for poor connections | -| Call buttons not appearing | Calls SDK not detected | Ensure `@cometchat/calls-sdk-javascript` is installed — UI Kit auto-detects it | -| Incoming call not showing | Call listener not registered | Register `CometChat.addCallListener()` at app root level | -| Presentation doesn't start | Invalid token or missing element | Ensure you've generated a valid call token and the HTML element exists in the DOM before calling `joinPresentation()` | -| Viewer can send audio/video | Wrong role | Verify `setIsPresenter(false)` is set for viewers. Viewers should not have outgoing streams | -| `onUserJoined` not firing | Listener not registered | Ensure the call event listener is registered before joining the presentation | -| Black screen after joining | Element not visible | Check that the HTML element passed to `joinPresentation()` is visible and has proper dimensions | -| More than 5 presenters needed | Limit reached | Presenter Mode supports a maximum of 5 presenters. Consider using a standard group call | -| CSS changes not applying | Specificity issue | The SDK may use inline styles or higher-specificity selectors. Try adding `!important` | -| Layout breaks after customization | Container resized | You may have resized the grid container or applied conflicting `display` or `position` properties | -| Styles only work in one mode | Mode-specific classes | Some CSS classes are mode-specific. Test in `DEFAULT`, `TILE`, and `SPOTLIGHT` modes | -| Muted button styles not showing | Wrong class | Use the `-muted` variant classes (e.g., `cc-audio-icon-container-muted`) for muted state styling | -| Custom styles disappear on SDK update | Class names changed | If the SDK updates internal class names, your custom CSS may stop working. Pin your SDK version | - ---- - -## WebSocket and Connection - -| Symptom | Cause | Fix | -| --- | --- | --- | -| Real-time events not received | WebSocket disconnected | Check `CometChat.getConnectionStatus()`. Reconnect if needed | -| WebSocket connection fails | Firewall blocking WebSocket | Check network configuration. Corporate firewalls may block WebSocket connections | -| Connection drops frequently | Network instability | Implement reconnection logic. Use `CometChat.addConnectionListener()` to monitor status | -| Events delayed or batched | Network latency | This is expected on slow connections. Events are delivered in order | -| `autoEstablishSocketConnection` not working | Set to `false` in AppSettings | If managing connections manually, call `CometChat.connect()` explicitly | -| Listener never fires | Registered before init | Ensure you register the listener after a successful `CometChat.init()` call | -| Stuck in "connecting" state | Network or config issue | Check your network connection and firewall settings. Verify `appId` and `region` are correct | -| Frequent disconnections | Network instability | The SDK automatically reconnects, but check for WebSocket-blocking proxies or VPNs | -| `getConnectionStatus()` returns `undefined` | SDK not initialized | The SDK hasn't been initialized yet. Call `CometChat.init()` first | -| Multiple `onConnected` callbacks | Multiple listeners | You likely have multiple listeners registered with different IDs. Remove old listeners | -| No real-time events after login | Auto-connect disabled | If you set `autoEstablishSocketConnection(false)`, you must call `CometChat.connect()` manually | -| `connect()` doesn't seem to work | Not logged in | Ensure the user is logged in first. `connect()` requires an authenticated session | -| Events stop after calling `disconnect()` | Expected behavior | Call `CometChat.connect()` to resume receiving events | -| `autoEstablishSocketConnection(false)` not taking effect | Set after init | Make sure you're passing it to the `AppSettingsBuilder` before calling `CometChat.init()` | +|---------|-------|-----| +| Calls SDK not found | Not installed | Run `npm install @cometchat/calls-sdk-javascript` | +| No audio/video | Permissions denied | Check browser permissions for camera/microphone | +| Call not connecting | Session ID mismatch | Verify both participants use same session ID | +| One-way audio | Firewall blocking WebRTC | Check network config. Corporate networks may block WebRTC | +| Incoming call not showing | Listener not registered | Register `addCallListener()` at app root level | +| Black screen after joining | Element not visible | Ensure HTML element has proper dimensions | +| CSS changes not applying | Specificity issue | Try adding `!important` | +| Styles only work in one mode | Mode-specific classes | Test in `DEFAULT`, `TILE`, and `SPOTLIGHT` modes | --- -## Extensions and AI Features +## WebSocket & Connection | Symptom | Cause | Fix | -| --- | --- | --- | -| AI features not appearing | Feature not enabled in Dashboard | Enable the specific AI feature from [Dashboard](https://app.cometchat.com) → AI Features | -| AI Agents not responding | Agent not configured or text message not sent | Configure Agent in Dashboard. Agents only respond to text messages | -| `onAIAssistantEventReceived` not firing | Listener not registered after login | Register `AIAssistantListener` after successful `init()` and `login()` | -| Moderation status always PENDING | Moderation rules not configured | Configure moderation rules in Dashboard → Moderation → Rules | -| Extension feature not appearing | Extension not activated | Enable the extension from [Dashboard](https://app.cometchat.com) → Extensions | -| Stickers/Polls not showing | Extension not enabled | Activate Stickers or Polls extension in Dashboard | -| `onMessageModerated` never fires | Moderation not enabled | Ensure moderation is enabled in the CometChat Dashboard and rules are configured | -| All messages show `PENDING` but never resolve | Rules not configured | Check that your moderation rules are properly configured and the moderation service is active | -| Custom messages not being moderated | Unsupported type | AI Moderation only supports Text, Image, and Video messages. Custom messages are not moderated | -| Moderation status is `undefined` | Old SDK version | You may be using an older SDK version. Update to the latest version | -| Disapproved messages still visible | UI not updated | Verify your `onMessageModerated` handler is updating the UI correctly | -| Agentic messages not arriving | Wrong listener | These come via `MessageListener` after the run completes. Register `onAIAssistantMessageReceived` | -| Duplicate AI events | Multiple listeners | Check that you're not registering multiple listeners with different IDs | -| Streaming events arrive but no final message | Run failed | The run may have failed. Check for error events in the `onAIAssistantEventReceived` callback | - ---- - -## SSR / Framework-Specific - -| Symptom | Cause | Fix | -| --- | --- | --- | -| SSR hydration error | CometChat uses browser APIs (`window`, `WebSocket`) | Wrap in `useEffect` or use dynamic import with `ssr: false`. See [SSR examples](/sdk/javascript/overview#server-side-rendering-ssr-compatibility) | -| "window is not defined" in Next.js | SDK accessed during server render | Use dynamic imports: `const CometChat = (await import('@cometchat/chat-sdk-javascript')).CometChat` | -| "document is not defined" in Nuxt | SDK accessed during server render | Import SDK in `mounted()` lifecycle hook, not at module level | -| Astro components fail | SSR tries to render on server | Use `client:only="react"` directive for CometChat components | -| React Native errors | Wrong SDK | Use `@cometchat/chat-sdk-react-native` for React Native, not the JavaScript SDK | +|---------|-------|-----| +| Real-time events not received | WebSocket disconnected | Check `getConnectionStatus()`. Reconnect if needed | +| WebSocket fails | Firewall blocking | Check network config. Corporate firewalls may block WebSocket | +| Connection drops frequently | Network instability | Use `addConnectionListener()` to monitor and reconnect | +| Stuck in "connecting" | Network or config issue | Verify network, `appId`, and `region` | +| No events after login | Auto-connect disabled | Call `CometChat.connect()` manually if `autoEstablishSocketConnection(false)` | +| `connect()` doesn't work | Not logged in | Ensure user is logged in first | --- ## Listeners | Symptom | Cause | Fix | -| --- | --- | --- | -| Events not firing | Listeners registered before init | Ensure listeners are registered after a successful `CometChat.init()` and `login()` | -| Duplicate events received | Multiple listeners | You likely have multiple listeners registered with the same or different IDs. Remove old listeners | -| Missing events after page navigation | Listeners removed | Listeners are removed when the component unmounts. Re-register them when the new component mounts | -| `onMessagesDelivered` / `onMessagesRead` not triggering | Receipts not sent | Delivery and read receipts must be explicitly sent by the recipient using `markAsDelivered()` / `markAsRead()` | -| Call events not received | Call listener not registered | Ensure you've registered a `CallListener` and that the CometChat Calling SDK is properly initialized | - ---- - -## Typing Indicators - -| Symptom | Cause | Fix | -| --- | --- | --- | -| Typing indicator not showing | Listener not registered | Verify `addMessageListener()` is called before typing starts | -| Indicator stuck on "typing" | `endTyping()` not called | Ensure `endTyping()` is called on message send, input blur, or after a timeout (3-5 seconds) | -| Multiple typing events firing | Duplicate listeners | Use unique listener IDs and remove listeners on component unmount | -| Wrong user shown typing | Wrong receiver ID | Verify the `receiverId` matches the current conversation's UID or GUID | +|---------|-------|-----| +| Events not firing | Registered before init | Register after `init()` and `login()` complete | +| Duplicate events | Multiple listeners | Remove old listeners before adding new ones | +| Missing events after navigation | Listeners removed | Re-register when new component mounts | +| Receipt events not triggering | Receipts not sent | Call `markAsDelivered()`/`markAsRead()` explicitly | --- -## Delivery & Read Receipts +## Typing, Receipts & Reactions | Symptom | Cause | Fix | -| --- | --- | --- | -| Receipts not updating | Missing handlers | Verify `addMessageListener()` includes receipt handlers (`onMessagesDelivered`, `onMessagesRead`) | -| Double-tick not showing | `markAsDelivered()` not called | Call `markAsDelivered()` on message fetch and real-time receive. It won't happen automatically | -| Read status not syncing | Parameter errors | Use the message object overload for `markAsRead()` for simpler implementation | -| Group receipts missing | Feature not enabled | Enable "Enhanced Messaging Status" in the [CometChat Dashboard](https://app.cometchat.com) | +|---------|-------|-----| +| Typing indicator stuck | `endTyping()` not called | Call on send, blur, or after 3-5s timeout | +| Double-tick not showing | `markAsDelivered()` not called | Call on message fetch and real-time receive | +| Group receipts missing | Feature not enabled | Enable "Enhanced Messaging Status" in Dashboard | +| Reaction not appearing | UI not synced | Call `updateMessageWithReactionInfo()` on events | +| Duplicate reactions | No check before adding | Use `getReactedByMe()` first | --- -## Reactions +## AI Features | Symptom | Cause | Fix | -| --- | --- | --- | -| Reaction not appearing | UI not synced | Call `updateMessageWithReactionInfo()` on real-time events to keep the UI in sync | -| Duplicate reactions | No check before adding | Use `getReactedByMe()` to check if the user already reacted before adding | -| Reactions out of sync | Missing handlers | Ensure `onMessageReactionAdded` and `onMessageReactionRemoved` handlers are registered | -| Can't remove reaction | Wrong emoji string | Use the exact same emoji string that was used when adding the reaction | +|---------|-------|-----| +| AI features not appearing | Not enabled | Enable in [Dashboard](https://app.cometchat.com) → AI Features | +| AI Agents not responding | Not configured | Configure Agent in Dashboard. Agents only respond to text | +| `onAIAssistantEventReceived` not firing | Listener not registered | Register `AIAssistantListener` after login | +| Moderation always PENDING | Rules not configured | Configure rules in Dashboard → Moderation → Rules | +| Agentic messages not arriving | Wrong listener | Use `MessageListener` with `onAIAssistantMessageReceived` | --- -## Mentions - -| Symptom | Cause | Fix | -| --- | --- | --- | -| Mention not parsed | Wrong format | Use the `<@uid:UID>` format exactly. Any deviation will prevent parsing | -| `getMentionedUsers()` returns empty | Local message | This only works on messages received from the server, not locally constructed messages | -| Missing user tags | Not requested | Add `mentionsWithTagInfo(true)` to your request builder | -| Blocked info missing | Not requested | Add `mentionsWithBlockedInfo(true)` to your request builder | - ---- - -## Conversations +## SSR / Framework-Specific | Symptom | Cause | Fix | -| --- | --- | --- | -| Conversation still visible after deletion | UI not updated | Refresh the conversation list after deletion. Update your UI immediately on success | -| Delete fails | Invalid ID | Verify the UID or GUID exists and is correct | -| Other user still sees messages | Local deletion only | The SDK deletes for the logged-in user only. Use the REST API to delete for all participants | -| "Conversation not found" error | Already deleted or wrong type | The conversation may already be deleted, or the `conversationType` doesn't match | +|---------|-------|-----| +| "window is not defined" | SDK accessed during SSR | Use dynamic imports or `useEffect` | +| Next.js SSR error | Server render | Use `await import('@cometchat/chat-sdk-javascript')` | +| Nuxt "document is not defined" | Server render | Import in `mounted()` lifecycle hook | +| React Native errors | Wrong SDK | Use `@cometchat/chat-sdk-react-native` | --- ## Upgrading from V3 | Symptom | Cause | Fix | -| --- | --- | --- | -| "Module not found" errors after upgrade | Old import paths | Search your project for `@cometchat-pro/chat` and replace with `@cometchat/chat-sdk-javascript` | -| Calls SDK not working | Wrong package name | The calls SDK package name also changed. Use `@cometchat/calls-sdk-javascript` | -| TypeScript type errors | Type definitions changed | Some type definitions may have changed. Check the [changelog](https://github.com/cometchat/chat-sdk-javascript/releases) | -| Both v3 and v4 installed | Package conflict | Having both versions can cause conflicts. Remove the v3 package completely before installing v4 | +|---------|-------|-----| +| "Module not found" | Old import paths | Replace `@cometchat-pro/chat` with `@cometchat/chat-sdk-javascript` | +| Calls SDK not working | Wrong package | Use `@cometchat/calls-sdk-javascript` | +| Both versions installed | Package conflict | Remove v3 package completely | --- -## Common Error Codes +## Error Codes -| Error Code | Description | Resolution | -| --- | --- | --- | -| `ERR_UID_NOT_FOUND` | User with specified UID doesn't exist | Create user via Dashboard or REST API | -| `ERR_AUTH_KEY_NOT_FOUND` | Invalid Auth Key | Verify Auth Key from Dashboard | -| `ERR_APP_NOT_FOUND` | Invalid App ID or Region | Check App ID and Region in Dashboard | -| `ERR_NOT_LOGGED_IN` | No active user session | Call `login()` before SDK operations | -| `ERR_GUID_NOT_FOUND` | Group with specified GUID doesn't exist | Create group or verify GUID | -| `ERR_NOT_A_MEMBER` | User is not a member of the group | Join group before sending messages | -| `ERR_BLOCKED` | User is blocked | Unblock user via Dashboard or SDK | -| `ERR_RATE_LIMIT_EXCEEDED` | Too many requests | Implement rate limiting. See [Rate Limits](/articles/rate-limits) | +| Code | Description | Resolution | +|------|-------------|------------| +| `ERR_UID_NOT_FOUND` | User doesn't exist | Create user via Dashboard or REST API | +| `ERR_AUTH_KEY_NOT_FOUND` | Invalid Auth Key | Verify in Dashboard | +| `ERR_APP_NOT_FOUND` | Invalid App ID or Region | Check Dashboard | +| `ERR_NOT_LOGGED_IN` | No active session | Call `login()` first | +| `ERR_GUID_NOT_FOUND` | Group doesn't exist | Create group or verify GUID | +| `ERR_NOT_A_MEMBER` | Not a group member | Join group first | +| `ERR_BLOCKED` | User is blocked | Unblock via Dashboard or SDK | +| `ERR_RATE_LIMIT_EXCEEDED` | Too many requests | See [Rate Limits](/articles/rate-limits) | --- @@ -282,11 +172,11 @@ description: "Common failure modes and fixes for the CometChat JavaScript SDK." Installation and initialization guide - - Login methods and session management + + Recommended patterns and practices - AI Agents, Moderation, and Copilot features + AI Agents, Moderation, and Copilot Open a support ticket From 09c4729cf95a63f4f517b8ffe8b78d3b41491b25 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 18 Mar 2026 20:35:31 +0530 Subject: [PATCH 40/43] Update interactive-messages.mdx --- sdk/javascript/interactive-messages.mdx | 588 ++++++++++++++++++------ 1 file changed, 440 insertions(+), 148 deletions(-) diff --git a/sdk/javascript/interactive-messages.mdx b/sdk/javascript/interactive-messages.mdx index c3101a09c..4937ced4f 100644 --- a/sdk/javascript/interactive-messages.mdx +++ b/sdk/javascript/interactive-messages.mdx @@ -4,238 +4,530 @@ sidebarTitle: "Interactive Messages" description: "Send and receive interactive messages with embedded forms, buttons, and other UI elements using the CometChat JavaScript SDK." --- -{/* TL;DR for Agents and Quick Reference */} - + + +| Component | Description | +| --- | --- | +| `InteractiveMessage` | Message containing interactive UI elements (forms, buttons, etc.) | +| `InteractionGoal` | Defines the desired outcome of user interactions | +| `Interaction` | Represents a single user action on an interactive element | ```javascript -// Send an interactive message +// Create and send an interactive form const interactiveMessage = new CometChat.InteractiveMessage( - receiverId, receiverType, "form", interactiveData + receiverId, + receiverType, + "form", + interactiveData ); await CometChat.sendInteractiveMessage(interactiveMessage); // Listen for interactive messages -CometChat.addMessageListener("interactive", new CometChat.MessageListener({ - onInteractiveMessageReceived: (message) => { }, - onInteractionGoalCompleted: (receipt) => { } +CometChat.addMessageListener("LISTENER_ID", new CometChat.MessageListener({ + onInteractiveMessageReceived: (message) => console.log("Received:", message), + onInteractionGoalCompleted: (receipt) => console.log("Goal completed:", receipt) })); ``` -An InteractiveMessage is a specialised object that encapsulates an interactive unit within a chat message, such as an embedded form that users can fill out directly within the chat interface. This enhances user engagement by making the chat experience more interactive and responsive to user input. +Interactive messages embed UI elements like forms, buttons, and dropdowns directly within chat messages. Users can interact with these elements without leaving the conversation, enabling surveys, quick actions, and data collection. ## InteractiveMessage -[`InteractiveMessage`](/sdk/reference/messages#interactivemessage) is a chat message with embedded interactive content. It can contain various properties: +The [`InteractiveMessage`](/sdk/reference/messages#interactivemessage) class represents a message with embedded interactive content. -| Parameter | Description | Required | -| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------- | -| receiverId | The UID or GUID of the recipient | Yes | -| receiverType | The type of the receiver to whom the message is to be sent i.e CometChatConstants.RECEIVER\_TYPE\_USER (user) or CometChatConstants.RECEIVER\_TYPE\_GROUP (group) | Yes | -| messageType | The type of the message that needs to be sent | Yes | -| interactiveData | A JSONObject holding structured data for the interactive element. | Yes | -| allowSenderInteraction | A boolean determining whether the message sender can interact with the message by default it is set to false. | Optional (Default: false) | -| interactionGoal | An InteractionGoal object encapsulating the intended outcome of interacting with the InteractiveMessage by default it is set to none | Optional (Default: none) | +| Parameter | Type | Description | Required | +| --- | --- | --- | --- | +| `receiverId` | `string` | UID of user or GUID of group | Yes | +| `receiverType` | `string` | `CometChat.RECEIVER_TYPE.USER` or `GROUP` | Yes | +| `messageType` | `string` | Type identifier (e.g., `"form"`, `"card"`) | Yes | +| `interactiveData` | `Object` | JSON structure defining the interactive elements | Yes | +| `allowSenderInteraction` | `boolean` | Whether sender can interact with the message | No (default: `false`) | +| `interactionGoal` | `InteractionGoal` | Defines when the interaction is considered complete | No (default: `none`) | -## Interaction +## Send an Interactive Message -An `Interaction` represents a user action involved with an `InteractiveMessage`. It includes: +Use `sendInteractiveMessage()` to send an interactive message. -* `elementId`: An identifier for a specific interactive element. -* `interactedAt`: A timestamp indicating when the interaction occurred. + + +```javascript +let receiverId = "UID"; +let receiverType = CometChat.RECEIVER_TYPE.USER; + +let interactiveData = { + title: "Survey", + formFields: [ + { + elementType: "textInput", + elementId: "name", + optional: false, + label: "Name", + placeholder: { text: "Enter your name" } + }, + { + elementType: "textInput", + elementId: "age", + optional: true, + label: "Age", + maxLines: 1, + placeholder: { text: "Enter your age" } + }, + { + elementType: "dropdown", + elementId: "gender", + optional: false, + label: "Gender", + defaultValue: "male", + options: [ + { label: "Male", value: "male" }, + { label: "Female", value: "female" } + ] + }, + { + elementType: "Select", + elementId: "interests", + optional: true, + label: "Interests", + defaultValue: ["tech"], + options: [ + { label: "Technology", value: "tech" }, + { label: "Sports", value: "sports" }, + { label: "Music", value: "music" } + ] + } + ], + submitElement: { + elementType: "button", + elementId: "submitButton", + buttonText: "Submit", + disableAfterInteracted: true, + action: { + actionType: "urlNavigation", + url: "https://www.cometchat.com/" + } + } +}; -## Goal Completion +let interactiveMessage = new CometChat.InteractiveMessage( + receiverId, + receiverType, + "form", + interactiveData +); -A key feature of `InteractiveMessage` is checking whether a user's interactions with the message meet the defined `InteractionGoal` +CometChat.sendInteractiveMessage(interactiveMessage).then( + (message) => { + console.log("Interactive message sent successfully", message); + }, + (error) => { + console.log("Interactive message sending failed with error:", error); + } +); +``` + + +```typescript +let receiverId: string = "UID"; +let receiverType: string = CometChat.RECEIVER_TYPE.USER; + +let interactiveData: Object = { + title: "Survey", + formFields: [ + { + elementType: "textInput", + elementId: "name", + optional: false, + label: "Name", + placeholder: { text: "Enter your name" } + }, + { + elementType: "textInput", + elementId: "age", + optional: true, + label: "Age", + maxLines: 1, + placeholder: { text: "Enter your age" } + }, + { + elementType: "dropdown", + elementId: "gender", + optional: false, + label: "Gender", + defaultValue: "male", + options: [ + { label: "Male", value: "male" }, + { label: "Female", value: "female" } + ] + }, + { + elementType: "Select", + elementId: "interests", + optional: true, + label: "Interests", + defaultValue: ["tech"], + options: [ + { label: "Technology", value: "tech" }, + { label: "Sports", value: "sports" }, + { label: "Music", value: "music" } + ] + } + ], + submitElement: { + elementType: "button", + elementId: "submitButton", + buttonText: "Submit", + disableAfterInteracted: true, + action: { + actionType: "urlNavigation", + url: "https://www.cometchat.com/" + } + } +}; -You would be tracking every interaction users perform on an `InteractiveMessage` (captured as `Interaction` objects) and comparing those with the defined `InteractionGoal`. The completion of a goal can vary depending on the goal type: +let interactiveMessage: CometChat.InteractiveMessage = new CometChat.InteractiveMessage( + receiverId, + receiverType, + "form", + interactiveData +); -| Goals | Description | Keys | -| -------------------------------- | ---------------------------------------------------------------------- | --------------------------------------------- | -| **Any Interaction** | The goal is considered completed if there is at least one interaction. | CometChatConstants.INTERACTION\_TYPE\_ANY | -| **Any of Specific Interactions** | The goal is achieved if any of the specified interactions occurred. | CometChatConstants.INTERACTION\_TYPE\_ANY\_OF | -| **All of Specific Interactions** | The goal is completed when all specified interactions occur. | CometChatConstants.INTERACTION\_TYPE\_ALL\_OF | -| **None** | The goal is never completed. | CometChatConstants.INTERACTION\_TYPE\_NONE | +CometChat.sendInteractiveMessage(interactiveMessage).then( + (message: CometChat.InteractiveMessage) => { + console.log("Interactive message sent successfully", message); + }, + (error: CometChat.CometChatException) => { + console.log("Interactive message sending failed with error:", error); + } +); +``` + + -This user interaction tracking mechanism provides a flexible and efficient way to monitor user engagement within an interactive chat session. By defining clear interaction goals and checking user interactions against these goals, you can manage user engagement and improve the overall chat experience in your CometChat-enabled application. +On success, `sendInteractiveMessage()` returns an [`InteractiveMessage`](/sdk/reference/messages#interactivemessage) object. -## InteractionGoal +| Field | Getter | Return Type | Description | +| --- | --- | --- | --- | +| interactiveData | `getInteractiveData()` | `Object` | The structured JSON data for the interactive element | +| interactionGoal | `getInteractionGoal()` | [`InteractionGoal`](/sdk/reference/auxiliary#interactiongoal) | The intended outcome of interacting with the message | +| interactions | `getInteractions()` | [`Interaction[]`](/sdk/reference/auxiliary#interaction) | List of user interactions performed on the message | +| allowSenderInteraction | `getIsSenderInteractionAllowed()` | `boolean` | Whether the sender can interact with the message | -The `InteractionGoal` represents the desired outcome of an interaction with an `InteractiveMessage`. It includes: +## Interactive Elements -* `elementIds`: A list of identifiers for the interactive elements. -* `type`: The type of interaction goal from the `CometChatConstants`. +The `interactiveData` object defines the UI elements. Common element types: -## Sending InteractiveMessages +| Element Type | Description | +| --- | --- | +| `textInput` | Single or multi-line text field | +| `dropdown` | Single-select dropdown menu | +| `Select` | Multi-select checkbox group | +| `button` | Clickable button with action | -The `InteractiveMessage` can be sent using the `sendInteractiveMessage` method of the `CometChat` class. The method requires an `InteractiveMessage` object and a `CallbackListener` for handling the response. +### Text Input -Here is an example of how to use it: +```javascript +{ + elementType: "textInput", + elementId: "name", + optional: false, + label: "Name", + maxLines: 1, // Optional: limit to single line + placeholder: { text: "Enter text here" } +} +``` - - -```js -const interactiveData = { -title: "Survey", -formFields: [ - { - elementType: "textInput", - elementId: "name", - optional: false, - label: "Name", - placeholder: { - text: "Enter text here" - } - }, - { - elementType: "textInput", - elementId: "age", - optional: true, - label: "Age", - maxLines: 1, - placeholder: { - text: "Enter text here" - } - }, - { - elementType: "Select", - elementId: "checkBox1", - optional: true, - label: "Check box element", - defaultValue: ["chk_option_2"], - options: [ - { - label: "Option 1", - value: "chk_option_1" - }, - { - label: "Option 2", - value: "chk_option_2" - } - ] - }, - { - elementType: "dropdown", - elementId: "gender", - optional: false, - label: "Gender", - defaultValue: "male", - options: [ - { - label: "Male", - value: "male" - }, - { - label: "Female", - value: "female" - } - ] - } -], -submitElement: { +### Dropdown (Single Select) + +```javascript +{ + elementType: "dropdown", + elementId: "country", + optional: false, + label: "Country", + defaultValue: "us", + options: [ + { label: "United States", value: "us" }, + { label: "United Kingdom", value: "uk" }, + { label: "Canada", value: "ca" } + ] +} +``` + +### Checkbox (Multi Select) + +```javascript +{ + elementType: "Select", + elementId: "preferences", + optional: true, + label: "Preferences", + defaultValue: ["email"], + options: [ + { label: "Email notifications", value: "email" }, + { label: "SMS notifications", value: "sms" }, + { label: "Push notifications", value: "push" } + ] +} +``` + +### Submit Button + +```javascript +{ elementType: "button", - elementId: "submitButton", + elementId: "submitBtn", buttonText: "Submit", - disableAfterInteracted: false, + disableAfterInteracted: true, action: { actionType: "urlNavigation", - url: "https://www.cometchat.com/" + url: "https://example.com/submit" } } -}; +``` +## Interaction Goals +An `InteractionGoal` defines when the user's interaction with the message is considered complete. Use this to track engagement and trigger follow-up actions. -const interactiveMessage = new CometChat.InteractiveMessage(receiverId,receiverType,"form", interactiveData); +| Goal Type | Constant | Description | +| --- | --- | --- | +| Any Interaction | `CometChat.GoalType.ANY_ACTION` | Complete when any element is interacted with | +| Any of Specific | `CometChat.GoalType.ANY_OF` | Complete when any of the specified elements is interacted with | +| All of Specific | `CometChat.GoalType.ALL_OF` | Complete when all specified elements are interacted with | +| None | `CometChat.GoalType.NONE` | Never considered complete (default) | +### Set an Interaction Goal -CometChat.sendInteractiveMessage(interactiveMessage) - .then((message: CometChat.InteractiveMessage) => { - // This block is executed when the InteractiveMessage is sent successfully. - }) - .catch((error: CometChat.CometChatException) => { - // This block is executed if an error occurs while sending the InteractiveMessage. - }); -``` + + +```javascript +let interactionGoal = new CometChat.InteractionGoal( + CometChat.GoalType.ALL_OF, + ["name", "gender", "submitButton"] +); + +let interactiveMessage = new CometChat.InteractiveMessage( + receiverId, + receiverType, + "form", + interactiveData +); +interactiveMessage.setInteractionGoal(interactionGoal); +CometChat.sendInteractiveMessage(interactiveMessage).then( + (message) => { + console.log("Interactive message sent successfully", message); + }, + (error) => { + console.log("Interactive message sending failed with error:", error); + } +); +``` + +```typescript +let interactionGoal: CometChat.InteractionGoal = new CometChat.InteractionGoal( + CometChat.GoalType.ALL_OF, + ["name", "gender", "submitButton"] +); + +let interactiveMessage: CometChat.InteractiveMessage = new CometChat.InteractiveMessage( + receiverId, + receiverType, + "form", + interactiveData +); +interactiveMessage.setInteractionGoal(interactionGoal); +CometChat.sendInteractiveMessage(interactiveMessage).then( + (message: CometChat.InteractiveMessage) => { + console.log("Interactive message sent successfully", message); + }, + (error: CometChat.CometChatException) => { + console.log("Interactive message sending failed with error:", error); + } +); +``` + -The `sendInteractiveMessage()` method returns an [`InteractiveMessage`](/sdk/reference/messages#interactivemessage) object. Access the response data using getter methods: +## Interactions -| Field | Getter | Return Type | Description | -|-------|--------|-------------|-------------| -| interactiveData | `getInteractiveData()` | `Object` | The structured JSON data for the interactive element | -| interactionGoal | `getInteractionGoal()` | [`InteractionGoal`](/sdk/reference/auxiliary#interactiongoal) | The intended outcome of interacting with the message | -| interactions | `getInteractions()` | [`Interaction[]`](/sdk/reference/auxiliary#interaction) | List of user interactions performed on the message | -| allowSenderInteraction | `getIsSenderInteractionAllowed()` | `boolean` | Whether the sender can interact with the message | +An `Interaction` represents a single user action on an interactive element. -## Event Listeners +| Property | Type | Description | +| --- | --- | --- | +| `elementId` | `string` | Identifier of the interacted element | +| `interactedAt` | `number` | Unix timestamp of the interaction | -CometChat SDK provides event listeners to handle real-time events related to `InteractiveMessage`. +## Mark as Interacted -## On InteractiveMessage Received +Use `markAsInteracted()` to record when a user interacts with an element. -The `onInteractiveMessageReceived` event listener is triggered when an `InteractiveMessage` is received. + + +```javascript +let messageId = 123; +let elementId = "submitButton"; -Here is an example: +CometChat.markAsInteracted(messageId, elementId).then( + (response) => { + console.log("Marked as interacted successfully", response); + }, + (error) => { + console.log("Failed to mark as interacted:", error); + } +); +``` + + +```typescript +let messageId: number = 123; +let elementId: string = "submitButton"; + +CometChat.markAsInteracted(messageId, elementId).then( + (response: string) => { + console.log("Marked as interacted successfully", response); + }, + (error: CometChat.CometChatException) => { + console.log("Failed to mark as interacted:", error); + } +); +``` + + + +## Real-Time Events + +Register a `MessageListener` to receive interactive message events. + +### Receive Interactive Messages -```js +```javascript +let listenerID = "UNIQUE_LISTENER_ID"; + CometChat.addMessageListener( - "UNIQUE_ID", + listenerID, new CometChat.MessageListener({ - onInteractiveMessageReceived: (message: CometChat.InteractiveMessage) => { - // This block is executed when an InteractiveMessage is received. - // Here you can define logic to handle the received InteractiveMessage and display it in your chat interface. - }, + onInteractiveMessageReceived: (message) => { + console.log("Interactive message received", message); + // Render the interactive UI based on message.getInteractiveData() + } }) ); ``` - + +```typescript +let listenerID: string = "UNIQUE_LISTENER_ID"; +CometChat.addMessageListener( + listenerID, + new CometChat.MessageListener({ + onInteractiveMessageReceived: (message: CometChat.InteractiveMessage) => { + console.log("Interactive message received", message); + // Render the interactive UI based on message.getInteractiveData() + } + }) +); +``` + -On Interaction Goal Completed - -The `onInteractionGoalCompleted` event listener is invoked when an interaction goal is achieved. +### Interaction Goal Completed -Here is an example: +Triggered when a user's interactions satisfy the defined `InteractionGoal`. -```js +```javascript +let listenerID = "UNIQUE_LISTENER_ID"; + CometChat.addMessageListener( - "UNIQUE_ID", + listenerID, new CometChat.MessageListener({ - onInteractionGoalCompleted: (receipt: CometChat.InteractionReceipt) => { - // This block is executed when an interaction goal is completed. - // Here you can specify the actions your application should take once an interaction goal is achieved, such as updating the UI or notifying the user. - }, + onInteractionGoalCompleted: (receipt) => { + console.log("Interaction goal completed", receipt); + // Handle goal completion (e.g., show confirmation, trigger next step) + } }) ); ``` - + +```typescript +let listenerID: string = "UNIQUE_LISTENER_ID"; +CometChat.addMessageListener( + listenerID, + new CometChat.MessageListener({ + onInteractionGoalCompleted: (receipt: CometChat.InteractionReceipt) => { + console.log("Interaction goal completed", receipt); + // Handle goal completion (e.g., show confirmation, trigger next step) + } + }) +); +``` + -These event listeners offer your application a way to provide real-time updates in response to incoming interactive messages and goal completions, contributing to a more dynamic and responsive user chat experience. - -Always remove message listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. +Always remove listeners when they're no longer needed to prevent memory leaks. ```javascript -CometChat.removeMessageListener("UNIQUE_ID"); +CometChat.removeMessageListener("UNIQUE_LISTENER_ID"); ``` -## Usage +## Allow Sender Interaction + +By default, the sender cannot interact with their own interactive message. Enable sender interaction: + + + +```javascript +let interactiveMessage = new CometChat.InteractiveMessage( + receiverId, + receiverType, + "form", + interactiveData +); +interactiveMessage.setIsSenderInteractionAllowed(true); -An InteractiveMessage is constructed with the receiver's UID, the receiver type, the interactive type, and interactive data as a JSONObject. Once created, the InteractiveMessage can be sent using CometChat's sendInteractiveMessage() method. Incoming InteractiveMessages can be received and processed via CometChat's message listener framework. +CometChat.sendInteractiveMessage(interactiveMessage).then( + (message) => { + console.log("Interactive message sent successfully", message); + }, + (error) => { + console.log("Interactive message sending failed with error:", error); + } +); +``` + + +```typescript +let interactiveMessage: CometChat.InteractiveMessage = new CometChat.InteractiveMessage( + receiverId, + receiverType, + "form", + interactiveData +); +interactiveMessage.setIsSenderInteractionAllowed(true); + +CometChat.sendInteractiveMessage(interactiveMessage).then( + (message: CometChat.InteractiveMessage) => { + console.log("Interactive message sent successfully", message); + }, + (error: CometChat.CometChatException) => { + console.log("Interactive message sending failed with error:", error); + } +); +``` + + --- From d521e59eabc089e0552ae6a0b66c90923667b2ef Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 18 Mar 2026 20:36:11 +0530 Subject: [PATCH 41/43] Update interactive-messages.mdx --- sdk/javascript/interactive-messages.mdx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/sdk/javascript/interactive-messages.mdx b/sdk/javascript/interactive-messages.mdx index 4937ced4f..db180414d 100644 --- a/sdk/javascript/interactive-messages.mdx +++ b/sdk/javascript/interactive-messages.mdx @@ -302,9 +302,10 @@ An `InteractionGoal` defines when the user's interaction with the message is con ```javascript +let elementIds = ["name", "gender", "submitButton"]; let interactionGoal = new CometChat.InteractionGoal( CometChat.GoalType.ALL_OF, - ["name", "gender", "submitButton"] + elementIds ); let interactiveMessage = new CometChat.InteractiveMessage( @@ -327,9 +328,10 @@ CometChat.sendInteractiveMessage(interactiveMessage).then( ```typescript +let elementIds: Array = ["name", "gender", "submitButton"]; let interactionGoal: CometChat.InteractionGoal = new CometChat.InteractionGoal( CometChat.GoalType.ALL_OF, - ["name", "gender", "submitButton"] + elementIds ); let interactiveMessage: CometChat.InteractiveMessage = new CometChat.InteractiveMessage( From 195ec6c5b323a1d6a378c99ca1c34d3321a66beb Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 18 Mar 2026 20:39:40 +0530 Subject: [PATCH 42/43] Update delivery-read-receipts.mdx --- sdk/javascript/delivery-read-receipts.mdx | 741 +++++++--------------- 1 file changed, 237 insertions(+), 504 deletions(-) diff --git a/sdk/javascript/delivery-read-receipts.mdx b/sdk/javascript/delivery-read-receipts.mdx index 4f26435c5..3d42ec12d 100644 --- a/sdk/javascript/delivery-read-receipts.mdx +++ b/sdk/javascript/delivery-read-receipts.mdx @@ -4,832 +4,565 @@ sidebarTitle: "Delivery & Read Receipts" description: "Mark messages as delivered, read, or unread and receive real-time receipt events using the CometChat JavaScript SDK." --- -{/* TL;DR for Agents and Quick Reference */} - + -```javascript -// Mark message as delivered (pass message object) -await CometChat.markAsDelivered(message); - -// Mark message as read (pass message object) -await CometChat.markAsRead(message); +| Method | Description | +| --- | --- | +| `markAsDelivered(message)` | Mark a message as delivered | +| `markAsRead(message)` | Mark a message as read | +| `markConversationAsDelivered(id, type)` | Mark entire conversation as delivered | +| `markConversationAsRead(id, type)` | Mark entire conversation as read | +| `markMessageAsUnread(message)` | Mark a message as unread | +| `getMessageReceipts(messageId)` | Get delivery/read receipts for a message | -// Mark entire conversation as read -await CometChat.markConversationAsRead("USER_UID", "user"); +```javascript +// Mark as delivered/read (pass message object) +CometChat.markAsDelivered(message); +CometChat.markAsRead(message); -// Mark message as unread -await CometChat.markMessageAsUnread(message); +// Mark entire conversation +CometChat.markConversationAsRead("UID", "user"); // Listen for receipt events -CometChat.addMessageListener("receipts", new CometChat.MessageListener({ +CometChat.addMessageListener("LISTENER_ID", new CometChat.MessageListener({ onMessagesDelivered: (receipt) => { }, onMessagesRead: (receipt) => { }, - onMessagesDeliveredToAll: (receipt) => { }, // Group only - onMessagesReadByAll: (receipt) => { } // Group only + onMessagesDeliveredToAll: (receipt) => { }, // Groups only + onMessagesReadByAll: (receipt) => { } // Groups only })); ``` -Delivery and read receipts let you track whether messages have been delivered to and read by recipients. This page covers marking messages as delivered, read, or unread, and receiving real-time receipt events. - -## Mark Messages as Delivered - -You can mark the messages for a particular conversation as read using the `markAsDelivered()` method. This method takes the below parameters as input: - -| Parameter | Information | -| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `messageId` | The ID of the message above which all the messages for a particular conversation are to be marked as read. | -| `receiverId` | In case of one to one conversation message's sender `UID` will be the receipt's receiver Id. In case of group conversation message's receiver Id will be the receipt's receiver Id. | -| `receiverType` | Type of the receiver. Could be either of the two values( user or group). | -| `senderId` | The `UID` of the sender of the message. | +Delivery and read receipts track whether messages have been delivered to and read by recipients. -Messages for both user & group conversations can be marked as read using this method. +## Mark as Delivered -Ideally, you would like to mark all the messages as delivered for any conversation when the user opens the chat window for that conversation. This includes two scenarios: +Use `markAsDelivered()` to mark messages as delivered. You can pass either a message object or individual parameters. -1. **When the list of messages for the conversation is fetched**: In this case you need to obtain the last message in the list of messages and pass the message ID of that message to the markAsDelivered() method. -2. **When the user is on the chat window and a real-time message is received:** In this case you need to obtain the message ID of the message and pass it to the markAsDelivered() method. +### Using Message Object - -```javascript -const messageId = "MESSAGE_ID"; -const receiverId = "MESSAGE_RECEIVER_UID"; -const receiverType = "user"; -const senderId = "MESSAGE_SENDER_UID"; -CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId); -``` - - - - + ```javascript -const messageId = "MESSAGE_ID"; -const receiverId = "MESSAGE_RECEIVER_GUID"; -const receiverType = "group"; -const senderId = "MESSAGE_SENDER_UID"; -CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId); -``` - - - - -```typescript -const messageId: string = "MESSAGE_ID"; -const receiverId: string = "MESSAGE_RECEIVER_UID"; -const receiverType: string = "user"; -const senderId: string = "MESSAGE_SENDER_UID"; -CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId); +CometChat.markAsDelivered(message).then( + () => { + console.log("Marked as delivered successfully"); + }, + (error) => { + console.log("Error marking as delivered:", error); + } +); ``` - - - + ```typescript -const messageId: string = "MESSAGE_ID"; -const receiverId: string = "MESSAGE_RECEIVER_GUID"; -const receiverType: string = "group"; -const senderId: string = "MESSAGE_SENDER_UID"; -CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId); +CometChat.markAsDelivered(message).then( + () => { + console.log("Marked as delivered successfully"); + }, + (error: CometChat.CometChatException) => { + console.log("Error marking as delivered:", error); + } +); ``` - - -This method will mark all the messages before the messageId specified, for the conversation with receiverId and receiverType(user/group) as delivered. +### Using Parameters -In case you would like to be notified of an error if the receipts fail to go through you can use `.then(successCallback, failureCallback)` of the `markAsDelivered` method. +| Parameter | Description | +| --- | --- | +| `messageId` | ID of the message to mark as delivered | +| `receiverId` | For user chats: sender's UID. For groups: group GUID | +| `receiverType` | `"user"` or `"group"` | +| `senderId` | UID of the message sender | ```javascript -CometChat.markAsDelivered( - message.getId(), - message.getSender().getUid(), - "user", - message.getSender().getUid() -).then( +let messageId = "MESSAGE_ID"; +let receiverId = "MESSAGE_SENDER_UID"; +let receiverType = "user"; +let senderId = "MESSAGE_SENDER_UID"; + +CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId).then( () => { - console.log("mark as delivered success."); + console.log("Marked as delivered successfully"); }, (error) => { - console.log( - "An error occurred when marking the message as delivered.", - error - ); + console.log("Error marking as delivered:", error); } ); ``` - - ```javascript -CometChat.markAsDelivered( - message.getId(), - message.getReceiverUid(), - "group", - message.getSender().getUid() -).then( - () => { - console.log("mark as delivered success."); - }, - (error) => { - console.log( - "An error occurred when marking the message as delivered.", - error - ); - } -); -``` - - +let messageId = "MESSAGE_ID"; +let receiverId = "GROUP_GUID"; +let receiverType = "group"; +let senderId = "MESSAGE_SENDER_UID"; - -```typescript -const messageId: string = "MESSAGE_ID"; -const receiverId: string = "MESSAGE_SENDER_UID"; -const receiverType: string = "user"; -const senderId: string = "MESSAGE_SENDER_UID"; CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId).then( () => { - console.log("mark as delivered success."); + console.log("Marked as delivered successfully"); }, - (error: CometChat.CometChatException) => { - console.log( - "An error occurred when marking the message as delivered.", - error - ); + (error) => { + console.log("Error marking as delivered:", error); } ); ``` - - - + ```typescript -const messageId: string = "MESSAGE_ID"; -const receiverId: string = "MESSAGE_RECEIVER_GUID"; -const receiverType: string = "group"; -const senderId: string = "MESSAGE_SENDER_UID"; +let messageId: string = "MESSAGE_ID"; +let receiverId: string = "MESSAGE_SENDER_UID"; +let receiverType: string = "user"; +let senderId: string = "MESSAGE_SENDER_UID"; + CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId).then( () => { - console.log("mark as delivered success."); + console.log("Marked as delivered successfully"); }, (error: CometChat.CometChatException) => { - console.log( - "An error occurred when marking the message as delivered.", - error - ); + console.log("Error marking as delivered:", error); } ); ``` - - - - - -Another option the CometChat SDK provides is to pass the entire message object to the markAsDelivered() method. - - - -```javascript -CometChat.markAsDelivered(message); -``` - - - + ```typescript -let message: CometChat.BaseMessage; -CometChat.markAsDelivered(message); -``` - - - - - -In case you would like to be notified of an error if the receipts fail to go through you can use `.then(successCallback, failureCallback)` of the `markAsDelivered` method. +let messageId: string = "MESSAGE_ID"; +let receiverId: string = "GROUP_GUID"; +let receiverType: string = "group"; +let senderId: string = "MESSAGE_SENDER_UID"; - - -```javascript -CometChat.markAsDelivered(message).then( - () => { - console.log("mark as delivered success."); - }, - (error) => { - console.log( - "An error occurred when marking the message as delivered.", - error - ); - } -); -``` - - - - -```typescript -let message: CometChat.BaseMessage; -CometChat.markAsDelivered(message).then( +CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId).then( () => { - console.log("mark as delivered success."); + console.log("Marked as delivered successfully"); }, (error: CometChat.CometChatException) => { - console.log( - "An error occurred when marking the message as delivered.", - error - ); + console.log("Error marking as delivered:", error); } ); ``` - - ## Mark Conversation as Delivered -You can mark an entire conversation as delivered for a user or group using the `markConversationAsDelivered()` method. This method takes the below parameters as input: - -| Parameter | Information | -| ------------------ | ------------------------------------------------------------------------------ | -| `conversationWith` | The ID of the user (UID) or group (GUID) for the conversation. | -| `conversationType` | Type of the conversation. Could be either `user` or `group`. | - -This method will mark all messages in the conversation as delivered. +Use `markConversationAsDelivered()` to mark all messages in a conversation as delivered. ```javascript -const conversationWith = "USER_UID"; -const conversationType = "user"; +let conversationWith = "USER_UID"; +let conversationType = "user"; CometChat.markConversationAsDelivered(conversationWith, conversationType).then( (response) => { console.log("Conversation marked as delivered", response); }, (error) => { - console.log("Error marking conversation as delivered", error); + console.log("Error:", error); } ); ``` - ```javascript -const conversationWith = "GROUP_GUID"; -const conversationType = "group"; +let conversationWith = "GROUP_GUID"; +let conversationType = "group"; CometChat.markConversationAsDelivered(conversationWith, conversationType).then( (response) => { console.log("Conversation marked as delivered", response); }, (error) => { - console.log("Error marking conversation as delivered", error); + console.log("Error:", error); } ); ``` - - + ```typescript -const conversationWith: string = "USER_UID"; -const conversationType: string = "user"; +let conversationWith: string = "USER_UID"; +let conversationType: string = "user"; CometChat.markConversationAsDelivered(conversationWith, conversationType).then( (response: string) => { console.log("Conversation marked as delivered", response); }, (error: CometChat.CometChatException) => { - console.log("Error marking conversation as delivered", error); + console.log("Error:", error); } ); ``` - - + ```typescript -const conversationWith: string = "GROUP_GUID"; -const conversationType: string = "group"; +let conversationWith: string = "GROUP_GUID"; +let conversationType: string = "group"; CometChat.markConversationAsDelivered(conversationWith, conversationType).then( (response: string) => { console.log("Conversation marked as delivered", response); }, (error: CometChat.CometChatException) => { - console.log("Error marking conversation as delivered", error); + console.log("Error:", error); } ); ``` -## Mark Messages as Read - -You can mark the messages for a particular conversation as read using the `markAsRead()` method. This method takes the below parameters as input: - -| Parameter | Information | -| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `messageId` | The ID of the message above which all the messages for a particular conversation are to be marked as read. | -| `receiverId` | In case of one to one conversation message's sender `UID` will be the receipt's receiver Id. In case of group conversation message's receiver Id will be the receipt's receiver Id | -| `receiverType` | Type of the receiver. Could be either of the two values( user or group) | -| `senderId` | The `UID` of the sender of the message. | +## Mark as Read -Messages for both user and group conversations can be marked as read using this method. +Use `markAsRead()` to mark messages as read. You can pass either a message object or individual parameters. -Ideally, you would like to mark all the messages as read for any conversation when the user opens the chat window for that conversation. This includes two scenarios: - -1. **When the list of messages for the conversation is fetched**: In this case you need to obtain the last message in the list of messages and pass the message ID of that message to the markAsRead() method. -2. **When the user is on the chat window and a real-time message is received:** In this case you need to obtain the message ID of the message and pass it to the markAsRead() method +### Using Message Object - + ```javascript -const messageId = "MESSAGE_ID"; -const receiverId = "MESSAGE_SENDER_UID"; -const receiverType = "user"; -const senderId = "MESSAGE_SENDER_UID"; -CometChat.markAsRead(messageId, receiverId, receiverType, senderId); -``` - - - - -```javascript -const receiverId = "MESSAGE_RECEIVER_GUID"; -const receiverType = "group"; -const senderId = "MESSAGE_SENDER_UID"; -CometChat.markAsRead(messageId, receiverId, receiverType, senderId); -``` - - - - -```typescript -const messageId: string = "MESSAGE_ID"; -const receiverId: string = "MESSAGE_SENDER_UID"; -const receiverType: string = "user"; -const senderId: string = "MESSAGE_SENDER_UID"; -CometChat.markAsRead(messageId, receiverId, receiverType, senderId); +CometChat.markAsRead(message).then( + () => { + console.log("Marked as read successfully"); + }, + (error) => { + console.log("Error marking as read:", error); + } +); ``` - - - + ```typescript -const messageId: string = "MESSAGE_ID"; -const receiverId: string = "MESSAGE_RECEIVER_GUID"; -const receiverType: string = "group"; -const senderId: string = "MESSAGE_SENDER_UID"; -CometChat.markAsRead(messageId, receiverId, receiverType, senderId); +CometChat.markAsRead(message).then( + () => { + console.log("Marked as read successfully"); + }, + (error: CometChat.CometChatException) => { + console.log("Error marking as read:", error); + } +); ``` - - -This method will mark all the messages before the messageId specified, for the conversation with receiverId and receiverType(user/group) as read. - -In case you would like to be notified of an error if the receipts fail to go through you can use `.then(successCallback, failureCallback)` of the `markAsDelivered` method. +### Using Parameters ```javascript -CometChat.markAsRead( - message.getId(), - message.getSender().getUid(), - "user", - message.getSender().getUid() -).then( +let messageId = "MESSAGE_ID"; +let receiverId = "MESSAGE_SENDER_UID"; +let receiverType = "user"; +let senderId = "MESSAGE_SENDER_UID"; + +CometChat.markAsRead(messageId, receiverId, receiverType, senderId).then( () => { - console.log("mark as read success."); + console.log("Marked as read successfully"); }, (error) => { - console.log("An error occurred when marking the message as read.", error); + console.log("Error marking as read:", error); } ); ``` - - ```javascript -CometChat.markAsRead( - message.getId(), - message.getReceiverUid(), - "group", - message.getSender().getUid() -).then( - () => { - console.log("mark as read success."); - }, - (error) => { - console.log("An error occurred when marking the message as read.", error); - } -); -``` - - +let messageId = "MESSAGE_ID"; +let receiverId = "GROUP_GUID"; +let receiverType = "group"; +let senderId = "MESSAGE_SENDER_UID"; - -```typescript -const messageId: string = "MESSAGE_ID"; -const receiverId: string = "MESSAGE_SENDER_UID"; -const receiverType: string = "user"; -const senderId: string = "MESSAGE_SENDER_UID"; CometChat.markAsRead(messageId, receiverId, receiverType, senderId).then( () => { - console.log("mark as read success."); + console.log("Marked as read successfully"); }, - (error: CometChat.CometChatException) => { - console.log("An error occurred when marking the message as read.", error); + (error) => { + console.log("Error marking as read:", error); } ); ``` - - - + ```typescript -const messageId: string = "MESSAGE_ID"; -const receiverId: string = "MESSAGE_RECEIVER_GUID"; -const receiverType: string = "group"; -const senderId: string = "MESSAGE_SENDER_UID"; +let messageId: string = "MESSAGE_ID"; +let receiverId: string = "MESSAGE_SENDER_UID"; +let receiverType: string = "user"; +let senderId: string = "MESSAGE_SENDER_UID"; + CometChat.markAsRead(messageId, receiverId, receiverType, senderId).then( () => { - console.log("mark as read success."); + console.log("Marked as read successfully"); }, (error: CometChat.CometChatException) => { - console.log("An error occurred when marking the message as read.", error); + console.log("Error marking as read:", error); } ); ``` - - - - -Another option the CometChat SDK provides is to pass the entire message object to the markAsRead() method. - - - -```javascript -CometChat.markAsRead(message); -``` - - - - + ```typescript -let message: CometChat.BaseMessage; -CometChat.markAsRead(message); -``` - - - - - -In case you would like to be notified of an error if the receipts fail to go through you can use `.then(successCallback, failureCallback)` of the `markAsDelivered` method. - - - -```javascript -CometChat.markAsRead(message).then( - () => { - console.log("mark as read success."); - }, - (error) => { - console.log("An error occurred when marking the message as read.", error); - } -); -``` - - +let messageId: string = "MESSAGE_ID"; +let receiverId: string = "GROUP_GUID"; +let receiverType: string = "group"; +let senderId: string = "MESSAGE_SENDER_UID"; - -```typescript -let message: CometChat.BaseMessage; -CometChat.markAsRead(message).then( +CometChat.markAsRead(messageId, receiverId, receiverType, senderId).then( () => { - console.log("mark as read success."); + console.log("Marked as read successfully"); }, (error: CometChat.CometChatException) => { - console.log("An error occurred when marking the message as read.", error); + console.log("Error marking as read:", error); } ); ``` - - ## Mark Conversation as Read -You can mark an entire conversation as read for a user or group using the `markConversationAsRead()` method. This method takes the below parameters as input: - -| Parameter | Information | -| ------------------ | ------------------------------------------------------------------------------ | -| `conversationWith` | The ID of the user (UID) or group (GUID) for the conversation. | -| `conversationType` | Type of the conversation. Could be either `user` or `group`. | - -This method will mark all messages in the conversation as read. +Use `markConversationAsRead()` to mark all messages in a conversation as read. ```javascript -const conversationWith = "USER_UID"; -const conversationType = "user"; +let conversationWith = "USER_UID"; +let conversationType = "user"; CometChat.markConversationAsRead(conversationWith, conversationType).then( (response) => { console.log("Conversation marked as read", response); }, (error) => { - console.log("Error marking conversation as read", error); + console.log("Error:", error); } ); ``` - ```javascript -const conversationWith = "GROUP_GUID"; -const conversationType = "group"; +let conversationWith = "GROUP_GUID"; +let conversationType = "group"; CometChat.markConversationAsRead(conversationWith, conversationType).then( (response) => { console.log("Conversation marked as read", response); }, (error) => { - console.log("Error marking conversation as read", error); + console.log("Error:", error); } ); ``` - - + ```typescript -const conversationWith: string = "USER_UID"; -const conversationType: string = "user"; +let conversationWith: string = "USER_UID"; +let conversationType: string = "user"; CometChat.markConversationAsRead(conversationWith, conversationType).then( (response: string) => { console.log("Conversation marked as read", response); }, (error: CometChat.CometChatException) => { - console.log("Error marking conversation as read", error); + console.log("Error:", error); } ); ``` - - + ```typescript -const conversationWith: string = "GROUP_GUID"; -const conversationType: string = "group"; +let conversationWith: string = "GROUP_GUID"; +let conversationType: string = "group"; CometChat.markConversationAsRead(conversationWith, conversationType).then( (response: string) => { console.log("Conversation marked as read", response); }, (error: CometChat.CometChatException) => { - console.log("Error marking conversation as read", error); + console.log("Error:", error); } ); ``` -## Mark Messages as Unread - -Mark messages as unread to revisit important messages later, even if they've been previously viewed. - -You can mark the messages for a particular conversation as unread using the `markMessageAsUnread()` method. This method takes the below parameters as input: +## Mark as Unread -| Parameter | Information | -| --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| message | To mark a message as unread, pass a non-null [`BaseMessage`](/sdk/reference/messages#basemessage) instance to the `markMessageAsUnread()` function. All messages below that message in the conversation will contribute to the unread messages count. Example: When User B sends User A a total of 10 messages, and User A invokes the `markMessageAsUnread()` method on the fifth message, all messages located below the fifth message within the conversation list will be designated as unread. This results in a notification indicating there are 5 unread messages in the conversation list. | +Use `markMessageAsUnread()` to mark a message as unread. All messages below that message will contribute to the unread count. You cannot mark your own messages as unread. This method only works for messages received from other users. - -```javascript -CometChat.markMessageAsUnread(message); -``` - - - - -```typescript -let message: CometChat.BaseMessage; -CometChat.markMessageAsUnread(message); -``` - - - - - -In case you would like to be notified of an error if the receipts fail to go through you can use `.then(successCallback, failureCallback).` On success, this method returns an updated [`Conversation`](/sdk/reference/entities#conversation) object with the updated unread message count and other conversation data. - - - + ```javascript CometChat.markMessageAsUnread(message).then( (conversation) => { - console.log("mark messages as unread success.", conversation); - console.log("Unread message count:", conversation.getUnreadMessageCount()); + console.log("Marked as unread successfully", conversation); + console.log("Unread count:", conversation.getUnreadMessageCount()); }, (error) => { - console.log("An error occurred when marking the message as unread.", error); + console.log("Error marking as unread:", error); } ); ``` - - ```typescript -let message: CometChat.BaseMessage; CometChat.markMessageAsUnread(message).then( (conversation: CometChat.Conversation) => { - console.log("mark messages as unread success.", conversation); - console.log("Unread message count:", conversation.getUnreadMessageCount()); + console.log("Marked as unread successfully", conversation); + console.log("Unread count:", conversation.getUnreadMessageCount()); }, (error: CometChat.CometChatException) => { - console.log("An error occurred when marking the message as unread.", error); + console.log("Error marking as unread:", error); } ); ``` - - -## Receive Delivery & Read Receipts +On success, returns an updated [`Conversation`](/sdk/reference/entities#conversation) object with the new unread message count. -### Real-time Events +## Real-Time Receipt Events -1. `onMessagesDelivered()` - This event is triggered when a message is delivered to a user. -2. `onMessagesRead()` - This event is triggered when a message is read by a user. -3. `onMessagesDeliveredToAll()` - This event is triggered when a group message is delivered to all members of the group. This event is only for Group conversations. -4. `onMessagesReadByAll()` - This event is triggered when a group message is read by all members of the group. This event is only for Group conversations. +Register a `MessageListener` to receive delivery and read receipt events. + +| Callback | Description | +| --- | --- | +| `onMessagesDelivered` | Message delivered to a user | +| `onMessagesRead` | Message read by a user | +| `onMessagesDeliveredToAll` | Group message delivered to all members | +| `onMessagesReadByAll` | Group message read by all members | - + ```javascript -let listenerId = "UNIQUE_LISTENER_ID"; +let listenerID = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener( - "listenerId", + listenerID, new CometChat.MessageListener({ onMessagesDelivered: (messageReceipt) => { - console.log("Message is delivered to a user: ", { messageReceipt }); + console.log("Message delivered:", messageReceipt); }, onMessagesRead: (messageReceipt) => { - console.log("Message is read by a user: ", { messageReceipt }); + console.log("Message read:", messageReceipt); }, - /** This event is only for Group Conversation. */ onMessagesDeliveredToAll: (messageReceipt) => { - console.log("Message delivered to all members of group: ", { - messageReceipt, - }); + console.log("Message delivered to all group members:", messageReceipt); }, - /** This event is only for Group Conversation. */ onMessagesReadByAll: (messageReceipt) => { - console.log("Message read by all members of group: ", { messageReceipt }); - }, + console.log("Message read by all group members:", messageReceipt); + } }) ); ``` - - ```typescript -let listenerId: string = "UNIQUE_LISTENER_ID"; +let listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener( - listenerId, + listenerID, new CometChat.MessageListener({ onMessagesDelivered: (messageReceipt: CometChat.MessageReceipt) => { - console.log("Message is delivered to a user: ", { messageReceipt }); + console.log("Message delivered:", messageReceipt); }, onMessagesRead: (messageReceipt: CometChat.MessageReceipt) => { - console.log("Message is read by a user: ", { messageReceipt }); + console.log("Message read:", messageReceipt); }, - /** This event is only for Group Conversation. */ onMessagesDeliveredToAll: (messageReceipt: CometChat.MessageReceipt) => { - console.log("Message delivered to all members of group: ", { - messageReceipt, - }); + console.log("Message delivered to all group members:", messageReceipt); }, - /** This event is only for Group Conversation. */ onMessagesReadByAll: (messageReceipt: CometChat.MessageReceipt) => { - console.log("Message read by all members of group: ", { messageReceipt }); - }, + console.log("Message read by all group members:", messageReceipt); + } }) ); ``` - - -You will receive events in the form of `MessageReceipt` objects. The message receipt contains the below parameters: + +Always remove listeners when no longer needed to prevent memory leaks. -| Parameter | Information | -| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | -| `messageId` | The Id of the message prior to which all the messages for that particular conversation have been marked as read. | -| `sender` | User object containing the details of the user who has marked the message as read. System User for `deliveredToAll` & `readByAll` events. | -| `receiverId` | Id of the receiver whose conversation has been marked as read. | -| `receiverType` | type of the receiver (user/group) | -| `receiptType` | Type of the receipt (read/delivered) | -| `deliveredAt` | The timestamp of the time when the message was delivered. This will only be present if the receiptType is delivered. | -| `readAt` | The timestamp of the time when the message was read. This will only be present when the receiptType is read. | +```javascript +CometChat.removeMessageListener("UNIQUE_LISTENER_ID"); +``` + + +### MessageReceipt Object -The listener callbacks receive a [`MessageReceipt`](/sdk/reference/auxiliary#messagereceipt) object. Access the data using getter methods: +The listener callbacks receive a [`MessageReceipt`](/sdk/reference/auxiliary#messagereceipt) object: | Field | Getter | Return Type | Description | -|-------|--------|-------------|-------------| -| messageId | `getMessageId()` | `string` | ID of the message this receipt is for | +| --- | --- | --- | --- | +| messageId | `getMessageId()` | `string` | ID of the message | | sender | `getSender()` | [`User`](/sdk/reference/entities#user) | User who triggered the receipt | -| receiptType | `getReceiptType()` | `string` | Type of receipt (`"delivery"` or `"read"`) | -| timestamp | `getTimestamp()` | `string` | Timestamp of the receipt event | -| deliveredAt | `getDeliveredAt()` | `number` | Timestamp when the message was delivered | -| readAt | `getReadAt()` | `number` | Timestamp when the message was read | - -The `markAsDelivered()` and `markAsRead()` methods are fire-and-forget — they do not return a `MessageReceipt` object. Use the listener callbacks above to receive delivery and read confirmations. - -### Missed Receipts +| receiverId | `getReceiverId()` | `string` | ID of the receiver | +| receiverType | `getReceiverType()` | `string` | `"user"` or `"group"` | +| receiptType | `getReceiptType()` | `string` | `"delivery"` or `"read"` | +| deliveredAt | `getDeliveredAt()` | `number` | Timestamp when delivered | +| readAt | `getReadAt()` | `number` | Timestamp when read | -You will receive message receipts when you load offline messages. While fetching messages in bulk, the message object will have two fields i.e. `deliveredAt` and `readAt` which hold the timestamp for the time the message was delivered and read respectively. Using these two variables, the delivery and read status for a message can be obtained. +## Get Receipt History -However, for a group message, if you wish to fetch the `deliveredAt` and `readAt` fields of individual member of the group you can use the below-described method. - -### Receipt History for a Single Message - -To fetch the message receipts, you can use the `getMessageReceipts()` method. +Use `getMessageReceipts()` to fetch delivery and read receipts for a specific message. Useful for group messages to see which members have received/read the message. - + ```javascript -let messageId = msgId; +let messageId = 123; + CometChat.getMessageReceipts(messageId).then( (receipts) => { - console.log("Message details fetched:", receipts); + console.log("Message receipts:", receipts); }, (error) => { - console.log("Error in getting messag details ", error); + console.log("Error fetching receipts:", error); } ); ``` - - ```typescript -let messageId: number = 1; +let messageId: number = 123; + CometChat.getMessageReceipts(messageId).then( (receipts: CometChat.MessageReceipt[]) => { - console.log("Message details fetched:", receipts); + console.log("Message receipts:", receipts); }, (error: CometChat.CometChatException) => { - console.log("Error in getting messag details ", error); + console.log("Error fetching receipts:", error); } ); ``` - - -You will receive a list of [`MessageReceipt`](/sdk/reference/auxiliary#messagereceipt) objects. - - +Returns an array of [`MessageReceipt`](/sdk/reference/auxiliary#messagereceipt) objects. -The following features will be available only if the **Enhanced Messaging Status** feature is enabled for your app. +## Missed Receipts -* `onMessagesDeliveredToAll` event, -* `onMessagesReadByAll` event, -* `deliveredAt` field in a group message, -* `readAt` field in a group message. -* `markMessageAsUnread` method. - - - - -Always remove message listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. +When fetching messages, each message object includes `deliveredAt` and `readAt` timestamps indicating when the message was delivered and read. ```javascript -CometChat.removeMessageListener("UNIQUE_LISTENER_ID"); +let deliveredAt = message.getDeliveredAt(); +let readAt = message.getReadAt(); ``` - + + +The following features require **Enhanced Messaging Status** to be enabled for your app: +- `onMessagesDeliveredToAll` event +- `onMessagesReadByAll` event +- `deliveredAt` field in group messages +- `readAt` field in group messages +- `markMessageAsUnread()` method + --- @@ -837,7 +570,7 @@ CometChat.removeMessageListener("UNIQUE_LISTENER_ID"); - Show real-time typing status to users in conversations + Show real-time typing status in conversations Listen for incoming messages in real time From c42d5701b25c7a1b2b122d10d1fcf95af52d6e9e Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 18 Mar 2026 21:03:09 +0530 Subject: [PATCH 43/43] Update overview.mdx --- sdk/javascript/overview.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/javascript/overview.mdx b/sdk/javascript/overview.mdx index b0059c9eb..9be62764f 100644 --- a/sdk/javascript/overview.mdx +++ b/sdk/javascript/overview.mdx @@ -76,7 +76,7 @@ Skip the UI work and use our pre-built components: ## Chat Widget -For the fastest integration, embed our [Chat Widget](/widget/html-bootstrap-jquery) with just a few lines of code — no SDK knowledge required. +For the fastest integration, embed our [Chat Widget](/widget/html/overview) with just a few lines of code — no SDK knowledge required. ## Resources