From 4332f97c3fd352ce4714d23a32acaeb4f828a23b Mon Sep 17 00:00:00 2001 From: aanshisingh-cometchat Date: Tue, 17 Feb 2026 17:34:26 +0530 Subject: [PATCH 001/139] 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 002/139] 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 003/139] 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 004/139] 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 005/139] 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 006/139] 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 561dffb9659c71134930625a649968091f906937 Mon Sep 17 00:00:00 2001 From: Hritika Date: Mon, 9 Mar 2026 17:53:06 +0530 Subject: [PATCH 007/139] Basic changes --- sdk/android/additional-message-filtering.mdx | 126 ++++++--- sdk/android/advanced-overview.mdx | 33 +++ sdk/android/ai-agents.mdx | 64 ++++- sdk/android/ai-chatbots-overview.mdx | 3 +- sdk/android/ai-moderation.mdx | 62 ++++- sdk/android/ai-user-copilot-overview.mdx | 3 +- sdk/android/android-overview.mdx | 39 ++- sdk/android/authentication-overview.mdx | 68 ++++- sdk/android/block-users.mdx | 131 ++++++++- sdk/android/call-logs.mdx | 154 ++++++++++- sdk/android/calling-overview.mdx | 32 +++ sdk/android/calling-setup.mdx | 98 ++++++- sdk/android/connection-behaviour.mdx | 147 +++++++++-- sdk/android/connection-status.mdx | 58 ++++ sdk/android/create-group.mdx | 110 ++++++-- sdk/android/default-calling.mdx | 94 +++++++ sdk/android/delete-conversation.mdx | 88 ++++++- sdk/android/delete-group.mdx | 78 +++++- sdk/android/delete-message.mdx | 105 +++++++- sdk/android/delivery-read-receipts.mdx | 102 ++++++- sdk/android/direct-calling.mdx | 106 +++++++- sdk/android/edit-message.mdx | 108 +++++++- sdk/android/extensions-overview.mdx | 41 ++- sdk/android/flag-message.mdx | 91 +++++++ sdk/android/group-add-members.mdx | 99 ++++++- sdk/android/group-change-member-scope.mdx | 102 ++++++- sdk/android/group-kick-member.mdx | 105 +++++++- sdk/android/groups-overview.mdx | 37 ++- sdk/android/interactive-messages.mdx | 244 ++++++++++------- sdk/android/join-group.mdx | 104 +++++++- sdk/android/key-concepts.mdx | 61 ++++- sdk/android/leave-group.mdx | 88 ++++++- sdk/android/login-listeners.mdx | 57 ++++ sdk/android/mentions.mdx | 249 +++++++++++------- .../message-structure-and-hierarchy.mdx | 59 ++++- sdk/android/messaging-overview.mdx | 50 +++- sdk/android/overview.mdx | 100 +++++-- sdk/android/presenter-mode.mdx | 137 ++++++++-- sdk/android/publishing-app-on-playstore.mdx | 106 +++++++- sdk/android/rate-limits.mdx | 90 ++++++- sdk/android/reactions.mdx | 120 ++++++++- sdk/android/real-time-listeners.mdx | 84 ++++++ sdk/android/receive-messages.mdx | 40 +-- sdk/android/recording.mdx | 71 ++++- sdk/android/resources-overview.mdx | 31 +++ sdk/android/retrieve-conversations.mdx | 102 ++++++- sdk/android/retrieve-group-members.mdx | 92 ++++++- sdk/android/retrieve-groups.mdx | 103 +++++++- sdk/android/retrieve-users.mdx | 86 +++++- sdk/android/send-message.mdx | 20 +- sdk/android/session-timeout.mdx | 88 ++++++- sdk/android/setup.mdx | 83 ++++-- sdk/android/standalone-calling.mdx | 105 ++++++++ sdk/android/threaded-messages.mdx | 97 ++++++- sdk/android/transfer-group-ownership.mdx | 91 ++++++- sdk/android/transient-messages.mdx | 61 ++++- sdk/android/typing-indicators.mdx | 95 ++++++- sdk/android/update-group.mdx | 102 ++++++- sdk/android/upgrading-from-v3-guide.mdx | 98 ++++++- sdk/android/user-management.mdx | 118 ++++++++- sdk/android/user-presence.mdx | 125 +++++++-- sdk/android/users-overview.mdx | 30 ++- sdk/android/video-view-customisation.mdx | 92 ++++++- sdk/android/webhooks-overview.mdx | 39 ++- 64 files changed, 5024 insertions(+), 578 deletions(-) diff --git a/sdk/android/additional-message-filtering.mdx b/sdk/android/additional-message-filtering.mdx index a215f75c7..8b2866e81 100644 --- a/sdk/android/additional-message-filtering.mdx +++ b/sdk/android/additional-message-filtering.mdx @@ -1,8 +1,28 @@ --- title: "Additional Message Filtering" +description: "Filter messages by category, type, timestamp, tags, and other parameters using MessagesRequest in the Android SDK" --- + +**Quick Reference for AI Agents & Developers** +```kotlin +// Build filtered message request +val messagesRequest = MessagesRequestBuilder() + .setUID("user_uid") // User conversation + .setLimit(50) // Max 100 per request + .setCategories(listOf("message")) // Filter by category + .setTypes(listOf("text", "image")) // Filter by type + .setUnread(true) // Only unread messages + .hideDeletedMessages(true) // Exclude deleted + .hideReplies(true) // Exclude threaded messages + .build() + +// Fetch messages +messagesRequest.fetchNext(callback) +messagesRequest.fetchPrevious(callback) +``` + 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. @@ -27,9 +47,9 @@ Now that you are clear how to use the `MessagesRequest` class, below are the var ## Number of messages fetched -*In other words, how do I set the number of messages fetched in a single iteration* +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`. +To achieve this, 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`. @@ -84,9 +104,9 @@ val messagesRequest = MessagesRequestBuilder() ## Messages for a user conversation -*In other words, how do I fetch messages between me and any user* +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. +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 returns all the messages that are a part of the conversation between the logged-in user and the UID that has been specified. @@ -113,9 +133,9 @@ val messagesRequest = MessagesRequestBuilder() ## Messages for a group conversation -*In other words, how do I fetch messages for any group conversation* +How do I fetch messages for any 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. +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 returns all the messages that are a part of the group conversation. Note that the logged-in user must be a member of the group to fetch the messages for that group. MessagesRequest messagesRequest = new MessagesRequest.MessagesRequestBuilder() .setGUID("cometchat-guid-1") .setLimit(50) .build(); @@ -144,9 +164,9 @@ val messagesRequest = MessagesRequestBuilder() ## Messages before/after a message -*In other words, how do I fetch messages before or after a particular message* +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. +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 whether the fetchNext() or fetchPrevious() method is triggered. @@ -207,9 +227,9 @@ This method can be used along with `setUID()` or `setGUID()` methods to fetch me ## Messages before/after a given time -*In other words, how do I fetch messages before or after a particular date or time* +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. +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 whether fetchNext() or fetchPrevious() method is triggered. @@ -270,9 +290,9 @@ This method can be used along with `setUID()` or `setGUID()` methods to fetch me ## Unread messages -*In other words, how do I fetch unread messages* +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. +This can easily be achieved by setting the unread flag to true. For this, use the `setUnread()` method. This method takes a boolean value as input. If the value is set to true, the SDK returns just the unread messages. @@ -333,9 +353,9 @@ This method along with `setGUID()` or `setUID()` can be used to fetch unread mes ## Exclude messages from blocked users -*In other words, how do I fetch messages excluding the messages from the users I have blocked* +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. +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 of 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, meaning if this method is not used, the messages from blocked users will be included in the fetched messages. @@ -396,9 +416,9 @@ This method can be used to hide the messages by users blocked by logged in user ## Updated and received messages -*In other words, how do I fetch messages that have been received or updated after a particular date or time* +How do I fetch messages that have been received or updated after a particular date or time? -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. +This method accepts a Unix timestamp value and returns 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. @@ -459,9 +479,9 @@ This can be useful in finding the messages that have been received or updated af ## Updated messages only -*In other words, how do I fetch messages that have been updated after a particular date or time* +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. +This can be achieved easily by setting the updatesOnly parameter to true. To do so, use the `updatesOnly()` method. This method takes a boolean input and can be used with the `setUpdatedAfter()` method to get just 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. @@ -524,11 +544,11 @@ val messagesRequest = MessagesRequestBuilder() ## Messages for multiple categories -*In other words, how do I fetch messages belonging to multiple categories* +How do I fetch messages belonging to multiple categories? We recommend before trying this, you refer to the [Message structure and hierarchy guide](/sdk/android/message-structure-and-hierarchy) to get familiar with the various categories of messages. -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. +For this, use the `setCategories()` method. This method accepts a list of categories. This tells the SDK to fetch messages only belonging to these categories. @@ -601,7 +621,7 @@ The above snippet will help you get only the messages belonging to the `message` ## Messages for multiple types -*In other words, how do I fetch messages belonging to multiple types* +How do I fetch messages belonging to multiple types? We recommend before trying this, you refer to the [Message structure and hierarchy guide](/sdk/android/message-structure-and-hierarchy) to get familiar with the various types of messages. @@ -698,9 +718,9 @@ Using the above code snippet, you can fetch all the media messages. This along w ## 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* +How do I fetch messages that are a part of a thread and not directly a user/group conversation? -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. +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 returns the messages only belonging to the thread with the specified parent Id. @@ -760,9 +780,9 @@ The above code snippet returns the messages that belong to the thread with paren ## Hide threaded messages in user/group conversations -*In other words, how do I exclude threaded messages from the normal user/group conversations* +How do I exclude threaded messages from the normal 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. +To do this, use the `hideReplies()` method. This method is also related to threaded conversations. This method takes a boolean as input. This boolean when set to true ensures that the messages that belong to threads are not fetched. If set to false, which is also the default value, the messages belonging to the threads will also be fetched along with other messages. @@ -821,9 +841,9 @@ val messagesRequest = MessagesRequestBuilder() ## Hide deleted messages in user/group conversations -*In other words, how do I exclude deleted messages a user/group conversations* +How do I exclude deleted messages from a user/group conversation? -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. +To do this, use the `hideDeletedMessages()` method. This method takes a boolean as input. This boolean when set to true ensures 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. @@ -882,9 +902,9 @@ val messagesRequest = MessagesRequestBuilder() ## Hide quoted messages in user/group conversations -*In other words, how do I exclude quoted messages in a user/group conversations* +How do I exclude quoted messages in a user/group conversation? -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. +To do this, use the `hideQuotedMessages()` method. This method takes a boolean as input. This boolean when set to true ensures 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. @@ -943,9 +963,9 @@ val messagesRequest = MessagesRequestBuilder() ## Messages by tags -*In other words, how do I fetch messages belonging to specific tags* +How do I fetch messages belonging to specific 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. +To do this, use the `setTags()` method. This method accepts a list of tags. This tells the SDK to fetch messages only belonging to these tags. @@ -982,9 +1002,9 @@ val messagesRequest = MessagesRequestBuilder() ## Messages with tags -*In other words, how do I fetch messages with the tags information* +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 information. When set to `false` , the SDK will not fetch tags information associated with messages. The default value for this parameter is `false` . +To do this, use the `withTags()` method. This method accepts a boolean as input. When set to `true`, the SDK fetches messages along with the tags information. When set to `false`, the SDK does not fetch tags information associated with messages. The default value for this parameter is `false`. @@ -1270,3 +1290,43 @@ val UID = "cometchat-uid-1" + + +## Best Practices + + + + Set a reasonable limit (20-50 messages) using `setLimit()` to balance performance and user experience. Fetch more messages as users scroll using `fetchNext()` or `fetchPrevious()`. + + + Combine multiple filters to create specific views (e.g., unread media messages, messages with links, messages from specific time ranges). This reduces client-side filtering. + + + Store filtered message results in local storage to provide offline access and reduce API calls. Refresh the cache when new messages arrive via listeners. + + + Use `setUpdatedAfter()` with `updatesOnly(true)` to efficiently sync messages that have been edited, deleted, or marked as read/delivered since your last fetch. + + + For advanced filtering (links, attachments, reactions, mentions), ensure "Conversation & Advanced Search" is enabled in your CometChat Dashboard under Chats → Settings → General Configuration. + + + +--- + +## Next Steps + + + + Handle incoming messages with message listeners + + + Understand message categories and types + + + Implement threaded conversations with parent messages + + + Fetch conversation list with unread counts + + diff --git a/sdk/android/advanced-overview.mdx b/sdk/android/advanced-overview.mdx index 18501a4d5..272b0c4f2 100644 --- a/sdk/android/advanced-overview.mdx +++ b/sdk/android/advanced-overview.mdx @@ -1,6 +1,39 @@ --- title: "Advanced" sidebarTitle: "Overview" +description: "Advanced features and customization options for the CometChat Android SDK" --- + +**Quick Reference for AI Agents & Developers** + +Explore advanced features: +- **Real-Time Listeners** → [real-time-listeners](/sdk/android/real-time-listeners) - Handle all SDK events +- **Message Structure** → [message-structure-and-hierarchy](/sdk/android/message-structure-and-hierarchy) - Understand message types +- **Additional Filtering** → [additional-message-filtering](/sdk/android/additional-message-filtering) - Advanced message queries +- **Connection Status** → [connection-status](/sdk/android/connection-status) - Monitor SDK connectivity +- **Login Listeners** → [login-listeners](/sdk/android/login-listeners) - Track authentication events + + +Advanced features provide deeper control and customization of the CometChat SDK. These guides cover event handling, message filtering, connection management, and other sophisticated capabilities for building robust chat applications. + +--- + +## Next Steps + + + + Handle all SDK events with comprehensive listeners + + + Understand message types and hierarchy + + + Advanced message queries and filtering options + + + Monitor and handle SDK connectivity changes + + + diff --git a/sdk/android/ai-agents.mdx b/sdk/android/ai-agents.mdx index 853da43a7..f58b6d6f2 100644 --- a/sdk/android/ai-agents.mdx +++ b/sdk/android/ai-agents.mdx @@ -1,7 +1,32 @@ --- title: "AI Agents" +description: "Integrate AI-powered agents for intelligent, automated interactions in the Android SDK" --- + +**Quick Reference for AI Agents & Developers** + +```kotlin +// Listen for real-time AI events +CometChat.addAIAssistantListener("LISTENER_ID", object : CometChat.AIAssistantListener() { + override fun onAIAssistantEventReceived(event: AIAssistantBaseEvent) { + // Handle run start, tool calls, text streaming, run finished + } +}) + +// Listen for persisted agentic messages +CometChat.addMessageListener("LISTENER_ID", object : CometChat.MessageListener() { + override fun onAIAssistantMessageReceived(message: AIAssistantMessage) { } + override fun onAIToolResultReceived(message: AIToolResultMessage) { } + override fun onAIToolArgumentsReceived(message: AIToolArgumentMessage) { } +}) +``` + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/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). @@ -130,4 +155,41 @@ These events are received via the **`MessageListener`** after the run completes. ``` - \ No newline at end of file + + + +## Best Practices + + + + Remove AI assistant and message listeners in `onDestroy()` or `onPause()` to prevent memory leaks. Use unique listener IDs to manage multiple listeners effectively. + + + Use `Text Message Content` events to render AI responses incrementally as they arrive. This provides a better user experience than waiting for the complete response. + + + Show users when the agent is invoking tools (e.g., "Searching for flights...") using `Tool Call Start` and `Tool Call End` events. This provides transparency about agent actions. + + + Persist `AIAssistantMessage`, `AIToolResultMessage`, and `AIToolArgumentMessage` objects locally to display conversation history when users return to the chat. + + + +--- + +## Next Steps + + + + Learn about AI agent capabilities and configuration + + + Send text messages to AI agents to trigger runs + + + Handle incoming messages including AI responses + + + Configure and manage AI agents in the CometChat Dashboard + + diff --git a/sdk/android/ai-chatbots-overview.mdx b/sdk/android/ai-chatbots-overview.mdx index 453c5e30f..663cb5c1e 100644 --- a/sdk/android/ai-chatbots-overview.mdx +++ b/sdk/android/ai-chatbots-overview.mdx @@ -1,4 +1,5 @@ --- -title: "AI" +title: "AI Chatbots" +description: "Implement custom AI chatbots for automated conversations in your Android application" url: "/ai-chatbots/overview" --- \ No newline at end of file diff --git a/sdk/android/ai-moderation.mdx b/sdk/android/ai-moderation.mdx index 3c3a0214c..80c9390f6 100644 --- a/sdk/android/ai-moderation.mdx +++ b/sdk/android/ai-moderation.mdx @@ -1,7 +1,36 @@ --- title: "AI Moderation" +description: "Automatically review messages for inappropriate content using AI moderation in the Android SDK" --- + +**Quick Reference for AI Agents & Developers** + +```kotlin +// Send message (automatically moderated) +val textMessage = TextMessage(receiverUID, "Hello!", CometChatConstants.RECEIVER_TYPE_USER) +CometChat.sendMessage(textMessage, object : CometChat.CallbackListener() { + override fun onSuccess(message: TextMessage) { + if (message.moderationStatus == ModerationStatus.PENDING) { + // Show pending indicator + } + } + override fun onError(e: CometChatException) { } +}) + +// Listen for moderation results +CometChat.addMessageListener("LISTENER_ID", object : CometChat.MessageListener() { + override fun onMessageModerated(message: BaseMessage) { + // Handle APPROVED or DISAPPROVED status + } +}) +``` + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/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. @@ -234,4 +263,35 @@ When a message is disapproved, handle it appropriately in your UI: ## 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/android/flag-message) documentation. + + + + Configure moderation rules and manage flagged messages + + + Allow users to report inappropriate messages + + + Send text, image, and video messages with automatic moderation + + + Enable and configure AI moderation in the CometChat Dashboard + + + +## Best Practices + + + + Display a visual indicator (e.g., clock icon, "Pending review" label) for messages with `PENDING` moderation status. This informs users that their message is being reviewed. + + + When a message is disapproved, show a user-friendly message explaining why it was blocked. Avoid technical jargon and provide guidance on acceptable content. + + + Set up moderation rules in the [CometChat Dashboard](https://app.cometchat.com) under Moderation > Rules. Define what content should be flagged or blocked based on your app's policies. + + + Test moderation with various content types (text, images, videos) in a development environment to ensure rules work as expected before deploying to production. + + diff --git a/sdk/android/ai-user-copilot-overview.mdx b/sdk/android/ai-user-copilot-overview.mdx index 3e798a3fb..f3f59149b 100644 --- a/sdk/android/ai-user-copilot-overview.mdx +++ b/sdk/android/ai-user-copilot-overview.mdx @@ -1,4 +1,5 @@ --- -title: "AI" +title: "AI User Copilot" +description: "Enhance user experience with AI-powered assistance and suggestions in the Android SDK" url: "/fundamentals/ai-user-copilot/overview" --- \ No newline at end of file diff --git a/sdk/android/android-overview.mdx b/sdk/android/android-overview.mdx index c85f2beb4..a62b764f7 100644 --- a/sdk/android/android-overview.mdx +++ b/sdk/android/android-overview.mdx @@ -1,4 +1,41 @@ --- title: "Java UI Kit" +description: "Pre-built UI components for Android chat applications using CometChat" url: "/ui-kit/android/overview" ---- \ No newline at end of file +--- + + +**Quick Reference for AI Agents & Developers** + +The CometChat Android UI Kit provides pre-built UI components for rapid chat app development: +- **Pre-built Chat UI** - Ready-to-use chat screens and components +- **Customizable Themes** - Match your app's design language +- **Message Types** - Text, media, custom messages supported +- **Group Chat** - Built-in group conversation UI +- **Calling UI** - Voice and video call interfaces + +**Learn more:** [Android UI Kit Overview](/ui-kit/android/overview) + + +The Android UI Kit is a collection of pre-built UI components that accelerate chat application development. It provides ready-to-use screens for conversations, user lists, group management, and calling interfaces. + +For detailed information about the UI Kit, installation instructions, customization options, and implementation guides, visit the [Android UI Kit Overview](/ui-kit/android/overview). + +--- + +## Next Steps + + + + Explore the complete Android UI Kit documentation + + + Build custom UI with the Android SDK + + + Install and initialize the Android SDK + + + Start building messaging features + + \ No newline at end of file diff --git a/sdk/android/authentication-overview.mdx b/sdk/android/authentication-overview.mdx index 7e3f45b6b..bf7ed504a 100644 --- a/sdk/android/authentication-overview.mdx +++ b/sdk/android/authentication-overview.mdx @@ -1,9 +1,38 @@ --- title: "Authentication" sidebarTitle: "Overview" +description: "Log users into CometChat using Auth Key for development or Auth Token for production" --- + +**Quick Reference for AI Agents & Developers** +```kotlin +// Check if user is already logged in +val loggedInUser = CometChat.getLoggedInUser() + +// Login with Auth Key (development only) +CometChat.login("UID", "AUTH_KEY", object : CometChat.CallbackListener() { + override fun onSuccess(user: User?) { } + override fun onError(e: CometChatException?) { } +}) + +// Login with Auth Token (production) +CometChat.login("AUTH_TOKEN", object : CometChat.CallbackListener() { + override fun onSuccess(user: User?) { } + override fun onError(e: CometChatException?) { } +}) + +// Logout +CometChat.logout(object : CometChat.CallbackListener() { + override fun onSuccess(p0: String?) { } + override fun onError(p0: CometChatException?) { } +}) +``` + +**Required Credentials:** App ID (from init), Auth Key (dev) or Auth Token (prod) +**Get from:** [CometChat Dashboard](https://app.cometchat.com) → Your App → API & Auth Keys + ### Create User @@ -15,23 +44,31 @@ Before you log in a user, you must add the user to CometChat. Sample Users -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`. +We have set up 5 users for testing with UIDs: `cometchat-uid-1`, `cometchat-uid-2`, `cometchat-uid-3`, `cometchat-uid-4`, and `cometchat-uid-5`. -Once initialization is successful, you will need to log the user into CometChat using the `login()` method. +Once initialization is successful, you 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. +We recommend calling the CometChat `login()` method once your user logs into your app. The `login()` method only needs to be called once. + + +`CometChat.init()` must be called before any other SDK method. Calling `login()`, `sendMessage()`, or registering listeners before `init()` will fail. + -The CometChat SDK maintains the session of the logged-in user within the SDK. Thus you do not need to call the login method for every session. You can use the CometChat.getLoggedInUser() method to check if there is any existing session in the SDK. This method should return the details of the logged-in user. If this method returns null, it implies there is no session present within the SDK and you need to log the user into ComeChat. +The CometChat SDK maintains the session of the logged-in user within the SDK. You do not need to call the login method for every session. Use the `CometChat.getLoggedInUser()` method to check if there is any existing session in the SDK. This method should return the details of the logged-in user. If this method returns `null`, it means there is no session present within the SDK and you need to log the user into CometChat. ## Login using Auth Key -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. +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](#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. + @@ -86,7 +123,7 @@ After the user logs in, their information is returned in the `User` object. ## Login using Auth Token -This advanced authentication procedure does not use the Auth Key directly in your client code thus ensuring safety. +This advanced authentication procedure does not use the Auth Key directly in your client code, ensuring better security. 1. [Create a User](https://api-explorer.cometchat.com/reference/creates-user) via the CometChat API when the user signs up in your app. 2. [Create an Auth Token](https://api-explorer.cometchat.com/reference/create-authtoken) via the CometChat API for the new user every time the user logs in to your app. @@ -175,3 +212,22 @@ CometChat.logout(object : CometChat.CallbackListener() { + +--- + +## Next Steps + + + + Start sending text, media, and custom messages to users and groups + + + Retrieve and manage users in your application + + + Review SDK installation and initialization steps + + + Understand core CometChat concepts and terminology + + diff --git a/sdk/android/block-users.mdx b/sdk/android/block-users.mdx index d48752d66..745c03489 100644 --- a/sdk/android/block-users.mdx +++ b/sdk/android/block-users.mdx @@ -1,14 +1,86 @@ --- title: "Block Users" +description: "Block and unblock users to control communication in your Android app" --- + +**Quick Reference for AI Agents & Developers** + + +```kotlin +// Block users +val uids = listOf("UID1", "UID2", "UID3") +CometChat.blockUsers(uids, object : CometChat.CallbackListener>() { + override fun onSuccess(resultMap: HashMap) { + // resultMap contains UID -> "success"/"fail" + } + override fun onError(e: CometChatException) { } +}) + +// Unblock users +CometChat.unblockUsers(uids, object : CometChat.CallbackListener>() { + override fun onSuccess(resultMap: HashMap) { } + override fun onError(e: CometChatException) { } +}) + +// Get blocked users list +val request = BlockedUsersRequestBuilder() + .setLimit(30) + .setDirection(BlockedUsersRequest.DIRECTION_BLOCKED_BY_ME) + .build() +request.fetchNext(object : CallbackListener>() { + override fun onSuccess(users: List) { } + override fun onError(e: CometChatException) { } +}) +``` + + +```java +// Block users +List uids = Arrays.asList("UID1", "UID2", "UID3"); +CometChat.blockUsers(uids, new CometChat.CallbackListener>() { + @Override + public void onSuccess(HashMap resultMap) { + // resultMap contains UID -> "success"/"fail" + } + @Override + public void onError(CometChatException e) { } +}); + +// Unblock users +CometChat.unblockUsers(uids, new CometChat.CallbackListener>() { + @Override + public void onSuccess(HashMap resultMap) { } + @Override + public void onError(CometChatException e) { } +}); + +// Get blocked users list +BlockedUsersRequest request = new BlockedUsersRequest.BlockedUsersRequestBuilder() + .setLimit(30) + .setDirection(BlockedUsersRequest.DIRECTION_BLOCKED_BY_ME) + .build(); +request.fetchNext(new CometChat.CallbackListener>() { + @Override + public void onSuccess(List users) { } + @Override + public void onError(CometChatException e) { } +}); +``` + + + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) + ## Block Users -*In other words, as a logged-in user, how do I block a user from sending me messages?* +*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 `List` as a parameter which holds the list of `UIDs` to be blocked. +You can block users using the `blockUsers()` method. Once any user is blocked, all communication to and from that user will be completely blocked. You can block multiple users in a single operation. The `blockUsers()` method takes a `List` as a parameter which holds the list of `UIDs` to be blocked. @@ -54,13 +126,13 @@ override fun onError(e: CometChatException) { -In the `onSuccess()` callback, you receive a HashMap which contains `UIDs` as the keys and `success` or `fail` as the value based on if the block operation for the `UID` was successful or not. +In the `onSuccess()` callback, you receive a HashMap which contains `UIDs` as the keys and `success` or `fail` as the value based on whether the block operation for the `UID` was successful or not. ## Unblock Users -*In other words, as a logged-in user, how do I unblock a user I previously blocked?* +*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 `List` as a parameter which holds the list of `UIDs` to be unblocked. +You can unblock previously blocked users using the `unblockUsers()` method. You can unblock multiple users in a single operation. The `unblockUsers()` method takes a `List` as a parameter which holds the list of `UIDs` to be unblocked. @@ -106,15 +178,17 @@ override fun onError(e: CometChatException) { -In the `onSuccess()` callback, you receive a HashMap which contains `UIDs` as the keys and `success` or `fail` as the value based on if the unblock operation for the `UID` was successful or not. +In the `onSuccess()` callback, you receive a HashMap which contains `UIDs` as the keys and `success` or `fail` as the value based on whether the unblock operation for the `UID` was successful or not. + +--- ## 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?* +*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. +To fetch the list of blocked users, you can use the `BlockedUsersRequest` class. 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: +The `BlockedUsersRequestBuilder` class allows you to set the following parameters: ### Set Limit @@ -168,9 +242,9 @@ val blockedUsersRequest = BlockedUsersRequestBuilder() ### Set Direction -* CometChat.BlockedUsersRequest.DIRECTION.BLOCKED\_BY\_ME - This will ensure that the list of blocked users only contains the users blocked by the logged in user. -* CometChat.BlockedUsersRequest.DIRECTION.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.DIRECTION.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. +* `CometChat.BlockedUsersRequest.DIRECTION.BLOCKED_BY_ME` - Ensures that the list of blocked users only contains users blocked by the logged-in user. +* `CometChat.BlockedUsersRequest.DIRECTION.HAS_BLOCKED_ME` - Ensures that the list of blocked users only contains users that have blocked the logged-in user. +* `CometChat.BlockedUsersRequest.DIRECTION.BOTH` - Ensures the list of users includes both of the above cases. This is the default value for the direction variable if it is not set. @@ -239,3 +313,36 @@ override fun onError(e: CometChatException) { + +## Best Practices + + + + When blocking multiple users, use a single `blockUsers()` call with a list of UIDs instead of multiple individual calls. This reduces network overhead and improves performance. + + + The `onSuccess()` callback returns a HashMap with individual success/fail status for each UID. Always check the result map to handle cases where some users were blocked successfully while others failed. + + + After blocking a user, update your UI to reflect the change immediately. Remove blocked users from conversation lists and prevent message sending to blocked users on the client side for better UX. + + + +--- + +## Next Steps + + + + Fetch and filter user lists in your app + + + Learn about user objects and properties + + + Send messages to users and groups + + + Track user online/offline status + + diff --git a/sdk/android/call-logs.mdx b/sdk/android/call-logs.mdx index ef02868d2..733a1bcfb 100644 --- a/sdk/android/call-logs.mdx +++ b/sdk/android/call-logs.mdx @@ -1,20 +1,45 @@ --- title: "Call Logs" +description: "Retrieve and display call history for users and groups using the Android SDK" --- + +**Quick Reference for AI Agents & Developers** +```kotlin +// Build call log request +val callLogRequest = CallLogRequest.CallLogRequestBuilder() + .setAuthToken(CometChat.getUserAuthToken()) + .setLimit(50) + .setCallCategory(CometChatCallsConstants.CALL_CATEGORY_CALL) + .build() + +// Fetch call logs +callLogRequest.fetchNext(object : CometChatCalls.CallbackListener>() { + override fun onSuccess(callLogs: List) { /* Display logs */ } + override fun onError(e: CometChatException) { } +}) + +// Get specific call details +CometChatCalls.getCallDetails(sessionID, callback) +``` + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [Dashboard](https://app.cometchat.com) + ## Overview -CometChat's Android 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. +CometChat's Android Call SDK provides a comprehensive way to integrate call logs into your application, helping users 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. +This feature allows users to review past interactions and revisit important conversation details. With the flexibility to fetch call logs, filter them by specific parameters, and obtain detailed information about individual calls, you can 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 Android application. +The following sections walk you through working with call logs and how to use this feature effectively in your Android application. ## Fetching Call Logs -To fetch all call logs in your Android application, you should use the `CallLogRequestBuilder`, This builder allows you to customize the call logs fetching process according to your needs. +To fetch call logs in your Android application, use the `CallLogRequestBuilder`. This builder allows you to customize the call log fetching process according to your needs. ```java CallLogRequest callLogRequest = new CallLogRequest.CallLogRequestBuilder() @@ -40,8 +65,31 @@ CallLogRequest callLogRequest = new CallLogRequest.CallLogRequestBuilder() ### Fetch Next -The**`fetchNext()`**method retrieves the next set of call logs. +The `fetchNext()` method retrieves the next set of call logs. + + + +```kotlin +val callLogRequest = CallLogRequest.CallLogRequestBuilder() + .setAuthToken(CometChat.getUserAuthToken()) + .setLimit(50) + .setCallCategory(CometChatCallsConstants.CALL_CATEGORY_CALL) + .build() + +callLogRequest.fetchNext(object : CometChatCalls.CallbackListener>() { + override fun onSuccess(callLogs: List) { + // Handle the fetched call logs + } + + override fun onError(e: CometChatException) { + // Handle the error + } +}) +``` + + + ```java CallLogRequest callLogRequest = new CallLogRequest.CallLogRequestBuilder() .setAuthToken(CometChat.getUserAuthToken()) @@ -62,10 +110,37 @@ callLogRequest.fetchNext(new CometChatCalls.CallbackListener>() { }); ``` + + + + ### Fetch Previous -The**`fetchPrevious()`**method retrieves the previous set of call logs. +The `fetchPrevious()` method retrieves the previous set of call logs. + + + +```kotlin +val callLogRequest = CallLogRequest.CallLogRequestBuilder() + .setAuthToken(CometChat.getUserAuthToken()) + .setLimit(50) + .setCallCategory(CometChatCallsConstants.CALL_CATEGORY_CALL) + .build() +callLogRequest.fetchPrevious(object : CometChatCalls.CallbackListener>() { + override fun onSuccess(callLogs: List) { + // Handle the fetched call logs + } + + override fun onError(e: CometChatException) { + // Handle the error + } +}) +``` + + + + ```java CallLogRequest callLogRequest = new CallLogRequest.CallLogRequestBuilder() .setAuthToken(CometChat.getUserAuthToken()) @@ -86,10 +161,32 @@ callLogRequest.fetchPrevious(new CometChatCalls.CallbackListener>( }); ``` + + + + ## 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 session ID and a callback listener. + + + +```kotlin +val sessionID = "SESSION_ID" +CometChatCalls.getCallDetails(sessionID, object : CometChatCalls.CallbackListener>() { + override fun onSuccess(callLogs: List) { + // Handle the fetched call details + } + override fun onError(e: CometChatException) { + // Handle the error + } +}) +``` + + + + ```java String sessionID = "SESSION_ID"; CometChatCalls.getCallDetails(sessionID, new CometChatCalls.CallbackListener>() { @@ -105,4 +202,45 @@ CometChatCalls.getCallDetails(sessionID, new CometChatCalls.CallbackListener + + + +Note: Replace `"SESSION_ID"` with the ID of the session you are interested in. + + +## Best Practices + + + + Use `setLimit()` to fetch call logs in manageable batches (e.g., 20-50 logs per request). This improves performance and reduces memory usage, especially for users with extensive call histories. + + + Use filters like `setCallStatus()`, `setCallType()`, and `setCallDirection()` to show relevant call logs to users. For example, show only missed calls in a "Missed Calls" tab. + + + Store fetched call logs in local storage (Room database or SharedPreferences) to provide offline access and reduce API calls. Refresh the cache periodically or when the app comes to the foreground. + + + Show call duration, status (missed, rejected, completed), and timestamps in your UI to help users quickly understand their call history. + + + +--- + +## Next Steps + + + + Implement complete calling workflow with incoming/outgoing call UI + + + Start and manage call sessions with video and audio controls + + + Record calls and access recordings from the Dashboard + + + Access call logs via REST API for server-side integration + + diff --git a/sdk/android/calling-overview.mdx b/sdk/android/calling-overview.mdx index 19ef1c0f2..573bf735c 100644 --- a/sdk/android/calling-overview.mdx +++ b/sdk/android/calling-overview.mdx @@ -1,8 +1,21 @@ --- title: "Calling" sidebarTitle: "Overview" +description: "Implement voice and video calling in your Android application with CometChat" --- + +**Quick Reference for AI Agents & Developers** + +Choose your calling implementation: +- **Default Calling** → [default-calling](/sdk/android/default-calling) - Complete ringing flow with UI +- **Direct Calling** → [direct-calling](/sdk/android/direct-calling) - Direct session management +- **Standalone Calling** → [standalone-calling](/sdk/android/standalone-calling) - Calls SDK without Chat SDK +- **Calling Setup** → [calling-setup](/sdk/android/calling-setup) - Install and initialize Calls SDK +- **Call Logs** → [call-logs](/sdk/android/call-logs) - Retrieve call history +- **Recording** → [recording](/sdk/android/recording) - Record call sessions + + ## Overview CometChat provides voice and video calling capabilities for your Android application. This guide helps you choose the right implementation approach based on your use case. @@ -89,3 +102,22 @@ Use this when you want: Configure automatic call termination when participants are inactive. + +--- + +## Next Steps + + + + Install and initialize the CometChat Calls SDK + + + Implement complete calling flow with ringing UI + + + Start call sessions directly without ringing flow + + + Use Calls SDK without Chat SDK dependency + + diff --git a/sdk/android/calling-setup.mdx b/sdk/android/calling-setup.mdx index d7fbb4469..20c96c03e 100644 --- a/sdk/android/calling-setup.mdx +++ b/sdk/android/calling-setup.mdx @@ -1,12 +1,36 @@ --- title: "Setup" +description: "Install and initialize the CometChat Calls SDK for Android applications" --- + +**Quick Reference for AI Agents & Developers** + +```kotlin +// Add dependency to build.gradle +implementation 'com.cometchat:calls-sdk-android:4.3.3' + +// Initialize (run once at app start) +val callAppSettings = CallAppSettingBuilder() + .setAppId("APP_ID") + .setRegion("REGION") + .build() + +CometChatCalls.init(context, callAppSettings, object : CometChatCalls.CallbackListener() { + override fun onSuccess(s: String?) { } + override fun onError(e: CometChatException) { } +}) +``` + +**Required Credentials:** App ID, Region +**Get from:** [CometChat Dashboard](https://app.cometchat.com) → Your App → API & Auth Keys + + ## Get your Application Keys -[Signup for CometChat](https://app.cometchat.com/signup) and then: +[Sign up for CometChat](https://app.cometchat.com/signup) and then: 1. Create a new app 2. Head over to the API Keys section and note the Auth Key, App ID & Region @@ -58,11 +82,18 @@ dependencies { ## Initialize CometChatCalls -The `init()` method initialises the settings required for CometChatCalls. The`init()`method takes the below parameters: +The `init()` method initializes the settings required for CometChatCalls. The `init()` method takes the following parameters: + +- `context` - Your activity context +- `callAppSettings` - An object of the `CallAppSettings` class created using the `CallAppSettingBuilder` class. The `appId` and `region` fields are mandatory and can be set using the `setAppId()` and `setRegion()` methods. + +The `CallAppSettings` class allows you to configure three settings: -context - Your activity context callAppSettings - An object of the CallAppSettings class can be created using the CallAppSettingBuilder class. The appId and region field is mandatory and can be set using the `setAppId()` and `setRegion()` method. The `CallAppSettings` class allows you to configure three settings: +- App ID: CometChat app ID. +- Region: The region where your app was created. +- Host (host: 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. -App ID: CometChat app ID. Region: The region where you app was created. Host(host: 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. We suggest you call the `init()` method on activity onCreate() method. +We recommend calling the `init()` method in the activity's `onCreate()` method. @@ -126,3 +157,62 @@ CometChatCalls.init( | ----------------- | -------------------------------------- | | `context` | Android context for your application | | `callAppSettings` | An object of the CallAppSettings class | + +--- + +## Best Practices + + + + Call `CometChatCalls.init()` in your Application class or main activity's `onCreate()` method to ensure the SDK is ready before any calling features are accessed. + + + Double-check your App ID and Region values from the CometChat Dashboard before deploying to production. Incorrect values will cause initialization failures. + + + Always implement the `onError()` callback to catch initialization failures. Common issues include network connectivity problems or incorrect credentials. + + + +## Troubleshooting + + + + **Symptom:** `CometChatCalls.init()` fails with "Invalid App ID" or "Invalid Region" error. + + **Cause:** Incorrect App ID or Region value in initialization code. + + **Solution:** Verify your App ID and Region in the [CometChat Dashboard](https://app.cometchat.com) under API & Auth Keys. Ensure the region is exactly "us" or "eu". + + + **Symptom:** Gradle sync fails with "Could not resolve com.cometchat:calls-sdk-android" error. + + **Cause:** Maven repository URL not added to project-level build.gradle. + + **Solution:** Add the CometChat maven repository URL to the `allprojects` section in your project-level build.gradle file as shown in the setup instructions. + + + **Symptom:** Build fails with "Requires API level 24" error. + + **Cause:** Your app's minSdkVersion is below the required API level 24 for calls SDK. + + **Solution:** Update your app-level build.gradle to set `minSdkVersion 24` or higher. + + + +## Next Steps + + + + Implement one-on-one and group calling with default UI + + + Use Calls SDK without Chat SDK for calling-only apps + + + Initiate calls directly without user interaction + + + Customize the call UI appearance and layout + + diff --git a/sdk/android/connection-behaviour.mdx b/sdk/android/connection-behaviour.mdx index 02a960181..5a5ef2036 100644 --- a/sdk/android/connection-behaviour.mdx +++ b/sdk/android/connection-behaviour.mdx @@ -1,28 +1,55 @@ --- title: "Connection Behaviour" +description: "Understand and configure WebSocket connection management in the CometChat Android SDK" --- + +**Quick Reference for AI Agents & Developers** + +```kotlin +// Auto mode (default) - SDK manages connection automatically +val appSettings = AppSettings.AppSettingsBuilder() + .setRegion("REGION") + .autoEstablishSocketConnection(true) // default + .build() + +// Manual mode - You control connection +val appSettings = AppSettings.AppSettingsBuilder() + .setRegion("REGION") + .autoEstablishSocketConnection(false) + .build() + +// Manual connection management +CometChat.connect(callback) // Establish connection +CometChat.disconnect(callback) // Break connection +CometChat.ping(callback) // Keep alive (call within 30 seconds) +``` + +**Default:** Auto mode - SDK handles connection automatically +**Manual mode:** Requires explicit connect/disconnect calls + -## Default SDK behaviour on login -When the login method of the SDK is called, the SDK performs the below operations: +## Default SDK Behaviour on Login + +When the login method of the SDK is called, the SDK performs the following operations: 1. Logs the user into the SDK -2. Saves the details of the logged in user locally. -3. Creates a web-socket connection for the logged in user. +2. Saves the details of the logged-in user locally +3. Creates a WebSocket connection for the logged-in user -This makes sure that the logged in user starts receiving real-time messages sent to him or any groups that he is a part of as soon as he logs in. +This ensures that the logged-in user starts receiving real-time messages sent to them or any groups they are a part of as soon as they log in. -When the app is reopened, and the init() method is called, the web-socket connection to the server is established automatically. +When the app is reopened and the `init()` method is called, the WebSocket connection to the server is established automatically. -This is the default behaviour of the CometChat SDKs. However, if you wish to take control of the web-socket connection i.e if you wish to connect and disconnect to the web-socket server manually, you can refer to the Managing Web-socket Connection section. +This is the default behaviour of the CometChat SDKs. However, if you want to take control of the WebSocket connection (connect and disconnect manually), refer to the Managing WebSocket Connection section. ## Auto Mode -CometChat SDK default connection behaviour is auto mode. Auto mode, the SDK automatically establishes and maintains the WebSocket connection. You do not need to explicitly call any methods to do this. +CometChat SDK's default connection behaviour is auto mode. In auto mode, the SDK automatically establishes and maintains the WebSocket connection. You do not need to explicitly call any methods to do this. -To enable auto mode, you need to set the autoEstablishSocketConnection() method of AppSettings builder class to true. If you do not set this, the SDK will automatically apply the auto mode as the default behaviour for the WebSocket connection. +To enable auto mode, set the `autoEstablishSocketConnection()` method of the `AppSettings` builder class to `true`. If you do not set this, the SDK automatically applies auto mode as the default behaviour for the WebSocket connection. @@ -39,13 +66,13 @@ If the app is in the foreground and there is no internet connection, the SDK wil ## Manual Mode -In manual mode, you have to explicitly establish and disconnect the WebSocket connection. To do this, you need to set the `autoEstablishSocketConnection()` method to false and then call the `CometChat.connect()` method to establish the connection and the `CometChat.disconnect()` method to disconnect the connection. +In manual mode, you must explicitly establish and disconnect the WebSocket connection. To do this, set the `autoEstablishSocketConnection()` method to `false` and then call the `CometChat.connect()` method to establish the connection and the `CometChat.disconnect()` method to disconnect. -By default, if manual mode is activated, the SDK will disconnect the WebSocket connection after 30 seconds if the app goes into the background. This means that the WebSocket connection will remain alive for 30 seconds after the app goes into the background, but it will be disconnected after that time if no pings are received. +By default, if manual mode is activated, the SDK disconnects the WebSocket connection after 30 seconds if the app goes into the background. This means the WebSocket connection remains alive for 30 seconds after the app goes into the background, but it disconnects after that time if no pings are received. -To keep the WebSocket connection alive even if your app goes in the background, you need to call the `CometChat.ping()` method from your app within 30 seconds. This method sends a ping message to the CometChat server, which tells the server that the app is still active. +To keep the WebSocket connection alive even if your app goes into the background, call the `CometChat.ping()` method from your app within 30 seconds. This method sends a ping message to the CometChat server, which tells the server that the app is still active. -If you do not call the `CometChat.ping()` method within 30 seconds, the SDK will disconnect the WebSocket connection. This means that you will lose any messages that are sent to your app while it is in the background. +If you do not call the `CometChat.ping()` method within 30 seconds, the SDK disconnects the WebSocket connection. This means you will lose any messages sent to your app while it is in the background. @@ -58,11 +85,11 @@ If you do not call the `CometChat.ping()` method within 30 seconds, the SDK will ## Managing Manually -The CometChat SDK also allows you to modify the above default behaviour of the SDK and take the control of the web-socket connection into your own hands. In order to achieve this, you need to follow the below steps: +The CometChat SDK also allows you to modify the default behaviour and take control of the WebSocket connection yourself. To achieve this, follow the steps below. ## Enable Manual Mode -While calling the init() function on the app startup, you need to inform the SDK that you will be managing the web socket connect. You can do so by using the `autoEstablishSocketConnection()` method provided by the `AppSettingsBuilder` class. This method takes a boolean value as an input. If set to true , the SDK will manage the web-socket connection internally based on the default behaviour mentioned above. If set to `false` , the web socket connection can will not be managed by the SDK and you will have to handle it manually. You can refer to the below code snippet for the same: +While calling the `init()` function on app startup, you need to inform the SDK that you will be managing the WebSocket connection. You can do so by using the `autoEstablishSocketConnection()` method provided by the `AppSettingsBuilder` class. This method takes a boolean value as input. If set to `true`, the SDK manages the WebSocket connection internally based on the default behaviour mentioned above. If set to `false`, the WebSocket connection is not managed by the SDK and you must handle it manually. Refer to the code snippet below: @@ -117,11 +144,11 @@ CometChat.init(this, appId, appSettings, new CometChat.CallbackListener( -You can manage the connection to the web-socket server using the connect() , disconnect() and ping() methods provided by the SDK. +You can manage the connection to the WebSocket server using the `connect()`, `disconnect()`, and `ping()` methods provided by the SDK. -## Connect to the web-socket server +## Connect to the WebSocket Server -You need to use the `connect()` method provided by the `CometChat` class to establish the connection to the web-socket server. Please make sure that the user is logged in to the SDK before calling this method. You can use the CometChat.getLoggedInUser() method to check this. Once the connection is established, you will start receiving all the real-time events for the logged in user +Use the `connect()` method provided by the `CometChat` class to establish the connection to the WebSocket server. Make sure the user is logged in to the SDK before calling this method. You can use the `CometChat.getLoggedInUser()` method to check this. Once the connection is established, you start receiving all real-time events for the logged-in user. @@ -158,9 +185,9 @@ CometChat.connect(object : CallbackListener() { -## Disconnect from the web-socket server +## Disconnect from the WebSocket Server -You can use the `disconnect()` method provided by the `CometChat` class to break the established connection. Once the connection is broken, you will stop receiving all the real-time events for the logged in user. +Use the `disconnect()` method provided by the `CometChat` class to break the established connection. Once the connection is broken, you stop receiving all real-time events for the logged-in user. @@ -197,15 +224,15 @@ CometChat.disconnect(object : CallbackListener() { -## Maintain long-standing background connection +## Maintain Long-Standing Background Connection -To ensure that the WebSocket connection is always alive, you can create a service or background service that calls the `CometChat.ping()` method in a loop. This will ensure that the ping message is sent to the server every 30 seconds, even if the app is not in the foreground. +To ensure that the WebSocket connection is always alive, you can create a service or background service that calls the `CometChat.ping()` method in a loop. This ensures that the ping message is sent to the server every 30 seconds, even if the app is not in the foreground. -You can maintain a long-standing background connection event when your app is in the background, call the `CometChat.ping()` method within 30 seconds of your app entering the background or after the previous ping() call. +You can maintain a long-standing background connection even when your app is in the background by calling the `CometChat.ping()` method within 30 seconds of your app entering the background or after the previous `ping()` call. @@ -242,4 +269,76 @@ CometChat.ping(object : CallbackListener() { -Reconnection If manual mode is enabled and the app is in the foreground, the SDK will automatically reconnect the WebSocket if the internet connection is lost. However, if the app is in the background and the WebSocket is disconnected or you called `CometChat.disconnect()`, then you will need to call the `CometChat.connect()` method to create a new WebSocket connection. +Reconnection: If manual mode is enabled and the app is in the foreground, the SDK automatically reconnects the WebSocket if the internet connection is lost. However, if the app is in the background and the WebSocket is disconnected or you called `CometChat.disconnect()`, you need to call the `CometChat.connect()` method to create a new WebSocket connection. + +--- + +## Best Practices + + + + Auto mode is recommended for most applications as it handles connection management automatically. Only use manual mode if you have specific requirements for background connectivity or custom connection logic. + + + If using manual mode with background connectivity, implement a foreground service or WorkManager to call `CometChat.ping()` every 30 seconds. This ensures the connection stays alive when the app is backgrounded. + + + Implement connection listeners to track connection state changes and update your UI accordingly. Show connection status to users so they know when messages can be sent/received. + + + Thoroughly test your app's behavior when moving between foreground and background states. Verify messages are received correctly and the connection is managed as expected. + + + Maintaining a persistent background connection consumes battery. Balance real-time message delivery needs with battery efficiency. Consider using push notifications for background message delivery instead. + + + +## Troubleshooting + + + + **Symptom:** `CometChat.connect()` fails or times out in manual mode. + + **Cause:** User may not be logged in, or network connectivity issues. + + **Solution:** Verify the user is logged in using `CometChat.getLoggedInUser()` before calling `connect()`. Check network connectivity and ensure the SDK is initialized. Review error messages in the callback for specific issues. + + + **Symptom:** Real-time messages are not received when the app is in the background. + + **Cause:** In auto mode, the WebSocket disconnects immediately when the app is backgrounded. In manual mode, the connection times out after 30 seconds without a ping. + + **Solution:** For auto mode, this is expected behavior - use push notifications for background message delivery. For manual mode, implement a background service that calls `CometChat.ping()` every 30 seconds to keep the connection alive. + + + **Symptom:** WebSocket connection drops frequently even when the app is in the foreground. + + **Cause:** Network instability, server issues, or incorrect SDK configuration. + + **Solution:** The SDK automatically handles reconnection in auto mode. Check your network stability. Ensure you're not calling `disconnect()` unintentionally. Review SDK logs for specific error messages. + + + **Symptom:** `CometChat.ping()` doesn't keep the connection alive in manual mode. + + **Cause:** Ping is not being called frequently enough (must be within 30 seconds), or the connection was already disconnected. + + **Solution:** Ensure `ping()` is called at least every 30 seconds. Verify the connection is established before calling `ping()`. Implement a reliable background service or timer to call `ping()` consistently. + + + +## Next Steps + + + + Configure SDK initialization settings + + + Monitor SDK connection status changes + + + Handle user authentication events + + + Receive real-time messages and events + + diff --git a/sdk/android/connection-status.mdx b/sdk/android/connection-status.mdx index c56576884..88654ff53 100644 --- a/sdk/android/connection-status.mdx +++ b/sdk/android/connection-status.mdx @@ -1,8 +1,29 @@ --- title: "Connection Status" +description: "Monitor real-time connection status to CometChat web-socket servers in the Android SDK" --- + +**Quick Reference for AI Agents & Developers** +```kotlin +// Add connection listener +CometChat.addConnectionListener("LISTENER_ID", object : ConnectionListener { + override fun onConnected() { /* Connection established */ } + override fun onConnecting() { /* Attempting to connect */ } + override fun onDisconnected() { /* Connection lost */ } + override fun onFeatureThrottled() { /* Features throttled */ } + override fun onError(e: CometChatException) { /* Connection error */ } +}) + +// Get current connection status +val status = CometChat.getConnectionStatus() +// Returns: WS_STATE_CONNECTED, WS_STATE_CONNECTING, WS_STATE_DISCONNECTED, or WS_STATE_FEATURE_THROTTLED + +// Remove listener +CometChat.removeConnectionListener("LISTENER_ID") +``` + CometChat SDK provides you with a mechanism to get real-time status of the connection to CometChat web-socket servers. To achieve this you need to use the `ConnectionListener` class provided by the CometChat SDK @@ -115,3 +136,40 @@ The above method will return either of the below 3 values: Know more about CometChat SDK connection behaviour [click here](/sdk/android/connection-behaviour) + + +## Best Practices + + + + Display connection status indicators in your UI (e.g., "Connecting...", "Connected", "Offline") to inform users about network issues. Update the UI based on connection listener callbacks. + + + The SDK automatically attempts to reconnect when disconnected. Show a reconnecting indicator and avoid blocking the UI. Don't manually call `login()` again during reconnection. + + + Queue user actions (sending messages, making calls) when disconnected and execute them once the connection is restored. This provides a better user experience during network fluctuations. + + + Remove connection listeners in `onDestroy()` to prevent memory leaks. Use unique listener IDs to manage multiple listeners across different activities. + + + +--- + +## Next Steps + + + + Learn about SDK connection behavior and reconnection logic + + + Initialize the SDK and establish connection + + + Track user online/offline status + + + Register listeners for messages, users, groups, and calls + + diff --git a/sdk/android/create-group.mdx b/sdk/android/create-group.mdx index eecf3e26f..6c7cda96d 100644 --- a/sdk/android/create-group.mdx +++ b/sdk/android/create-group.mdx @@ -1,27 +1,48 @@ --- title: "Create A Group" +description: "Create public, private, and password-protected groups using the Android SDK" --- + +**Quick Reference for AI Agents & Developers** +```kotlin +// Create a public group +val group = Group("GUID", "Group Name", CometChatConstants.GROUP_TYPE_PUBLIC, "") +CometChat.createGroup(group, object : CometChat.CallbackListener() { + override fun onSuccess(group: Group) { } + override fun onError(e: CometChatException) { } +}) + +// Create with members +val groupMembers = listOf( + GroupMember("uid1", CometChatConstants.SCOPE_ADMIN), + GroupMember("uid2", CometChatConstants.SCOPE_PARTICIPANT) +) +CometChat.createGroupWithMembers(group, groupMembers, emptyList(), callback) +``` + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) + ## Create a Group -*In other words, as a logged-in user, how do I create a public, private or password-protected group?* +*As a logged-in user, how do I create a public, private, or password-protected group?* -You can create a group using `createGroup()` method. This method takes a `Group` object as input. +You can create a group using the `createGroup()` method. This method takes a `Group` object as input. -To create an object of `Group` class, you can use either of the below two constructors: +To create an object of the `Group` class, you can use either of the following 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.`CometChatConstants.GROUP_TYPE_PUBLIC` (public) +The `groupType` needs to be one of the following values: -2.`CometChatConstants.GROUP_TYPE_PASSWORD` (password) - -3.`CometChatConstants.GROUP_TYPE_PRIVATE` (private) +1. `CometChatConstants.GROUP_TYPE_PUBLIC` (public) +2. `CometChatConstants.GROUP_TYPE_PASSWORD` (password) +3. `CometChatConstants.GROUP_TYPE_PRIVATE` (private) @@ -76,30 +97,30 @@ The `createGroup()` method takes the following parameters: | --------- | ---------------------------- | | `group` | An instance of `Group` class | -After the successful creation of the group, you will receive an instance of `Group` class which contains all the information about the particular group. +After the successful creation of the group, you will receive an instance of the `Group` class which contains all the information about the particular group. -GUID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. +GUID can be alphanumeric with underscore and hyphen. Spaces, punctuation, and other special characters are not allowed. ## 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. +You can create a group and add members at the same time using the `createGroupWithMembers()` method. This method takes the `Group` object, an array of `GroupMember` objects to be added, and an array of `UIDs` to be banned. -To create an object of `Group` class, you can use either of the below two constructors: +To create an object of the `Group` class, you can use either of the following 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: +The `groupType` needs to be one of the following values: 1. `CometChat.GROUP_TYPE.PUBLIC` 2. `CometChat.GROUP_TYPE.PASSWORD` 3. `CometChat.GROUP_TYPE.PRIVATE` -To create an object of `Group Member` class, you can use the below constructor: +To create an object of the `GroupMember` class, you can use the following constructor: * `new GroupMember(String UID, String scope)` @@ -164,10 +185,10 @@ object : CreateGroupWithMembersListener() { -The `onSuccess()` block of this method will provide you with 2 set of info: +The `onSuccess()` block of this method provides you with 2 sets of information: -1. Group : The group object containing the information about the group that is created. -2. HashMap\ : A Hashmap that contains the key as the uid of the user that was supposed to be added and the value as success or error message. +1. `Group`: The group object containing information about the group that was created. +2. `HashMap`: A HashMap that contains the UID of the user that was supposed to be added as the key and `success` or an error message as the value. ## Group Class @@ -188,3 +209,56 @@ The `onSuccess()` block of this method will provide you with 2 set of info: | 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. | + + +## Best Practices + + + + Choose meaningful GUIDs and names that help identify groups. GUIDs should be alphanumeric with underscores/hyphens only - avoid spaces and special characters. + + + Use PUBLIC for open communities, PRIVATE for invite-only groups, and PASSWORD for semi-private groups. Choose based on your privacy requirements. + + + Use the metadata field to store custom group properties like categories, tags, or business-specific data without creating custom group types. + + + +## Troubleshooting + + + + **Symptom:** `createGroup()` fails with "Invalid GUID" error. + + **Cause:** GUID contains spaces, punctuation, or special characters other than underscore and hyphen. + + **Solution:** Use only alphanumeric characters, underscores, and hyphens in GUIDs. Example: `"my_group_123"` or `"group-abc-456"`. + + + **Symptom:** `createGroup()` fails with "Group already exists" error. + + **Cause:** A group with the same GUID already exists in your app. + + **Solution:** Use unique GUIDs for each group. Consider using UUIDs or timestamp-based identifiers to ensure uniqueness. + + + +--- + +## Next Steps + + + + Join existing groups to participate in conversations + + + Add members to your created groups + + + Modify group details and settings + + + Start sending messages in your group + + diff --git a/sdk/android/default-calling.mdx b/sdk/android/default-calling.mdx index 654dc8448..1c02aaea8 100644 --- a/sdk/android/default-calling.mdx +++ b/sdk/android/default-calling.mdx @@ -1,7 +1,34 @@ --- title: "Ringing" +description: "Implement complete calling workflow with ringing, call acceptance, rejection, and cancellation in the Android SDK" --- + +**Quick Reference for AI Agents & Developers** + +```kotlin +// Initiate call +val call = Call("UID", CometChatConstants.RECEIVER_TYPE_USER, CometChatConstants.CALL_TYPE_VIDEO) +CometChat.initiateCall(call, object : CometChat.CallbackListener() { + override fun onSuccess(call: Call) { /* Show outgoing UI */ } + override fun onError(e: CometChatException) { } +}) + +// Accept call +CometChat.acceptCall(sessionID, object : CometChat.CallbackListener() { + override fun onSuccess(call: Call) { /* Start session */ } + override fun onError(e: CometChatException) { } +}) + +// Reject/Cancel call +CometChat.rejectCall(sessionID, CometChatConstants.CALL_STATUS_REJECTED, callback) +``` + + + +**Available via:** SDK | [UI Kits](/ui-kit/android/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**. @@ -203,6 +230,10 @@ CometChat.removeCallListener(listenerId) + +Always remove call listeners when they're no longer needed (e.g., in `onDestroy()` or when navigating away). Failing to remove listeners can cause memory leaks and duplicate event handling. + + ### Events | Event | Description | @@ -561,3 +592,66 @@ CometChat.rejectCall(sessionID, status, object : CometChat.CallbackListener + + +## Best Practices + + + + Remove call listeners in `onDestroy()` or `onPause()` to prevent memory leaks and duplicate callbacks. Use unique listener IDs to manage multiple listeners effectively. + + + Implement all call listener callbacks (`onIncomingCallReceived`, `onOutgoingCallAccepted`, `onOutgoingCallRejected`, `onIncomingCallCancelled`) to provide a complete user experience and handle edge cases. + + + Store the `sessionId` from the `Call` object after initiating a call. You'll need it for accepting, rejecting, canceling, and ending the call. + + + Display different UI for incoming calls (accept/reject buttons), outgoing calls (cancel button), and active calls (end call button) to match user expectations. + + + +## Troubleshooting + + + + **Symptom:** `initiateCall()` fails with "User not logged in" or "Invalid receiver" error. + + **Cause:** User not logged in or invalid receiver UID/GUID. + + **Solution:** Ensure `CometChat.login()` is called successfully before initiating calls. Verify the receiver UID or GUID exists using `CometChat.getUser()` or `CometChat.getGroup()`. + + + **Symptom:** Call listener callbacks are not triggered when calls are received or accepted. + + **Cause:** Listener not registered or removed prematurely. + + **Solution:** Register the call listener in `onCreate()` or `onResume()` and ensure it's not removed until `onDestroy()` or `onPause()`. Verify the listener ID is unique. + + + **Symptom:** After accepting a call, the call session doesn't start or shows a black screen. + + **Cause:** Missing token generation or incorrect call settings. + + **Solution:** Ensure you call `generateToken()` and `startSession()` in the `acceptCall()` success callback. Verify the video container layout exists in your XML. See [Call Session](/sdk/android/direct-calling#start-call-session) for details. + + + +--- + +## Next Steps + + + + Start and manage call sessions with video and audio controls + + + Retrieve and display call history for users and groups + + + Record calls and access recordings from the Dashboard + + + Configure calling dependencies and initialization + + diff --git a/sdk/android/delete-conversation.mdx b/sdk/android/delete-conversation.mdx index 01b3924e8..605e71466 100644 --- a/sdk/android/delete-conversation.mdx +++ b/sdk/android/delete-conversation.mdx @@ -1,12 +1,33 @@ --- title: "Delete A Conversation" +description: "Delete conversations from the recent chats list using the Android SDK" --- + +**Quick Reference for AI Agents & Developers** +```kotlin +// Delete user conversation +CometChat.deleteConversation("UID", CometChatConstants.RECEIVER_TYPE_USER, + object : CallbackListener() { + override fun onSuccess(message: String) { } + override fun onError(e: CometChatException) { } + }) + +// Delete group conversation +CometChat.deleteConversation("GUID", CometChatConstants.RECEIVER_TYPE_GROUP, callback) +``` + +**Note:** This deletes the conversation only for the logged-in user. To delete for all users, use the [REST API](https://api-explorer.cometchat.com/reference/deletes-conversation). + -In case you want to delete a conversation, you can use the `deleteConversation()` method. + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) + -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. +To delete a conversation, use the `deleteConversation()` method. + +This method takes two parameters: the unique id (UID/GUID) of the conversation to be deleted and the type (user/group) of conversation to be deleted. @@ -83,3 +104,66 @@ 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 | + + +## Best Practices + + + + Prompt users to confirm before deleting conversations, especially for important chats, as this action removes the conversation from their list. + + + SDK deletion only removes the conversation for the logged-in user. Use REST API if you need to delete conversations for all participants. + + + Consider offering an "archive" feature using conversation tags instead of deletion, allowing users to hide conversations without losing them permanently. + + + Remove the conversation from your UI immediately after successful deletion to provide instant feedback to users. + + + +## Troubleshooting + + + + **Symptom:** `deleteConversation()` fails with "Conversation not found" error. + + **Cause:** The conversation doesn't exist or has already been deleted. + + **Solution:** Verify the UID/GUID is correct and the conversation exists by fetching it first using [retrieve-conversations](/sdk/android/retrieve-conversations). + + + **Symptom:** Delete fails with "Invalid receiver type" error. + + **Cause:** Receiver type doesn't match the conversation type. + + **Solution:** Use `RECEIVER_TYPE_USER` for user conversations and `RECEIVER_TYPE_GROUP` for group conversations. Check the conversation type before deleting. + + + **Symptom:** Deleted conversation reappears when new messages arrive. + + **Cause:** Deleting a conversation only removes it from the list. New messages create a new conversation entry. + + **Solution:** This is expected behavior. If you want to prevent messages, consider [blocking the user](/sdk/android/block-users) or leaving the group instead. + + + +--- + +## Next Steps + + + + Fetch list of conversations + + + Block users to prevent messages + + + Leave group conversations + + + Delete individual messages + + diff --git a/sdk/android/delete-group.mdx b/sdk/android/delete-group.mdx index 36d3eb938..e57bacc7d 100644 --- a/sdk/android/delete-group.mdx +++ b/sdk/android/delete-group.mdx @@ -1,12 +1,29 @@ --- title: "Delete A Group" +description: "Permanently delete groups as an admin using the Android SDK" --- + +**Quick Reference for AI Agents & Developers** +```kotlin +// Delete a group (admin only) +CometChat.deleteGroup("GUID", object : CometChat.CallbackListener() { + override fun onSuccess(message: String) { } + override fun onError(e: CometChatException) { } +}) +``` + +**Note:** Only group admins can delete groups. This action is permanent and cannot be undone. + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) + ## Delete 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. +To delete a group, use the `deleteGroup()` method. The user must be an **Admin** of the group they are trying to delete. @@ -49,6 +66,59 @@ CometChat.deleteGroup(GUID,object :CometChat.CallbackListener(){ The `deleteGroup()` method takes the following parameters: -| Parameter | Description | -| --------- | ---------------------------------------------- | -| `GUID` | The GUID of the group you would like to delete | +| Parameter | Description | +| --------- | ---------------------------------------- | +| `GUID` | The GUID of the group you want to delete | + + +## Best Practices + + + + Always prompt users to confirm deletion with a clear warning that this action is permanent and will remove all group messages and data. + + + Check the user's scope before showing delete options. Only admins can delete groups. + + + Consider sending a notification or message to group members before deleting the group to give them time to save important information. + + + +## Troubleshooting + + + + **Symptom:** `deleteGroup()` fails with "Insufficient permissions" error. + + **Cause:** User is not an admin of the group. + + **Solution:** Only group admins can delete groups. Check the user's scope using `group.getScope()` before attempting deletion. + + + **Symptom:** `deleteGroup()` fails with "Group not found" error. + + **Cause:** The group GUID is incorrect or the group has already been deleted. + + **Solution:** Verify the GUID is correct and the group still exists by fetching it first using [retrieve-groups](/sdk/android/retrieve-groups). + + + +--- + +## Next Steps + + + + Leave groups without deleting them + + + Modify group details instead of deleting + + + Transfer admin rights to another member + + + Create a new group + + diff --git a/sdk/android/delete-message.mdx b/sdk/android/delete-message.mdx index 082a8ba12..f9f2c83b8 100644 --- a/sdk/android/delete-message.mdx +++ b/sdk/android/delete-message.mdx @@ -1,8 +1,32 @@ --- title: "Delete A Message" +description: "Delete messages from conversations using the Android SDK with real-time event handling" --- + +**Quick Reference for AI Agents & Developers** +```kotlin +// Delete a message by ID +val messageId = 1234 + +CometChat.deleteMessage(messageId, object : CometChat.CallbackListener() { + override fun onSuccess(message: BaseMessage) { + // message.deletedAt contains deletion timestamp + } + override fun onError(e: CometChatException) { } +}) + +// Listen for delete events +CometChat.addMessageListener("LISTENER_ID", object : CometChat.MessageListener() { + override fun onMessageDeleted(message: BaseMessage?) { } +}) +``` + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) + While [deleting a message](/sdk/android/delete-message#delete-a-message) is straightforward, receiving events for deleted messages with CometChat has two parts: @@ -11,9 +35,9 @@ While [deleting a message](/sdk/android/delete-message#delete-a-message) is stra ## Delete a Message -*In other words, as a sender, how do I delete a message?* +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. +To delete a message, use the `deleteMessage()` method. This method takes the message ID of the message to be deleted. For more details on message properties, see [Message Structure & Hierarchy](/sdk/android/message-structure-and-hierarchy). @@ -67,9 +91,9 @@ 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?* +How do I know when someone deletes a message while 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. +To receive real-time events for a message being deleted, override the `onMessageDeleted()` method of the `MessageListener` class. For more information on message listeners, see [Real-Time Listeners](/sdk/android/real-time-listeners). @@ -97,11 +121,19 @@ CometChat.addMessageListener(listenerID, object : CometChat.MessageListener() { + +Always remove listeners when they're no longer needed (e.g., in `onDestroy()` or when navigating away). Failing to remove listeners can cause memory leaks and duplicate event handling. + +```kotlin +CometChat.removeMessageListener("LISTENER_ID") +``` + + ## 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?* +How do I know if someone deleted a message while 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, if 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 `Action` message informing you that the message with ID 50 has been deleted. +When you retrieve the list of previous messages, for the messages that were deleted, the `deletedAt` and the `deletedBy` fields will be set. For example, if the total number of messages for a conversation is 100, and the message with message ID 50 was deleted, the message with ID 50 will have the `deletedAt` and the `deletedBy` fields set whenever it is pulled from the history. Additionally, the 101st message will be an `Action` 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- @@ -115,3 +147,64 @@ For the message deleted event, in the `Action` object received, the following fi In order to 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. + +--- + +## Best Practices + + + + Check user roles before allowing deletions in your UI. Only message senders, group admins, and group moderators can delete messages to prevent unauthorized deletions. + + + Use the `deletedAt` and `deletedBy` fields to identify deleted messages when displaying message history. Consider showing a placeholder like "This message was deleted" instead of removing the message entirely. + + + When a message is deleted, the message object remains in history with `deletedAt` set. This preserves conversation flow and allows users to see that a message existed but was removed. + + + +## Troubleshooting + + + + **Symptom:** `deleteMessage()` fails with "Permission denied" error. + + **Cause:** User attempting to delete a message they didn't send, or lacking admin/moderator privileges in a group. + + **Solution:** Verify the logged-in user is either the message sender or has admin/moderator role in the group. Use `message.getSender().getUid()` to check message ownership before allowing deletion. + + + **Symptom:** `deleteMessage()` fails with "Message not found" error. + + **Cause:** The message ID provided doesn't exist or the message was already deleted. + + **Solution:** Verify the message ID is correct and the message exists. Check if `message.getDeletedAt()` is already set, indicating the message was previously deleted. + + + **Symptom:** Deleted messages continue to show in the message list. + + **Cause:** UI not properly handling the `onMessageDeleted()` callback or not checking the `deletedAt` field when rendering messages. + + **Solution:** Implement the `onMessageDeleted()` listener to update your UI in real-time. When fetching message history, check if `message.getDeletedAt()` is set and render accordingly. + + + +--- + +## Next Steps + + + + Modify text and custom messages after sending + + + Send text, media, and custom messages + + + Handle real-time message events with listeners + + + Understand message types and properties + + diff --git a/sdk/android/delivery-read-receipts.mdx b/sdk/android/delivery-read-receipts.mdx index 93f59de93..67ed1205f 100644 --- a/sdk/android/delivery-read-receipts.mdx +++ b/sdk/android/delivery-read-receipts.mdx @@ -1,14 +1,37 @@ --- title: "Delivery & Read Receipts" +description: "Track message delivery and read status using the Android SDK" --- + +**Quick Reference for AI Agents & Developers** +```kotlin +// Mark messages as delivered +CometChat.markAsDelivered(message.id, message.receiverUid, + CometChatConstants.RECEIVER_TYPE_USER, message.sender.uid) + +// Mark messages as read +CometChat.markAsRead(message.id, message.sender.uid, + CometChatConstants.RECEIVER_TYPE_USER, message.sender.uid) + +// Listen for receipt events +CometChat.addMessageListener("LISTENER_ID", object : MessageListener() { + override fun onMessagesDelivered(receipt: MessageReceipt) { } + override fun onMessagesRead(receipt: MessageReceipt) { } +}) +``` + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) + ## Mark Messages as Delivered -*In other words, as a recipient, how do I inform the sender that I've received a message?* +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: +You can mark the messages for a particular conversation as read using the `markAsDelivered()` method. This method takes the following parameters as input: | Parameter | Information | | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | @@ -190,9 +213,9 @@ Starting v3, the messages will not be marked delivered internally by the SDK. Yo ## Mark Messages as Read -*In other words, as a recipient, how do I inform the sender I've read a message?* +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: +You can mark the messages for a particular conversation as read using the `markAsRead()` method. This method takes the following parameters as input: | Parameter | Information | | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | @@ -466,7 +489,7 @@ CometChat.markAsUnread(message, object : CometChat.CallbackListener() { ## 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?* +How do I know when a message I sent has been delivered or read by someone? ### Real-time events @@ -602,3 +625,72 @@ The following features will be available only if the **Enhanced Messaging Status * `markAsUnread` method. + + +Always remove message listeners when they're no longer needed (e.g., in `onDestroy()` or when navigating away). Failing to remove listeners can cause memory leaks and duplicate event handling. + + +## Best Practices + + + + Call `markAsDelivered()` when fetching messages and when receiving real-time messages to ensure senders know their messages were received. + + + Call `markAsRead()` only when messages are actually visible to the user (e.g., when chat window is open and focused) for accurate read status. + + + Use `markAsDelivered(message)` and `markAsRead(message)` overloads for simpler code when you have the message object available. + + + Listen for receipt events to update your UI with delivery/read indicators (checkmarks) in real-time. + + + Enable "Enhanced Messaging Status" in Dashboard for group message receipts and advanced features like `markAsUnread`. + + + +## Troubleshooting + + + + **Symptom:** `markAsDelivered()` or `markAsRead()` fails silently. + + **Cause:** User not logged in, or incorrect parameters provided. + + **Solution:** Verify user is logged in using `CometChat.getLoggedInUser()`. Use the callback version of methods to catch errors. + + + **Symptom:** `onMessagesDeliveredToAll` or `onMessagesReadByAll` not triggered. + + **Cause:** "Enhanced Messaging Status" feature not enabled in Dashboard. + + **Solution:** Enable the feature in [CometChat Dashboard](https://app.cometchat.com) under your app settings. + + + **Symptom:** Receipt listener methods not being called. + + **Cause:** Message listener not registered or removed prematurely. + + **Solution:** Ensure `addMessageListener()` is called before messages are sent/received. Don't remove listeners while still needed. + + + +--- + +## Next Steps + + + + Show when users are typing + + + Handle incoming messages with listeners + + + Fetch conversation list with unread counts + + + Learn more about event listeners + + diff --git a/sdk/android/direct-calling.mdx b/sdk/android/direct-calling.mdx index 1c5523339..696493e23 100644 --- a/sdk/android/direct-calling.mdx +++ b/sdk/android/direct-calling.mdx @@ -1,7 +1,36 @@ --- title: "Call Session" +description: "Start and manage call sessions with video and audio controls in the Android SDK" --- + +**Quick Reference for AI Agents & Developers** + +```kotlin +// Generate token +val sessionId = "SESSION_ID" +val userAuthToken = CometChat.getUserAuthToken() +CometChatCalls.generateToken(sessionId, userAuthToken, object : CometChatCalls.CallbackListener() { + override fun onSuccess(token: GenerateToken) { /* Start session */ } + override fun onError(e: CometChatException) { } +}) + +// Start session +val callSettings = CometChatCalls.CallSettingsBuilder(context, videoContainer) + .setDefaultLayoutEnable(true) + .setIsAudioOnly(false) + .build() +CometChatCalls.startSession(token, callSettings, callback) + +// End session +CometChatCalls.endSession() +``` + + + +**Available via:** SDK | [UI Kits](/ui-kit/android/overview) + + ## Overview This section demonstrates how to start a call session in an Android application. Previously known as **Direct Calling**. @@ -298,7 +327,9 @@ CometChatCalls.addCallsEventListeners(listenerId, object: CometChatCallsEventsLi - + +Always remove call event listeners when they're no longer needed (e.g., in `onDestroy()` or when navigating away). Failing to remove listeners can cause memory leaks and duplicate event handling. + ### Events @@ -663,3 +694,76 @@ CometChatCalls.endSession() + + +## Best Practices + + + + Remove call event listeners in `onDestroy()` or `onPause()` to prevent memory leaks. Use unique listener IDs to manage multiple listeners across different activities or fragments. + + + Ensure the `RelativeLayout` for the video container exists in your XML layout before calling `startSession()`. The container must be visible and properly sized to display video streams. + + + Always implement error handling for `generateToken()`. Token generation can fail due to network issues or invalid session IDs. Inform users and provide retry options. + + + Set `setIsAudioOnly(true)` for audio-only calls to save bandwidth and improve performance. Use `startWithAudioMuted()` or `startWithVideoMuted()` when appropriate for user privacy. + + + Always call `endSession()` when leaving the call screen to release camera, microphone, and network resources. For ringing flow, call `CometChat.endCall()` first to notify participants. + + + +## Troubleshooting + + + + **Symptom:** `generateToken()` fails with "Invalid session ID" or "Unauthorized" error. + + **Cause:** Invalid session ID or user not logged in. + + **Solution:** Verify the session ID is correct (from `Call` object in ringing flow or generated randomly for standalone). Ensure `CometChat.login()` was called successfully and `getUserAuthToken()` returns a valid token. + + + **Symptom:** Call starts but shows a black screen instead of video. + + **Cause:** Video container not properly configured or camera permissions denied. + + **Solution:** Verify the `RelativeLayout` exists in your XML and is visible. Check that camera permissions are granted in `AndroidManifest.xml` and at runtime. Ensure `setIsAudioOnly(false)` is set for video calls. + + + **Symptom:** `startSession()` fails or doesn't trigger any callbacks. + + **Cause:** Invalid call token or missing calling setup. + + **Solution:** Ensure you've completed the [Calling Setup](/sdk/android/calling-setup) including adding the Calls SDK dependency. Verify the `GenerateToken` object is valid and not expired. Check that the activity context is valid. + + + **Symptom:** Video works but no audio is transmitted or received. + + **Cause:** Microphone permissions denied or audio muted. + + **Solution:** Check that microphone permissions are granted. Verify `startWithAudioMuted(false)` is set. Test audio output device using `setAudioMode()` to switch between speaker and earpiece. + + + +--- + +## Next Steps + + + + Implement complete calling workflow with incoming/outgoing call UI + + + Retrieve and display call history for users and groups + + + Record calls and access recordings from the Dashboard + + + Customize video tile layouts and appearance + + diff --git a/sdk/android/edit-message.mdx b/sdk/android/edit-message.mdx index 9385d0b71..079443db8 100644 --- a/sdk/android/edit-message.mdx +++ b/sdk/android/edit-message.mdx @@ -1,8 +1,35 @@ --- title: "Edit A Message" +description: "Edit text and custom messages sent to users and groups using the Android SDK" --- + +**Quick Reference for AI Agents & Developers** +```kotlin +// Edit a text message +val updatedMessage = TextMessage( + message.receiverUid, + "Updated text", + message.receiverType +) +updatedMessage.id = message.id + +CometChat.editMessage(updatedMessage, object: CometChat.CallbackListener() { + override fun onSuccess(message: BaseMessage) { } + override fun onError(e: CometChatException) { } +}) + +// Listen for edit events +CometChat.addMessageListener("LISTENER_ID", object : CometChat.MessageListener() { + override fun onMessageEdited(message: BaseMessage) { } +}) +``` + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) + While [editing a message](/sdk/android/edit-message#edit-a-message) is straightforward, receiving events for edited messages with CometChat has two parts: @@ -11,9 +38,9 @@ While [editing a message](/sdk/android/edit-message#edit-a-message) is straightf ## Edit a Message -*In other words, as a sender, how do I edit a message?* +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. +To edit a message, use the `editMessage()` method. This method takes an object of the `BaseMessage` class. Currently, you can only edit `TextMessage` and `CustomMessage`. Thus, the `BaseMessage` object must either be a Text or a Custom Message. For more details on message types, see [Message Structure & Hierarchy](/sdk/android/message-structure-and-hierarchy). ### Add/Update Tags @@ -100,9 +127,9 @@ 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?* +How do I know when someone has edited their message while 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. +To receive real-time events for messages being edited, override the `onMessageEdited()` method of the `MessageListener` class. For more information on message listeners, see [Real-Time Listeners](/sdk/android/real-time-listeners). @@ -130,11 +157,19 @@ CometChat.addMessageListener(listenerID, object : CometChat.MessageListener() { + +Always remove listeners when they're no longer needed (e.g., in `onDestroy()` or when navigating away). Failing to remove listeners can cause memory leaks and duplicate event handling. + +```kotlin +CometChat.removeMessageListener("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?* +How do I know when someone edited their message while 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, if the total number of messages for a conversation is 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 an `Action` message informing you that the message with ID 50 has been edited.. +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, if the total number of messages for a conversation is 100, and the message with message ID 50 was edited, the message with ID 50 will have the `editedAt` and the `editedBy` fields set whenever it is pulled from the history. Additionally, the 101st message will be an `Action` message informing you that the message with ID 50 has been edited.. For the message edited event, in the `Action` object received, the following fields can help you get the relevant information- @@ -148,3 +183,64 @@ 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. + +--- + +## Best Practices + + + + Always set the message ID from the original message using `setId()` before calling `editMessage()`. Without the correct ID, the edit operation will fail. + + + Tags set during editing completely replace the original tags. If you want to preserve existing tags, retrieve them first and merge with new tags before calling `setTags()`. + + + Check user roles before allowing edits in your UI. Only message senders, group owners, and group moderators can edit messages to prevent unauthorized modifications. + + + +## Troubleshooting + + + + **Symptom:** `editMessage()` fails with "Permission denied" error. + + **Cause:** User attempting to edit a message they didn't send, or lacking admin/moderator privileges in a group. + + **Solution:** Verify the logged-in user is either the message sender or has admin/moderator role in the group. Use `message.getSender().getUid()` to check message ownership. + + + **Symptom:** `editMessage()` fails with "Invalid message ID" error. + + **Cause:** The message ID was not set on the updated message object before calling `editMessage()`. + + **Solution:** Always call `updatedMessage.setId(originalMessage.getId())` before editing. The ID is required to identify which message to update. + + + **Symptom:** Attempting to edit a media message fails. + + **Cause:** CometChat only supports editing `TextMessage` and `CustomMessage` types. Media messages cannot be edited. + + **Solution:** Check the message type before allowing edits. Only enable edit functionality for text and custom messages in your UI. + + + +--- + +## Next Steps + + + + Remove messages from conversations + + + Send text, media, and custom messages + + + Handle real-time message events with listeners + + + Understand message types and properties + + diff --git a/sdk/android/extensions-overview.mdx b/sdk/android/extensions-overview.mdx index 29c1774bd..23b1f6552 100644 --- a/sdk/android/extensions-overview.mdx +++ b/sdk/android/extensions-overview.mdx @@ -1,4 +1,43 @@ --- title: "Extensions" +description: "Enhance your Android app with CometChat extensions for moderation, translation, and more" url: "/fundamentals/extensions-overview" ---- \ No newline at end of file +--- + + +**Quick Reference for AI Agents & Developers** + +CometChat Extensions add powerful features to your chat application: +- **Content Moderation** - Filter inappropriate content automatically +- **Message Translation** - Translate messages in real-time +- **Sentiment Analysis** - Analyze message sentiment +- **Profanity Filter** - Block offensive language +- **Image Moderation** - Scan images for inappropriate content +- **Thumbnail Generation** - Auto-generate image thumbnails +- **Link Preview** - Display rich previews for URLs + +**Learn more:** [Extensions Overview](/fundamentals/extensions-overview) + + +Extensions are server-side features that enhance your CometChat implementation without requiring additional client-side code. They are configured through the [CometChat Dashboard](https://app.cometchat.com) and work automatically once enabled. + +For detailed information about available extensions, configuration options, and implementation guides, visit the [Extensions Overview](/fundamentals/extensions-overview) in the Fundamentals section. + +--- + +## Next Steps + + + + Explore all available CometChat extensions + + + Implement AI-powered content moderation + + + Configure extensions in your dashboard + + + Set up server-side event notifications + + \ No newline at end of file diff --git a/sdk/android/flag-message.mdx b/sdk/android/flag-message.mdx index 0843d2902..992be0b12 100644 --- a/sdk/android/flag-message.mdx +++ b/sdk/android/flag-message.mdx @@ -1,11 +1,40 @@ --- title: "Flag Message" +description: "Report inappropriate messages to moderators using the Android SDK flagging system" --- + +**Quick Reference for AI Agents & Developers** + +```kotlin +// Get available flag reasons +CometChat.getFlagReasons(object : CometChat.CallbackListener>() { + override fun onSuccess(reasons: MutableList?) { + // Display reasons to user + } + override fun onError(e: CometChatException) { } +}) + +// Flag a message +val flagDetail = FlagDetail().apply { + reasonId = "spam" + remark = "Promotional content" +} +CometChat.flagMessage(messageId, flagDetail, object : CometChat.CallbackListener() { + override fun onSuccess(response: String?) { } + override fun onError(e: CometChatException?) { } +}) +``` + + ## 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](https://app.cometchat.com) + + For a complete understanding of how flagged messages are reviewed and managed, see the [Flagged Messages](/moderation/flagged-messages) documentation. @@ -225,3 +254,65 @@ Here's a complete implementation showing how to build a report message flow: ``` + +## Best Practices + + + + Fetch flag reasons once during app initialization and cache them locally. This reduces API calls and provides instant access when users need to report messages. + + + Display flag reasons in a user-friendly dialog or bottom sheet. Include the optional remark field to allow users to provide additional context about why they're reporting the message. + + + Show a confirmation dialog before submitting the flag to prevent accidental reports. Explain to users that flagged messages will be reviewed by moderators. + + + If a user tries to flag the same message multiple times, handle the error gracefully and inform them the message has already been reported. + + + +## Troubleshooting + + + + **Symptom:** `getFlagReasons()` or `flagMessage()` fails with "Moderation is not enabled" error. + + **Cause:** Moderation feature is not enabled for your app in the CometChat Dashboard. + + **Solution:** Enable moderation in the [CometChat Dashboard](https://app.cometchat.com) under **Moderation > Settings**. Configure flag reasons under **Advanced Settings**. + + + **Symptom:** `flagMessage()` fails with "Invalid reason ID" error. + + **Cause:** The reasonId provided doesn't match any configured flag reasons. + + **Solution:** Always use reason IDs from the `getFlagReasons()` response. Verify the reason ID exists in your Dashboard configuration. + + + **Symptom:** `flagMessage()` fails with "Message already flagged" error. + + **Cause:** The user has already flagged this message previously. + + **Solution:** Inform the user that they've already reported this message. Consider disabling the flag button for previously flagged messages. + + + +--- + +## Next Steps + + + + Review and manage flagged messages in the Dashboard + + + Automatically detect and filter inappropriate content + + + Allow users to block other users from contacting them + + + Delete messages from conversations + + diff --git a/sdk/android/group-add-members.mdx b/sdk/android/group-add-members.mdx index a135b4615..8bb455bb0 100644 --- a/sdk/android/group-add-members.mdx +++ b/sdk/android/group-add-members.mdx @@ -1,8 +1,31 @@ --- title: "Add Members To A Group" +description: "Add members to groups with specific roles using the Android SDK" --- + +**Quick Reference for AI Agents & Developers** +```kotlin +// Add members to a group +val members = listOf( + GroupMember("uid1", CometChatConstants.SCOPE_MODERATOR), + GroupMember("uid2", CometChatConstants.SCOPE_PARTICIPANT) +) + +CometChat.addMembersToGroup("GUID", members, null, + object : CallbackListener>() { + override fun onSuccess(result: HashMap) { } + override fun onError(e: CometChatException) { } + }) +``` + +**Note:** Only admins and moderators can add members. The result HashMap contains UID as key and "success" or error message as value. + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) + ## Add Members to Group @@ -60,7 +83,7 @@ In the `onSuccess()` method of the `CallbackListener`, you will receive a HashMa ## 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?* +How do I know when someone is added to the group while my app is running? @@ -68,9 +91,9 @@ When a group member is added by another member, this event is triggered. When a -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. +To receive real-time events whenever a new member is added to a group, implement the `onMemberAddedToGroup()` method 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. +* `onMemberAddedToGroup()` - This method is triggered when any user is added to the group, informing the logged-in user of the other members added to the group. @@ -100,9 +123,9 @@ CometChat.addGroupListener("UNIQUE_ID", object : CometChat.GroupListener() { ## 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?* +How do I know when someone is added to the group while 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. +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 the `BaseMessage` class. For the group member added event, in the `Action` object received, the following fields can help you get the relevant information- @@ -110,3 +133,69 @@ 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 + + +Always remove group listeners when they're no longer needed (e.g., in `onDestroy()` or when navigating away). Failing to remove listeners can cause memory leaks and duplicate event handling. + + +## Best Practices + + + + Choose member scopes carefully: ADMIN for full control, MODERATOR for moderation tasks, PARTICIPANT for regular members. Limit admin count to maintain control. + + + Add multiple members in a single call instead of multiple individual calls to improve performance and reduce API overhead. + + + Check the result HashMap for each UID - some additions may succeed while others fail. Handle each case appropriately in your UI. + + + Verify user UIDs exist before attempting to add them to avoid unnecessary API errors. + + + +## Troubleshooting + + + + **Symptom:** `addMembersToGroup()` fails with "Insufficient permissions" error. + + **Cause:** User is not an admin or moderator of the group. + + **Solution:** Only admins and moderators can add members. Check the user's scope before showing add member options. + + + **Symptom:** Result HashMap shows errors for some UIDs. + + **Cause:** UIDs may not exist, users may already be members, or users may be banned. + + **Solution:** Check the error message for each UID in the result HashMap. Verify UIDs exist and users aren't already members or banned. + + + **Symptom:** Adding members to private group fails. + + **Cause:** Private groups have restricted membership. + + **Solution:** Ensure you have admin or moderator permissions. Private groups require explicit member additions by authorized users. + + + +--- + +## Next Steps + + + + Remove members from groups + + + Update member roles and permissions + + + Fetch list of group members + + + Handle real-time group events + + diff --git a/sdk/android/group-change-member-scope.mdx b/sdk/android/group-change-member-scope.mdx index 13303f53b..c3d1a7a17 100644 --- a/sdk/android/group-change-member-scope.mdx +++ b/sdk/android/group-change-member-scope.mdx @@ -1,12 +1,38 @@ --- title: "Change Member Scope" +description: "Update group member roles and permissions using the Android SDK" --- + +**Quick Reference for AI Agents & Developers** +```kotlin +// Change member scope (admin only) +CometChat.updateGroupMemberScope( + "UID", + "GUID", + CometChatConstants.SCOPE_MODERATOR, + object : CallbackListener() { + override fun onSuccess(message: String) { } + override fun onError(e: CometChatException) { } + }) +``` + +**Available Scopes:** +- `SCOPE_ADMIN` - Full control over group +- `SCOPE_MODERATOR` - Can moderate members and content +- `SCOPE_PARTICIPANT` - Regular member (default) + +**Note:** Only group admins can change member scopes. + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) + ## Change Scope of a Group Member -In order to change the scope of a group member, you can use the `changeGroupMemberScope()`. +To change the scope of a group member, use the `changeGroupMemberScope()` method. @@ -63,9 +89,9 @@ The default scope of any member is `participant`. Only the **Admin** of the grou ## 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?* +How do I know when someone's scope is changed while my app is running? -In order to receive real-time events whenever a group member's scope changes, you will need to override the `onGroupMemberScopeChanged()` method of the `GroupListener` class +To receive real-time events whenever a group member's scope changes, override the `onGroupMemberScopeChanged()` method of the `GroupListener` class. @@ -95,9 +121,9 @@ CometChat.addGroupListener("ListenerID", object : CometChat.GroupListener() { ## 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?* +How do I know when someone's scope is changed while 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. +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 the `BaseMessage` class. For the group member scope changed event, in the `Action` object received, the following fields can help you get the relevant information- @@ -107,3 +133,69 @@ 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 + + +Always remove group listeners when they're no longer needed (e.g., in `onDestroy()` or when navigating away). Failing to remove listeners can cause memory leaks and duplicate event handling. + + +## Best Practices + + + + Keep the number of admins small (2-3) to maintain clear ownership and control. Too many admins can lead to conflicts and management issues. + + + Use the moderator role for trusted members who help manage the group without full admin privileges. This provides a middle tier of authority. + + + Prompt admins to confirm before changing member scopes, especially when promoting to admin or demoting from admin/moderator roles. + + + Listen for scope change events to maintain an audit log of permission changes for security and accountability. + + + +## Troubleshooting + + + + **Symptom:** `updateGroupMemberScope()` fails with "Insufficient permissions" error. + + **Cause:** User is not an admin of the group. + + **Solution:** Only group admins can change member scopes. Moderators cannot change scopes. Check the user's scope before showing this option. + + + **Symptom:** Admin cannot change their own scope. + + **Cause:** Admins cannot demote themselves to prevent accidental loss of admin access. + + **Solution:** Have another admin change your scope, or use [transfer-group-ownership](/sdk/android/transfer-group-ownership) if you want to step down. + + + **Symptom:** Scope change fails with "Invalid scope" error. + + **Cause:** Scope value is not one of the valid constants. + + **Solution:** Use only `CometChatConstants.SCOPE_ADMIN`, `SCOPE_MODERATOR`, or `SCOPE_PARTICIPANT`. + + + +--- + +## Next Steps + + + + Add new members with specific scopes + + + Remove members from groups + + + Transfer group ownership to another admin + + + Fetch list of group members + + diff --git a/sdk/android/group-kick-member.mdx b/sdk/android/group-kick-member.mdx index fbbd7cb5c..d8ce9d656 100644 --- a/sdk/android/group-kick-member.mdx +++ b/sdk/android/group-kick-member.mdx @@ -1,8 +1,31 @@ --- title: "Ban/Kick Member From A Group" +description: "Kick, ban, and unban group members using the Android SDK" --- + +**Quick Reference for AI Agents & Developers** +```kotlin +// Kick a member (can rejoin) +CometChat.kickGroupMember("UID", "GUID", object : CallbackListener() { + override fun onSuccess(message: String) { } + override fun onError(e: CometChatException) { } +}) + +// Ban a member (cannot rejoin without unban) +CometChat.banGroupMember("UID", "GUID", callback) + +// Unban a member +CometChat.unbanGroupMember("UID", "GUID", callback) +``` + +**Note:** Only admins and moderators can kick, ban, or unban members. + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) + There are certain actions that can be performed on the group members: @@ -171,9 +194,9 @@ The unbanned user can now 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. +To fetch the list of banned group members for a group, use the `BannedGroupMembersRequest` class. 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 fetched. -The `BannedGroupMembersRequestBuilder` class allows you to set the below parameters: +The `BannedGroupMembersRequestBuilder` class allows you to set the following 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. @@ -227,9 +250,9 @@ val bannedGroupMembersRequest = BannedGroupMembersRequestBuilder(GUID) -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. +Finally, once all the parameters are set on the builder class, 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 you have the object of the `BannedGroupMembersRequest` class, call the `fetchNext()` method. This method returns a list of `GroupMember` objects containing n number of banned members where n is the limit set in the builder class. @@ -278,9 +301,9 @@ bannedGroupMembersRequest?.fetchNext(object :CometChat.CallbackListener +Always remove group listeners when they're no longer needed (e.g., in `onDestroy()` or when navigating away). Failing to remove listeners can cause memory leaks and duplicate event handling. + + +## Best Practices + + + + Use kick for temporary removal (user can rejoin). Use ban for permanent removal (requires unban to rejoin). Choose based on severity of violation. + + + Always prompt admins/moderators to confirm before kicking or banning members, as these actions immediately remove users from the group. + + + Store ban reasons in your database or use metadata to track why members were banned for future reference and appeals. + + + Use `BannedGroupMembersRequest` to review banned members list and consider unbanning users after appropriate time periods. + + + +## Troubleshooting + + + + **Symptom:** Operation fails with "Insufficient permissions" error. + + **Cause:** User is not an admin or moderator of the group. + + **Solution:** Only admins and moderators can kick or ban members. Check the user's scope before showing these options. + + + **Symptom:** Operation fails when trying to kick or ban an admin. + + **Cause:** Admins have elevated permissions and cannot be kicked or banned by moderators. + + **Solution:** Only group owners or other admins can remove admin members. Consider changing their scope first using [group-change-member-scope](/sdk/android/group-change-member-scope). + + + **Symptom:** `unbanGroupMember()` fails with "User not banned" error. + + **Cause:** The user is not currently banned from the group. + + **Solution:** Fetch the banned members list first using `BannedGroupMembersRequest` to verify the user is banned. + + + +--- + +## Next Steps + + + + Add new members to groups + + + Update member roles and permissions + + + Fetch list of group members + + + Handle real-time group events + + diff --git a/sdk/android/groups-overview.mdx b/sdk/android/groups-overview.mdx index 99e877026..e2abf72e2 100644 --- a/sdk/android/groups-overview.mdx +++ b/sdk/android/groups-overview.mdx @@ -1,10 +1,43 @@ --- title: "Groups" sidebarTitle: "Overview" +description: "Manage group creation, membership, and permissions in the Android SDK" --- + +**Quick Reference for AI Agents & Developers** +Choose your path: +- **Create Groups** → [create-group](/sdk/android/create-group) - Public, private, password-protected groups +- **Join Groups** → [join-group](/sdk/android/join-group) - Participate in group conversations +- **Retrieve Groups** → [retrieve-groups](/sdk/android/retrieve-groups) - Fetch groups list +- **Manage Members** → [group-add-members](/sdk/android/group-add-members) - Add, remove, update members + -Groups help your users to converse together in a single space. You can have three types of groups- private, public and password protected. +Groups help your users 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- admin, moderator, member. + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) + + +Each group includes three kinds of users: admin, moderator, and member. + + +--- + +## Next Steps + + + + Create public, private, or password-protected groups + + + Join existing groups to participate in conversations + + + Fetch and filter groups list + + + Add, remove, and update group members + + diff --git a/sdk/android/interactive-messages.mdx b/sdk/android/interactive-messages.mdx index d6f468c0e..758df6634 100644 --- a/sdk/android/interactive-messages.mdx +++ b/sdk/android/interactive-messages.mdx @@ -1,8 +1,38 @@ --- title: "Interactive Messages" +description: "Send messages with embedded interactive content like forms and buttons for enhanced user engagement" --- + +**Quick Reference for AI Agents & Developers** +```kotlin +// Create interactive message with form +val interactiveData = JSONObject().apply { + put("title", "Demo Form") + put("formFields", JSONArray().apply { + put(JSONObject().apply { + put("elementType", "textInput") + put("elementId", "element1") + put("label", "Name") + }) + }) +} + +val interactiveMessage = InteractiveMessage("receiverId", CometChatConstants.RECEIVER_TYPE_USER, "form", interactiveData) +CometChat.sendInteractiveMessage(interactiveMessage, object : CallbackListener() { + override fun onSuccess(message: InteractiveMessage) { } + override fun onError(e: CometChatException) { } +}) + +// Mark as interacted +CometChat.markAsInteracted(messageId, "elementId", callback) +``` + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) + 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. This enhances user engagement by making the chat experience more interactive and responsive to user input. @@ -31,25 +61,6 @@ An Interaction represents a user action involved with an `InteractiveMessage`. I This method marks a message as interacted by identifying it with the provided Id. it also logs the interactive element associated with the interaction. - -```java -int messageId = 1; -String elementId = "elementId"; -CometChat.markAsInteracted(messageId, elementId, new CometChat.CallbackListener() { - @Override - public void onSuccess(Void unused) { - - } - - @Override - public void onError(CometChatException e) { - - } -}); -``` - - - ```kotlin val messageId = 1 @@ -65,9 +76,24 @@ CometChat.markAsInteracted(messageId, elementId, object : CometChat.CallbackList } }) ``` - + +```java +int messageId = 1; +String elementId = "elementId"; +CometChat.markAsInteracted(messageId, elementId, new CometChat.CallbackListener() { + @Override + public void onSuccess(Void unused) { + } + + @Override + public void onError(CometChatException e) { + + } +}); +``` + ### Goal Completion @@ -94,9 +120,52 @@ The `InteractionGoal` represents the desired outcome of an interaction with an I 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. +Before sending interactive messages, ensure you have [initialized the SDK](/sdk/android/setup) and [logged in a user](/sdk/android/authentication-overview). + Here is an example of how to use it: + +```kotlin +val interactiveData = JSONObject() +try { + interactiveData.put("title", "Demo Form") + val jsonArray = JSONArray() + val textInput = JSONObject() + textInput.put("elementType", "textInput") + textInput.put("elementId", "element1") + textInput.put("label", "Name") + textInput.put("optional", false) + textInput.put("maxLines", 1) + jsonArray.put(textInput) + interactiveData.put("formFields", jsonArray) + val submitElement = JSONObject() + submitElement.put("elementType", "button") + submitElement.put("elementId", "element8") + submitElement.put("buttonText", "Submit") + submitElement.put("disableAfterInteracted", true) + val action = JSONObject() + action.put("actionType", "urlNavigation") + action.put("url", "https://www.cometchat.com/") + submitElement.put("action", action) + interactiveData.put("submitElement", submitElement) +} catch (e: JSONException) { + throw RuntimeException(e) +} + +val interactiveMessage = InteractiveMessage(receiverId, receiverType, "form", interactiveData) + +CometChat.sendInteractiveMessage(interactiveMessage, object : CometChat.CallbackListener() { + override fun onSuccess(interactiveMessage: InteractiveMessage) { + // This block is executed when the InteractiveMessage is sent successfully. + } + + override fun onError(e: CometChatException) { + // This block is executed if an error occurs while sending the InteractiveMessage. + } +}) +``` + ```java JSONObject interactiveData = new JSONObject(); @@ -139,63 +208,28 @@ CometChat.sendInteractiveMessage(interactiveMessage, new CometChat.CallbackListe } }); ``` - - - -```kotlin -val interactiveData = JSONObject() -try { - interactiveData.put("title", "Demo Form") - val jsonArray = JSONArray() - val textInput = JSONObject() - textInput.put("elementType", "textInput") - textInput.put("elementId", "element1") - textInput.put("label", "Name") - textInput.put("optional", false) - textInput.put("maxLines", 1) - jsonArray.put(textInput) - interactiveData.put("formFields", jsonArray) - val submitElement = JSONObject() - submitElement.put("elementType", "button") - submitElement.put("elementId", "element8") - submitElement.put("buttonText", "Submit") - submitElement.put("disableAfterInteracted", true) - val action = JSONObject() - action.put("actionType", "urlNavigation") - action.put("url", "https://www.cometchat.com/") - submitElement.put("action", action) - interactiveData.put("submitElement", submitElement) -} catch (e: JSONException) { - throw RuntimeException(e) -} - -val interactiveMessage = InteractiveMessage(receiverId, receiverType, "form", interactiveData) - -CometChat.sendInteractiveMessage(interactiveMessage, object : CometChat.CallbackListener() { - override fun onSuccess(interactiveMessage: InteractiveMessage) { - // This block is executed when the InteractiveMessage is sent successfully. - } - - override fun onError(e: CometChatException) { - // This block is executed if an error occurs while sending the InteractiveMessage. - } -}) -``` - - - ### Event Listeners -CometChat SDK provides event listeners to handle real-time events related to `InteractiveMessage`. +CometChat SDK provides event listeners to handle real-time events related to `InteractiveMessage`. For more details on listener management, see [Real-Time Listeners](/sdk/android/real-time-listeners). On `InteractiveMessage` Received The `onInteractiveMessageReceived` event listener is triggered when an InteractiveMessage is received. Here is an example: + +```kotlin +CometChat.addMessageListener("UNIQUE_ID", object : CometChat.MessageListener() { + override fun onInteractiveMessageReceived(interactiveMessage: 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. + } +}) +``` + ```java CometChat.addMessageListener("UNIQUE_ID", new CometChat.MessageListener() { @@ -206,23 +240,13 @@ CometChat.addMessageListener("UNIQUE_ID", new CometChat.MessageListener() { } }); ``` - - - -```kotlin -CometChat.addMessageListener("UNIQUE_ID", object : CometChat.MessageListener() { - override fun onInteractiveMessageReceived(interactiveMessage: 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. - } -}) -``` - - - + +Always remove listeners when they're no longer needed (e.g., in `onDestroy()` or when navigating away). Failing to remove listeners can cause memory leaks and duplicate event handling. + + ### On Interaction Goal Completed The `onInteractionGoalCompleted` event listener is invoked when an interaction goal is achieved. @@ -230,6 +254,16 @@ The `onInteractionGoalCompleted` event listener is invoked when an interaction g Here is an example: + +```kotlin +CometChat.addMessageListener("UNIQUE_ID", object : CometChat.MessageListener() { + override fun onInteractionGoalCompleted(interactionReceipt: 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. + } +}) +``` + ```java CometChat.addMessageListener("UNIQUE_ID", new CometChat.MessageListener() { @@ -240,21 +274,7 @@ CometChat.addMessageListener("UNIQUE_ID", new CometChat.MessageListener() { } }); ``` - - - - -```kotlin -CometChat.addMessageListener("UNIQUE_ID", object : CometChat.MessageListener() { - override fun onInteractionGoalCompleted(interactionReceipt: 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. - } -}) -``` - - 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. @@ -262,3 +282,39 @@ These event listeners offer your application a way to provide real-time updates ## 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. + +## Best Practices + + + + Always validate your JSONObject structure before sending interactive messages. Ensure all required fields (elementType, elementId, etc.) are present to avoid runtime errors. + + + Assign unique element IDs to each interactive component within a message. This ensures accurate tracking of user interactions and prevents conflicts when processing interaction events. + + + Choose the right interaction goal type based on your use case. Use `ANY` for simple acknowledgments, `ANY_OF` for optional selections, and `ALL_OF` for required form completions. + + + Implement the `onInteractionGoalCompleted` listener to track when users complete interactive elements. This enables you to trigger follow-up actions or update your UI accordingly. + + + +--- + +## Next Steps + + + + Learn how to send text, media, and custom messages + + + Mention specific users in messages for better engagement + + + Handle incoming messages with real-time listeners + + + Manage event listeners for real-time updates + + diff --git a/sdk/android/join-group.mdx b/sdk/android/join-group.mdx index 514297a66..c88c6ce0d 100644 --- a/sdk/android/join-group.mdx +++ b/sdk/android/join-group.mdx @@ -1,12 +1,31 @@ --- title: "Join A Group" +description: "Join public, private, and password-protected groups using the Android SDK" --- + +**Quick Reference for AI Agents & Developers** +```kotlin +// Join a public group +CometChat.joinGroup("GUID", CometChatConstants.GROUP_TYPE_PUBLIC, "", + object : CometChat.CallbackListener() { + override fun onSuccess(group: Group) { } + override fun onError(e: CometChatException) { } + }) + +// Join a password-protected group +CometChat.joinGroup("GUID", CometChatConstants.GROUP_TYPE_PASSWORD, "password123", callback) +``` + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/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. +To start participating in group conversations, you need to join a group. You can do so using the `joinGroup()` method. @@ -50,23 +69,23 @@ CometChat.joinGroup(GUID,groupType,password,object:CometChat.CallbackListener -The `joinGroup()` method takes the below parameters +The `joinGroup()` method takes the following parameters: | 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.CometChatConstants.GROUP\_TYPE\_PUBLIC (public) 2.CometChatConstants.GROUP\_TYPE\_PASSWORD (password) 3.CometChatConstants.GROUP\_TYPE\_PRIVATE (private) | -| `password` | Password is mandatory in case of a password protected group. | +| `groupType` | Type of the group. CometChat provides 3 types of groups: 1. `CometChatConstants.GROUP_TYPE_PUBLIC` (public) 2. `CometChatConstants.GROUP_TYPE_PASSWORD` (password) 3. `CometChatConstants.GROUP_TYPE_PRIVATE` (private) | +| `password` | Password is mandatory for password-protected groups. | 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 everytime you want to communicate in the group. +CometChat keeps track of the groups you have joined, so you do not need to join the group every time you want to communicate in it. You can identify if a group is joined using the `hasJoined` parameter in the `Group` object. -## Real-time Group Member Joined Events +## 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?* +*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. @@ -98,12 +117,75 @@ CometChat.addGroupListener(UNIQUE_LISTENER_ID, object : GroupListener() { ## 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?* +*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. +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 the `BaseMessage` class. -For the group member joined event, in the `Action` object received, the following fields can help you get the relevant information- +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 +3. `actionFor` - Group object containing the details of the group the user has joined + + +Always remove group listeners when they're no longer needed (e.g., in `onDestroy()` or when navigating away). Failing to remove listeners can cause memory leaks and duplicate event handling. + + +## Best Practices + + + + Use the `hasJoined` property of the Group object to avoid attempting to join groups you're already a member of. + + + Always prompt users for passwords when joining password-protected groups. Store passwords securely if needed for re-authentication. + + + Register group listeners to receive real-time notifications when other users join groups you're a member of. + + + +## Troubleshooting + + + + **Symptom:** `joinGroup()` fails with "Already a member" error. + + **Cause:** User is already a member of the group. + + **Solution:** Check the `hasJoined` property before calling `joinGroup()`. CometChat tracks joined groups automatically. + + + **Symptom:** `joinGroup()` fails with "Incorrect password" error for password-protected groups. + + **Cause:** Wrong password provided for a password-protected group. + + **Solution:** Verify the password is correct. Passwords are case-sensitive. + + + **Symptom:** `joinGroup()` fails with "Cannot join private group" error. + + **Cause:** Attempting to join a private group without an invitation. + + **Solution:** Private groups require an admin or moderator to add members. Use the [group-add-members](/sdk/android/group-add-members) functionality instead. + + + +--- + +## Next Steps + + + + Leave groups you no longer want to participate in + + + Fetch list of group members + + + Start sending messages in the group + + + Handle real-time group events + + diff --git a/sdk/android/key-concepts.mdx b/sdk/android/key-concepts.mdx index 71f0f4bf3..6d7f2c34d 100644 --- a/sdk/android/key-concepts.mdx +++ b/sdk/android/key-concepts.mdx @@ -1,8 +1,31 @@ --- title: "Key Concepts" +description: "Understand core CometChat concepts including users, groups, authentication, and messaging" --- + +**Quick Reference for AI Agents & Developers** +**Core Entities:** +- **Users**: Identified by UID (alphanumeric with underscore/hyphen) +- **Groups**: Identified by GUID (alphanumeric with underscore/hyphen) +- **Auth Token**: Per user per device, generated server-side +- **Roles**: Categories for grouping similar users (e.g., "Premium") + +**Group Types:** +- **Public**: Any user can join +- **Password**: Requires password to join +- **Private**: Invitation only + +**Member Scopes:** +- **Admin**: Full control (change scopes, kick/ban, update/delete group) +- **Moderator**: Moderate members (kick/ban participants, update group) +- **Participant**: Send and receive messages/calls + +**Message Categories:** message, custom, action, call + +**Connection Modes:** Auto (WebSocket in foreground only) | Manual (explicit connect/disconnect) + ### CometChat Dashboard @@ -11,13 +34,14 @@ The CometChat Dashboard enables you to create new apps (projects) and manage you 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.\ -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! +Ideally, you should 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. +* 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 need to create an Auth Key (from the Dashboard) which can be used for user authentication. ### Auth & Rest API Keys @@ -45,17 +69,17 @@ UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and othe ### 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. +* A single user can have multiple auth tokens. Auth tokens should be per user per device. +* Auth tokens should ideally be generated via a server-to-server API call. The auth token should then be passed to CometChat for login. +* An Auth Token can only be deleted via the dashboard or using the REST API. ### Authentication To allow a user to use CometChat, the user must log in to CometChat. -**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. +**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**. The user never directly logs in to CometChat. -**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. +**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), you can associate them as friends in CometChat. ### Typical Workflow @@ -148,3 +172,22 @@ Know more about manual mode connection [click here](/sdk/android/connection-beha | ----------------- | ------------------------------------------------------------------------------------------------------------------ | | App in foreground | Call `CometChat.connect()` to create the WebSocket connection | | App in background | Disconnect the WebSocket connection if no ping is received within 30 seconds after the app goes in the background. | + +--- + +## Next Steps + + + + Install and initialize the CometChat Android SDK + + + Learn how to log users into CometChat + + + Start sending messages to users and groups + + + Create and manage groups in your application + + diff --git a/sdk/android/leave-group.mdx b/sdk/android/leave-group.mdx index baa6f2fce..401194164 100644 --- a/sdk/android/leave-group.mdx +++ b/sdk/android/leave-group.mdx @@ -1,12 +1,32 @@ --- title: "Leave A Group" +description: "Leave groups to stop receiving messages and updates using the Android SDK" --- + +**Quick Reference for AI Agents & Developers** +```kotlin +// Leave a group +CometChat.leaveGroup("GUID", object : CometChat.CallbackListener() { + override fun onSuccess(message: String) { } + override fun onError(e: CometChatException) { } +}) + +// Listen for member left events +CometChat.addGroupListener("LISTENER_ID", object : GroupListener() { + override fun onGroupMemberLeft(action: Action?, leftUser: User?, leftGroup: Group?) { } +}) +``` + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/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. +To stop receiving updates and messages for any particular joined group, you need to leave the group using the `leaveGroup()` method. @@ -53,9 +73,9 @@ CometChat.leaveGroup(GUID,object :CometChat.CallbackListener(){ Once a group is left, the user will no longer receive any updates or messages pertaining to the group. -## Real-time Group Member Left Events +## Real-Time 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 running?* +*As a member of a group, how do I know if someone has left it when my app is running?* If a user leaves a group, the members of the group receive a real-time event in the `onGroupMemberLeft()` method of the `GroupListener` class. @@ -87,12 +107,68 @@ CometChat.addGroupListener(UNIQUE_LISTENER_ID, object : GroupListener() { ## 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?* +*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. +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 the `BaseMessage` class. -For the group member left event, in the `Action` object received, the following fields can help you get the relevant information- +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 + + +Always remove group listeners when they're no longer needed (e.g., in `onDestroy()` or when navigating away). Failing to remove listeners can cause memory leaks and duplicate event handling. + + +## Best Practices + + + + Prompt users to confirm before leaving a group, especially for private groups where rejoining requires an invitation. + + + After leaving a group, consider clearing cached messages and group data from local storage to free up space. + + + Update your UI immediately when receiving leave events to reflect the current group membership status. + + + +## Troubleshooting + + + + **Symptom:** `leaveGroup()` fails with "Not a member" error. + + **Cause:** User is not currently a member of the group. + + **Solution:** Check the `hasJoined` property of the Group object before attempting to leave. + + + **Symptom:** `leaveGroup()` fails when trying to leave as the last admin. + + **Cause:** Groups require at least one admin. The last admin cannot leave without transferring ownership or deleting the group. + + **Solution:** Either [transfer ownership](/sdk/android/transfer-group-ownership) to another member or [delete the group](/sdk/android/delete-group) if you want to remove it entirely. + + + +--- + +## Next Steps + + + + Rejoin groups or join new ones + + + Permanently delete groups you own + + + Fetch list of available groups + + + Handle real-time group events + + diff --git a/sdk/android/login-listeners.mdx b/sdk/android/login-listeners.mdx index 9acb5ea90..e074b3382 100644 --- a/sdk/android/login-listeners.mdx +++ b/sdk/android/login-listeners.mdx @@ -1,8 +1,24 @@ --- title: "Login Listeners" +description: "Receive real-time updates for login and logout events in the Android SDK" --- + +**Quick Reference for AI Agents & Developers** +```kotlin +// Add login listener +CometChat.addLoginListener("LISTENER_ID", object : LoginListener() { + override fun loginSuccess(user: User) { /* Login successful */ } + override fun loginFailure(e: CometChatException) { /* Login failed */ } + override fun logoutSuccess() { /* Logout successful */ } + override fun logoutFailure(e: CometChatException) { /* Logout failed */ } +}) + +// Remove 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 +102,44 @@ CometChat.removeLoginListener("UNIQUE_ID") + + + +Always remove login listeners when they're no longer needed (e.g., in `onDestroy()` or when navigating away). Failing to remove listeners can cause memory leaks and duplicate event handling. + + +## Best Practices + + + + Use `loginSuccess()` to initialize user-specific data (fetch conversations, register message listeners) and `logoutSuccess()` to clean up resources and navigate to the login screen. + + + In `loginFailure()`, parse the `CometChatException` to show user-friendly error messages (e.g., "Invalid credentials", "Network error"). Provide retry options for transient failures. + + + Register login listeners before calling `CometChat.login()` to ensure you don't miss any events. Register in `onCreate()` or before authentication attempts. + + + Remove all listeners (message, user, group, call) in `logoutSuccess()` to prevent receiving events after logout. This ensures a clean session termination. + + + +--- + +## Next Steps + + + + Initialize the SDK before logging in users + + + Learn about authentication methods and best practices + + + Monitor connection status to CometChat servers + + + Register listeners for messages, users, groups, and calls + + diff --git a/sdk/android/mentions.mdx b/sdk/android/mentions.mdx index ce0320209..68cbf206d 100644 --- a/sdk/android/mentions.mdx +++ b/sdk/android/mentions.mdx @@ -1,8 +1,30 @@ --- title: "Mentions" +description: "Mention specific users in messages to enhance engagement and collaboration in group conversations" --- + +**Quick Reference for AI Agents & Developers** + +```kotlin +// Send message with mention to user +val textMessage = TextMessage("UID", "Hello <@uid:cometchat-uid-1>", CometChatConstants.RECEIVER_TYPE_USER) +CometChat.sendMessage(textMessage, object : CallbackListener() { + override fun onSuccess(message: TextMessage) { } + override fun onError(e: CometChatException) { } +}) + +// Check if logged-in user was mentioned +val wasMentioned = message.hasMentionedMe() +// Get list of mentioned users +val mentionedUsers = message.mentionedUsers +``` + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) + ## Mentions @@ -14,8 +36,30 @@ Mentions in messages enable users to refer to specific individuals within a conv Every User object has a String unique identifier associated with them which can be found in a property called uid. To mention a user in a message, the message text should contain the uid in following format:` <@uid:UID_OF_THE_USER>`. For example, to mention the user with UID cometchat-uid-1 in a text message, your text should be `"<@uid:cometchat-uid-1>"` +Before sending messages with mentions, ensure you have [initialized the SDK](/sdk/android/setup) and [logged in a user](/sdk/android/authentication-overview). + + + - + +```kotlin +private val receiverID = "UID" +private val messageText = "Hello <@uid:cometchat-uid-1>" +private val receiverType = CometChatConstants.RECEIVER_TYPE_USER + +val textMessage = TextMessage(receiverID, messageText, receiverType) +CometChat.sendMessage(textMessage, object : CallbackListener() { + override fun onSuccess(textMessage: TextMessage) { + Log.d(TAG, "Message sent successfully: $textMessage") + } + + override fun onError(e: CometChatException) { + Log.d(TAG, "Message sending failed with exception: " + e.message) + } +}) +``` + + ```java private String receiverID = "UID"; private String messageText = "Hello, <@uid:cometchat-uid-1>"; @@ -35,14 +79,17 @@ CometChat.sendMessage(textMessage, new CometChat.CallbackListener() } }); ``` - + + - + + + ```kotlin -private val receiverID = "UID" +private val receiverID = "GUID" private val messageText = "Hello <@uid:cometchat-uid-1>" -private val receiverType = CometChatConstants.RECEIVER_TYPE_USER +private val receiverType = CometChatConstants.RECEIVER_TYPE_GROUP val textMessage = TextMessage(receiverID, messageText, receiverType) CometChat.sendMessage(textMessage, object : CallbackListener() { @@ -55,10 +102,8 @@ CometChat.sendMessage(textMessage, object : CallbackListener() { } }) ``` - - - + ```java private String receiverID = "GUID"; private String messageText = "Hello <@uid:cometchat-uid-1>"; @@ -78,27 +123,8 @@ CometChat.sendMessage(textMessage, new CometChat.CallbackListener() } }); ``` - - - -```kotlin -private val receiverID = "GUID" -private val messageText = "Hello <@uid:cometchat-uid-1>" -private val receiverType = CometChatConstants.RECEIVER_TYPE_GROUP - -val textMessage = TextMessage(receiverID, messageText, receiverType) -CometChat.sendMessage(textMessage, object : CallbackListener() { - override fun onSuccess(textMessage: TextMessage) { - Log.d(TAG, "Message sent successfully: $textMessage") - } - - override fun onError(e: CometChatException) { - Log.d(TAG, "Message sending failed with exception: " + e.message) - } -}) -``` - + @@ -111,7 +137,7 @@ You can mention user in text message and media messages captions ## Mentioned Messages -By default, the SDK will fetch all the messages irrespective of the fact that the logged-in user is mentioned or not in the message. The SDK has other optional filters such as tag info and blocked info. +By default, the SDK will fetch all the messages irrespective of the fact that the logged-in user is mentioned or not in the message. The SDK has other optional filters such as tag info and blocked info. For more filtering options, see [Additional Message Filtering](/sdk/android/additional-message-filtering). | Setting | Description | | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | @@ -123,7 +149,34 @@ By default, the SDK will fetch all the messages irrespective of the fact that th To get a list of messages in a conversation where users are mentioned along with the user tags of the mentioned users. - + + + +```kotlin +val UID = "cometchat-uid-1" + +val messagesRequest = MessagesRequest.MessagesRequestBuilder() + .setLimit(50) + .setUID(UID) + .mentionsWithTagInfo(true) + .build() + +messagesRequest.fetchPrevious(object : CometChat.CallbackListener>() { + override fun onSuccess(messages: List) { + for (messageObj in messages) { + for (user in messageObj.mentionedUsers) { + Log.e(TAG, "tag: ${user.tags}") + } + } + } + + override fun onError(e: CometChatException) { + Log.e(TAG, "onError: " + e) + } +}) +``` + + ```java String UID = "cometchat-uid-1"; @@ -149,16 +202,19 @@ messagesRequest.fetchPrevious(new CometChat.CallbackListener>( } }); ``` - + + - + + + ```kotlin -val UID = "cometchat-uid-1" +val GUID = "cometchat-guid-1" val messagesRequest = MessagesRequest.MessagesRequestBuilder() .setLimit(50) - .setUID(UID) + .setGUID(GUID) .mentionsWithTagInfo(true) .build() @@ -176,10 +232,8 @@ messagesRequest.fetchPrevious(object : CometChat.CallbackListener - - + ```java String GUID = "cometchat-guid-1"; @@ -205,24 +259,35 @@ messagesRequest.fetchPrevious(new CometChat.CallbackListener>( } }); ``` - + + + + - +## Mentions With Blocked Info + +To get a list of messages in a conversation where users are mentioned along with the blocked relationship of the mentioned users with the logged-in user. + + + + + ```kotlin -val GUID = "cometchat-guid-1" +val UID = "cometchat-uid-1" val messagesRequest = MessagesRequest.MessagesRequestBuilder() .setLimit(50) - .setGUID(GUID) - .mentionsWithTagInfo(true) + .setUID(UID) + .mentionsWithBlockedInfo(true) .build() messagesRequest.fetchPrevious(object : CometChat.CallbackListener>() { override fun onSuccess(messages: List) { for (messageObj in messages) { for (user in messageObj.mentionedUsers) { - Log.e(TAG, "tag: ${user.tags}") + Log.e(TAG, "isBlockedByMe: ${user.isBlockedByMe}") + Log.e(TAG, "isHasBlockedMe: ${user.isHasBlockedMe}") } } } @@ -232,17 +297,8 @@ messagesRequest.fetchPrevious(object : CometChat.CallbackListener - - - -## Mentions With Blocked Info - -To get a list of messages in a conversation where users are mentioned along with the blocked relationship of the mentioned users with the logged-in user. - - - + ```java String UID = "cometchat-uid-1"; @@ -269,16 +325,19 @@ messagesRequest.fetchPrevious(new CometChat.CallbackListener>( } }); ``` - + + - + + + ```kotlin -val UID = "cometchat-uid-1" +val GUID = "cometchat-guid-1" val messagesRequest = MessagesRequest.MessagesRequestBuilder() .setLimit(50) - .setUID(UID) + .setGUID(GUID) .mentionsWithBlockedInfo(true) .build() @@ -297,10 +356,8 @@ messagesRequest.fetchPrevious(object : CometChat.CallbackListener - - + ```java String GUID = "cometchat-guid-1"; @@ -327,35 +384,8 @@ messagesRequest.fetchPrevious(new CometChat.CallbackListener>( } }); ``` - - - -```kotlin -val GUID = "cometchat-guid-1" - -val messagesRequest = MessagesRequest.MessagesRequestBuilder() - .setLimit(50) - .setGUID(GUID) - .mentionsWithBlockedInfo(true) - .build() - -messagesRequest.fetchPrevious(object : CometChat.CallbackListener>() { - override fun onSuccess(messages: List) { - for (messageObj in messages) { - for (user in messageObj.mentionedUsers) { - Log.e(TAG, "isBlockedByMe: ${user.isBlockedByMe}") - Log.e(TAG, "isHasBlockedMe: ${user.isHasBlockedMe}") - } - } - } - - override fun onError(e: CometChatException) { - Log.e(TAG, "onError: " + e) - } -}) -``` - + @@ -386,18 +416,47 @@ message.mentionedUsers To check if the logged-in user has been mentioned in a particular message we can use the `hasMentionedMe()` method on any `BaseMessage`. This method will return a boolean value, `true` if the logged-in user has been mentioned, otherwise `false`. + +```kotlin +message.hasMentionedMe +``` + ```java message.hasMentionedMe() ``` - + - -```kotlin -message.hasMentionedMe -``` +## Best Practices - + + + Mentions are ideal for drawing attention in group conversations. Use them when you need to ensure specific users see critical messages or action items. + + + Always verify that the user ID exists before including it in a mention. Invalid UIDs will display as plain text rather than interactive mentions. + + + When a user is mentioned, consider sending a push notification to ensure they're alerted even when not actively using the app. This enhances engagement and responsiveness. + + - +--- + +## Next Steps + + + + Learn how to send text, media, and custom messages + + + Handle incoming messages with real-time listeners + + + Create messages with embedded forms and interactive elements + + + Fetch user lists to enable mention autocomplete + + diff --git a/sdk/android/message-structure-and-hierarchy.mdx b/sdk/android/message-structure-and-hierarchy.mdx index 4ed4ed248..441e3c2a0 100644 --- a/sdk/android/message-structure-and-hierarchy.mdx +++ b/sdk/android/message-structure-and-hierarchy.mdx @@ -1,8 +1,28 @@ --- title: "Message Structure And Hierarchy" +description: "Understand message categories, types, and hierarchy in the CometChat Android SDK" --- - + +**Quick Reference for AI Agents & Developers** + +**Message Categories:** +- **Message**: text, image, video, audio, file +- **Custom**: Developer-defined types (e.g., location) +- **Interactive**: form, card, customInteractive +- **Action**: groupMember, message (system-generated) +- **Call**: audio, video (with status: initiated, ongoing, ended, etc.) + +**Check message type:** +```kotlin +when (message.category) { + CometChatConstants.CATEGORY_MESSAGE -> { /* Handle message */ } + CometChatConstants.CATEGORY_CUSTOM -> { /* Handle custom */ } + CometChatConstants.CATEGORY_ACTION -> { /* Handle action */ } + CometChatConstants.CATEGORY_CALL -> { /* Handle call */ } +} +``` + The below diagram helps you better understand the various message categories and types that a CometChat message can belong to. @@ -85,3 +105,40 @@ 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. + + +## Best Practices + + + + Always check the message category using `message.getCategory()` before casting to specific message types (TextMessage, MediaMessage, etc.) to avoid ClassCastException errors. + + + Implement handlers for all message categories and types your app supports. Use a default case to handle unknown or future message types gracefully. + + + Use custom messages with unique types for content that doesn't fit standard categories (e.g., location sharing, polls, stickers). This keeps your implementation flexible and extensible. + + + Use `MessagesRequest.setCategories()` to fetch only the message categories you need. This improves performance and reduces unnecessary data transfer. + + + +--- + +## Next Steps + + + + Send text, media, and custom messages + + + Handle incoming messages of all types + + + Filter messages by category, type, and other parameters + + + Create and handle interactive form and card messages + + diff --git a/sdk/android/messaging-overview.mdx b/sdk/android/messaging-overview.mdx index 36e57feff..836438887 100644 --- a/sdk/android/messaging-overview.mdx +++ b/sdk/android/messaging-overview.mdx @@ -1,12 +1,58 @@ --- title: "Messaging" sidebarTitle: "Overview" +description: "Send, receive, and manage messages with CometChat's Android SDK messaging features" --- + +**Quick Reference for AI Agents & Developers** +Choose your messaging path: +- **Send Messages** → [send-message](/sdk/android/send-message) - Text, media, and custom messages +- **Receive Messages** → [receive-messages](/sdk/android/receive-messages) - Real-time message handling +- **Edit Messages** → [edit-message](/sdk/android/edit-message) - Modify sent messages +- **Delete Messages** → [delete-message](/sdk/android/delete-message) - Remove messages +- **Threaded Messages** → [threaded-messages](/sdk/android/threaded-messages) - Organize conversations +- **Reactions** → [reactions](/sdk/android/reactions) - Add emoji reactions +- **Mentions** → [mentions](/sdk/android/mentions) - Tag users in messages +- **Interactive Messages** → [interactive-messages](/sdk/android/interactive-messages) - Buttons and forms + -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/android/send-message) and [receiving messages](/sdk/android/receive-messages). + +Messaging is one of the core features of CometChat. We've created methods to help you send, receive, and fetch message history. + +At minimum, you must add code for [sending messages](/sdk/android/send-message) and [receiving messages](/sdk/android/receive-messages). Once you've implemented that, you can proceed to more advanced features like [typing indicators](/sdk/android/typing-indicators) and [delivery & read receipts](/sdk/android/delivery-read-receipts). + +--- + +## Next Steps + + + + Send text, media, and custom messages to users and groups + + + Handle real-time incoming messages with listeners + + + Modify sent messages after delivery + + + Remove messages from conversations + + + Create organized conversation threads + + + Add emoji reactions to messages + + + Tag users in group conversations + + + Send messages with buttons and forms + + diff --git a/sdk/android/overview.mdx b/sdk/android/overview.mdx index a55d7d6ce..80ce77425 100644 --- a/sdk/android/overview.mdx +++ b/sdk/android/overview.mdx @@ -1,10 +1,39 @@ --- title: "Overview" +description: "Get started with the CometChat Android SDK - install, initialize, and add real-time chat to your Android application" --- + +**Quick Setup Reference** +```kotlin +// 1. Add dependency to build.gradle +implementation "com.cometchat:chat-sdk-android:4.1.8" + +// 2. Initialize (run once at app start) +val appSettings = AppSettings.AppSettingsBuilder() + .subscribePresenceForAllUsers() + .setRegion("REGION") + .build() +CometChat.init(context, "APP_ID", appSettings, callback) + +// 3. Login user +CometChat.login("UID", "AUTH_KEY", callback) // Dev only +``` + +**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 + + + +`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. + -This guide demonstrates how to add chat to an Android application. Before you begin, we strongly recommend you read the [Key Concepts](/sdk/android/key-concepts) guide. +This guide demonstrates how to add chat to an Android application. Before you begin, we strongly recommend reading the [Key Concepts](/sdk/android/key-concepts) guide. #### **I want to integrate with my app** @@ -12,7 +41,7 @@ This guide demonstrates how to add chat to an Android application. Before you be 2. [Add the CometChat dependency](./overview#add-the-cometchat-dependency) 3. [Initialize CometChat](./overview#initialise-cometchat) 4. [Register and Login your user](./overview#register-and-login-your-user) -5. [Integrate Our UI Kits](./overview#integrate-our-ui-kits) +5. [Integrate our UI Kits](./overview#integrate-our-ui-kits) #### **I want to explore a sample app (includes UI)** @@ -24,7 +53,7 @@ Import the app into Android Studio and follow the steps mentioned in the `README ### Get your Application Keys -[Signup for CometChat](https://app.cometchat.com) and then: +[Sign up for CometChat](https://app.cometchat.com) and then: 1. Create a new app 2. Head over to the **API Keys** section and note the **Auth Key**, **App ID** & **Region** @@ -33,14 +62,14 @@ Import the app into Android Studio and follow the steps mentioned in the `README Minimum Requirements * Android API Level 21 -* Android API level 24 (in case you are using the calls SDKS) -* Androidx Compatibility +* Android API Level 24 (if you are using the Calls SDK) +* AndroidX Compatibility ### Add the CometChat Dependency -First, add the repository URL to the **project level**`build.gradle` file in the `repositories` block under the `allprojects` section. +First, add the repository URL to the **project level** `build.gradle` file in the `repositories` block under the `allprojects` section. @@ -58,7 +87,7 @@ allprojects { -Then, add CometChat to the **app level**`build.gradle` file in the `dependencies` section. +Then, add CometChat to the **app level** `build.gradle` file in the `dependencies` section. @@ -74,11 +103,11 @@ dependencies { -v2.4+ onwards, Voice & Video Calling functionality has been moved to a separate library. In case you plan to use the calling feature, please add the Calling dependency `implementation 'com.cometchat:calls-sdk-android:4.3.3'` in the dependencies section of the app-level `build.gradle` file. +Starting from v2.4+, Voice & Video Calling functionality has been moved to a separate library. If you plan to use the calling feature, add the Calling dependency `implementation 'com.cometchat:calls-sdk-android:4.3.3'` in the dependencies section of the app-level `build.gradle` file. -Finally, add the below lines `android` section of the **app level** gradle file +Finally, add the following lines to the `android` section of the **app level** gradle file. @@ -97,18 +126,18 @@ android { ### Initialise CometChat -The `init()` method initializes the settings required for CometChat. The `init()` method takes the below parameters: +The `init()` method initializes the settings required for CometChat. This method takes the following 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. +1. `appID` - Your CometChat App ID +2. `appSettings` - An object of the `AppSettings` class 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 three settings: +The `AppSettings` class allows you to configure the following settings: -* **Region**: The region where you app was created. -* [Presence Subscription](/sdk/android/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 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. +* **Region**: The region where your app was created. +* **[Presence Subscription](/sdk/android/user-presence)**: Represents the subscription type for user presence (real-time online/offline status). +* **autoEstablishSocketConnection(boolean value)**: When set to `true`, the SDK manages the WebSocket connection internally. When set to `false`, you must manage the WebSocket connection manually. The default value is `true`. For more information, see the Managing Web-Socket connections manually section. +* **overrideAdminHost(adminHost: string)**: Takes the admin URL as input and uses it instead of the default admin URL. This is useful for dedicated deployments of CometChat. +* **overrideClientHost(clientHost: string)**: Takes the client URL as input and uses it instead of the default client URL. This is useful for dedicated deployments of CometChat. @@ -168,13 +197,13 @@ CometChat.init( -Make sure you replace the `APP_ID` with your CometChat **App ID** and `region` with your **App Region** in the above code. +Make sure you replace `APP_ID` with your CometChat **App ID** and `region` with your **App Region** in the above code. ### Register and Login your User -Once initialization is successful, you will need to create a user. +Once initialization is successful, you 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. +To create users on the fly, 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. @@ -221,11 +250,11 @@ CometChat.createUser(user, authKey, object : CometChat.CallbackListener() -Make sure that `UID` and `name` are specified as these are mandatory fields to create a user. +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. +Once you have created the user successfully, you 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. +We recommend calling the CometChat `login()` method once your user logs into your app. The `login()` method only needs to be called once. @@ -286,7 +315,7 @@ if (CometChat.getLoggedInUser() == null) { -Make sure you replace the `AUTH_KEY` with your App **Auth Key** in the above code. +Make sure you replace `AUTH_KEY` with your App **Auth Key** in the above code. The `login()` method returns the `User` object containing all the information of the logged-in user. @@ -298,4 +327,23 @@ UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and othe ### Integrate our UI Kits -* Please refer [Android Java UI Kit](/ui-kit/android/overview) section to integrate Android Java UI Kit inside your app. +* Refer to the [Android Java UI Kit](/ui-kit/android/overview) section to integrate the Android Java UI Kit into your app. + +--- + +## Next Steps + + + + Detailed installation and initialization guide for the Android SDK + + + Understand core concepts like users, groups, messages, and conversations + + + Learn about secure authentication with Auth Tokens for production apps + + + Start sending text, media, and custom messages to users and groups + + diff --git a/sdk/android/presenter-mode.mdx b/sdk/android/presenter-mode.mdx index e68bfd29d..7902745e6 100644 --- a/sdk/android/presenter-mode.mdx +++ b/sdk/android/presenter-mode.mdx @@ -1,44 +1,66 @@ --- title: "Presenter Mode" +description: "Create webinar-style calling experiences with presenters and viewers using the Android SDK" --- + +**Quick Reference for AI Agents & Developers** + +```kotlin +// Join as presenter +val presenterSettings = CometChatCalls.PresentationSettingsBuilder(context) + .setDefaultLayoutEnable(true) + .setIsPresenter(true) // true = presenter, false = viewer + .setEventListener(eventListener) + .build() + +CometChatCalls.joinPresentation(callToken, presenterSettings, videoContainer, object : CometChatCalls.CallbackListener() { + override fun onSuccess(s: String) { } + override fun onError(e: CometChatException) { } +}) +``` + +**Use Cases:** Webinars, online classes, keynote speeches, all-hands meetings +**Capacity:** Up to 5 presenters + 95 viewers (100 total) + + ## Overview The Presenter Mode feature allows developers to create a calling service experience in which: -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. +1. There are one or more users who are presenting their video, audio, and/or screen (maximum 5) +2. Viewers 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. are enabled only for the Presenter in this mode +5. Other call participants do not get these features, so they act like passive viewers in the call -Using this feature developers can create experiences such as: +Using this feature, developers can create experiences such as: 1. All hands calls 2. Keynote speeches 3. Webinars 4. Talk shows -5. Online classes and many more... +5. Online classes and many more -About this guide +## About This Guide -This guide demonstrates how to start a presentation into an Android application. Before you begin, we strongly recommend you read the calling setup guide. +This guide demonstrates how to start a presentation in an Android 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. You need to call this method for the call token. +Before starting a call session, you need to generate a call token. You need to call this method for the call token. -Start Presentation Session +## 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. +The most important class used in the implementation is the `PresentationSettings` class. This class allows you to set the various parameters for Presenter Mode. To set the various parameters of the `PresentationSettings` class, use the `PresentationSettingsBuilder` class. Below are the various options available with the `PresentationSettings` class. -`PresentationSettingsBuilder` class takes the 1 mandatory parameter as a part of the constructor: +The `PresentationSettingsBuilder` class takes 1 mandatory parameter as part of the constructor: -1. Context of the application. +1. Context of the application -You will also 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` isPresenter(true/false)` +You also need to set the User Type. There are 2 types of users in Presenter Mode: `Presenter` and `Participant`. You can set this in `PresentationSettingsBuilder` by using the method `isPresenter(true/false)`. -A basic example of how to start a Presentation: +Here is a basic example of how to start a Presentation: @@ -188,11 +210,14 @@ 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 `PresentationSettings` class is the most important class when it comes to implementing the Calling feature. This class allows you to customize the overall calling experience. The properties for the call/conference can be set using the `PresentationSettingsBuilder` class. This gives you an object of the `PresentationSettings` class which you can pass to the `joinPresentation()` method to start the call. + +The **mandatory** parameters required for any call/conference to work are: -The **mandatory** parameters that are required to be present for any call/conference to work are: +- Context - context of the activity/application +- RelativeLayout - A RelativeLayout object in which the calling UI is loaded -Context - context of the activity/application RelativeLayout - A RelativeLayout object in which the calling UI is loaded. The options available for customization of calls are: +The options available for customization of calls are: | Setting | Description | | ------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | @@ -210,6 +235,76 @@ Context - context of the activity/application RelativeLayout - A RelativeLayout | `showRecordingButton(boolean value)` | If set to `true`, it displays the Recording Button. If set to `false`, it hides the Recording Button. Default value = `false` | | `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. +If you want to achieve a completely customized 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 methods below to achieve different functionalities for the embedded buttons. + +For the use case where you want 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 methods below to perform the corresponding operations: + + + +Always remove call event listeners when they're no longer needed (e.g., in `onDestroy()` or when navigating away). Failing to remove listeners can cause memory leaks and duplicate event handling. + + +--- -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: +## Best Practices + + + + Keep the number of presenters to 5 or fewer for optimal performance. More presenters increase bandwidth requirements and can degrade the experience for viewers. + + + Clearly distinguish between presenters and viewers using `setIsPresenter()`. Presenters have full control (audio, video, screen share), while viewers are passive consumers. + + + Test your presentation with close to 100 participants to ensure your infrastructure can handle the load. Monitor bandwidth and CPU usage during testing. + + + Show visual indicators to users about their role (presenter vs viewer) and available controls. Viewers should understand they cannot send audio/video. + + + Implement logic to handle scenarios where a presenter disconnects unexpectedly. Consider promoting another user to presenter or ending the session gracefully. + + + +## Troubleshooting + + + + **Symptom:** Viewers join the presentation but cannot see the presenter's video stream. + + **Cause:** Presenter may have started with video muted, or network issues are preventing video transmission. + + **Solution:** Ensure the presenter has `startWithVideoMuted(false)` in their settings. Check network connectivity and bandwidth for both presenter and viewers. + + + **Symptom:** `joinPresentation()` fails with "Invalid call token" error. + + **Cause:** The call token is invalid or expired. + + **Solution:** Ensure you're using a valid call token generated for the specific session. Verify the token hasn't expired and matches the session ID. + + + **Symptom:** User cannot join as presenter even though `setIsPresenter(true)` is set. + + **Cause:** The maximum limit of 5 presenters has been reached. + + **Solution:** Wait for an existing presenter to leave, or join as a viewer instead. Implement logic to check presenter count before allowing users to join as presenters. + + + +## Next Steps + + + + Implement standard one-on-one and group calling + + + Customize the call UI appearance and layout + + + Record presentation sessions for later playback + + + Configure idle timeout for inactive sessions + + diff --git a/sdk/android/publishing-app-on-playstore.mdx b/sdk/android/publishing-app-on-playstore.mdx index 7e2815d76..a105d210f 100644 --- a/sdk/android/publishing-app-on-playstore.mdx +++ b/sdk/android/publishing-app-on-playstore.mdx @@ -1,28 +1,43 @@ --- title: "Publishing App On PlayStore" +description: "Guide to preparing and publishing your CometChat Android app on Google Play Store" --- + +**Quick Reference for AI Agents & Developers** + +Publishing checklist: +1. **Reduce app size** - Remove unused resources, enable ProGuard/R8 +2. **Prepare signed bundle** - Generate signed AAB with proper versioning +3. **Create Play Console account** - One-time $25 fee +4. **Upload app bundle** - Submit to Google Play Console +5. **Complete store listing** - Add screenshots, description, privacy policy + +**Key tools:** Android Studio → Build → Generate Signed Bundle/APK +**Play Console:** [https://play.google.com/console](https://play.google.com/console) + + -Publishing an App on PlayStore is an easy task once you are done with your development. Below we have mentioned few steps which will help you to understand more in detail. +Publishing an app on the Play Store is straightforward once you have completed your development. Below are a few steps that will help you understand the process in more detail. -### 1. Reduce App Size. +### 1. Reduce App Size -App Size is a prior concern before publishing App on the Play Store. **Android Studio** provides few plugins and tools that will help you reduce the app size. One way to reduce app size is to remove unused resources. Android Studio provides an option "**Remove unused Resources**" under "**Refactor**" Menu which will help you to remove unused resources from your app. +App size is a key concern before publishing on the Play Store. **Android Studio** provides plugins and tools that help you reduce app size. One way to reduce app size is to remove unused resources. Android Studio provides an option called "**Remove unused Resources**" under the "**Refactor**" menu, which helps you remove unused resources from your app. -Please check below link to get different ways to reduce your app size. +Check the link below for different ways to reduce your app size: [https://developer.android.com/topic/performance/reduce-apk-size](https://developer.android.com/topic/performance/reduce-apk-size) *** -### 2. Prepare the Signed Release App Bundle. +### 2. Prepare the Signed Release App Bundle -Before preparing the signed release app bundle, we suggest you to check that the **android:debuggable** attribute should not be present in your manifest file. Also you need to maintain\*\* versionCode \*\*and **versionName** available in ( app-level ) **build.gradle** for each release. +Before preparing the signed release app bundle, ensure that the **android:debuggable** attribute is not present in your manifest file. Also, maintain the **versionCode** and **versionName** in your (app-level) **build.gradle** for each release. @@ -41,28 +56,93 @@ android { -After above steps you need to sign your app and upload it to the play store. Android Studio provides an option to generate a signed app bundle. From the menu bar, click **Build > Build > Generate Signed Bundle/APK**. After that you can reuse your existing key or create a new one if you don't have one +After the above steps, you need to sign your app and upload it to the Play Store. Android Studio provides an option to generate a signed app bundle. From the menu bar, click **Build > Build > Generate Signed Bundle/APK**. After that, you can reuse your existing key or create a new one if you don't have one. -For more details please check below link. +For more details, check the link below: [https://developer.android.com/studio/publish/app-signing](https://developer.android.com/studio/publish/app-signing) *** -### 3 Upload an App. +### 3. Upload an App -To upload an app on Google Play Store, you need google account, sign-in to your google account or create a new if you don't have one. Then click on the below mentioned link. +To upload an app on Google Play Store, you need a Google account. Sign in to your Google account or create a new one if you don't have one. Then click on the link below: [https://play.google.com/apps/publish/](https://play.google.com/apps/publish/) -If you already have merchant account then it will show you list of your published apps or else it will tell you to sign as merchant account and you need to pay one-time charge. +If you already have a merchant account, it shows you a list of your published apps. Otherwise, it prompts you to sign up as a merchant account and pay a one-time charge. -It will charge you a once in a lifetime fee i.e 25$. Just do it to start uploading your first app. Later you can publish other apps through this account and you won't be charged. +This is a one-time fee of $25. Pay it to start uploading your first app. You can publish other apps through this account later without being charged again. -Check below link for more details on how to create and upload app in play store. +Check the link below for more details on how to create and upload an app to the Play Store: [https://developer.android.com/studio/publish/upload-bundle](https://developer.android.com/studio/publish/upload-bundle) + +--- + +## Best Practices + + + + Always test your signed release build on multiple devices before uploading to Play Store. Release builds may behave differently than debug builds due to ProGuard/R8 optimizations. + + + Increment `versionCode` for every release (even minor updates) and update `versionName` to reflect the user-facing version. Google Play requires increasing version codes for updates. + + + Store your app signing key securely and create backups. Losing your signing key means you cannot update your app on Play Store. Consider using Google Play App Signing for additional security. + + + Enable code shrinking and obfuscation in your release build to reduce app size and protect your code. Test thoroughly after enabling to catch any ProGuard-related issues. + + + Provide high-quality screenshots and promotional graphics that showcase your app's key features. Good visuals significantly impact download rates. + + + +## Troubleshooting + + + + **Symptom:** Google Play Console rejects your app bundle upload. + + **Cause:** Version code is not higher than the previous release, or the bundle is not properly signed. + + **Solution:** Ensure `versionCode` in build.gradle is higher than the current production version. Verify the bundle is signed with the correct keystore. Check for any validation errors in the Play Console. + + + **Symptom:** App works in debug mode but crashes in release build. + + **Cause:** ProGuard/R8 may be removing necessary code, or debug-specific code is causing issues. + + **Solution:** Review ProGuard rules and add keep rules for CometChat SDK classes. Remove any `android:debuggable="true"` from your manifest. Test the release build thoroughly before publishing. + + + **Symptom:** Play Console warns about large app size affecting downloads. + + **Cause:** Unused resources, large assets, or unoptimized libraries are included in the bundle. + + **Solution:** Use Android Studio's "Remove Unused Resources" feature. Enable resource shrinking in build.gradle. Consider using Android App Bundle format which automatically optimizes for different device configurations. + + + +## Next Steps + + + + Review SDK setup and configuration + + + Optimize WebSocket connection for production + + + Understand API rate limiting for production + + + Official Android publishing documentation + + diff --git a/sdk/android/rate-limits.mdx b/sdk/android/rate-limits.mdx index 17581b144..da5c9aa0b 100644 --- a/sdk/android/rate-limits.mdx +++ b/sdk/android/rate-limits.mdx @@ -1,29 +1,44 @@ --- title: "Rate Limits" +description: "Understand CometChat REST API rate limits and how to handle rate limit responses" --- + +**Quick Reference for AI Agents & Developers** + +**Rate Limits:** +- **Core Operations:** 10,000 requests/minute (login, create/delete user, create/join group) +- **Standard Operations:** 20,000 requests/minute (all other operations) + +**Rate Limit Response:** +- **Status Code:** 429 (Too Many Requests) +- **Headers:** `Retry-After`, `X-Rate-Limit-Reset`, `X-Rate-Limit`, `X-Rate-Limit-Remaining` + +**Best Practice:** Monitor `X-Rate-Limit-Remaining` header and implement exponential backoff when approaching limits. + + ### CometChat REST API Rate Limits -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. +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 login a user, add a user to a group, remove a user from a group, etc., for a total of 100 requests per minute. -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. +1. **Core Operations:** Core operations are rate limited to `10,000` requests per minute. Core operations include user login, create/delete user, and 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 ? +## What Happens When the 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. +The request isn't processed and a response is sent containing a 429 response code. Along with the response code, a couple of headers are sent that specify the time in seconds you must wait before you can try the request again. `Retry-After: 15` `X-Rate-Limit-Reset: 1625143246` -## Is there any endpoint that returns rate limit of all resources ? +## Is There an Endpoint That Returns Rate Limits for All Resources? No, we don't provide a rate-limit endpoint. @@ -32,3 +47,68 @@ However, we do provide the following response headers that you can use to confir `X-Rate-Limit: 700` `X-Rate-Limit-Remaining: 699` + +--- + +## Best Practices + + + + Always check the `X-Rate-Limit-Remaining` header in API responses to track how many requests you have left in the current minute. Implement logic to slow down requests when approaching the limit. + + + When you receive a 429 response, implement exponential backoff retry logic. Use the `Retry-After` header value to determine when to retry the request. + + + Group multiple operations into batch requests where the API supports it. This reduces the total number of API calls and helps stay within rate limits. + + + Cache user lists, group information, and other frequently accessed data locally to reduce the number of API calls. Only fetch fresh data when necessary. + + + If your application consistently hits rate limits, contact CometChat support to discuss increasing limits based on your use case and plan. Rate limits can be adjusted per-need basis. + + + +## Troubleshooting + + + + **Symptom:** Application frequently receives 429 (Too Many Requests) responses. + + **Cause:** Your application is making too many API requests within the rate limit window (1 minute). + + **Solution:** Implement request throttling on the client side. Monitor `X-Rate-Limit-Remaining` header and slow down requests when approaching the limit. Consider caching data locally to reduce API calls. If legitimate high volume, contact support for limit increase. + + + **Symptom:** Unclear when rate limit will reset after hitting the limit. + + **Cause:** Misunderstanding the `X-Rate-Limit-Reset` header format. + + **Solution:** The `X-Rate-Limit-Reset` header contains a Unix timestamp (seconds since epoch). Convert it to a readable date/time in your timezone. The `Retry-After` header provides seconds to wait, which is often simpler to use. + + + **Symptom:** Rate limits are hit even though the app doesn't seem to be making many requests. + + **Cause:** Multiple instances of your app (different users, devices, or servers) share the same rate limit pool. Background sync or polling may be consuming quota. + + **Solution:** Rate limits are per app, not per user or device. Audit all API calls including background operations. Implement efficient polling strategies (use WebSocket for real-time updates instead of polling). Consider request prioritization to ensure critical operations succeed. + + + +## Next Steps + + + + Configure SDK for optimal API usage + + + Use WebSocket for real-time updates instead of polling + + + Receive updates via WebSocket to reduce API calls + + + Explore REST API endpoints and rate limits + + diff --git a/sdk/android/reactions.mdx b/sdk/android/reactions.mdx index b7a903654..ce93656b2 100644 --- a/sdk/android/reactions.mdx +++ b/sdk/android/reactions.mdx @@ -1,8 +1,80 @@ --- title: "Reactions" +description: "Add, remove, and manage emoji reactions on messages in your Android chat application" --- + +**Quick Reference for AI Agents & Developers** + + + +```kotlin +// Add reaction +CometChat.addReaction(messageId, "😊", object : CallbackListener() { + override fun onSuccess(message: BaseMessage) { } + override fun onError(e: CometChatException) { } +}) + +// Remove reaction +CometChat.removeReaction(messageId, "😊", object : CallbackListener() { + override fun onSuccess(message: BaseMessage) { } + override fun onError(e: CometChatException) { } +}) + +// Fetch reactions for a message +val reactionRequest = ReactionRequest.ReactionRequestBuilder() + .setMessageId(messageId) + .setLimit(30) + .build() +reactionRequest.fetchNext(callback) + +// Listen for real-time reaction events +CometChat.addMessageListener(listenerID, object : MessageReactionListener { + override fun onMessageReactionAdded(reaction: MessageReaction) { } + override fun onMessageReactionRemoved(reaction: MessageReaction) { } +}) +``` + + +```java +// Add reaction +CometChat.addReaction(messageId, "😊", new CallbackListener() { + @Override + public void onSuccess(BaseMessage message) { } + @Override + public void onError(CometChatException e) { } +}); +// Remove reaction +CometChat.removeReaction(messageId, "😊", new CallbackListener() { + @Override + public void onSuccess(BaseMessage message) { } + @Override + public void onError(CometChatException e) { } +}); + +// Fetch reactions for a message +ReactionRequest reactionRequest = new ReactionRequest.ReactionRequestBuilder() + .setMessageId(messageId) + .setLimit(30) + .build(); +reactionRequest.fetchNext(callback); + +// Listen for real-time reaction events +CometChat.addMessageListener(listenerID, new MessageReactionListener() { + @Override + public void onMessageReactionAdded(MessageReaction reaction) { } + @Override + public void onMessageReactionRemoved(MessageReaction reaction) { } +}); +``` + + + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) + 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 Android SDK. @@ -53,7 +125,7 @@ CometChat.addReaction(messageId, emoji, object : CometChat.CallbackListener -You can react on Text, Media and Custom messages. +You can react on Text, Media and Custom messages. For more details on message types, see [Message Structure & Hierarchy](/sdk/android/message-structure-and-hierarchy). @@ -235,7 +307,7 @@ reactionRequest.fetchPrevious(object : CometChat.CallbackListener @@ -285,7 +357,7 @@ To stop listening for reaction events, remove the listener as follows: ```java private String listenerID = "UNIQUE_LISTENER_ID"; -CometChat.removeMessageListener("reactionListener"); +CometChat.removeMessageListener(listenerID); ``` @@ -294,13 +366,17 @@ CometChat.removeMessageListener("reactionListener"); ```kotlin val listenerID = "UNIQUE_LISTENER_ID" -CometChat.removeMessageListener("reactionListener") +CometChat.removeMessageListener(listenerID) ``` + +Always remove listeners when they're no longer needed (e.g., in `onDestroy()` or when navigating away). Failing to remove listeners can cause memory leaks and duplicate event handling. + + ## Get Reactions List To retrieve the list of reactions reacted on particular message, you can use the `message.getReactions()` method. This method will return an array containing the reactions, or an empty array if no one reacted on the message. @@ -400,3 +476,39 @@ val modifiedBaseMessage: BaseMessage = CometChatHelper.updateMessageWithReaction 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. + +## Best Practices + + + + Define a specific set of allowed emoji reactions in your app to maintain consistency and prevent inappropriate reactions. Consider using a reaction picker UI component with predefined options. + + + Update your UI immediately when a user adds or removes a reaction, then handle the server response. This provides instant feedback and improves perceived performance. + + + Always use `CometChatHelper.updateMessageWithReactionInfo()` when receiving real-time reaction events to keep your message objects synchronized with the latest reaction data. + + + Consider implementing limits on the number of reactions per message or per user to prevent spam and maintain a clean UI. + + + +--- + +## Next Steps + + + + Learn how to send text, media, and custom messages + + + Handle real-time message events with listeners + + + Organize conversations with message threads + + + Tag users in messages with @mentions + + diff --git a/sdk/android/real-time-listeners.mdx b/sdk/android/real-time-listeners.mdx index 04e653071..4f9d80073 100644 --- a/sdk/android/real-time-listeners.mdx +++ b/sdk/android/real-time-listeners.mdx @@ -1,8 +1,29 @@ --- title: "All Real Time Listeners" +description: "Register and manage real-time event listeners for users, groups, messages, and calls in the Android SDK" --- + +**Quick Reference for AI Agents & Developers** +```kotlin +// User listener +CometChat.addUserListener("LISTENER_ID", object : CometChat.UserListener() { + override fun onUserOnline(user: User) { } + override fun onUserOffline(user: User) { } +}) + +// Message listener +CometChat.addMessageListener("LISTENER_ID", object : CometChat.MessageListener() { + override fun onTextMessageReceived(message: TextMessage) { } + override fun onMediaMessageReceived(message: MediaMessage) { } +}) + +// Remove listeners (important!) +CometChat.removeUserListener("LISTENER_ID") +CometChat.removeMessageListener("LISTENER_ID") +``` + CometChat provides 4 listeners viz. @@ -40,6 +61,21 @@ CometChat.addUserListener(UNIQUE_LISTENER_ID, new CometChat.UserListener() { + +```kotlin +CometChat.addUserListener(UNIQUE_LISTENER_ID, object : CometChat.UserListener() { + override fun onUserOnline(user: User) { + + } + + override fun onUserOffline(user: User) { + + } +}) +``` + + + where `UNIQUE_LISTENER_ID` is the unique identifier for the listener. Please make sure that no two listeners are added with the same listener id as this could lead to unexpected behavior resulting in loss of events. @@ -54,8 +90,19 @@ CometChat.removeUserListener(UNIQUE_LISTENER_ID) + +```kotlin +CometChat.removeUserListener(UNIQUE_LISTENER_ID) +``` + + + + +Always remove listeners when they're no longer needed (e.g., in `onDestroy()` or when navigating away). Failing to remove listeners can cause memory leaks and duplicate event handling. + + ## Group Listener The `GroupListener` class provides you with all the real-time events related to groups. Below are the callback methods provided by the `GroupListener` class. @@ -385,3 +432,40 @@ CometChat.addCallListener(UNIQUE_LISTENER_ID, object : CometChat.CallListener() Where `UNIQUE_LISTENER_ID` is the unique identifier for the listener. Make sure that no two listeners are added with the same listener ID as this could lead to unexpected behavior resulting in loss of events. Once the activity/fragment where the `MessageListener` is declared is not in use, you need to remove the listener using the `removeMessageListener()` method which takes the id of the listener to be removed as the parameter. We suggest you call this method in the `onPause()` method of the activity/fragment. + + +## Best Practices + + + + Remove all listeners in `onDestroy()` or `onPause()` to prevent memory leaks. Store listener IDs as constants to ensure consistent removal. + + + Use unique, descriptive listener IDs (e.g., "ChatActivity_MessageListener") to avoid conflicts. Never reuse the same ID for different listeners. + + + Register listeners in `onCreate()` or `onResume()` to ensure you don't miss any events. Register before fetching messages or loading conversations. + + + Implement all relevant callback methods even if you don't need them immediately. This prevents crashes if the SDK triggers unexpected events. + + + +--- + +## Next Steps + + + + Handle incoming messages with message listeners + + + Track user online/offline status with user listeners + + + Handle incoming calls with call listeners + + + Monitor group events with group listeners + + diff --git a/sdk/android/receive-messages.mdx b/sdk/android/receive-messages.mdx index 6cd321878..c8912dbdd 100644 --- a/sdk/android/receive-messages.mdx +++ b/sdk/android/receive-messages.mdx @@ -11,11 +11,11 @@ Receiving messages with CometChat has two parts: ## Real-time Messages -*In other words, as a recipient, how do I receive messages when my app is running?* +How do I receive messages when my app is running? -For every activity or fragment you wish to receive messages in, you need to register the `MessageListener` using the `addMessageListener()` method. +For every activity or fragment you wish to receive messages in, register the `MessageListener` using the `addMessageListener()` method. -We suggest adding the listener in the `onResume()` method of the activity or the fragment where you wish to receive these events in. +We suggest adding the listener in the `onResume()` method of the activity or fragment where you wish to receive these events. @@ -100,7 +100,7 @@ As a sender, you will not receive your own message in a real-time message event. ## Missed Messages -*In other words, as a recipient, how do I receive messages that I missed when my app was not running?* +How do I receive messages that I missed when my app was not running? 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 the message history (say, last 100 messages) instead. @@ -266,9 +266,9 @@ messagesRequest.fetchNext(object : CallbackListener>() { ## Unread Messages -*In other words, as a logged-in user, how do I fetch the messages I've not read?* +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. +Using the `MessagesRequest` class described above, you can fetch the unread messages for the logged-in user. To achieve this, set the `unread` variable in the builder to `true` using the `setUnread()` method so that only the unread messages are fetched. ### Fetch Unread Messages of a particular one-on-one conversation @@ -409,7 +409,7 @@ The list of messages received is in the form of objects of `BaseMessage` class. ## Message History -*In other words, as a logged-in user, how do I fetch the message history for a user or a group conversation?* +How do I fetch the message history for a user or a group conversation? ### Fetch Message History of a particular one-on-one conversation @@ -551,9 +551,9 @@ Calling the `fetchPrevious()` method on the same object repeatedly allows you to ## Search Messages -In other words, as a logged-in user, how do I search a message? +How do I search for 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`. +To search messages, use the `setSearchKeyword()` method. This method accepts a string as input. When set, the SDK will fetch messages that match the `searchKeyword`. @@ -690,13 +690,13 @@ messagesRequest.fetchPrevious(object : CallbackListener>() { ## Unread Messages Count -*In other words, as a logged-in user, how do I find out the number of unread messages that I have?* +How do I find out the number of unread messages that I have? ### 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?* +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 (with respect to the logged-in user), you can use the `getUnreadMessageCountForUser()`. +To get the unread message count for a particular user (with respect to the logged-in user), use the `getUnreadMessageCountForUser()` method. This method has the two variants: @@ -779,9 +779,9 @@ In the `onSuccess()` callback, you will receive a Hashmap which will contain the ### 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?* +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()`. +To get the unread message count for a particular group, use the `getUnreadMessageCountForGroup()` method. This method has two variants: @@ -865,9 +865,9 @@ In the `onSuccess()` callback, you will receive a Hashmap which will contain the ### 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?* +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 counts, you can use the `getUnreadMessageCount()` method. This method has two variants: +To get all the unread message counts, use the `getUnreadMessageCount()` method. This method has two variants: @@ -947,9 +947,9 @@ In the `onSuccess()` callback, you will receive a hashmap having two keys: ### Fetch Unread Message Count of all one-on-one conversations -*In other words, how do I find out the number of unread messages I have for every user?* +How do I find out the number of unread messages I have for every user? -In order to fetch the unread message counts for just the users, you can use the `getUnreadMessageCountForAllUsers()` method. +To fetch the unread message counts for just the users, use the `getUnreadMessageCountForAllUsers()` method. This method, just like others, has two variants: @@ -1028,9 +1028,9 @@ In the `onSuccess()` callback, you will receive a Hashmap that will contain the ### Fetch Unread Message Count of all group conversations -*In other words, how do I find out the number of unread messages for every group?* +How do I find out the number of unread messages for every group? -In order to fetch the unread message counts for all groups, you can use the `getUnreadMessageCountForAllGroups()` method. +To fetch the unread message counts for all groups, use the `getUnreadMessageCountForAllGroups()` method. This method has two variants: diff --git a/sdk/android/recording.mdx b/sdk/android/recording.mdx index 8f497bb70..661a739a4 100644 --- a/sdk/android/recording.mdx +++ b/sdk/android/recording.mdx @@ -1,18 +1,40 @@ --- title: "Recording" +description: "Record calls and access recordings from the Dashboard using the Android SDK" --- + +**Quick Reference for AI Agents & Developers** +```kotlin +// Configure call settings with recording +val callSettings = CallSettingsBuilder(this, videoContainer) + .setSessionId(sessionId) + .showCallRecordButton(true) + .startRecordingOnCallStart(false) + .build() + +// Start recording manually +CallManager.getInstance().startRecording() + +// Stop recording +CallManager.getInstance().stopRecording() +``` + + + +**Available via:** SDK | [Dashboard](https://app.cometchat.com) + -This section will guide you to implement call recording feature for the voice and video calls. +This section guides you through implementing the call recording feature for voice and video calls. ## Implementation -Once you have decided to implement [Default Calling](/sdk/android/default-calling) or [Direct Calling](/sdk/android/direct-calling) calling and followed the steps to implement them. Just few additional listeners and methods will help you quickly implement call recording in your app. +Once you have decided to implement [Default Calling](/sdk/android/default-calling) or [Direct Calling](/sdk/android/direct-calling) and followed the steps to implement them, a few additional listeners and methods will help you quickly implement call recording in your app. -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/android/default-calling) or [Direct Calling](/sdk/android/direct-calling). +You need to make changes in the `CometChat.startCall` method and add the required listeners for recording. Make sure your `callSettings` is configured accordingly for [Default Calling](/sdk/android/default-calling) or [Direct Calling](/sdk/android/direct-calling). -A basic example of how to make changes to implement recording for a direct/default call: +Here is a basic example of how to implement recording for a direct/default call: @@ -56,9 +78,9 @@ CometChat.startCall(callSettings, object : OngoingCallListener { ## 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 `startCall()` method to start the call. +The `CallSettings` class allows you to customize the overall calling experience. The properties for the call/conference can be set using the `CallSettingsBuilder` class. This gives you an object of the `CallSettings` class which you can pass to the `startCall()` method to start the call. -The options available for recording of calls are: +The options available for recording calls are: | Setting | Description | | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | @@ -106,3 +128,40 @@ CallManager.getInstance().stopRecording() + + +## Best Practices + + + + Always notify participants when recording starts or stops. Use the `onRecordingStarted()` and `onRecordingStopped()` callbacks to display visual indicators (e.g., a red recording icon) in your UI. + + + Ensure your app has the necessary permissions to record audio and video. Request permissions at runtime and handle cases where users deny recording permissions. + + + Only enable `startRecordingOnCallStart(true)` when required by your use case (e.g., compliance, training). For most applications, let users manually control recording to respect privacy. + + + Recordings are stored on CometChat servers and can be accessed from the [Dashboard](https://app.cometchat.com). Inform users where they can find their recordings after the call ends. + + + +--- + +## Next Steps + + + + Implement complete calling workflow with incoming/outgoing call UI + + + Start and manage call sessions with video and audio controls + + + Retrieve and display call history for users and groups + + + Access and manage call recordings from the CometChat Dashboard + + diff --git a/sdk/android/resources-overview.mdx b/sdk/android/resources-overview.mdx index 59e91dad5..f35a268b5 100644 --- a/sdk/android/resources-overview.mdx +++ b/sdk/android/resources-overview.mdx @@ -1,7 +1,19 @@ --- title: "Resources" +description: "Additional resources, guides, and references for the CometChat Android SDK" --- + +**Quick Reference for AI Agents & Developers** + +Helpful resources: +- **Real-Time Listeners** → [real-time-listeners](/sdk/android/real-time-listeners) - Complete event handling guide +- **Upgrading from v3** → [upgrading-from-v3-guide](/sdk/android/upgrading-from-v3-guide) - Migration guide +- **Rate Limits** → [rate-limits](/sdk/android/rate-limits) - API rate limiting information +- **Webhooks** → [webhooks-overview](/sdk/android/webhooks-overview) - Server-side event notifications +- **Connection Behaviour** → [connection-behaviour](/sdk/android/connection-behaviour) - SDK connectivity patterns + + We have a number of resources that will help you while integrating CometChat in your app. @@ -9,3 +21,22 @@ We have a number of resources that will help you while integrating CometChat in You can begin with the [all real-time listeners](/sdk/android/real-time-listeners) guide. If you're upgrading from v1, we recommend reading our [upgrading from v3](/sdk/android/upgrading-from-v3-guide) guide. + +--- + +## Next Steps + + + + Complete guide to handling all SDK events + + + Migration guide for v3 to v4 upgrade + + + Understand API rate limiting and quotas + + + Configure server-side event notifications + + diff --git a/sdk/android/retrieve-conversations.mdx b/sdk/android/retrieve-conversations.mdx index 62aa4de7a..64ef2e7b1 100644 --- a/sdk/android/retrieve-conversations.mdx +++ b/sdk/android/retrieve-conversations.mdx @@ -1,18 +1,41 @@ --- title: "Retrieve Conversations" +description: "Fetch and manage conversation lists for recent chats using the Android SDK" --- + +**Quick Reference for AI Agents & Developers** +```kotlin +// Fetch conversations with filters +val conversationsRequest = ConversationsRequestBuilder() + .setLimit(50) + .setConversationType(CometChatConstants.CONVERSATION_TYPE_USER) + .build() + +conversationsRequest.fetchNext(object : CallbackListener>() { + override fun onSuccess(conversations: List) { } + override fun onError(e: CometChatException) { } +}) + +// Get specific conversation +CometChat.getConversation("UID_or_GUID", "user", callback) +``` + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) + 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. ## 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?* +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. +To fetch the list of conversations, use the `ConversationsRequest` class. 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 fetched. -The `ConversationsRequestBuilder` class allows you to set the below parameters: +The `ConversationsRequestBuilder` class allows you to set the following parameters: ### Set Limit @@ -398,9 +421,9 @@ The `Conversation` object consists of the following fields: ## Tag Conversation -*In other words, as a logged-in user, how do I tag a conversation?* +How do I tag a conversation? -To tag a specific conversation, you can use the `tagConversation()` method. The `tagConversation()` method accepts three parameters. +To tag a specific conversation, use the `tagConversation()` method. The `tagConversation()` method accepts three parameters. 1. `conversationWith`: UID/GUID of the user/group whose conversation you want to fetch. @@ -466,9 +489,9 @@ The tags for conversations are one-way. This means that if user A tags a convers ## Retrieve Single Conversation -*In other words, as a logged-in user, how do I retrieve a specific conversation?* +How do I retrieve a specific conversation? -In order to fetch a specific conversation, you can use the `getConversation` method. The `getConversation` method accepts two parameters. +To fetch a specific conversation, use the `getConversation` method. The `getConversation` method accepts two 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: @@ -539,3 +562,68 @@ val conversation = CometChatHelper.getConversationFromMessage(message) While converting a `Message` object to a `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. + +## Best Practices + + + + Set a reasonable limit (30-50) and fetch conversations in batches. Maximum limit is 50 conversations per request. + + + Use `setConversationType()` to fetch only user or group conversations when building separate tabs or views. + + + Enable "Conversation & Advanced Search" in Dashboard and use `setSearchKeyword()` for better user experience with many conversations. + + + Tag conversations (e.g., "archived", "pinned", "important") to organize and filter conversations based on user preferences. + + + When converting messages to conversations, manage unread counts in your app since they're not included in the conversion. + + + +## Troubleshooting + + + + **Symptom:** `fetchNext()` returns an empty list even though conversations exist. + + **Cause:** User hasn't sent or received any messages, or filters are too restrictive. + + **Solution:** Remove filters temporarily to verify conversations exist. Check if the user has participated in any chats. + + + **Symptom:** `setSearchKeyword()` doesn't filter conversations. + + **Cause:** "Conversation & Advanced Search" feature not enabled in Dashboard. + + **Solution:** Enable the feature in [CometChat Dashboard](https://app.cometchat.com) under Chats → Settings → General Configuration. Available in Advanced & Custom plans only. + + + **Symptom:** `setUnread(true)` doesn't filter unread conversations. + + **Cause:** "Conversation & Advanced Search" feature not enabled. + + **Solution:** Enable the feature in Dashboard. This is a premium feature available in Advanced & Custom plans. + + + +--- + +## Next Steps + + + + Remove conversations from the list + + + Show when users are typing + + + Track message delivery and read status + + + Start sending messages in conversations + + diff --git a/sdk/android/retrieve-group-members.mdx b/sdk/android/retrieve-group-members.mdx index 46001c72a..b0f44ddeb 100644 --- a/sdk/android/retrieve-group-members.mdx +++ b/sdk/android/retrieve-group-members.mdx @@ -1,14 +1,35 @@ --- title: "Retrieve Group Members" +description: "Fetch and filter group members list using the Android SDK" --- + +**Quick Reference for AI Agents & Developers** +```kotlin +// Fetch group members with filters +val groupMembersRequest = GroupMembersRequestBuilder("GUID") + .setLimit(30) + .setSearchKeyword("search") + .setScopes(listOf("admin", "moderator")) + .build() + +groupMembersRequest.fetchNext(object : CallbackListener>() { + override fun onSuccess(members: List) { } + override fun onError(e: CometChatException) { } +}) +``` + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/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. +To fetch the list of group members for a group, use the `GroupMembersRequest` class. 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 group members are fetched. -The `GroupMembersRequestBuilder` class allows you to set the below parameters: +The `GroupMembersRequestBuilder` class allows you to set the following parameters: The `GUID` of the group for which the members are to be fetched must be specified in the constructor of the `GroupMembersRequestBuilder` class. @@ -93,9 +114,9 @@ val groupMembersRequest = GroupMembersRequestBuilder(GUID) -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. +Finally, once all the parameters are set on the builder class, 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 depending on the limit set. +Once you have the object of the `GroupMembersRequest` class, call the `fetchNext()` method. This method returns a list of `GroupMember` objects containing N number of members depending on the limit set. @@ -141,3 +162,66 @@ groupMembersRequest?.fetchNext(object:CometChat.CallbackListener + + +## Best Practices + + + + Set an appropriate limit (e.g., 30) and call `fetchNext()` multiple times to load members in batches, especially for large groups. + + + Use `setScopes()` to fetch only admins and moderators when building admin panels or management interfaces. + + + Use `setSearchKeyword()` to allow users to quickly find specific members by name or UID in large groups. + + + Cache fetched member lists locally to reduce API calls and improve performance when users navigate back to member lists. + + + +## Troubleshooting + + + + **Symptom:** `fetchNext()` returns an empty list even though the group has members. + + **Cause:** The GUID is incorrect, or filters are too restrictive. + + **Solution:** Verify the GUID is correct. Remove filters temporarily to check if members exist. + + + **Symptom:** `fetchNext()` fails with "Not a member" error. + + **Cause:** User is not a member of the group (for private groups). + + **Solution:** Ensure the user has joined the group before fetching members. Use [join-group](/sdk/android/join-group) first. + + + **Symptom:** `setScopes()` returns all members instead of filtered results. + + **Cause:** Scope values must be lowercase strings: "admin", "moderator", "participant". + + **Solution:** Use lowercase scope values. Check the [Group Class](/sdk/android/create-group#group-class) for valid scope constants. + + + +--- + +## Next Steps + + + + Add new members to groups + + + Remove members from groups + + + Update member roles and permissions + + + Fetch list of available groups + + diff --git a/sdk/android/retrieve-groups.mdx b/sdk/android/retrieve-groups.mdx index 7b1878481..e7bb35e46 100644 --- a/sdk/android/retrieve-groups.mdx +++ b/sdk/android/retrieve-groups.mdx @@ -1,14 +1,38 @@ --- title: "Retrieve Groups" +description: "Fetch and filter groups list using the Android SDK" --- + +**Quick Reference for AI Agents & Developers** +```kotlin +// Fetch groups with filters +val groupsRequest = GroupsRequestBuilder() + .setLimit(30) + .joinedOnly(true) + .setSearchKeyWord("search") + .build() + +groupsRequest.fetchNext(object : CallbackListener>() { + override fun onSuccess(groups: List) { } + override fun onError(e: CometChatException) { } +}) + +// Get specific group details +CometChat.getGroup("GUID", callback) +``` + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/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?* +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. +To fetch the list of groups, use the `GroupsRequest` class. 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 fetched. ### Set Limit @@ -62,7 +86,7 @@ val groupsRequest = GroupsRequestBuilder() ### Joined Only -This method when used, will ask CometChat to only return the groups that the user has joined or is a part of. +This method tells CometChat to only return the groups that the user has joined or is a part of. @@ -145,11 +169,11 @@ val groupsRequest = 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. +Finally, once all the parameters are set on the builder class, call the `build()` method to get the object of the `GroupsRequest` class. -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 depending on the limit set. +Once you have the object of the `GroupsRequest` class, call the `fetchNext()` method. This method returns a list of `Group` objects containing N number of groups depending on the limit set. -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 that private group. +The list of groups fetched will only include public and password type groups. Private groups are only included if the user is a member of that private group. @@ -195,9 +219,9 @@ override fun onError(e: CometChatException) { ## Retrieve Particular Group Details -*In other words, as a logged-in user, how do I retrieve information for a specific group?* +How do I retrieve information for a specific group? -To get the information of a group, you can use the `getGroup()` method. +To get the information of a group, use the `getGroup()` method. @@ -292,3 +316,66 @@ override fun onError(e: CometChatException) { This method returns a `Hashmap` with the GUID of the group as the key and the online member count for that group as the value. + + +## Best Practices + + + + Set an appropriate limit (e.g., 30) and call `fetchNext()` multiple times to load groups in batches, improving performance and user experience. + + + Use `joinedOnly(true)` to fetch only groups the user has joined, reducing unnecessary data transfer and improving load times. + + + Use `setSearchKeyWord()` to allow users to quickly find specific groups by name, especially in apps with many groups. + + + Organize groups with tags and use `setTags()` to fetch groups by category (e.g., "sports", "work", "friends"). + + + +## Troubleshooting + + + + **Symptom:** `fetchNext()` returns an empty list even though groups exist. + + **Cause:** Filters may be too restrictive, or the user hasn't joined any groups (when using `joinedOnly(true)`). + + **Solution:** Remove filters temporarily to verify groups exist. Check if `joinedOnly()` is appropriate for your use case. + + + **Symptom:** Private groups are missing from the fetched list. + + **Cause:** Private groups only appear if the user is a member. + + **Solution:** This is expected behavior. Users must be added to private groups by admins before they can see them. + + + **Symptom:** `getGroup()` fails with "Group not found" error. + + **Cause:** The GUID is incorrect, or the group has been deleted. + + **Solution:** Verify the GUID is correct. Check if the group still exists by fetching the groups list first. + + + +--- + +## Next Steps + + + + Create new groups for your users + + + Join groups to participate in conversations + + + Fetch list of group members + + + Learn more about advanced filtering options + + diff --git a/sdk/android/retrieve-users.mdx b/sdk/android/retrieve-users.mdx index ecbf5de36..ffcad6aa3 100644 --- a/sdk/android/retrieve-users.mdx +++ b/sdk/android/retrieve-users.mdx @@ -1,8 +1,38 @@ --- title: "Retrieve Users" +description: "Fetch user details, retrieve user lists with filters, and get online user counts using the Android SDK" --- + +**Quick Reference for AI Agents & Developers** +```kotlin +// Get logged-in user +val user = CometChat.getLoggedInUser() + +// Fetch user list with filters +val usersRequest = UsersRequestBuilder() + .setLimit(30) + .setSearchKeyword("john") + .hideBlockedUsers(true) + .build() + +usersRequest.fetchNext(object : CallbackListener>() { + override fun onSuccess(list: List) { } + override fun onError(e: CometChatException) { } +}) + +// Get specific user details +CometChat.getUser("UID", object : CometChat.CallbackListener() { + override fun onSuccess(user: User) { } + override fun onError(e: CometChatException) { } +}) +``` + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) + ## Retrieve Logged In User Details @@ -29,9 +59,9 @@ This method will return a `User` object containing all the information related t ## 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. +To fetch the list of users, you can use the `UsersRequest` class. 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: +The `UsersRequestBuilder` class allows you to set the following parameters: ### Set Limit @@ -87,7 +117,7 @@ val usersRequest = 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. +This method allows you to define in which user property the `searchKeyword` should be searched. This method only works in combination with `setSearchKeyword()`. By default, the keyword is searched in both UID and Name. @@ -122,12 +152,12 @@ val usersRequest = 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: +The status based on which the users are to be fetched. The status parameter can contain one of the following values: -* 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` - Returns the list of only online users. +* `CometChat.USER_STATUS.OFFLINE` - Returns the list of only offline users. -If this parameter is not set, will return all the available users. +If this parameter is not set, all available users will be returned. @@ -152,11 +182,11 @@ val usersRequest = UsersRequestBuilder() -If this parameter is not set, will return all users. +If this parameter is not set, all users will be returned. ### 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. +This method determines if blocked users should be returned as part of the user list. If set to `true`, the user list will not contain users blocked by the logged-in user. @@ -336,7 +366,7 @@ val usersRequest = 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`. +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 passed to the `sortBy()` method, the user list will be sorted by `name => UID`. @@ -524,3 +554,39 @@ override fun onError(e: CometChatException) { + +--- + +## Best Practices + + + + Always set a reasonable limit (20-50 users) and use `fetchNext()` to paginate through results. This prevents memory issues and improves performance when dealing with large user bases. + + + Use `UsersRequestBuilder` filters (search, status, roles, tags) to fetch only the users you need rather than fetching all users and filtering client-side. This reduces bandwidth and improves response times. + + + Store frequently accessed user details locally to reduce API calls. Use `getLoggedInUser()` to check login status without making network requests. + + + You can chain multiple filters like `setSearchKeyword()`, `hideBlockedUsers()`, and `setUserStatus()` to create precise queries that return exactly the users you need. + + + +## Next Steps + + + + Track and subscribe to user online/offline status updates + + + Block and unblock users to control interactions + + + Create, update, and manage user accounts + + + Start sending messages to retrieved users + + diff --git a/sdk/android/send-message.mdx b/sdk/android/send-message.mdx index 254f6254b..9c4065e5b 100644 --- a/sdk/android/send-message.mdx +++ b/sdk/android/send-message.mdx @@ -15,9 +15,9 @@ You can also send metadata along with a text or media message. Think, for exampl ## Text Message -*In other words, as a sender, how do I send a text message?* +How do I send a text message? -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. +To send a text message to a single user or group, use the `sendMessage()` method and pass a `TextMessage` object to it. ### Add Metadata @@ -198,9 +198,9 @@ When a text message is sent successfully, the response will include a `TextMessa ## Media Message -*In other words, as a sender, how do I send a media message like photos, videos & files?* +How do I send a media message like photos, videos, and 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. +To send a media message to any user or group, use the `sendMediaMessage()` method and pass a `MediaMessage` object to it. ### Add Metadata @@ -752,11 +752,11 @@ You can use the `setMetadata()`, `setCaption()` & `setTags()` methods to add met ## Custom Message -*In other words, as a sender, how do I send a custom message like location co-ordinates?* +How do I send a custom message like location coordinates? CometChat allows you to send custom messages which are neither text nor media messages. -In order to send a custom message, you need to use the `sendCustomMessage()` method. +To send a custom message, use the `sendCustomMessage()` method. The `sendCustomMessage()` methods takes an object of the `CustomMessage` which can be obtained using the below constructor. @@ -922,9 +922,9 @@ On success, you will receive an object of `CustomMessage` class. ### Update Conversation -*How can I decide whether the custom message should update the last message of a conversation?* +How can I decide whether the custom message should update the last message of a conversation? -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(boolean value)` method of the Custom Message. +By default, a custom message will update the last message of a conversation. If you do not want to update the last message of the conversation when a custom message is sent, use the `shouldUpdateConversation(boolean value)` method of the Custom Message. @@ -1035,9 +1035,9 @@ CometChat.sendCustomMessage(customMessage, object : CallbackListener diff --git a/sdk/android/session-timeout.mdx b/sdk/android/session-timeout.mdx index 23470881f..de1f55ab0 100644 --- a/sdk/android/session-timeout.mdx +++ b/sdk/android/session-timeout.mdx @@ -1,7 +1,28 @@ --- title: "Session Timeout Flow" +description: "Configure idle timeout and auto-termination for inactive call sessions in Android" --- + +**Quick Reference for AI Agents & Developers** + +```kotlin +// Configure idle timeout (default: 180 seconds) +val callSettings = CometChatCalls.CallSettingsBuilder(context, videoContainer) + .setIdleTimeoutPeriod(300) // 300 seconds = 5 minutes + .setEventListener(object : CometChatCallsEventsListener { + override fun onSessionTimeout() { + // Handle auto-termination due to inactivity + } + }) + .build() +``` + +**Available since:** v4.1.0 +**Default timeout:** 180 seconds (3 minutes alone) +**Warning shown:** 60 seconds before auto-termination + + Available since v4.1.0 @@ -10,14 +31,14 @@ Available since v4.1.0 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: -1. After 120 seconds of being alone in the session, the participant will see a dialog box +1. After 120 seconds of being alone in the session, the participant sees a dialog box 2. This dialog provides options to either: * Stay in the call * Leave immediately -3. If no action is taken within the next 60 seconds, the call will automatically end +3. If no action is taken within the next 60 seconds, the call automatically ends 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. @@ -32,3 +53,66 @@ 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. + + +--- + +## Best Practices + + + + Choose a timeout duration that balances resource management with user experience. 180 seconds (3 minutes) is suitable for most use cases, but consider longer durations for scenarios where users may step away briefly. + + + Implement the `onSessionTimeout()` callback to clean up resources and navigate users away from the call screen. Show a clear message explaining why the call ended. + + + Display information about the idle timeout policy in your app's help section or during onboarding so users understand why calls may auto-terminate. + + + Test the timeout flow thoroughly, including the warning dialog and auto-termination, to ensure users have enough time to respond and the experience is smooth. + + + +## Troubleshooting + + + + **Symptom:** Call terminates before the expected timeout period. + + **Cause:** The `setIdleTimeoutPeriod()` value may be set too low, or the timeout is being triggered by other factors. + + **Solution:** Verify the timeout value in your `CallSettingsBuilder`. Ensure you're setting the value in seconds (e.g., 300 for 5 minutes). Check that the call isn't ending due to other reasons like network issues. + + + **Symptom:** Call terminates without showing the 60-second warning dialog. + + **Cause:** The default UI layout may be disabled, or the dialog is being blocked by custom UI elements. + + **Solution:** Ensure `setDefaultLayoutEnable(true)` is set in your call settings. Check that no custom views are overlaying the call UI and blocking the dialog. + + + **Symptom:** The `onSessionTimeout()` callback is not triggered when the call auto-terminates. + + **Cause:** Event listener may not be properly registered or the SDK version doesn't support this callback. + + **Solution:** Verify you're using SDK v4.1.0 or later. Ensure the event listener is registered using `setEventListener()` in your call settings before starting the session. + + + +## Next Steps + + + + Implement one-on-one and group calling with default UI + + + Use Calls SDK without Chat SDK integration + + + Create webinar-style calling experiences + + + Retrieve and display call history + + diff --git a/sdk/android/setup.mdx b/sdk/android/setup.mdx index 55cef555d..4fc231653 100644 --- a/sdk/android/setup.mdx +++ b/sdk/android/setup.mdx @@ -1,27 +1,47 @@ --- title: "Setup" +description: "Install and initialize the CometChat Android SDK in your application" --- + +**Quick Setup Reference** + +```kotlin +// 1. Add dependency to build.gradle +implementation "com.cometchat:chat-sdk-android:4.1.8" + +// 2. Initialize (run once at app start) +val appSettings = AppSettings.AppSettingsBuilder() + .subscribePresenceForAllUsers() + .setRegion("REGION") + .build() +CometChat.init(context, "APP_ID", appSettings, callback) + +// 3. Login user +CometChat.login("UID", "AUTH_KEY", callback) // Dev only +``` +**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 + -Skip the create new app step. Your existing v2 app can be migrated to v3. > > Follow steps mentioned in **Add the CometChat dependency** section below to upgrade to latest version of v3 - +Skip the create new app step. Your existing v2 app can be migrated to v3. Follow the steps mentioned in the **Add the CometChat dependency** section below to upgrade to the latest version of v3. ### Get your Application Keys -[Signup for CometChat](https://app.cometchat.com) and then: +[Sign up for CometChat](https://app.cometchat.com) and then: 1. Create a new app 2. Head over to the **API Keys** section and note the **Auth Key**, **App ID** & **Region** -Minimum Requirement +Minimum Requirements * Android API Level 21 -* Android API level 24 (in case you are using the calls SDKS) -* Androidx Compatibility +* Android API Level 24 (if you are using the Calls SDK) +* AndroidX Compatibility @@ -63,11 +83,11 @@ dependencies { -In case you plan to use the calling feature, please add the Calling dependency `implementation 'com.cometchat:calls-sdk-android:4.3.3'` in the dependencies section of the app-level `build.gradle` file. +If you plan to use the calling feature, add the Calling dependency `implementation 'com.cometchat:calls-sdk-android:4.3.3'` in the dependencies section of the app-level `build.gradle` file. -Finally, add the below lines `android` section of the **app level** gradle file. +Finally, add the following lines to the `android` section of the **app level** gradle file. @@ -86,20 +106,24 @@ android { ## Initialize CometChat -The `init()` method initialises the settings required for CometChat. The `init()` method takes the below parameters: +The `init()` method initializes the settings required for CometChat. This method takes the following 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. +1. `appID` - Your CometChat App ID +2. `appSettings` - An object of the `AppSettings` class 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 three settings: +The `AppSettings` class allows you to configure the following settings: -* **Region**: The region where you app was created. -* **[Presence Subscription](/sdk/android/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 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. +* **Region**: The region where your app was created. +* **[Presence Subscription](/sdk/android/user-presence)**: Represents the subscription type for user presence (real-time online/offline status). +* **autoEstablishSocketConnection(boolean value)**: When set to `true`, the SDK manages the WebSocket connection internally. When set to `false`, you must manage the WebSocket connection manually. The default value is `true`. For more information, see the Managing Web-Socket connections manually section. +* **overrideAdminHost(adminHost: string)**: Takes the admin URL as input and uses it instead of the default admin URL. This is useful for dedicated deployments of CometChat. +* **overrideClientHost(clientHost: string)**: Takes the client URL as input and uses it instead of the default client URL. This is useful for dedicated deployments of CometChat. -We suggest you call the `init()` method on app startup. +We recommend calling the `init()` method on app startup. + + +`CometChat.init()` must be called before any other SDK method. Calling `login()`, `sendMessage()`, or registering listeners before `init()` will fail. + @@ -186,3 +210,26 @@ Know more about manual mode connection [click here](/sdk/android/connection-beha | ----------------- | ------------------------------------------------------------------------------------------------------------------ | | App in foreground | Call `CometChat.connect()` to create the WebSocket connection | | App in background | Disconnect the WebSocket connection if no ping is received within 30 seconds after the app goes in the background. | + + +**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. + + +--- + +## Next Steps + + + + Learn about secure authentication with Auth Tokens for production apps + + + Start sending text, media, and custom messages to users and groups + + + Understand core concepts like users, groups, messages, and conversations + + + Create and manage users in your CometChat application + + diff --git a/sdk/android/standalone-calling.mdx b/sdk/android/standalone-calling.mdx index 77b4e628c..2d167bea0 100644 --- a/sdk/android/standalone-calling.mdx +++ b/sdk/android/standalone-calling.mdx @@ -1,7 +1,36 @@ --- title: "Standalone Calling" +description: "Implement calling functionality using only the CometChat Calls SDK without the Chat SDK" --- + +**Quick Reference for AI Agents & Developers** + +```kotlin +// Generate call token +val sessionId = "UNIQUE_SESSION_ID" +val userAuthToken = "USER_AUTH_TOKEN" // From REST API +CometChatCalls.generateToken(sessionId, userAuthToken, object : CometChatCalls.CallbackListener() { + override fun onSuccess(generateToken: GenerateToken) { + // Start session with token + } + override fun onError(e: CometChatException) { } +}) + +// Start call session +val callSettings = CometChatCalls.CallSettingsBuilder(context, videoContainer) + .setDefaultLayoutEnable(true) + .setIsAudioOnly(false) + .build() +CometChatCalls.startSession(callToken, callSettings, callback) + +// End session +CometChatCalls.endSession() +``` + +**Prerequisites:** [Calls SDK setup](/sdk/android/calling-setup), User auth token from REST API + + ## 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. @@ -502,6 +531,10 @@ CometChatCalls.exitPIPMode() + +Always remove call event listeners when they're no longer needed (e.g., in `onDestroy()` or when navigating away). Failing to remove listeners can cause memory leaks and duplicate event handling. + + ### Switch To Video Call Upgrades an ongoing audio call to a video call. This enables the camera and starts transmitting video to other participants. The remote participant receives the `onCallSwitchedToVideo()` callback. @@ -585,3 +618,75 @@ CometChatCalls.endSession() + +--- + +## Best Practices + + + + Store user auth tokens securely using Android's EncryptedSharedPreferences or KeyStore. Never hardcode tokens in your application code. + + + Use UUIDs or timestamp-based IDs for session IDs to ensure uniqueness. Participants joining the same call must use the same session ID. + + + Auth tokens can expire. Implement token refresh logic and handle token expiration errors gracefully by requesting new tokens from your backend. + + + Always call `CometChatCalls.endSession()` when leaving a call to release camera, microphone, and network resources. Also remove event listeners in `onDestroy()`. + + + Test audio routing on different devices and scenarios (Bluetooth connected, headphones plugged in) to ensure proper audio device selection. + + + +## Troubleshooting + + + + **Symptom:** `generateToken()` fails with "Invalid auth token" error. + + **Cause:** The user auth token is invalid, expired, or incorrectly formatted. + + **Solution:** Verify the auth token was obtained correctly from the REST API. Check token expiration and request a new token if needed. Ensure the token is passed as a string without extra whitespace. + + + **Symptom:** `startSession()` fails with "Invalid call token" error. + + **Cause:** The call token is invalid or the session ID doesn't match. + + **Solution:** Ensure you're using the `GenerateToken` object received from `generateToken()` onSuccess callback. Verify all participants use the same session ID to join the same call. + + + **Symptom:** Call starts but no video is displayed. + + **Cause:** The `RelativeLayout` video container is not properly configured or has zero dimensions. + + **Solution:** Ensure the video container has non-zero width and height in your layout XML. Verify the container is visible and not hidden behind other views. + + + **Symptom:** Video call fails with "Camera permission denied" error. + + **Cause:** The app doesn't have camera and microphone permissions. + + **Solution:** Request `CAMERA` and `RECORD_AUDIO` permissions at runtime before starting a call. Handle permission denial gracefully by showing an explanation to the user. + + + +## Next Steps + + + + Implement calling with Chat SDK integration + + + Customize the call UI appearance and layout + + + Configure idle timeout and auto-termination + + + Record call sessions for later playback + + diff --git a/sdk/android/threaded-messages.mdx b/sdk/android/threaded-messages.mdx index 8a8787c3a..c0d7a1b3b 100644 --- a/sdk/android/threaded-messages.mdx +++ b/sdk/android/threaded-messages.mdx @@ -1,8 +1,68 @@ --- title: "Threaded Messages" +description: "Send and receive threaded messages to organize conversations around specific topics in the Android SDK" --- + +**Quick Reference for AI Agents & Developers** + + +```kotlin +// Send message in thread +val textMessage = TextMessage("UID", "Reply text", CometChatConstants.RECEIVER_TYPE_USER) +textMessage.parentMessageId = 100 +CometChat.sendMessage(textMessage, object : CallbackListener() { + override fun onSuccess(message: TextMessage) { } + override fun onError(e: CometChatException) { } +}) + +// Fetch thread messages +val messagesRequest = MessagesRequest.MessagesRequestBuilder() + .setParentMessageId(100) + .setLimit(30) + .build() +messagesRequest.fetchPrevious(callback) + +// Exclude threads from main conversation +val messagesRequest = MessagesRequest.MessagesRequestBuilder() + .setUID("user_uid") + .hideReplies(true) + .build() +``` + + +```java +// Send message in thread +TextMessage textMessage = new TextMessage("UID", "Reply text", CometChatConstants.RECEIVER_TYPE_USER); +textMessage.setParentMessageId(100); +CometChat.sendMessage(textMessage, new CallbackListener() { + @Override + public void onSuccess(TextMessage message) { } + @Override + public void onError(CometChatException e) { } +}); + +// Fetch thread messages +MessagesRequest messagesRequest = new MessagesRequest.MessagesRequestBuilder() + .setParentMessageId(100) + .setLimit(30) + .build(); +messagesRequest.fetchPrevious(callback); + +// Exclude threads from main conversation +MessagesRequest messagesRequest = new MessagesRequest.MessagesRequestBuilder() + .setUID("user_uid") + .hideReplies(true) + .build(); +``` + + + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) + 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. @@ -18,7 +78,7 @@ A message can be categorized as: Any of the above messages can be sent in a thread. As a thread is identified with a parent message, the `parentMessageId` must be set for the message. This will indicate that the message to be sent has to be a part of the thread of the message 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. +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. For more details on message types, see [Message Structure & Hierarchy](/sdk/android/message-structure-and-hierarchy). **Example to Send a Text Message in a thread in a user conversation.** @@ -135,7 +195,7 @@ CometChat.addMessageListener(listenerID, object : MessageListener() { ### Fetch all the messages for any particular thread. -You can fetch all the messages belonging to a particular thread by using the `MessagesRequest` class. +You can fetch all the messages belonging to a particular thread by using the `MessagesRequest` class. For more information on message filtering, see [Additional Message Filtering](/sdk/android/additional-message-filtering). The `MessageRequestBuilder` builds the `MessageRequest` object using the following functions: @@ -241,3 +301,36 @@ messagesRequest.fetchPrevious(object : CallbackListener?>() { 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. + +## Best Practices + + + + Always use `hideReplies(true)` when fetching messages for main user/group conversations to keep threads separate and maintain a clean conversation view. This prevents thread replies from cluttering the main message list. + + + When receiving real-time messages, always check the `parentMessageId` to determine if a message belongs to an active thread. This ensures proper message routing in your UI. + + + Before allowing users to reply in a thread, verify that the parent message still exists and hasn't been deleted. This prevents orphaned thread messages. + + + +--- + +## Next Steps + + + + Learn how to send text, media, and custom messages + + + Handle real-time message events with listeners + + + Understand message objects and their properties + + + Add emoji reactions to messages + + diff --git a/sdk/android/transfer-group-ownership.mdx b/sdk/android/transfer-group-ownership.mdx index 6663488bf..f9185e652 100644 --- a/sdk/android/transfer-group-ownership.mdx +++ b/sdk/android/transfer-group-ownership.mdx @@ -1,14 +1,36 @@ --- title: "Transfer Group Ownership" +description: "Transfer group ownership to another member using the Android SDK" --- + +**Quick Reference for AI Agents & Developers** +```kotlin +// Transfer ownership to another member (owner only) +CometChat.transferGroupOwnership("GUID", "NEW_OWNER_UID", + object : CallbackListener() { + override fun onSuccess(message: String) { } + override fun onError(e: CometChatException) { } + }) +``` + +**Important:** +- Only the current owner can transfer ownership +- The new owner must be an existing group member +- Original owner becomes a regular admin after transfer +- Required before owner can leave the group + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) + -*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?* +How do I transfer the ownership of a group if I am the owner? -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. +To transfer the ownership of any group, you must first be the owner of the group. If you are the owner, 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. +This is useful because the owner is not allowed to leave the group. If you want to leave the group as the owner, you must first transfer your ownership to another member of the group, and only then can you leave. @@ -51,3 +73,66 @@ CometChat.transferGroupOwnership(GUID, UID, object : CallbackListener() + + +## Best Practices + + + + Transfer ownership only to trusted, active members who understand group management responsibilities. Consider their activity level and commitment. + + + Inform the new owner before transferring ownership so they're prepared for the responsibility and understand their new role. + + + If you plan to leave the group, transfer ownership first. Owners cannot leave without transferring ownership or deleting the group. + + + Ensure the target member is an active participant (not banned or kicked) before attempting to transfer ownership. + + + +## Troubleshooting + + + + **Symptom:** `transferGroupOwnership()` fails with "Not the owner" error. + + **Cause:** User is not the current owner of the group. + + **Solution:** Only the current owner can transfer ownership. Check `group.getOwner()` to verify ownership. + + + **Symptom:** Transfer fails with "User not found" or "Not a member" error. + + **Cause:** The target UID doesn't exist or is not a member of the group. + + **Solution:** Verify the UID is correct and the user is an active member. Use [retrieve-group-members](/sdk/android/retrieve-group-members) to confirm membership. + + + **Symptom:** `leaveGroup()` fails when user is the owner. + + **Cause:** Owners must transfer ownership before leaving. + + **Solution:** Use `transferGroupOwnership()` first, then call `leaveGroup()`. Alternatively, use [delete-group](/sdk/android/delete-group) to remove the group entirely. + + + +--- + +## Next Steps + + + + Leave the group after transferring ownership + + + Update member roles and permissions + + + Permanently delete the group instead + + + View group members to choose new owner + + diff --git a/sdk/android/transient-messages.mdx b/sdk/android/transient-messages.mdx index efeceec14..5f6c6e61a 100644 --- a/sdk/android/transient-messages.mdx +++ b/sdk/android/transient-messages.mdx @@ -1,11 +1,33 @@ --- title: "Transient Messages" +description: "Send ephemeral real-time messages that are not stored or tracked using the Android SDK" --- + +**Quick Reference for AI Agents & Developers** +```kotlin +// Send transient message to user +val data = JSONObject() +data.put("LIVE_REACTION", "heart") +val transientMessage = TransientMessage("UID", CometChatConstants.RECEIVER_TYPE_USER, data) +CometChat.sendTransientMessage(transientMessage) + +// Receive transient messages +CometChat.addMessageListener("LISTENER_ID", object : MessageListener() { + override fun onTransientMessageReceived(transientMessage: TransientMessage) { + Log.d(TAG, "Transient message: ${transientMessage.data}") + } +}) +``` + 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/android/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. @@ -41,7 +63,7 @@ CometChat.sendTransientMessage(transientMessage) ## Real-time Transient Messages -*In other words, as a recipient, how do I know when someone sends a transient message?* +How do I know when someone sends a transient message? You will receive the transient message in the `onTransientMessageReceived()` method of the registered `MessageListener` class. @@ -79,3 +101,40 @@ 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. | + + +Always remove listeners when they're no longer needed (e.g., in `onDestroy()` or when navigating away). Failing to remove listeners can cause memory leaks and duplicate event handling. + + +## Best Practices + + + + Transient messages are ideal for temporary events like typing indicators, live reactions, or presence updates. For messages that need to be stored or retrieved later, use regular text or custom messages instead. + + + Since transient messages are sent in real-time, keep the data payload minimal to reduce network overhead and improve delivery speed. Avoid sending large objects or binary data. + + + Transient messages are only delivered to online users. If delivery confirmation is critical, implement a fallback mechanism using regular messages or check user presence before sending. + + + +--- + +## Next Steps + + + + Send text, media, and custom messages that are stored and retrievable + + + Handle real-time message delivery with message listeners + + + Show real-time typing status for users and groups + + + Learn about all available real-time event listeners + + diff --git a/sdk/android/typing-indicators.mdx b/sdk/android/typing-indicators.mdx index 452fd1f4a..d671065f2 100644 --- a/sdk/android/typing-indicators.mdx +++ b/sdk/android/typing-indicators.mdx @@ -1,12 +1,34 @@ --- title: "Typing Indicators" +description: "Show real-time typing status in conversations using the Android SDK" --- + +**Quick Reference for AI Agents & Developers** +```kotlin +// Start typing indicator +val typingIndicator = TypingIndicator("UID", CometChatConstants.RECEIVER_TYPE_USER) +CometChat.startTyping(typingIndicator) + +// Stop typing indicator +CometChat.endTyping(typingIndicator) + +// Listen for typing events +CometChat.addMessageListener("LISTENER_ID", object : MessageListener() { + override fun onTypingStarted(indicator: TypingIndicator) { } + override fun onTypingEnded(indicator: TypingIndicator) { } +}) +``` + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) + ## Send a Typing Indicator -*In other words, as a sender, how do I let the recipient(s) know that I'm typing?* +How do I let the recipient(s) know that I'm typing? ### Start Typing @@ -103,7 +125,7 @@ You can use the `metadata` field of the `TypingIndicator` class to pass addition ## Real-time Typing Indicators -*In other words, as a recipient, how do I know when someone is typing?* +How do I know when someone is typing? You will receive the typing indicators in the `onTypingStarted()` and the `onTypingEnded()` method of the registered `MessageListener` class. @@ -152,3 +174,72 @@ The `TypingIndicator` class consists of the below parameters: | `receiverId` | `UID` of the receiver. This is the ID of the group or the user the typing indicator is being 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. `CometChatConstants.RECEIVER_TYPE_USER` 2. `CometChatConstants.RECEIVER_TYPE_GROUP` | | `metadata` | A JSONObject to provider additional data | + + +Always remove message listeners when they're no longer needed (e.g., in `onDestroy()` or when navigating away). Failing to remove listeners can cause memory leaks and duplicate event handling. + + +## Best Practices + + + + Don't send typing indicators on every keystroke. Use a debounce mechanism (e.g., 300-500ms delay) to reduce API calls and improve performance. + + + Automatically call `endTyping()` after 3-5 seconds of inactivity to handle cases where users stop typing without sending a message. + + + Always call `endTyping()` immediately after sending a message to clear the typing indicator for recipients. + + + In group chats, display "User1, User2, and 3 others are typing..." to handle multiple simultaneous typers gracefully. + + + Use the metadata field to send additional context like "recording audio" or "uploading photo" for richer status indicators. + + + +## Troubleshooting + + + + **Symptom:** `onTypingStarted()` or `onTypingEnded()` not being called. + + **Cause:** Message listener not registered or removed prematurely. + + **Solution:** Ensure `addMessageListener()` is called before typing indicators are sent. Keep the listener active while the chat is open. + + + **Symptom:** Typing indicator shows indefinitely without clearing. + + **Cause:** `endTyping()` not called when user stops typing or leaves the chat. + + **Solution:** Call `endTyping()` when user sends a message, clears input, or navigates away. Implement auto-timeout after 3-5 seconds. + + + **Symptom:** Performance issues or rate limiting due to excessive typing indicator calls. + + **Cause:** Sending typing indicators on every keystroke without debouncing. + + **Solution:** Implement debouncing to send typing indicators at most once every 300-500ms. + + + +--- + +## Next Steps + + + + Track message delivery and read status + + + Handle incoming messages with listeners + + + Fetch conversation list + + + Learn more about event listeners + + diff --git a/sdk/android/update-group.mdx b/sdk/android/update-group.mdx index a122d63ea..531415f14 100644 --- a/sdk/android/update-group.mdx +++ b/sdk/android/update-group.mdx @@ -1,14 +1,35 @@ --- title: "Update A Group" +description: "Modify group details, settings, and metadata using the Android SDK" --- + +**Quick Reference for AI Agents & Developers** +```kotlin +// Update group details +val group = Group("GUID", "New Name", CometChatConstants.GROUP_TYPE_PUBLIC, "") +group.description = "Updated description" +group.icon = "https://example.com/icon.png" + +CometChat.updateGroup(group, object : CometChat.CallbackListener() { + override fun onSuccess(updatedGroup: Group) { } + override fun onError(e: CometChatException) { } +}) +``` + +**Note:** Only admins and moderators can update group details. See [Group Class](/sdk/android/create-group#group-class) for editable fields. + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) + ## Update Group -*In other words, as a group owner, how can I update the group details?* +*As a group owner, how can I update the group details?* -You can update the existing details of the group using the `updateGroup()` method. +You can update the existing details of a group using the `updateGroup()` method. @@ -56,12 +77,75 @@ CometChat.updateGroup(group,object :CometChat.CallbackListener(){ -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` | +This method takes an instance of the `Group` class as a parameter, which should contain the data you wish to update. + +| Parameter | Description | +| --------- | ------------------------------ | +| `group` | An instance of the `Group` class | + +After the successful update of the group, you will receive an instance of the `Group` class containing the updated information of the group. + +For more information on the `Group` class, see [here](/sdk/android/create-group#group-class). + + +## Best Practices + + + + Create a Group object with the GUID and only set the fields you want to update. Unchanged fields will retain their existing values. + + + Store custom group properties in the metadata field as JSON to extend group functionality without modifying the core schema. + + + Validate group names, descriptions, and icon URLs before calling updateGroup() to avoid API errors and improve user experience. + + + Listen for group update events to keep your UI synchronized when other admins or moderators modify group details. + + + +## Troubleshooting + + + + **Symptom:** `updateGroup()` fails with "Insufficient permissions" error. + + **Cause:** User is not an admin or moderator of the group. + + **Solution:** Only admins and moderators can update group details. Check the user's scope using `group.getScope()` before attempting updates. + + + **Symptom:** `updateGroup()` fails with "Group not found" error. + + **Cause:** The GUID in the Group object is incorrect or the group doesn't exist. + + **Solution:** Verify the GUID is correct. Fetch the group first using [retrieve-groups](/sdk/android/retrieve-groups) to ensure it exists. + + + **Symptom:** Group type doesn't change after calling `updateGroup()`. + + **Cause:** Group type (public/private/password) cannot be changed after creation. + + **Solution:** Group type is immutable. If you need a different type, create a new group and migrate members. + + -After the successful update of the group, you will receive an instance of `Group` class containing updated information of the group. +--- -For more information on the `Group` class, please check [here](/sdk/android/create-group#group-class) +## Next Steps + + + + Learn about the Group class and editable fields + + + Permanently delete groups you own + + + Add or remove group members + + + Transfer admin rights to another member + + diff --git a/sdk/android/upgrading-from-v3-guide.mdx b/sdk/android/upgrading-from-v3-guide.mdx index 14bccd7a3..db82e9519 100644 --- a/sdk/android/upgrading-from-v3-guide.mdx +++ b/sdk/android/upgrading-from-v3-guide.mdx @@ -1,12 +1,30 @@ --- title: "Upgrading From V3" +description: "Migration guide for upgrading from CometChat Android SDK v3 to v4" --- + +**Quick Reference for AI Agents & Developers** +**Migration Steps:** +1. Update Maven URL to `https://dl.cloudsmith.io/public/cometchat/cometchat/maven/` +2. Update dependency to `com.cometchat:chat-sdk-android:4.1.7` (or latest v4) +3. Change all imports from `com.cometchat.pro.*` to `com.cometchat.chat.*` +4. Rebuild and test your application -Upgrading from v3.x to v4 is fairly simple. Below are the major changes that are released as a part of CometChat v4: +**Key Changes:** +- Package name changed from `com.cometchat.pro` to `com.cometchat.chat` +- Maven repository URL updated +- API remains largely compatible with v3 -Please follow the [setup](/sdk/android/setup) instructions to upgrade to the latest V4 version. +**Full guide:** Follow the [setup](/sdk/android/setup) instructions for detailed v4 setup. + + + + +Upgrading from v3.x to v4 is straightforward. Below are the major changes released as part of CometChat v4: + +Follow the [setup](/sdk/android/setup) instructions to upgrade to the latest V4 version. ## Maven URL Change @@ -40,6 +58,78 @@ dependencies { -## Change The Import Classes Packages +## Change the Import Class Packages + +In v3, the import class package name starts with `com.cometchat.pro.*`. Change it to `com.cometchat.chat.*` everywhere in the project and you are done with the v3 to v4 migration. + +--- + +## Best Practices + + + + After updating imports and dependencies, thoroughly test all CometChat functionality in your app. Pay special attention to initialization, authentication, messaging, and calling features. + + + Use your IDE's find-and-replace feature to update all `com.cometchat.pro` imports to `com.cometchat.chat` across your entire project. Don't miss any files. + + + While the API is largely compatible, review the v4 changelog for any breaking changes that might affect your specific use case. Test edge cases and error handling. + + + Ensure your project-level build.gradle includes the new Maven URL in the repositories section. Clean and rebuild your project after making changes. + + + Perform the migration in a separate git branch so you can easily revert if issues arise. Test thoroughly before merging to your main branch. + + + +## Troubleshooting + + + + **Symptom:** Gradle sync or build fails with "Could not resolve com.cometchat:chat-sdk-android" error. + + **Cause:** Maven repository URL not updated in project-level build.gradle. + + **Solution:** Ensure the new Maven URL `https://dl.cloudsmith.io/public/cometchat/cometchat/maven/` is added to the `allprojects` repositories section in your project-level build.gradle. Clean and rebuild the project. + + + **Symptom:** IDE shows "Cannot resolve symbol" errors for CometChat classes. + + **Cause:** Not all import statements were updated from `com.cometchat.pro.*` to `com.cometchat.chat.*`. + + **Solution:** Use your IDE's find-and-replace feature to search for all occurrences of `com.cometchat.pro` and replace with `com.cometchat.chat`. Rebuild the project and resolve any remaining import errors manually. + + + **Symptom:** App builds successfully but crashes at runtime with ClassNotFoundException or similar errors. + + **Cause:** ProGuard/R8 rules may need updating, or some imports were missed. + + **Solution:** Update ProGuard rules to use the new package name `com.cometchat.chat.*`. Verify all imports are updated. Clean and rebuild the project. Check for any reflection-based code that might reference old package names. + + + **Symptom:** `CometChat.init()` fails with errors after migration. + + **Cause:** Incorrect App ID, Region, or Auth Key, or SDK not properly initialized. + + **Solution:** Verify your App ID and Region are correct in the initialization code. Ensure you're using the v4 initialization pattern. Check that the SDK dependency was properly updated to v4. Review initialization logs for specific error messages. + + + +## Next Steps -In v3 the import class package name start from `com.cometchat.pro.*` . Change it to `com.cometchat.chat.*` everywhere in the project and you are done with v3 to v4 migration + + + Review complete v4 setup instructions + + + Test messaging functionality after migration + + + Update calling features to v4 + + + Verify event listeners work correctly + + diff --git a/sdk/android/user-management.mdx b/sdk/android/user-management.mdx index 9c423f8b9..509f1d391 100644 --- a/sdk/android/user-management.mdx +++ b/sdk/android/user-management.mdx @@ -1,12 +1,43 @@ --- title: "User Management" +description: "Create, update, and delete user accounts in CometChat using the Android SDK" --- + +**Quick Reference for AI Agents & Developers** +```kotlin +// Create user (use API Key - dev/testing only) +val apiKey = "API_KEY" +val user = User() +user.uid = "user1" +user.name = "Kevin" + +CometChat.createUser(user, apiKey, object : CometChat.CallbackListener() { + override fun onSuccess(user: User) { } + override fun onError(e: CometChatException) { } +}) + +// Update logged-in user (no API Key needed) +val updatedUser = User() +updatedUser.name = "Andrew Joseph" + +CometChat.updateCurrentUserDetails(updatedUser, object : CallbackListener() { + override fun onSuccess(user: User) { } + override fun onError(e: CometChatException) { } +}) +``` -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. +**Note:** User creation/updates should ideally happen on your backend using [REST API](https://api-explorer.cometchat.com). + -Summing up- + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) + + +When a user logs into your app, you need to programmatically log the user into CometChat. But before you log in the user to CometChat, you need to create the user. + +In summary: **When a user registers in your app** @@ -20,11 +51,11 @@ Summing up- ## 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. +Ideally, user creation should take place at your backend. Refer to 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. However, if you wish to create users on the fly, you can use the `createUser()` method. This method takes a `User` object and the `API Key` as input parameters and returns the created `User` object if the request is successful. -For more details on the fields present in the User class, please check [this](/sdk/android/user-management#user-class) +For more details on the fields present in the User class, see the [User Class](/sdk/android/user-management#user-class) section. @@ -71,6 +102,10 @@ override fun onError(e: CometChatException) { + +**API Key Security:** The API Key should only be used for development and testing. In production, create and update users on your backend server using the [REST API](https://api-explorer.cometchat.com) to keep your API Key secure. Never expose API Keys in production client code. + + UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. @@ -79,7 +114,7 @@ UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and othe ## Updating a 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 using the `updateUser()` method. This method takes a `User` object and the API Key as inputs and returns the updated `User` object on successful execution of the request. +Updating a user, similar to creating a user, should ideally be achieved at your backend using the RESTful APIs. For more information, see the [update a user](https://api-explorer.cometchat.com/reference/update-user) section. However, this can also be achieved on the fly using the `updateUser()` method. This method takes a `User` object and the API Key as inputs and returns the updated `User` object on successful execution of the request. @@ -126,11 +161,11 @@ override fun onError(e: CometChatException) { -Please make sure the `User` object provided to the `updateUser()` method has the `UID` of the user to be updated set. +Please make sure the `User` object provided to the `updateUser()` method has the `UID` of the user to be updated. ## 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. +Updating a logged-in user is similar to updating a user. The only difference is that this method does not require an Auth Key. This method takes a `User` object as input and returns the updated `User` object on successful execution of the request. @@ -173,11 +208,11 @@ override fun onError(e: CometChatException) { -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. +By using the `updateCurrentUserDetails()` method, you can only update the logged-in user regardless of the UID passed. Also, it is not possible to update the role of a logged-in 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. +Deleting a user can only be achieved via the RESTful APIs. For more information, see the [delete a user](https://api-explorer.cometchat.com/reference/delete-user) section. ## User Class @@ -195,3 +230,68 @@ 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 | + +--- + +## Best Practices + + + + Always create and update users on your backend server using the REST API. This keeps your API Key secure and allows you to validate user data before creating accounts in CometChat. + + + When updating the currently logged-in user's profile, use `updateCurrentUserDetails()` instead of `updateUser()`. This method doesn't require an API Key and is more secure for client-side updates. + + + Ensure UIDs are alphanumeric with only underscores and hyphens. Validate UID format before calling `createUser()` to avoid API errors. + + + Keep user data synchronized between your app's database and CometChat. When a user updates their profile in your app, update it in CometChat as well to maintain consistency. + + + Store additional user information (preferences, settings, custom attributes) in the `metadata` field as JSON. This allows you to extend user profiles without modifying the core schema. + + + +## Troubleshooting + + + + **Symptom:** `createUser()` fails with "User with this UID already exists" error. + + **Cause:** Attempting to create a user with a UID that's already registered in CometChat. + + **Solution:** Check if the user exists before creating by calling `CometChat.getUser()` first. If the user exists, use `updateUser()` instead of `createUser()`. + + + **Symptom:** `createUser()` or `updateUser()` fails with "Invalid API Key" error. + + **Cause:** Incorrect API Key or using Auth Key instead of API Key. + + **Solution:** Verify your API Key in the [CometChat Dashboard](https://app.cometchat.com) under API & Auth Keys. Ensure you're using the API Key (for user management), not the Auth Key (for authentication). + + + **Symptom:** `updateCurrentUserDetails()` doesn't update the user's role. + + **Cause:** The `updateCurrentUserDetails()` method cannot modify user roles for security reasons. + + **Solution:** Update user roles on your backend using the [REST API](https://api-explorer.cometchat.com/reference/update-user). Role changes should be controlled server-side. + + + +## Next Steps + + + + Log users into CometChat after creating their accounts + + + Fetch user lists and search for specific users + + + Track user online/offline status in real-time + + + Implement user blocking and unblocking features + + diff --git a/sdk/android/user-presence.mdx b/sdk/android/user-presence.mdx index 58c0f69f4..c523864ab 100644 --- a/sdk/android/user-presence.mdx +++ b/sdk/android/user-presence.mdx @@ -1,30 +1,86 @@ --- title: "User Presence" +description: "Track and subscribe to user online/offline status and presence updates in your Android app" --- + +**Quick Reference for AI Agents & Developers** + + +```kotlin +// Subscribe to presence during init +val appSettings = AppSettings.AppSettingsBuilder() + .subscribePresenceForAllUsers() + .setRegion("REGION") + .build() +CometChat.init(context, "APP_ID", appSettings, callback) + +// Add user listener +CometChat.addUserListener("LISTENER_ID", object : CometChat.UserListener() { + override fun onUserOnline(user: User?) { + Log.d(TAG, "${user?.name} is online") + } + override fun onUserOffline(user: User?) { + Log.d(TAG, "${user?.name} is offline") + } +}) -User Presence helps us understand if a user is available to chat or not. +// Remove listener (important!) +CometChat.removeUserListener("LISTENER_ID") +``` + + +```java +// Subscribe to presence during init +AppSettings appSettings = new AppSettings.AppSettingsBuilder() + .subscribePresenceForAllUsers() + .setRegion("REGION") + .build(); +CometChat.init(context, "APP_ID", appSettings, callback); + +// Add user listener +CometChat.addUserListener("LISTENER_ID", new CometChat.UserListener() { + @Override public void onUserOnline(User user) { + Log.d(TAG, user.getName() + " is online"); + } + @Override public void onUserOffline(User user) { + Log.d(TAG, user.getName() + " is offline"); + } +}); + +// Remove listener (important!) +CometChat.removeUserListener("LISTENER_ID"); +``` + + + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) + + +User Presence helps you understand if a user is available to chat or not. ## Real-time Presence -*In other words, as a logged-in user, how do I know if a user is online or offline?* +*As a logged-in user, how do I know if a user is online or offline?* -Based on the settings provided in the `AppSettings` class while initializing CometChat using the `init()` method, the logged-in user will receive the presence for the other users in the app. +Based on the settings provided in the `AppSettings` class while initializing CometChat using the `init()` method, the logged-in user will receive the presence for other users in the app. In the `AppSettings` class, you can set the type of presence you wish to receive. -For presence subscription, the `AppSettingsBuilder` provides 3 methods : +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(List 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 when any of their friends come online or go offline. +* `subscribePresenceForAllUsers()` - Informs the logged-in user when any user in the app comes online or goes offline. +* `subscribePresenceForRoles(List roles)` - Informs the logged-in user only when users with the specified roles come online or go offline. +* `subscribePresenceForFriends()` - Informs the logged-in user when any of their friends come online or go offline. If none of the above methods are set, no presence will be sent to the logged-in user. -For every activity or fragment you wish to receive user events in, you need to register the `UserListener` using the `addUserListener()` method. +For every activity or fragment where you wish to receive user events, you need to register the `UserListener` using the `addUserListener()` method. -We suggest adding the listener in the `onResume()` method of the activity or the fragment where you wish to receive these events in. +We suggest adding the listener in the `onResume()` method of the activity or fragment where you wish to receive these events. @@ -67,7 +123,7 @@ CometChat.addUserListener(listenerID,object :CometChat.UserListener(){ You will receive an object of the `User` class in the listener methods. -We recommend you remove the listener once the activity or fragment is not in use. We suggest adding this method in the `onPause()` method of the activity or the fragment where you wish to receive these events in. +We recommend removing the listener once the activity or fragment is not in use. We suggest adding this method in the `onPause()` method of the activity or fragment where you wish to receive these events. @@ -90,15 +146,54 @@ CometChat.removeUserListener(listenerID) + +Always remove listeners when they're no longer needed (e.g., in `onPause()` or `onDestroy()`). Failing to remove listeners can cause memory leaks and duplicate event handling. + + ## 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?* +*As a logged-in user, when I retrieve the user list, how do I know if a user is online/offline?* When you [retrieve the list of users](/sdk/android/retrieve-users), in the [User](/sdk/android/user-management#user-class) object, you will receive 2 keys: -1. `status` - This will hold either of the two values : +1. `status` - This holds either of the two values: + +* `online` - Indicates that the user is currently online and available to chat. +* `offline` - Indicates that the user is currently offline and not available to chat. + +2. `lastActiveAt` - If the user is offline, this field holds the timestamp of when the user was last online. This can be used to display a **Last seen** indicator for that user. -* `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. +--- + +## Best Practices + + + + Use `subscribePresenceForAllUsers()` for small communities (under 1000 users), `subscribePresenceForFriends()` for social apps where users have friend lists, or `subscribePresenceForRoles()` for role-based presence to optimize performance and reduce unnecessary presence updates. + + + Batch presence updates in your UI to avoid excessive re-renders when multiple users change status simultaneously. Consider debouncing presence updates if you're displaying a large user list. + + + Display a "Last seen" indicator using the `lastActiveAt` timestamp for offline users to provide better context about user availability. + + + +--- -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 a **Last seen** for that user. +## Next Steps + + + + Fetch user lists with presence information + + + Monitor SDK connection state and handle reconnection + + + Learn about user objects and properties + + + Understand all available event listeners + + diff --git a/sdk/android/users-overview.mdx b/sdk/android/users-overview.mdx index ea9156b7a..5f01a4d9a 100644 --- a/sdk/android/users-overview.mdx +++ b/sdk/android/users-overview.mdx @@ -1,10 +1,38 @@ --- title: "Users" sidebarTitle: "Overview" +description: "Manage users, retrieve user lists, and track user presence in your Android application" --- + +**Quick Reference for AI Agents & Developers** +Choose your user management path: +- **User Management** → [user-management](/sdk/android/user-management) - Create and sync users +- **Retrieve Users** → [retrieve-users](/sdk/android/retrieve-users) - Fetch user lists with filters +- **User Presence** → [user-presence](/sdk/android/user-presence) - Track online/offline status +- **Block Users** → [block-users](/sdk/android/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. +The primary aim of our users functionality is to allow you to quickly retrieve and add users to CometChat. You can begin with [user management](/sdk/android/user-management) to sync your users to CometChat. Once that is done, you can [retrieve users](/sdk/android/retrieve-users) and display them in your app. + +--- + +## Next Steps + + + + Create and sync users with CometChat + + + Fetch user lists with filtering and search + + + Track and display user online/offline status + + + Block and unblock users to control interactions + + diff --git a/sdk/android/video-view-customisation.mdx b/sdk/android/video-view-customisation.mdx index 75040b362..9fa286eac 100644 --- a/sdk/android/video-view-customisation.mdx +++ b/sdk/android/video-view-customisation.mdx @@ -1,20 +1,41 @@ --- title: "Video View Customisation" +description: "Customize the main video container appearance, aspect ratio, and UI controls in Android calls" --- + +**Quick Reference for AI Agents & Developers** +```kotlin +// Customize main video container +val videoSettings = MainVideoContainerSetting() +videoSettings.mainVideoAspectRatio = CometChatCallsConstants.ASPECT_RATIO_CONTAIN +videoSettings.setFullScreenButtonParams(CometChatCallsConstants.POSITION_BOTTOM_RIGHT, true) +videoSettings.setNameLabelParams(CometChatCallsConstants.POSITION_BOTTOM_LEFT, true, "#333333") +videoSettings.setZoomButtonParams(CometChatCallsConstants.POSITION_BOTTOM_RIGHT, true) + +// Apply to call settings +val callSettings = CometChatCalls.CallSettingsBuilder(context, videoContainer) + .setMainVideoContainerSetting(videoSettings) + .build() +``` -This section will guide you to customise the main video container. +**Prerequisites:** [Default Calling](/sdk/android/default-calling) or [Direct Calling](/sdk/android/direct-calling) setup + + + + +This section guides you through customizing the main video container. ## Implementation -Once you have decided to implement [Default Calling](/sdk/android/direct-calling) or [Direct Calling](/sdk/android/default-calling) calling and followed the steps to implement them. Just few additional methods will help you quickly customize the main video container. +Once you have decided to implement [Default Calling](/sdk/android/default-calling) or [Direct Calling](/sdk/android/direct-calling) and followed the steps to implement them, a few additional methods will help you quickly customize the main video container. -Please make sure your callSettings is configured accordingly for [Default Calling](/sdk/android/direct-calling) or [Direct Calling](/sdk/android/default-calling). +Make sure your `callSettings` is configured accordingly for [Default Calling](/sdk/android/default-calling) or [Direct Calling](/sdk/android/direct-calling). ## 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 is required when you want to customize the main video view. You need to pass the object of the `MainVideoContainerSetting` class in the `setMainVideoContainerSetting()` method of the `CallSettingsBuilder`. | Setting | Description | | --------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | @@ -54,3 +75,66 @@ videoSettings.setUserListButtonParams(CometChatCallsConstants.POSITION_BOTTOM_RI + + +--- + +## Best Practices + + + + Use `ASPECT_RATIO_CONTAIN` to show the entire video without cropping (may have letterboxing). Use `ASPECT_RATIO_COVER` to fill the container completely (may crop edges). Choose based on your UI design requirements. + + + Place UI controls (full screen, zoom, user list buttons) in positions that don't overlap with important content. Test on different screen sizes to ensure controls remain accessible. + + + Choose name label background colors that contrast well with your video content. The default `#333333` works well for most scenarios, but adjust based on your app's theme. + + + Test video view customizations on devices with different screen sizes and aspect ratios (phones, tablets, foldables) to ensure consistent appearance. + + + +## Troubleshooting + + + + **Symptom:** Video doesn't display correctly, appearing stretched, squashed, or cropped unexpectedly. + + **Cause:** Incorrect aspect ratio setting for your use case. + + **Solution:** Switch between `ASPECT_RATIO_CONTAIN` (shows full video with possible letterboxing) and `ASPECT_RATIO_COVER` (fills container, may crop edges) to find the best fit for your layout. + + + **Symptom:** Full screen, zoom, or user list buttons are not showing up. + + **Cause:** Visibility is set to `false` or controls are positioned outside the visible area. + + **Solution:** Verify the visibility parameter is set to `true` in the respective button params methods. Check that the video container has sufficient dimensions to display controls. + + + **Symptom:** Participant names are difficult to read on the video. + + **Cause:** Background color doesn't provide enough contrast with the text. + + **Solution:** Adjust the background color in `setNameLabelParams()` to provide better contrast. Use darker colors (#000000 to #666666) for better text readability. + + + +## Next Steps + + + + Implement one-on-one and group calling with default UI + + + Initiate calls directly without user interaction + + + Create webinar-style calling experiences + + + Use Calls SDK without Chat SDK integration + + diff --git a/sdk/android/webhooks-overview.mdx b/sdk/android/webhooks-overview.mdx index 598d43500..a0a9fd005 100644 --- a/sdk/android/webhooks-overview.mdx +++ b/sdk/android/webhooks-overview.mdx @@ -1,4 +1,41 @@ --- title: "Webhooks" +description: "Configure server-side event notifications with CometChat webhooks" url: "/fundamentals/webhooks-overview" ---- \ No newline at end of file +--- + + +**Quick Reference for AI Agents & Developers** + +Webhooks send real-time HTTP notifications to your server when events occur in CometChat: +- **Message Events** - New messages, edits, deletions +- **User Events** - User creation, login, presence changes +- **Group Events** - Group creation, member joins/leaves +- **Call Events** - Call initiation, acceptance, completion + +**Configuration:** [CometChat Dashboard](https://app.cometchat.com) → Your App → Webhooks +**Learn more:** [Webhooks Overview](/fundamentals/webhooks-overview) + + +Webhooks allow your server to receive real-time notifications when events occur in CometChat. This enables server-side processing, logging, analytics, and integration with other systems without polling the API. + +For detailed information about webhook events, payload formats, security, and configuration, visit the [Webhooks Overview](/fundamentals/webhooks-overview) in the Fundamentals section. + +--- + +## Next Steps + + + + Complete guide to CometChat webhooks + + + Handle client-side events with SDK listeners + + + Server-side API for webhook processing + + + Configure webhooks in your dashboard + + \ No newline at end of file From 1169d911224d67b6617ad3be9c542b24db04f31d Mon Sep 17 00:00:00 2001 From: PrajwalDhuleCC Date: Tue, 10 Mar 2026 14:56:06 +0530 Subject: [PATCH 008/139] 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 27e937ea0b384ad2cf0d7c42a11c9917893967ba Mon Sep 17 00:00:00 2001 From: Hritika Date: Wed, 11 Mar 2026 19:20:25 +0530 Subject: [PATCH 009/139] Table Format Payload. --- sdk/android/ai-agents.mdx | 297 ++++++++++++++++++++++++ sdk/android/ai-chatbots-overview.mdx | 303 ++++++++++++++++++++++++- sdk/android/call-logs.mdx | 114 ++++++++++ sdk/android/calling-overview.mdx | 116 ++++++++++ sdk/android/create-group.mdx | 52 +++++ sdk/android/delivery-read-receipts.mdx | 64 ++++++ sdk/android/group-add-members.mdx | 51 +++++ sdk/android/interactive-messages.mdx | 163 +++++++++++++ sdk/android/reactions.mdx | 81 +++++++ sdk/android/receive-messages.mdx | 150 ++++++++++++ sdk/android/retrieve-conversations.mdx | 121 ++++++++++ sdk/android/retrieve-group-members.mdx | 51 +++++ sdk/android/retrieve-groups.mdx | 53 +++++ sdk/android/retrieve-users.mdx | 50 +++- sdk/android/send-message.mdx | 150 ++++++++++++ sdk/android/typing-indicators.mdx | 58 +++++ sdk/android/user-management.mdx | 50 ++++ 17 files changed, 1922 insertions(+), 2 deletions(-) diff --git a/sdk/android/ai-agents.mdx b/sdk/android/ai-agents.mdx index f58b6d6f2..895ea8ad2 100644 --- a/sdk/android/ai-agents.mdx +++ b/sdk/android/ai-agents.mdx @@ -158,6 +158,303 @@ These events are received via the **`MessageListener`** after the run completes. +## Agentic Message Payload Structures + + + +The `AIAssistantMessage` object contains the AI assistant's response: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `id` | long | Unique message identifier | +| `muid` | String | Developer-defined message ID | +| `sender` | [User](#user-object-ai) | User who sent the message | +| `receiver` | AppEntity | Message receiver ([User](#user-object-ai) or Group) | +| `receiverUid` | String | Receiver's unique identifier | +| `type` | String | Message type. Value: `"assistant"` | +| `receiverType` | String | Type of receiver. Values: `"user"`, `"group"` | +| `category` | String | Message category. Value: `"agentic"` | +| `sentAt` | long | Unix timestamp when sent | +| `deliveredAt` | long | Unix timestamp when delivered | +| `readAt` | long | Unix timestamp when read | +| `metadata` | JSONObject | Custom message metadata | +| `readByMeAt` | long | When logged-in user read message | +| `deliveredToMeAt` | long | When delivered to logged-in user | +| `deletedAt` | long | Unix timestamp when deleted (0 if not deleted) | +| `editedAt` | long | Unix timestamp when edited (0 if not edited) | +| `deletedBy` | String | UID of user who deleted (null if not deleted) | +| `editedBy` | String | UID of user who edited (null if not edited) | +| `updatedAt` | long | Unix timestamp of last update | +| `conversationId` | String | Associated conversation ID | +| `runId` | long | AI run identifier | +| `threadId` | String | AI thread identifier | +| `text` | String | AI response text | +| `tags` | Array\ | Message tags | + +**Sample AIAssistantMessage Object:** + +```json +{ + "id": 12345, + "muid": "msg_abc123", + "sender": { + "uid": "user_123", + "name": "John Doe", + "avatar": "https://example.com/avatar.png", + "status": "online", + "role": "default" + }, + "receiver": { + "uid": "user_456", + "name": "Jane Smith" + }, + "receiverUid": "user_456", + "type": "assistant", + "receiverType": "user", + "category": "agentic", + "sentAt": 1699900000, + "deliveredAt": 1699900001, + "readAt": 1699900002, + "metadata": {"priority": "high"}, + "readByMeAt": 1699900002, + "deliveredToMeAt": 1699900001, + "deletedAt": 0, + "editedAt": 0, + "deletedBy": null, + "editedBy": null, + "updatedAt": 1699900000, + "conversationId": "user_123_user_456", + "runId": 98765, + "threadId": "thread_abc", + "text": "Here's the answer...", + "tags": ["ai-response"] +} +``` + + + + + +The `AIToolArgumentMessage` object contains the arguments passed to a tool: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `id` | long | Unique message identifier | +| `muid` | String | Developer-defined message ID | +| `sender` | [User](#user-object-ai) | User who sent the message | +| `receiver` | AppEntity | Message receiver ([User](#user-object-ai) or Group) | +| `receiverUid` | String | Receiver's unique identifier | +| `type` | String | Message type. Value: `"tool_arguments"` | +| `receiverType` | String | Type of receiver. Values: `"user"`, `"group"` | +| `category` | String | Message category. Value: `"agentic"` | +| `sentAt` | long | Unix timestamp when sent | +| `deliveredAt` | long | Unix timestamp when delivered | +| `readAt` | long | Unix timestamp when read | +| `metadata` | JSONObject | Custom message metadata | +| `readByMeAt` | long | When logged-in user read message | +| `deliveredToMeAt` | long | When delivered to logged-in user | +| `deletedAt` | long | Unix timestamp when deleted (0 if not deleted) | +| `editedAt` | long | Unix timestamp when edited (0 if not edited) | +| `deletedBy` | String | UID of user who deleted (null if not deleted) | +| `editedBy` | String | UID of user who edited (null if not edited) | +| `updatedAt` | long | Unix timestamp of last update | +| `conversationId` | String | Associated conversation ID | +| `runId` | long | AI run identifier | +| `threadId` | String | AI thread identifier | +| `toolCalls` | Array\<[AIToolCall](#aitoolcall-object)\> | List of tool calls | +| `tags` | Array\ | Message tags | + +**Sample AIToolArgumentMessage Object:** + +```json +{ + "id": 12346, + "muid": "msg_tool_arg_123", + "sender": { + "uid": "user_123", + "name": "John Doe", + "avatar": "https://example.com/avatar.png", + "status": "online", + "role": "default" + }, + "receiver": { + "uid": "user_456", + "name": "Jane Smith" + }, + "receiverUid": "user_456", + "type": "tool_arguments", + "receiverType": "user", + "category": "agentic", + "sentAt": 1699900000, + "deliveredAt": 1699900001, + "readAt": 1699900002, + "metadata": {"priority": "high"}, + "readByMeAt": 1699900002, + "deliveredToMeAt": 1699900001, + "deletedAt": 0, + "editedAt": 0, + "deletedBy": null, + "editedBy": null, + "updatedAt": 1699900000, + "conversationId": "user_123_user_456", + "runId": 98765, + "threadId": "thread_abc", + "toolCalls": [ + { + "id": "call_abc123", + "name": "search_flights", + "arguments": {"origin": "NYC", "destination": "LA"} + } + ], + "tags": ["tool-arguments"] +} +``` + + + + + +The `AIToolResultMessage` object contains the result from a tool execution: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `id` | long | Unique message identifier | +| `muid` | String | Developer-defined message ID | +| `sender` | [User](#user-object-ai) | User who sent the message | +| `receiver` | AppEntity | Message receiver ([User](#user-object-ai) or Group) | +| `receiverUid` | String | Receiver's unique identifier | +| `type` | String | Message type. Value: `"tool_result"` | +| `receiverType` | String | Type of receiver. Values: `"user"`, `"group"` | +| `category` | String | Message category. Value: `"agentic"` | +| `sentAt` | long | Unix timestamp when sent | +| `deliveredAt` | long | Unix timestamp when delivered | +| `readAt` | long | Unix timestamp when read | +| `metadata` | JSONObject | Custom message metadata | +| `readByMeAt` | long | When logged-in user read message | +| `deliveredToMeAt` | long | When delivered to logged-in user | +| `deletedAt` | long | Unix timestamp when deleted (0 if not deleted) | +| `editedAt` | long | Unix timestamp when edited (0 if not edited) | +| `deletedBy` | String | UID of user who deleted (null if not deleted) | +| `editedBy` | String | UID of user who edited (null if not edited) | +| `updatedAt` | long | Unix timestamp of last update | +| `conversationId` | String | Associated conversation ID | +| `runId` | long | AI run identifier | +| `threadId` | String | AI thread identifier | +| `text` | String | Tool result text | +| `toolCallId` | String | ID of the tool call that produced this result | +| `tags` | Array\ | Message tags | + +**Sample AIToolResultMessage Object:** + +```json +{ + "id": 12347, + "muid": "msg_tool_result_123", + "sender": { + "uid": "user_123", + "name": "John Doe", + "avatar": "https://example.com/avatar.png", + "status": "online", + "role": "default" + }, + "receiver": { + "uid": "user_456", + "name": "Jane Smith" + }, + "receiverUid": "user_456", + "type": "tool_result", + "receiverType": "user", + "category": "agentic", + "sentAt": 1699900000, + "deliveredAt": 1699900001, + "readAt": 1699900002, + "metadata": {"priority": "high"}, + "readByMeAt": 1699900002, + "deliveredToMeAt": 1699900001, + "deletedAt": 0, + "editedAt": 0, + "deletedBy": null, + "editedBy": null, + "updatedAt": 1699900000, + "conversationId": "user_123_user_456", + "runId": 98765, + "threadId": "thread_abc", + "text": "Flight found: NYC to LA...", + "toolCallId": "call_abc123", + "tags": ["tool-result"] +} +``` + + + + + +The `AIToolCall` object represents a single tool invocation: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `id` | String | Unique identifier for the tool call | +| `name` | String | Name of the tool being called | +| `arguments` | JSONObject | Arguments passed to the tool | + +**Sample AIToolCall Object:** + +```json +{ + "id": "call_abc123", + "name": "search_flights", + "arguments": { + "origin": "NYC", + "destination": "LA", + "date": "2024-01-15" + } +} +``` + + + + + +The nested `User` object in `sender` contains: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `uid` | String | Unique identifier of the user | +| `name` | String | Display name of the user | +| `avatar` | String | URL to user's profile picture | +| `link` | String | URL to user's profile page | +| `role` | String | User role for access control | +| `metadata` | JSONObject | Custom data set by developer | +| `status` | String | User online status. Values: `"online"`, `"offline"` | +| `statusMessage` | String | Custom status message | +| `lastActiveAt` | long | Unix timestamp of last activity | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | +| `tags` | Array\ | List of tags for user identification | +| `deactivatedAt` | long | Unix timestamp when user was deactivated (0 if active) | + +**Sample User Object:** + +```json +{ + "uid": "user_123", + "name": "John Doe", + "avatar": "https://example.com/avatar.png", + "link": "https://example.com/profile/user_123", + "role": "default", + "metadata": {"department": "engineering"}, + "status": "online", + "statusMessage": "Available", + "lastActiveAt": 1699900000, + "hasBlockedMe": false, + "blockedByMe": false, + "tags": ["premium"], + "deactivatedAt": 0 +} +``` + + + ## Best Practices diff --git a/sdk/android/ai-chatbots-overview.mdx b/sdk/android/ai-chatbots-overview.mdx index 663cb5c1e..cb5d74dc1 100644 --- a/sdk/android/ai-chatbots-overview.mdx +++ b/sdk/android/ai-chatbots-overview.mdx @@ -2,4 +2,305 @@ title: "AI Chatbots" description: "Implement custom AI chatbots for automated conversations in your Android application" url: "/ai-chatbots/overview" ---- \ No newline at end of file +--- + +# AI Chatbots Overview + +AI Chatbots enable automated conversations within your application. They can process user messages and respond with contextually relevant information. For a broader introduction, see the [AI Chatbots section](/ai-chatbots). + +## Agentic Message Payload Structures + + + +The `AIAssistantMessage` object contains the AI assistant's response: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `id` | long | Unique message identifier | +| `muid` | String | Developer-defined message ID | +| `sender` | [User](#user-object-chatbot) | User who sent the message | +| `receiver` | AppEntity | Message receiver ([User](#user-object-chatbot) or Group) | +| `receiverUid` | String | Receiver's unique identifier | +| `type` | String | Message type. Value: `"assistant"` | +| `receiverType` | String | Type of receiver. Values: `"user"`, `"group"` | +| `category` | String | Message category. Value: `"agentic"` | +| `sentAt` | long | Unix timestamp when sent | +| `deliveredAt` | long | Unix timestamp when delivered | +| `readAt` | long | Unix timestamp when read | +| `metadata` | JSONObject | Custom message metadata | +| `readByMeAt` | long | When logged-in user read message | +| `deliveredToMeAt` | long | When delivered to logged-in user | +| `deletedAt` | long | Unix timestamp when deleted (0 if not deleted) | +| `editedAt` | long | Unix timestamp when edited (0 if not edited) | +| `deletedBy` | String | UID of user who deleted (null if not deleted) | +| `editedBy` | String | UID of user who edited (null if not edited) | +| `updatedAt` | long | Unix timestamp of last update | +| `conversationId` | String | Associated conversation ID | +| `runId` | long | AI run identifier | +| `threadId` | String | AI thread identifier | +| `text` | String | AI response text | +| `tags` | Array\ | Message tags | + +**Sample AIAssistantMessage Object:** + +```json +{ + "id": 12345, + "muid": "msg_abc123", + "sender": { + "uid": "user_123", + "name": "John Doe", + "avatar": "https://example.com/avatar.png", + "status": "online", + "role": "default" + }, + "receiver": { + "uid": "user_456", + "name": "Jane Smith" + }, + "receiverUid": "user_456", + "type": "assistant", + "receiverType": "user", + "category": "agentic", + "sentAt": 1699900000, + "deliveredAt": 1699900001, + "readAt": 1699900002, + "metadata": {"priority": "high"}, + "readByMeAt": 1699900002, + "deliveredToMeAt": 1699900001, + "deletedAt": 0, + "editedAt": 0, + "deletedBy": null, + "editedBy": null, + "updatedAt": 1699900000, + "conversationId": "user_123_user_456", + "runId": 98765, + "threadId": "thread_abc", + "text": "Here's the answer...", + "tags": ["ai-response"] +} +``` + + + + + +The `AIToolArgumentMessage` object contains the arguments passed to a tool: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `id` | long | Unique message identifier | +| `muid` | String | Developer-defined message ID | +| `sender` | [User](#user-object-chatbot) | User who sent the message | +| `receiver` | AppEntity | Message receiver ([User](#user-object-chatbot) or Group) | +| `receiverUid` | String | Receiver's unique identifier | +| `type` | String | Message type. Value: `"tool_arguments"` | +| `receiverType` | String | Type of receiver. Values: `"user"`, `"group"` | +| `category` | String | Message category. Value: `"agentic"` | +| `sentAt` | long | Unix timestamp when sent | +| `deliveredAt` | long | Unix timestamp when delivered | +| `readAt` | long | Unix timestamp when read | +| `metadata` | JSONObject | Custom message metadata | +| `readByMeAt` | long | When logged-in user read message | +| `deliveredToMeAt` | long | When delivered to logged-in user | +| `deletedAt` | long | Unix timestamp when deleted (0 if not deleted) | +| `editedAt` | long | Unix timestamp when edited (0 if not edited) | +| `deletedBy` | String | UID of user who deleted (null if not deleted) | +| `editedBy` | String | UID of user who edited (null if not edited) | +| `updatedAt` | long | Unix timestamp of last update | +| `conversationId` | String | Associated conversation ID | +| `runId` | long | AI run identifier | +| `threadId` | String | AI thread identifier | +| `toolCalls` | Array\<[AIToolCall](#aitoolcall-object-chatbot)\> | List of tool calls | +| `tags` | Array\ | Message tags | + +**Sample AIToolArgumentMessage Object:** + +```json +{ + "id": 12346, + "muid": "msg_tool_arg_123", + "sender": { + "uid": "user_123", + "name": "John Doe", + "avatar": "https://example.com/avatar.png", + "status": "online", + "role": "default" + }, + "receiver": { + "uid": "user_456", + "name": "Jane Smith" + }, + "receiverUid": "user_456", + "type": "tool_arguments", + "receiverType": "user", + "category": "agentic", + "sentAt": 1699900000, + "deliveredAt": 1699900001, + "readAt": 1699900002, + "metadata": {"priority": "high"}, + "readByMeAt": 1699900002, + "deliveredToMeAt": 1699900001, + "deletedAt": 0, + "editedAt": 0, + "deletedBy": null, + "editedBy": null, + "updatedAt": 1699900000, + "conversationId": "user_123_user_456", + "runId": 98765, + "threadId": "thread_abc", + "toolCalls": [ + { + "id": "call_abc123", + "name": "search_flights", + "arguments": {"origin": "NYC", "destination": "LA"} + } + ], + "tags": ["tool-arguments"] +} +``` + + + + + +The `AIToolResultMessage` object contains the result from a tool execution: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `id` | long | Unique message identifier | +| `muid` | String | Developer-defined message ID | +| `sender` | [User](#user-object-chatbot) | User who sent the message | +| `receiver` | AppEntity | Message receiver ([User](#user-object-chatbot) or Group) | +| `receiverUid` | String | Receiver's unique identifier | +| `type` | String | Message type. Value: `"tool_result"` | +| `receiverType` | String | Type of receiver. Values: `"user"`, `"group"` | +| `category` | String | Message category. Value: `"agentic"` | +| `sentAt` | long | Unix timestamp when sent | +| `deliveredAt` | long | Unix timestamp when delivered | +| `readAt` | long | Unix timestamp when read | +| `metadata` | JSONObject | Custom message metadata | +| `readByMeAt` | long | When logged-in user read message | +| `deliveredToMeAt` | long | When delivered to logged-in user | +| `deletedAt` | long | Unix timestamp when deleted (0 if not deleted) | +| `editedAt` | long | Unix timestamp when edited (0 if not edited) | +| `deletedBy` | String | UID of user who deleted (null if not deleted) | +| `editedBy` | String | UID of user who edited (null if not edited) | +| `updatedAt` | long | Unix timestamp of last update | +| `conversationId` | String | Associated conversation ID | +| `runId` | long | AI run identifier | +| `threadId` | String | AI thread identifier | +| `text` | String | Tool result text | +| `toolCallId` | String | ID of the tool call that produced this result | +| `tags` | Array\ | Message tags | + +**Sample AIToolResultMessage Object:** + +```json +{ + "id": 12347, + "muid": "msg_tool_result_123", + "sender": { + "uid": "user_123", + "name": "John Doe", + "avatar": "https://example.com/avatar.png", + "status": "online", + "role": "default" + }, + "receiver": { + "uid": "user_456", + "name": "Jane Smith" + }, + "receiverUid": "user_456", + "type": "tool_result", + "receiverType": "user", + "category": "agentic", + "sentAt": 1699900000, + "deliveredAt": 1699900001, + "readAt": 1699900002, + "metadata": {"priority": "high"}, + "readByMeAt": 1699900002, + "deliveredToMeAt": 1699900001, + "deletedAt": 0, + "editedAt": 0, + "deletedBy": null, + "editedBy": null, + "updatedAt": 1699900000, + "conversationId": "user_123_user_456", + "runId": 98765, + "threadId": "thread_abc", + "text": "Flight found: NYC to LA...", + "toolCallId": "call_abc123", + "tags": ["tool-result"] +} +``` + + + + + +The `AIToolCall` object represents a single tool invocation: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `id` | String | Unique identifier for the tool call | +| `name` | String | Name of the tool being called | +| `arguments` | JSONObject | Arguments passed to the tool | + +**Sample AIToolCall Object:** + +```json +{ + "id": "call_abc123", + "name": "search_flights", + "arguments": { + "origin": "NYC", + "destination": "LA", + "date": "2024-01-15" + } +} +``` + + + + + +The nested `User` object in `sender` contains: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `uid` | String | Unique identifier of the user | +| `name` | String | Display name of the user | +| `avatar` | String | URL to user's profile picture | +| `link` | String | URL to user's profile page | +| `role` | String | User role for access control | +| `metadata` | JSONObject | Custom data set by developer | +| `status` | String | User online status. Values: `"online"`, `"offline"` | +| `statusMessage` | String | Custom status message | +| `lastActiveAt` | long | Unix timestamp of last activity | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | +| `tags` | Array\ | List of tags for user identification | +| `deactivatedAt` | long | Unix timestamp when user was deactivated (0 if active) | + +**Sample User Object:** + +```json +{ + "uid": "user_123", + "name": "John Doe", + "avatar": "https://example.com/avatar.png", + "link": "https://example.com/profile/user_123", + "role": "default", + "metadata": {"department": "engineering"}, + "status": "online", + "statusMessage": "Available", + "lastActiveAt": 1699900000, + "hasBlockedMe": false, + "blockedByMe": false, + "tags": ["premium"], + "deactivatedAt": 0 +} +``` + + \ No newline at end of file diff --git a/sdk/android/call-logs.mdx b/sdk/android/call-logs.mdx index 733a1bcfb..b53b30265 100644 --- a/sdk/android/call-logs.mdx +++ b/sdk/android/call-logs.mdx @@ -226,6 +226,120 @@ Note: Replace `"SESSION_ID"` with the ID of the session you are interested in. +## Call Payload Structure + + + +The `Call` object extends `BaseMessage` and contains all call-related information: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `id` | long | Unique identifier of the call message | +| `muid` | String | Developer-defined message ID | +| `sender` | [User](#user-object-call-logs) | User who sent the call message | +| `receiver` | AppEntity | Call receiver ([User](#user-object-call-logs) or [Group](#group-object-call-logs)) | +| `receiverUid` | String | Receiver's unique identifier | +| `type` | String | Call type. Values: `"audio"`, `"video"` | +| `receiverType` | String | Type of receiver. Values: `"user"`, `"group"` | +| `category` | String | Message category. Value: `"call"` | +| `sentAt` | long | Unix timestamp when call was sent | +| `deliveredAt` | long | Unix timestamp when delivered | +| `readAt` | long | Unix timestamp when read | +| `metadata` | JSONObject | Custom call metadata | +| `conversationId` | String | Associated conversation identifier | +| `sessionId` | String | Unique call session identifier | +| `callStatus` | String | Status of the call. Values: `"initiated"`, `"ongoing"`, `"ended"`, `"cancelled"`, `"busy"`, `"rejected"`, `"unanswered"` | +| `action` | String | Action performed on call. Values: `"initiated"`, `"ongoing"`, `"ended"` | +| `rawData` | String | Raw JSON data of the call | +| `initiatedAt` | long | Unix timestamp when call was initiated | +| `joinedAt` | long | Unix timestamp when call was joined | +| `callInitiator` | [User](#user-object-call-logs) | User who initiated the call | +| `callReceiver` | AppEntity | User or Group receiving the call | + +**Sample Call Object:** + +```json +{ + "id": 12345, + "muid": "call_abc123", + "sender": { + "uid": "user_123", + "name": "John Doe", + "avatar": "https://example.com/avatar.png", + "status": "online" + }, + "receiver": { + "uid": "user_456", + "name": "Jane Smith" + }, + "receiverUid": "user_456", + "type": "video", + "receiverType": "user", + "category": "call", + "sentAt": 1699900000, + "deliveredAt": 1699900001, + "readAt": 1699900002, + "metadata": {}, + "conversationId": "user_123_user_456", + "sessionId": "v1.us.1234567890", + "callStatus": "ended", + "action": "ended", + "rawData": "{}", + "initiatedAt": 1699900000, + "joinedAt": 1699900005, + "callInitiator": { + "uid": "user_123", + "name": "John Doe", + "avatar": "https://example.com/avatar.png" + }, + "callReceiver": { + "uid": "user_456", + "name": "Jane Smith", + "avatar": "https://example.com/avatar2.png" + } +} +``` + + + + + +The nested `User` object (used in `sender`, `callInitiator`, `callReceiver`) contains: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `uid` | String | Unique identifier of the user | +| `name` | String | Display name of the user | +| `avatar` | String | URL to user's profile picture | +| `link` | String | URL to user's profile page | +| `role` | String | User role for access control | +| `metadata` | JSONObject | Custom data set by developer | +| `status` | String | User online status. Values: `"online"`, `"offline"` | +| `statusMessage` | String | Custom status message | +| `lastActiveAt` | long | Unix timestamp of last activity | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | +| `tags` | Array\ | List of tags for user identification | +| `deactivatedAt` | long | Unix timestamp when user was deactivated (0 if active) | + + + + + +When `receiverType` is `"group"`, the receiver/callReceiver contains a Group object: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `guid` | String | Unique identifier of the group | +| `name` | String | Display name of the group | +| `type` | String | Group type. Values: `"public"`, `"private"`, `"password"` | +| `icon` | String | URL to group icon | +| `description` | String | Group description | +| `owner` | String | UID of group owner | +| `membersCount` | int | Number of group members | + + + --- ## Next Steps diff --git a/sdk/android/calling-overview.mdx b/sdk/android/calling-overview.mdx index 573bf735c..214df245b 100644 --- a/sdk/android/calling-overview.mdx +++ b/sdk/android/calling-overview.mdx @@ -105,6 +105,122 @@ Use this when you want: --- +## Call Payload Structure + + + +The `Call` object extends `BaseMessage` and contains all call-related information: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `id` | long | Unique identifier of the call message | +| `muid` | String | Developer-defined message ID | +| `sender` | [User](#user-object-call) | User who sent the call message | +| `receiver` | AppEntity | Call receiver ([User](#user-object-call) or [Group](#group-object-call)) | +| `receiverUid` | String | Receiver's unique identifier | +| `type` | String | Call type. Values: `"audio"`, `"video"` | +| `receiverType` | String | Type of receiver. Values: `"user"`, `"group"` | +| `category` | String | Message category. Value: `"call"` | +| `sentAt` | long | Unix timestamp when call was sent | +| `deliveredAt` | long | Unix timestamp when delivered | +| `readAt` | long | Unix timestamp when read | +| `metadata` | JSONObject | Custom call metadata | +| `conversationId` | String | Associated conversation identifier | +| `sessionId` | String | Unique call session identifier | +| `callStatus` | String | Status of the call. Values: `"initiated"`, `"ongoing"`, `"ended"`, `"cancelled"`, `"busy"`, `"rejected"`, `"unanswered"` | +| `action` | String | Action performed on call. Values: `"initiated"`, `"ongoing"`, `"ended"` | +| `rawData` | String | Raw JSON data of the call | +| `initiatedAt` | long | Unix timestamp when call was initiated | +| `joinedAt` | long | Unix timestamp when call was joined | +| `callInitiator` | [User](#user-object-call) | User who initiated the call | +| `callReceiver` | AppEntity | User or Group receiving the call | + +**Sample Call Object:** + +```json +{ + "id": 12345, + "muid": "call_abc123", + "sender": { + "uid": "user_123", + "name": "John Doe", + "avatar": "https://example.com/avatar.png", + "status": "online" + }, + "receiver": { + "uid": "user_456", + "name": "Jane Smith" + }, + "receiverUid": "user_456", + "type": "video", + "receiverType": "user", + "category": "call", + "sentAt": 1699900000, + "deliveredAt": 1699900001, + "readAt": 1699900002, + "metadata": {}, + "conversationId": "user_123_user_456", + "sessionId": "v1.us.1234567890", + "callStatus": "ended", + "action": "ended", + "rawData": "{}", + "initiatedAt": 1699900000, + "joinedAt": 1699900005, + "callInitiator": { + "uid": "user_123", + "name": "John Doe", + "avatar": "https://example.com/avatar.png" + }, + "callReceiver": { + "uid": "user_456", + "name": "Jane Smith", + "avatar": "https://example.com/avatar2.png" + } +} +``` + + + + + +The nested `User` object (used in `sender`, `callInitiator`, `callReceiver`) contains: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `uid` | String | Unique identifier of the user | +| `name` | String | Display name of the user | +| `avatar` | String | URL to user's profile picture | +| `link` | String | URL to user's profile page | +| `role` | String | User role for access control | +| `metadata` | JSONObject | Custom data set by developer | +| `status` | String | User online status. Values: `"online"`, `"offline"` | +| `statusMessage` | String | Custom status message | +| `lastActiveAt` | long | Unix timestamp of last activity | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | +| `tags` | Array\ | List of tags for user identification | +| `deactivatedAt` | long | Unix timestamp when user was deactivated (0 if active) | + + + + + +When `receiverType` is `"group"`, the receiver/callReceiver contains a Group object: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `guid` | String | Unique identifier of the group | +| `name` | String | Display name of the group | +| `type` | String | Group type. Values: `"public"`, `"private"`, `"password"` | +| `icon` | String | URL to group icon | +| `description` | String | Group description | +| `owner` | String | UID of group owner | +| `membersCount` | int | Number of group members | + + + +--- + ## Next Steps diff --git a/sdk/android/create-group.mdx b/sdk/android/create-group.mdx index 6c7cda96d..7e71ceb3b 100644 --- a/sdk/android/create-group.mdx +++ b/sdk/android/create-group.mdx @@ -210,6 +210,58 @@ The `onSuccess()` block of this method provides you with 2 sets of information: | membersCount | No | The number of members in the groups | | tags | Yes | A list of tags to identify specific groups. | +## Group Payload Structure + + + +The `Group` object returned by SDK methods contains the following fields: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `guid` | String | Unique identifier of the group | +| `name` | String | Display name of the group | +| `type` | String | Group type. Values: `"public"`, `"private"`, `"password"` | +| `password` | String | Password for protected groups (null for public/private groups) | +| `icon` | String | URL to group icon image | +| `description` | String | Description of the group | +| `owner` | String | UID of the group owner | +| `metadata` | JSONObject | Custom data set by developer. Can contain any key-value pairs | +| `createdAt` | long | Unix timestamp when group was created | +| `updatedAt` | long | Unix timestamp of last group update | +| `hasJoined` | boolean | Whether the logged-in user has joined this group | +| `joinedAt` | long | Unix timestamp when logged-in user joined the group | +| `scope` | String | Logged-in user's scope in group. Values: `"admin"`, `"moderator"`, `"participant"` | +| `membersCount` | int | Total number of members in the group | +| `tags` | Array\ | List of tags for group identification and filtering | +| `isBannedFromGroup` | boolean | Whether the logged-in user is banned from this group | + +**Sample Group Object:** + +```json +{ + "guid": "group_123", + "name": "Developers", + "type": "public", + "password": null, + "icon": "https://example.com/icon.png", + "description": "A group for developers", + "owner": "user_123", + "metadata": { + "category": "tech", + "isVerified": true + }, + "createdAt": 1699800000, + "updatedAt": 1699900000, + "hasJoined": true, + "joinedAt": 1699850000, + "scope": "admin", + "membersCount": 25, + "tags": ["official", "support"], + "isBannedFromGroup": false +} +``` + + ## Best Practices diff --git a/sdk/android/delivery-read-receipts.mdx b/sdk/android/delivery-read-receipts.mdx index 67ed1205f..cf55b7c1b 100644 --- a/sdk/android/delivery-read-receipts.mdx +++ b/sdk/android/delivery-read-receipts.mdx @@ -630,6 +630,70 @@ The following features will be available only if the **Enhanced Messaging Status Always remove message listeners when they're no longer needed (e.g., in `onDestroy()` or when navigating away). Failing to remove listeners can cause memory leaks and duplicate event handling. +## MessageReceipt Payload Structure + + + +The `MessageReceipt` object contains information about message delivery and read status: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `messageId` | long | ID of the message | +| `sender` | [User](#user-object-receipts) | User who sent the receipt | +| `receiverType` | String | Type of receiver. Values: `"user"`, `"group"` | +| `receiverId` | String | ID of the receiver | +| `timestamp` | long | Unix timestamp of the receipt | +| `receiptType` | String | Type of receipt. Values: `"delivered"`, `"read"` | +| `deliveredAt` | long | Unix timestamp when message was delivered | +| `readAt` | long | Unix timestamp when message was read | +| `messageSender` | String | UID of the message sender | + +**Sample MessageReceipt Object:** + +```json +{ + "messageId": 12345, + "sender": { + "uid": "user_123", + "name": "John Doe", + "avatar": "https://example.com/avatar.png", + "status": "online", + "role": "default" + }, + "receiverType": "user", + "receiverId": "user_456", + "timestamp": 1699900000, + "receiptType": "read", + "deliveredAt": 1699900001, + "readAt": 1699900002, + "messageSender": "user_123" +} +``` + + + + + +The nested `User` object in `sender` contains: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `uid` | String | Unique identifier of the user | +| `name` | String | Display name of the user | +| `avatar` | String | URL to user's profile picture | +| `link` | String | URL to user's profile page | +| `role` | String | User role for access control | +| `metadata` | JSONObject | Custom data set by developer | +| `status` | String | User online status. Values: `"online"`, `"offline"` | +| `statusMessage` | String | Custom status message | +| `lastActiveAt` | long | Unix timestamp of last activity | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | +| `tags` | Array\ | List of tags for user identification | +| `deactivatedAt` | long | Unix timestamp when user was deactivated (0 if active) | + + + ## Best Practices diff --git a/sdk/android/group-add-members.mdx b/sdk/android/group-add-members.mdx index 8bb455bb0..a3d8f717b 100644 --- a/sdk/android/group-add-members.mdx +++ b/sdk/android/group-add-members.mdx @@ -138,6 +138,57 @@ For the group member added event, in the `Action` object received, the following Always remove group listeners when they're no longer needed (e.g., in `onDestroy()` or when navigating away). Failing to remove listeners can cause memory leaks and duplicate event handling. +## GroupMember Payload Structure + + + +The `GroupMember` object extends `User` and contains all User fields plus group-specific fields: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `uid` | String | Unique identifier of the user | +| `name` | String | Display name of the user | +| `avatar` | String | URL to user's profile picture | +| `link` | String | URL to user's profile page | +| `role` | String | User role for access control | +| `metadata` | JSONObject | Custom data set by developer | +| `status` | String | User online status. Values: `"online"`, `"offline"` | +| `statusMessage` | String | Custom status message | +| `lastActiveAt` | long | Unix timestamp of last activity | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | +| `tags` | Array\ | List of tags for user identification | +| `deactivatedAt` | long | Unix timestamp when user was deactivated (0 if active) | +| `scope` | String | Member's scope in the group. Values: `"admin"`, `"moderator"`, `"participant"` | +| `joinedAt` | long | Unix timestamp when member joined the group | + +**Sample GroupMember Object:** + +```json +{ + "uid": "user_123", + "name": "John Doe", + "avatar": "https://example.com/avatar.png", + "link": "https://example.com/profile", + "role": "default", + "metadata": { + "department": "Engineering", + "title": "Senior Developer" + }, + "status": "online", + "statusMessage": "Available", + "lastActiveAt": 1699900000, + "hasBlockedMe": false, + "blockedByMe": false, + "tags": ["premium", "verified"], + "deactivatedAt": 0, + "scope": "admin", + "joinedAt": 1699850000 +} +``` + + + ## Best Practices diff --git a/sdk/android/interactive-messages.mdx b/sdk/android/interactive-messages.mdx index 758df6634..90efb6ec1 100644 --- a/sdk/android/interactive-messages.mdx +++ b/sdk/android/interactive-messages.mdx @@ -283,6 +283,169 @@ These event listeners offer your application a way to provide real-time updates 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. +## InteractiveMessage Payload Structure + + + +The `InteractiveMessage` object contains interactive content like forms and buttons: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `id` | long | Unique message identifier | +| `muid` | String | Developer-defined message ID | +| `sender` | [User](#user-object-interactive) | User who sent the message | +| `receiver` | AppEntity | Message receiver ([User](#user-object-interactive) or Group) | +| `type` | String | Message type (e.g., `"form"`, `"card"`) | +| `receiverType` | String | Type of receiver. Values: `"user"`, `"group"` | +| `category` | String | Message category. Value: `"interactive"` | +| `sentAt` | long | Unix timestamp when sent | +| `metadata` | JSONObject | Custom message metadata | +| `conversationId` | String | Associated conversation ID | +| `interactiveData` | JSONObject | Interactive content data | +| `tags` | Array\ | Message tags | +| `interactionGoal` | [InteractionGoal](#interactiongoal-object) | Goal for interactions | +| `interactions` | Array\<[Interaction](#interaction-object)\> | User interactions | +| `allowSenderInteraction` | boolean | If sender can interact | + +**Sample InteractiveMessage Object:** + +```json +{ + "id": 12345, + "muid": "msg_abc123", + "sender": { + "uid": "user_123", + "name": "John Doe", + "avatar": "https://example.com/avatar.png", + "status": "online", + "role": "default" + }, + "receiver": { + "uid": "user_456", + "name": "Jane Smith" + }, + "type": "form", + "receiverType": "user", + "category": "interactive", + "sentAt": 1699900000, + "metadata": {"priority": "high"}, + "conversationId": "user_123_user_456", + "interactiveData": { + "title": "Demo Form", + "formFields": [ + { + "elementType": "textInput", + "elementId": "element1", + "label": "Name", + "optional": false, + "maxLines": 1 + } + ], + "submitElement": { + "elementType": "button", + "elementId": "element8", + "buttonText": "Submit", + "disableAfterInteracted": true, + "action": { + "actionType": "urlNavigation", + "url": "https://www.cometchat.com/" + } + } + }, + "tags": ["interactive"], + "interactionGoal": { + "type": "anyOf", + "elementIds": ["element1", "element8"] + }, + "interactions": [], + "allowSenderInteraction": false +} +``` + + + + + +The `InteractionGoal` object defines the desired outcome of interactions: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `type` | String | Goal type. Values: `"none"`, `"anyAction"`, `"anyOf"`, `"allOf"` | +| `elementIds` | Array\ | Target element IDs for the goal | + +**Sample InteractionGoal Object:** + +```json +{ + "type": "anyOf", + "elementIds": ["button_1", "input_1"] +} +``` + + + + + +The `Interaction` object represents a user action on an interactive element: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `elementId` | String | Identifier of the interacted element | +| `interactedAt` | long | Unix timestamp when interaction occurred | + +**Sample Interaction Object:** + +```json +{ + "elementId": "element1", + "interactedAt": 1699900500 +} +``` + + + + + +The nested `User` object in `sender` contains: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `uid` | String | Unique identifier of the user | +| `name` | String | Display name of the user | +| `avatar` | String | URL to user's profile picture | +| `link` | String | URL to user's profile page | +| `role` | String | User role for access control | +| `metadata` | JSONObject | Custom data set by developer | +| `status` | String | User online status. Values: `"online"`, `"offline"` | +| `statusMessage` | String | Custom status message | +| `lastActiveAt` | long | Unix timestamp of last activity | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | +| `tags` | Array\ | List of tags for user identification | +| `deactivatedAt` | long | Unix timestamp when user was deactivated (0 if active) | + +**Sample User Object:** + +```json +{ + "uid": "user_123", + "name": "John Doe", + "avatar": "https://example.com/avatar.png", + "link": "https://example.com/profile/user_123", + "role": "default", + "metadata": {"department": "engineering"}, + "status": "online", + "statusMessage": "Available", + "lastActiveAt": 1699900000, + "hasBlockedMe": false, + "blockedByMe": false, + "tags": ["premium"], + "deactivatedAt": 0 +} +``` + + + ## Best Practices diff --git a/sdk/android/reactions.mdx b/sdk/android/reactions.mdx index ce93656b2..b3172ac36 100644 --- a/sdk/android/reactions.mdx +++ b/sdk/android/reactions.mdx @@ -477,6 +477,87 @@ val modifiedBaseMessage: BaseMessage = CometChatHelper.updateMessageWithReaction 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. +## Reaction Payload Structure + + + +When fetching reactions for a message, each `Reaction` object contains the following fields: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `id` | String | Unique reaction identifier | +| `messageId` | long | ID of the message that was reacted to | +| `reaction` | String | The reaction emoji | +| `uid` | String | UID of the user who reacted | +| `reactedAt` | long | Unix timestamp when reaction was added | +| `reactedBy` | [User](#user-object-reactions) | User who added the reaction | + +**Sample Reaction Object:** + +```json +{ + "id": "reaction_123", + "messageId": 12345, + "reaction": "👍", + "uid": "user_123", + "reactedAt": 1699900000, + "reactedBy": { + "uid": "user_123", + "name": "John Doe", + "avatar": "https://example.com/avatar.png", + "status": "online", + "role": "default", + "tags": ["premium", "verified"] + } +} +``` + + + + + +The nested `User` object in `reactedBy` contains: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `uid` | String | Unique identifier of the user | +| `name` | String | Display name of the user | +| `avatar` | String | URL to user's profile picture | +| `link` | String | URL to user's profile page | +| `role` | String | User role for access control | +| `metadata` | JSONObject | Custom data set by developer | +| `status` | String | User online status. Values: `"online"`, `"offline"` | +| `statusMessage` | String | Custom status message | +| `lastActiveAt` | long | Unix timestamp of last activity | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | +| `tags` | Array\ | List of tags for user identification | +| `deactivatedAt` | long | Unix timestamp when user was deactivated (0 if active) | + + + + + +When accessing reactions on a message via `message.getReactions()`, each `ReactionCount` object contains: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `reaction` | String | The reaction emoji | +| `count` | int | Total count of this reaction | +| `reactedByMe` | boolean | Whether the logged-in user has reacted with this emoji | + +**Sample ReactionCount Object:** + +```json +{ + "reaction": "👍", + "count": 5, + "reactedByMe": true +} +``` + + + ## Best Practices diff --git a/sdk/android/receive-messages.mdx b/sdk/android/receive-messages.mdx index c8912dbdd..efa082ef8 100644 --- a/sdk/android/receive-messages.mdx +++ b/sdk/android/receive-messages.mdx @@ -1106,3 +1106,153 @@ override fun onError(e: CometChatException) { In the `onSuccess()` callback, you will receive a hashmap which will contain the `GUIDs` of the groups as the key and the unread message counts as the values. + +## Message Payload Structure + + + +The `BaseMessage` object returned by SDK methods contains the following fields. `TextMessage`, `MediaMessage`, and `CustomMessage` extend this base structure with additional type-specific fields. + +| Parameter | Type | Description | +|-----------|------|-------------| +| `id` | long | Unique message identifier | +| `muid` | String | Developer-defined message ID for deduplication | +| `sender` | [User](#user-object) | User who sent the message | +| `receiver` | AppEntity | Message receiver ([User](#user-object) or [Group](#group-object)) | +| `receiverUid` | String | Receiver's unique identifier | +| `type` | String | Message type. Values: `"text"`, `"image"`, `"video"`, `"audio"`, `"file"`, `"custom"` | +| `receiverType` | String | Type of receiver. Values: `"user"`, `"group"` | +| `category` | String | Message category. Values: `"message"`, `"action"`, `"call"`, `"custom"` | +| `sentAt` | long | Unix timestamp when message was sent | +| `deliveredAt` | long | Unix timestamp when message was delivered | +| `readAt` | long | Unix timestamp when message was read | +| `metadata` | JSONObject | Custom message metadata set by developer | +| `readByMeAt` | long | Unix timestamp when logged-in user read the message | +| `deliveredToMeAt` | long | Unix timestamp when message was delivered to logged-in user | +| `deletedAt` | long | Unix timestamp when message was deleted (0 if not deleted) | +| `editedAt` | long | Unix timestamp when message was edited (0 if not edited) | +| `deletedBy` | String | UID of user who deleted the message (null if not deleted) | +| `editedBy` | String | UID of user who edited the message (null if not edited) | +| `updatedAt` | long | Unix timestamp of last message update | +| `conversationId` | String | Associated conversation identifier | +| `parentMessageId` | long | Parent message ID for threaded messages (0 if not a reply) | +| `replyCount` | int | Number of replies in thread | +| `unreadRepliesCount` | int | Number of unread replies in thread | +| `mentionedUsers` | Array\<[User](#user-object)\> | List of users mentioned in the message | +| `hasMentionedMe` | boolean | Whether the logged-in user is mentioned | +| `reactions` | Array\<[ReactionCount](#reactioncount-object)\> | List of reaction counts on the message | +| `rawMessage` | JSONObject | Raw JSON message data | +| `quotedMessageId` | long | ID of the quoted message (0 if not quoting) | +| `quotedMessage` | BaseMessage | The quoted message object (null if not quoting) | + +**Sample BaseMessage Object:** + +```json +{ + "id": 12345, + "muid": "msg_abc123", + "sender": { + "uid": "user_123", + "name": "John Doe", + "avatar": "https://example.com/avatar.png", + "status": "online", + "role": "default", + "lastActiveAt": 1699900000 + }, + "receiver": { + "uid": "user_456", + "name": "Jane Smith", + "avatar": "https://example.com/avatar2.png" + }, + "receiverUid": "user_456", + "type": "text", + "receiverType": "user", + "category": "message", + "sentAt": 1699900000, + "deliveredAt": 1699900001, + "readAt": 1699900002, + "metadata": { + "priority": "high", + "customField": "value" + }, + "readByMeAt": 1699900002, + "deliveredToMeAt": 1699900001, + "deletedAt": 0, + "editedAt": 0, + "deletedBy": null, + "editedBy": null, + "updatedAt": 1699900000, + "conversationId": "user_123_user_456", + "parentMessageId": 0, + "replyCount": 5, + "unreadRepliesCount": 2, + "mentionedUsers": [], + "hasMentionedMe": false, + "reactions": [ + { + "reaction": "👍", + "count": 3, + "reactedByMe": true + } + ], + "rawMessage": {}, + "quotedMessageId": 0, + "quotedMessage": null +} +``` + + + + + +The nested `User` object (used in `sender`, `receiver`, `mentionedUsers`) contains: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `uid` | String | Unique identifier of the user | +| `name` | String | Display name of the user | +| `avatar` | String | URL to user's profile picture | +| `link` | String | URL to user's profile page | +| `role` | String | User role for access control | +| `metadata` | JSONObject | Custom data set by developer | +| `status` | String | User online status. Values: `"online"`, `"offline"` | +| `statusMessage` | String | Custom status message | +| `lastActiveAt` | long | Unix timestamp of last activity | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | +| `tags` | Array\ | List of tags for user identification | +| `deactivatedAt` | long | Unix timestamp when user was deactivated (0 if active) | + + + + + +The nested `Group` object (used in `receiver` for group messages) contains: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `guid` | String | Unique identifier of the group | +| `name` | String | Display name of the group | +| `type` | String | Group type. Values: `"public"`, `"private"`, `"password"` | +| `icon` | String | URL to group icon | +| `description` | String | Group description | +| `owner` | String | UID of group owner | +| `metadata` | JSONObject | Custom data set by developer | +| `membersCount` | int | Number of group members | +| `tags` | Array\ | List of tags for group identification | +| `hasJoined` | boolean | Whether logged-in user has joined | +| `scope` | String | User's scope in group. Values: `"admin"`, `"moderator"`, `"participant"` | + + + + + +The nested `ReactionCount` object (used in `reactions` array) contains: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `reaction` | String | The reaction emoji | +| `count` | int | Total count of this reaction | +| `reactedByMe` | boolean | Whether the logged-in user has reacted with this emoji | + + diff --git a/sdk/android/retrieve-conversations.mdx b/sdk/android/retrieve-conversations.mdx index 64ef2e7b1..95808087b 100644 --- a/sdk/android/retrieve-conversations.mdx +++ b/sdk/android/retrieve-conversations.mdx @@ -563,6 +563,127 @@ While converting a `Message` object to a `Conversation` object, the `unreadMessa +## Conversation Payload Structure + + + +The `Conversation` object returned by SDK methods contains the following fields: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `conversationId` | String | Unique conversation identifier | +| `conversationType` | String | Type of conversation. Values: `"user"`, `"group"` | +| `conversationWith` | AppEntity | The [User](#user-object-conversation) or [Group](#group-object-conversation) in the conversation | +| `lastMessage` | [BaseMessage](#lastmessage-object) | Last message in the conversation | +| `unreadMessageCount` | int | Number of unread messages in the conversation | +| `unreadMentionsCount` | int | Number of unread mentions in the conversation | +| `updatedAt` | long | Unix timestamp of last conversation update | +| `tags` | Array\ | List of tags for conversation organization | +| `lastReadMessageId` | long | ID of the last read message | +| `latestMessageId` | long | ID of the latest message | + +**Sample Conversation Object:** + +```json +{ + "conversationId": "user_123_user_456", + "conversationType": "user", + "conversationWith": { + "uid": "user_456", + "name": "John Doe", + "avatar": "https://example.com/avatar.png", + "status": "online", + "role": "default", + "lastActiveAt": 1699900000, + "tags": ["premium", "verified"] + }, + "lastMessage": { + "id": 12345, + "muid": "msg_abc123", + "type": "text", + "receiverType": "user", + "category": "message", + "sentAt": 1699900000, + "deliveredAt": 1699900001, + "readAt": 1699900002, + "metadata": {"priority": "high"}, + "conversationId": "user_123_user_456" + }, + "unreadMessageCount": 3, + "unreadMentionsCount": 1, + "updatedAt": 1699900000, + "tags": ["important", "work"], + "lastReadMessageId": 12340, + "latestMessageId": 12345 +} +``` + + + + + +When `conversationType` is `"user"`, the `conversationWith` field contains a User object: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `uid` | String | Unique identifier of the user | +| `name` | String | Display name of the user | +| `avatar` | String | URL to user's profile picture | +| `link` | String | URL to user's profile page | +| `role` | String | User role for access control | +| `metadata` | JSONObject | Custom data set by developer | +| `status` | String | User online status. Values: `"online"`, `"offline"` | +| `statusMessage` | String | Custom status message | +| `lastActiveAt` | long | Unix timestamp of last activity | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | +| `tags` | Array\ | List of tags for user identification | +| `deactivatedAt` | long | Unix timestamp when user was deactivated (0 if active) | + + + + + +When `conversationType` is `"group"`, the `conversationWith` field contains a Group object: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `guid` | String | Unique identifier of the group | +| `name` | String | Display name of the group | +| `type` | String | Group type. Values: `"public"`, `"private"`, `"password"` | +| `icon` | String | URL to group icon | +| `description` | String | Group description | +| `owner` | String | UID of group owner | +| `metadata` | JSONObject | Custom data set by developer | +| `membersCount` | int | Number of group members | +| `tags` | Array\ | List of tags for group identification | +| `hasJoined` | boolean | Whether logged-in user has joined | +| `scope` | String | User's scope in group. Values: `"admin"`, `"moderator"`, `"participant"` | +| `createdAt` | long | Unix timestamp when group was created | +| `updatedAt` | long | Unix timestamp of last group update | + + + + + +The `lastMessage` field contains a BaseMessage object with key fields: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `id` | long | Unique message identifier | +| `muid` | String | Developer-defined message ID | +| `type` | String | Message type. Values: `"text"`, `"image"`, `"video"`, `"audio"`, `"file"`, `"custom"` | +| `receiverType` | String | Type of receiver. Values: `"user"`, `"group"` | +| `category` | String | Message category. Values: `"message"`, `"action"`, `"call"` | +| `sentAt` | long | Unix timestamp when message was sent | +| `deliveredAt` | long | Unix timestamp when message was delivered | +| `readAt` | long | Unix timestamp when message was read | +| `metadata` | JSONObject | Custom message metadata | +| `conversationId` | String | Associated conversation identifier | +| `sender` | User | User who sent the message | + + + ## Best Practices diff --git a/sdk/android/retrieve-group-members.mdx b/sdk/android/retrieve-group-members.mdx index b0f44ddeb..02d776014 100644 --- a/sdk/android/retrieve-group-members.mdx +++ b/sdk/android/retrieve-group-members.mdx @@ -164,6 +164,57 @@ groupMembersRequest?.fetchNext(object:CometChat.CallbackListener +## GroupMember Payload Structure + + + +The `GroupMember` object extends `User` and contains all User fields plus group-specific fields: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `uid` | String | Unique identifier of the user | +| `name` | String | Display name of the user | +| `avatar` | String | URL to user's profile picture | +| `link` | String | URL to user's profile page | +| `role` | String | User role for access control | +| `metadata` | JSONObject | Custom data set by developer | +| `status` | String | User online status. Values: `"online"`, `"offline"` | +| `statusMessage` | String | Custom status message | +| `lastActiveAt` | long | Unix timestamp of last activity | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | +| `tags` | Array\ | List of tags for user identification | +| `deactivatedAt` | long | Unix timestamp when user was deactivated (0 if active) | +| `scope` | String | Member's scope in the group. Values: `"admin"`, `"moderator"`, `"participant"` | +| `joinedAt` | long | Unix timestamp when member joined the group | + +**Sample GroupMember Object:** + +```json +{ + "uid": "user_123", + "name": "John Doe", + "avatar": "https://example.com/avatar.png", + "link": "https://example.com/profile", + "role": "default", + "metadata": { + "department": "Engineering", + "title": "Senior Developer" + }, + "status": "online", + "statusMessage": "Available", + "lastActiveAt": 1699900000, + "hasBlockedMe": false, + "blockedByMe": false, + "tags": ["premium", "verified"], + "deactivatedAt": 0, + "scope": "admin", + "joinedAt": 1699850000 +} +``` + + + ## Best Practices diff --git a/sdk/android/retrieve-groups.mdx b/sdk/android/retrieve-groups.mdx index e7bb35e46..e2ca4adea 100644 --- a/sdk/android/retrieve-groups.mdx +++ b/sdk/android/retrieve-groups.mdx @@ -317,6 +317,59 @@ override fun onError(e: CometChatException) { This method returns a `Hashmap` with the GUID of the group as the key and the online member count for that group as the value. +## Group Payload Structure + + + +The `Group` object returned by SDK methods contains the following fields: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `guid` | String | Unique identifier of the group | +| `name` | String | Display name of the group | +| `type` | String | Group type. Values: `"public"`, `"private"`, `"password"` | +| `password` | String | Password for protected groups (null for public/private groups) | +| `icon` | String | URL to group icon image | +| `description` | String | Description of the group | +| `owner` | String | UID of the group owner | +| `metadata` | JSONObject | Custom data set by developer. Can contain any key-value pairs | +| `createdAt` | long | Unix timestamp when group was created | +| `updatedAt` | long | Unix timestamp of last group update | +| `hasJoined` | boolean | Whether the logged-in user has joined this group | +| `joinedAt` | long | Unix timestamp when logged-in user joined the group | +| `scope` | String | Logged-in user's scope in group. Values: `"admin"`, `"moderator"`, `"participant"` | +| `membersCount` | int | Total number of members in the group | +| `tags` | Array\ | List of tags for group identification and filtering | +| `isBannedFromGroup` | boolean | Whether the logged-in user is banned from this group | + +**Sample Group Object:** + +```json +{ + "guid": "group_123", + "name": "Developers", + "type": "public", + "password": null, + "icon": "https://example.com/icon.png", + "description": "A group for developers", + "owner": "user_123", + "metadata": { + "category": "tech", + "isVerified": true + }, + "createdAt": 1699800000, + "updatedAt": 1699900000, + "hasJoined": true, + "joinedAt": 1699850000, + "scope": "admin", + "membersCount": 25, + "tags": ["official", "support"], + "isBannedFromGroup": false +} +``` + + + ## Best Practices diff --git a/sdk/android/retrieve-users.mdx b/sdk/android/retrieve-users.mdx index ffcad6aa3..5bf29b847 100644 --- a/sdk/android/retrieve-users.mdx +++ b/sdk/android/retrieve-users.mdx @@ -555,7 +555,55 @@ override fun onError(e: CometChatException) { ---- +## User Payload Structure + + + +The `User` object returned by SDK methods contains the following fields: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `uid` | String | Unique identifier of the user | +| `name` | String | Display name of the user | +| `avatar` | String | URL to user's profile picture | +| `link` | String | URL to user's profile page | +| `role` | String | User role for role-based access control | +| `metadata` | JSONObject | Custom data set by developer. Can contain any key-value pairs | +| `status` | String | User online status. Values: `"online"`, `"offline"` | +| `statusMessage` | String | Custom status message set by user | +| `lastActiveAt` | long | Unix timestamp of last activity (milliseconds) | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | +| `tags` | Array\ | List of tags for user identification and filtering | +| `deactivatedAt` | long | Unix timestamp when user was deactivated (0 if active) | + +**Sample User Object:** + +```json +{ + "uid": "user_123", + "name": "John Doe", + "avatar": "https://example.com/avatar.png", + "link": "https://example.com/profile/user_123", + "role": "default", + "metadata": { + "customKey": "customValue", + "preferences": { + "theme": "dark", + "notifications": true + } + }, + "status": "online", + "statusMessage": "Available", + "lastActiveAt": 1699900000000, + "hasBlockedMe": false, + "blockedByMe": false, + "tags": ["premium", "verified"], + "deactivatedAt": 0 +} +``` + + ## Best Practices diff --git a/sdk/android/send-message.mdx b/sdk/android/send-message.mdx index 9c4065e5b..ccb25bcc2 100644 --- a/sdk/android/send-message.mdx +++ b/sdk/android/send-message.mdx @@ -1151,3 +1151,153 @@ CometChat.sendCustomMessage(customMessage, object : CallbackListener + +## Message Payload Structure + + + +The `BaseMessage` object returned by SDK methods contains the following fields. `TextMessage`, `MediaMessage`, and `CustomMessage` extend this base structure with additional type-specific fields. + +| Parameter | Type | Description | +|-----------|------|-------------| +| `id` | long | Unique message identifier | +| `muid` | String | Developer-defined message ID for deduplication | +| `sender` | [User](#user-object) | User who sent the message | +| `receiver` | AppEntity | Message receiver ([User](#user-object) or [Group](#group-object)) | +| `receiverUid` | String | Receiver's unique identifier | +| `type` | String | Message type. Values: `"text"`, `"image"`, `"video"`, `"audio"`, `"file"`, `"custom"` | +| `receiverType` | String | Type of receiver. Values: `"user"`, `"group"` | +| `category` | String | Message category. Values: `"message"`, `"action"`, `"call"`, `"custom"` | +| `sentAt` | long | Unix timestamp when message was sent | +| `deliveredAt` | long | Unix timestamp when message was delivered | +| `readAt` | long | Unix timestamp when message was read | +| `metadata` | JSONObject | Custom message metadata set by developer | +| `readByMeAt` | long | Unix timestamp when logged-in user read the message | +| `deliveredToMeAt` | long | Unix timestamp when message was delivered to logged-in user | +| `deletedAt` | long | Unix timestamp when message was deleted (0 if not deleted) | +| `editedAt` | long | Unix timestamp when message was edited (0 if not edited) | +| `deletedBy` | String | UID of user who deleted the message (null if not deleted) | +| `editedBy` | String | UID of user who edited the message (null if not edited) | +| `updatedAt` | long | Unix timestamp of last message update | +| `conversationId` | String | Associated conversation identifier | +| `parentMessageId` | long | Parent message ID for threaded messages (0 if not a reply) | +| `replyCount` | int | Number of replies in thread | +| `unreadRepliesCount` | int | Number of unread replies in thread | +| `mentionedUsers` | Array\<[User](#user-object)\> | List of users mentioned in the message | +| `hasMentionedMe` | boolean | Whether the logged-in user is mentioned | +| `reactions` | Array\<[ReactionCount](#reactioncount-object)\> | List of reaction counts on the message | +| `rawMessage` | JSONObject | Raw JSON message data | +| `quotedMessageId` | long | ID of the quoted message (0 if not quoting) | +| `quotedMessage` | BaseMessage | The quoted message object (null if not quoting) | + +**Sample BaseMessage Object:** + +```json +{ + "id": 12345, + "muid": "msg_abc123", + "sender": { + "uid": "user_123", + "name": "John Doe", + "avatar": "https://example.com/avatar.png", + "status": "online", + "role": "default", + "lastActiveAt": 1699900000 + }, + "receiver": { + "uid": "user_456", + "name": "Jane Smith", + "avatar": "https://example.com/avatar2.png" + }, + "receiverUid": "user_456", + "type": "text", + "receiverType": "user", + "category": "message", + "sentAt": 1699900000, + "deliveredAt": 1699900001, + "readAt": 1699900002, + "metadata": { + "priority": "high", + "customField": "value" + }, + "readByMeAt": 1699900002, + "deliveredToMeAt": 1699900001, + "deletedAt": 0, + "editedAt": 0, + "deletedBy": null, + "editedBy": null, + "updatedAt": 1699900000, + "conversationId": "user_123_user_456", + "parentMessageId": 0, + "replyCount": 5, + "unreadRepliesCount": 2, + "mentionedUsers": [], + "hasMentionedMe": false, + "reactions": [ + { + "reaction": "👍", + "count": 3, + "reactedByMe": true + } + ], + "rawMessage": {}, + "quotedMessageId": 0, + "quotedMessage": null +} +``` + + + + + +The nested `User` object (used in `sender`, `receiver`, `mentionedUsers`) contains: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `uid` | String | Unique identifier of the user | +| `name` | String | Display name of the user | +| `avatar` | String | URL to user's profile picture | +| `link` | String | URL to user's profile page | +| `role` | String | User role for access control | +| `metadata` | JSONObject | Custom data set by developer | +| `status` | String | User online status. Values: `"online"`, `"offline"` | +| `statusMessage` | String | Custom status message | +| `lastActiveAt` | long | Unix timestamp of last activity | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | +| `tags` | Array\ | List of tags for user identification | +| `deactivatedAt` | long | Unix timestamp when user was deactivated (0 if active) | + + + + + +The nested `Group` object (used in `receiver` for group messages) contains: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `guid` | String | Unique identifier of the group | +| `name` | String | Display name of the group | +| `type` | String | Group type. Values: `"public"`, `"private"`, `"password"` | +| `icon` | String | URL to group icon | +| `description` | String | Group description | +| `owner` | String | UID of group owner | +| `metadata` | JSONObject | Custom data set by developer | +| `membersCount` | int | Number of group members | +| `tags` | Array\ | List of tags for group identification | +| `hasJoined` | boolean | Whether logged-in user has joined | +| `scope` | String | User's scope in group. Values: `"admin"`, `"moderator"`, `"participant"` | + + + + + +The nested `ReactionCount` object (used in `reactions` array) contains: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `reaction` | String | The reaction emoji | +| `count` | int | Total count of this reaction | +| `reactedByMe` | boolean | Whether the logged-in user has reacted with this emoji | + + diff --git a/sdk/android/typing-indicators.mdx b/sdk/android/typing-indicators.mdx index d671065f2..4c9bd1783 100644 --- a/sdk/android/typing-indicators.mdx +++ b/sdk/android/typing-indicators.mdx @@ -175,6 +175,64 @@ 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. `CometChatConstants.RECEIVER_TYPE_USER` 2. `CometChatConstants.RECEIVER_TYPE_GROUP` | | `metadata` | A JSONObject to provider additional data | +## TypingIndicator Payload Structure + + + +The `TypingIndicator` object contains information about typing status: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `sender` | [User](#user-object-typing) | User who is typing | +| `receiverId` | String | ID of the receiver (user UID or group GUID) | +| `receiverType` | String | Type of receiver. Values: `"user"`, `"group"` | +| `metadata` | JSONObject | Custom typing metadata | +| `lastTimestamp` | long | Unix timestamp of last typing event | +| `typingStatus` | String | Typing status. Values: `"started"`, `"ended"` | + +**Sample TypingIndicator Object:** + +```json +{ + "sender": { + "uid": "user_123", + "name": "John Doe", + "avatar": "https://example.com/avatar.png", + "status": "online", + "role": "default" + }, + "receiverId": "user_456", + "receiverType": "user", + "metadata": {}, + "lastTimestamp": 1699900000, + "typingStatus": "started" +} +``` + + + + + +The nested `User` object in `sender` contains: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `uid` | String | Unique identifier of the user | +| `name` | String | Display name of the user | +| `avatar` | String | URL to user's profile picture | +| `link` | String | URL to user's profile page | +| `role` | String | User role for access control | +| `metadata` | JSONObject | Custom data set by developer | +| `status` | String | User online status. Values: `"online"`, `"offline"` | +| `statusMessage` | String | Custom status message | +| `lastActiveAt` | long | Unix timestamp of last activity | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | +| `tags` | Array\ | List of tags for user identification | +| `deactivatedAt` | long | Unix timestamp when user was deactivated (0 if active) | + + + Always remove message listeners when they're no longer needed (e.g., in `onDestroy()` or when navigating away). Failing to remove listeners can cause memory leaks and duplicate event handling. diff --git a/sdk/android/user-management.mdx b/sdk/android/user-management.mdx index 509f1d391..a80e05c99 100644 --- a/sdk/android/user-management.mdx +++ b/sdk/android/user-management.mdx @@ -231,6 +231,56 @@ 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 | +## User Payload Structure + + + +The `User` object returned by SDK methods contains the following fields: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `uid` | String | Unique identifier of the user | +| `name` | String | Display name of the user | +| `avatar` | String | URL to user's profile picture | +| `link` | String | URL to user's profile page | +| `role` | String | User role for role-based access control | +| `metadata` | JSONObject | Custom data set by developer. Can contain any key-value pairs | +| `status` | String | User online status. Values: `"online"`, `"offline"` | +| `statusMessage` | String | Custom status message set by user | +| `lastActiveAt` | long | Unix timestamp of last activity (milliseconds) | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | +| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | +| `tags` | Array\ | List of tags for user identification and filtering | +| `deactivatedAt` | long | Unix timestamp when user was deactivated (0 if active) | + +**Sample User Object:** + +```json +{ + "uid": "user_123", + "name": "John Doe", + "avatar": "https://example.com/avatar.png", + "link": "https://example.com/profile/user_123", + "role": "default", + "metadata": { + "customKey": "customValue", + "preferences": { + "theme": "dark", + "notifications": true + } + }, + "status": "online", + "statusMessage": "Available", + "lastActiveAt": 1699900000000, + "hasBlockedMe": false, + "blockedByMe": false, + "tags": ["premium", "verified"], + "deactivatedAt": 0 +} +``` + + + --- ## Best Practices From 4128de32ab12bc541b23fd9914ee4b3090ecf8b8 Mon Sep 17 00:00:00 2001 From: PrajwalDhuleCC Date: Fri, 13 Mar 2026 17:11:35 +0530 Subject: [PATCH 010/139] 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 011/139] 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 012/139] 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 013/139] 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 014/139] 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 015/139] 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 016/139] 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 017/139] 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 018/139] 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 019/139] 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 020/139] 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 021/139] 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 022/139] 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 023/139] 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 024/139] 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 025/139] 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 026/139] 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 027/139] 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 028/139] 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 029/139] 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 030/139] 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 031/139] 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 032/139] 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 033/139] 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 034/139] 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 035/139] 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 036/139] 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 037/139] 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 038/139] 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 039/139] 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 040/139] 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 041/139] 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 042/139] 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 043/139] 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 044/139] 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 045/139] 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 From 04c3d8fce71daece373fcd199c82e95e4131a39f Mon Sep 17 00:00:00 2001 From: PrajwalDhuleCC Date: Mon, 23 Mar 2026 16:34:58 +0530 Subject: [PATCH 046/139] docs(sdk/javascript): Add improved and concise reference tables and clarifications for message filtering and Users. - Add return type documentation for `fetchPrevious()` and `fetchNext()` methods in additional message filtering - Add reference table for message timestamp fields (editedAt, deletedAt, deliveredAt, readAt) with getters and return types - Add clarification on `updatesOnly(true)` behavior when combined with `setUpdatedAfter()` - Add reference tables for media message fields (attachment, attachments, url, caption) with getters and return types - Add reference table for reaction fields (reactions) with getter and return type - Add reference tables for mention fields (mentionedUsers, hasMentionedMe) with getters and return types - Add reference table for attachment type filter fields with getters and return types - Improve block users documentation with clearer object structure explanation - Enhance user management documentation with better method descriptions and return type clarity - Improve retrieve users documentation with additional context and examples --- .../additional-message-filtering.mdx | 58 +++++++++++++++++ sdk/javascript/block-users.mdx | 33 +++++----- sdk/javascript/retrieve-users.mdx | 65 +++++++++---------- sdk/javascript/user-management.mdx | 22 ++----- 4 files changed, 108 insertions(+), 70 deletions(-) diff --git a/sdk/javascript/additional-message-filtering.mdx b/sdk/javascript/additional-message-filtering.mdx index a2a971a10..f90b8a6c0 100644 --- a/sdk/javascript/additional-message-filtering.mdx +++ b/sdk/javascript/additional-message-filtering.mdx @@ -55,6 +55,8 @@ Once you have an object of the `MessagesRequest` class, you can call either the 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. +Both `fetchPrevious()` and `fetchNext()` return an array of [`BaseMessage`](/sdk/reference/messages#basemessage) objects (which may be [`TextMessage`](/sdk/reference/messages#textmessage), [`MediaMessage`](/sdk/reference/messages#mediamessage), [`CustomMessage`](/sdk/reference/messages#custommessage), or other subclasses depending on the filters applied). + 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: @@ -495,6 +497,16 @@ 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). + +Relevant fields to access on returned messages: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| editedAt | `getEditedAt()` | `number` | Timestamp when the message was edited | +| deletedAt | `getDeletedAt()` | `number` | Timestamp when the message was deleted | +| deliveredAt | `getDeliveredAt()` | `number` | Timestamp when the message was delivered | +| readAt | `getReadAt()` | `number` | Timestamp when the message was read | + ## Updated messages only *In other words, how do I fetch messages that have been updated after a particular date or time* @@ -567,6 +579,9 @@ 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. + +When `updatesOnly(true)` is combined with `setUpdatedAfter()`, only messages that were updated (edited, deleted, or had their read/delivered status changed) are returned — newly sent or received messages are excluded. + ## Messages for multiple categories *In other words, how do I fetch messages belonging to multiple categories* @@ -1241,6 +1256,16 @@ let GUID: string = "GUID", The response will contain a list of media message objects with attachment details, including file metadata and thumbnail URLs. + +Relevant fields to access on returned messages: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| attachment | `getAttachment()` | [`Attachment`](/sdk/reference/auxiliary#attachment) | The primary attachment of the media message | +| attachments | `getAttachments()` | [`Attachment[]`](/sdk/reference/auxiliary#attachment) | All attachments of the media message | +| url | `getURL()` | `string` | URL of the media file | +| caption | `getCaption()` | `string` | Caption text for the media message | + ## Messages with reactions In other words, as a logged-in user, how do I fetch messages that contains reactions? @@ -1311,6 +1336,13 @@ 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. + +Relevant fields to access on returned messages: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| reactions | `getReactions()` | [`ReactionCount[]`](/sdk/reference/auxiliary#reactioncount) | Array of reaction counts on the message | + ## Messages with mentions In other words, as a logged-in user, how do I fetch messages that contains mentions? @@ -1381,6 +1413,14 @@ 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. + +Relevant fields to access on returned messages: + +| 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 was mentioned in the message | + ## Messages with particular user mentions In other words, as a logged-in user, how do I fetch messages that mentions specific users? @@ -1451,6 +1491,14 @@ 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. + +Relevant fields to access on returned messages: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| mentionedUsers | `getMentionedUsers()` | [`User[]`](/sdk/reference/entities#user) | Array of mentioned users (filtered to the specified UIDs) | +| hasMentionedMe | `hasMentionedMe()` | `boolean` | Whether the logged-in user was mentioned in the message | + ## Messages with specific attachment types In other words, as a logged-in user, how do I fetch messages that contain specific types of attachments? @@ -1521,6 +1569,16 @@ 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. + +Relevant fields to access on returned messages: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| attachment | `getAttachment()` | [`Attachment`](/sdk/reference/auxiliary#attachment) | The primary attachment of the media message | +| attachments | `getAttachments()` | [`Attachment[]`](/sdk/reference/auxiliary#attachment) | All attachments filtered to the specified types | +| url | `getURL()` | `string` | URL of the media file | +| caption | `getCaption()` | `string` | Caption text for the media message | + - **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 d126facc1..d7467b36b 100644 --- a/sdk/javascript/block-users.mdx +++ b/sdk/javascript/block-users.mdx @@ -79,16 +79,10 @@ 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. +It returns an object where each key is a `UID`, and the value contains the result of the block operation for that user: -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 | +- `success`: Indicates whether the block operation was successful (`true` or `false`) +- `message`: Provides a descriptive message for the result of the operation ## Unblock Users @@ -143,16 +137,10 @@ 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. +It returns an object where each key is a `UID`, and the value contains the result of the unblock operation for that user: -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 | +- `success`: Indicates whether the unblock operation was successful (`true` or `false`) +- `message`: Provides a descriptive message for the result of the operation ## Get List of Blocked Users @@ -293,6 +281,15 @@ blockedUsersRequest.fetchNext().then( +The `fetchNext()` method returns an array of [`User`](/sdk/reference/entities#user) objects representing blocked users. + +Relevant fields to access on returned users: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| blockedByMe | `getBlockedByMe()` | `boolean` | Whether the logged-in user has blocked this user | +| hasBlockedMe | `getHasBlockedMe()` | `boolean` | Whether this user has blocked the logged-in user | + --- diff --git a/sdk/javascript/retrieve-users.mdx b/sdk/javascript/retrieve-users.mdx index e3dcb9e3a..a4a2178e6 100644 --- a/sdk/javascript/retrieve-users.mdx +++ b/sdk/javascript/retrieve-users.mdx @@ -60,23 +60,14 @@ 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 | +This method returns a [`User`](/sdk/reference/entities#user) object with the logged-in user's information ## 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. +Fetching using this builder will return [`User`](/sdk/reference/entities#user) objects + The `UsersRequestBuilder` class allows you to set the below parameters: ### Set Limit @@ -206,6 +197,12 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() +Relevant fields to access on returned users: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| status | `getStatus()` | `string` | Online status of the user (`"online"` or `"offline"`) | + ### 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. @@ -266,6 +263,12 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() +Relevant fields to access on returned users: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| role | `getRole()` | `string` | Role assigned to the user | + ### Friends Only This property when set to true will return only the friends of the logged-in user. @@ -326,6 +329,12 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() +Relevant fields to access on returned users: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| tags | `getTags()` | `string[]` | Tags associated with the user | + ### With Tags This property when set to true will fetch tags data along with the list of users. @@ -355,6 +364,12 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() +Relevant fields to access on returned users: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| tags | `getTags()` | `string[]` | Tags associated with the user | + ### 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. @@ -492,16 +507,7 @@ 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 | +The `fetchNext()` method returns an array of [`User`](/sdk/reference/entities#user) objects. ## Retrieve Particular User Details @@ -544,18 +550,7 @@ The `getUser()` method takes the following parameters: | --------- | ---------------------------------------------------------- | | UID | The UID of the user for whom the details are to be fetched | -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 | +It returns the [`User`](/sdk/reference/entities#user) object containing the details of the user. ## Get online user count @@ -592,6 +587,8 @@ CometChat.getOnlineUserCount().then( This method returns the total online user count for your app. +`getOnlineUserCount()` resolves with a `number` representing the total count of currently online users in your app. + --- diff --git a/sdk/javascript/user-management.mdx b/sdk/javascript/user-management.mdx index b7d4d0809..0655c2d1d 100644 --- a/sdk/javascript/user-management.mdx +++ b/sdk/javascript/user-management.mdx @@ -93,15 +93,7 @@ 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 | +The method returns a [`User`](/sdk/reference/entities#user) object. @@ -156,15 +148,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. -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 | +The method returns a [`User`](/sdk/reference/entities#user) object. ## Updating logged-in user @@ -211,6 +195,8 @@ 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. +The method returns a [`User`](/sdk/reference/entities#user) object. + ## 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. From d244371b1a54ab690f4c4b8fe55f2948f10b1ded Mon Sep 17 00:00:00 2001 From: PrajwalDhuleCC Date: Mon, 23 Mar 2026 19:50:26 +0530 Subject: [PATCH 047/139] docs(sdk/javascript): Add reference links and field documentation for message receipts and conversations - Add reference link to MessageReceipt auxiliary documentation in delivery-read-receipts.mdx - Remove duplicate MessageReceipt getter methods table from delivery-read-receipts.mdx - Add Conversation reference link and relevant fields documentation in retrieve-conversations.mdx - Add field accessor tables for conversationType, tags, and blocked user fields across conversation fetch methods - Consolidate and clarify getter method documentation for improved API reference clarity --- sdk/javascript/delivery-read-receipts.mdx | 15 +--- sdk/javascript/retrieve-conversations.mdx | 101 +++++++++++++++------- 2 files changed, 70 insertions(+), 46 deletions(-) diff --git a/sdk/javascript/delivery-read-receipts.mdx b/sdk/javascript/delivery-read-receipts.mdx index 5eb7474be..1946624a9 100644 --- a/sdk/javascript/delivery-read-receipts.mdx +++ b/sdk/javascript/delivery-read-receipts.mdx @@ -755,7 +755,7 @@ CometChat.addMessageListener( -You will receive events in the form of `MessageReceipt` objects. The message receipt contains the below parameters: +You will receive events in the form of [`MessageReceipt`](/sdk/reference/auxiliary#messagereceipt) objects. The message receipt contains the below parameters: | Parameter | Information | | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | @@ -767,17 +767,6 @@ 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 @@ -823,7 +812,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/retrieve-conversations.mdx b/sdk/javascript/retrieve-conversations.mdx index 737e5f88c..60442be6d 100644 --- a/sdk/javascript/retrieve-conversations.mdx +++ b/sdk/javascript/retrieve-conversations.mdx @@ -36,6 +36,8 @@ Conversations provide the last messages for every one-on-one and group conversat 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. +Fetching using this builder will return [`Conversation`](/sdk/reference/entities#conversation) objects. + The `ConversationsRequestBuilder` class allows you to set the below parameters: ### Set Limit @@ -106,6 +108,13 @@ 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. + +Relevant fields to access on returned conversations: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| conversationType | `getConversationType()` | `string` | Type of conversation (`"user"` or `"group"`) | + ### 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`. @@ -136,6 +145,13 @@ let limit: number = 30, When conversations are fetched successfully, the response will include `tags` arrays on the `conversationWith` objects (user or group). + +Relevant fields to access on returned conversations: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| conversationWith tags | `getConversationWith().getTags()` | `string[]` | Tags associated with the user or group in the conversation | + ### Set User Tags This method fetches user conversations that have the specified tags. @@ -168,6 +184,13 @@ let limit: number = 30, When conversations are fetched successfully, the response will include only user conversations where the user has the specified tags. + +Relevant fields to access on returned conversations: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| conversationWith tags | `getConversationWith().getTags()` | `string[]` | Tags associated with the user in the conversation | + ### Set Group Tags This method fetches group conversations that have the specified tags. @@ -200,6 +223,13 @@ let limit: number = 30, When conversations are fetched successfully, the response will include only group conversations where the group has the specified tags. + +Relevant fields to access on returned conversations: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| conversationWith tags | `getConversationWith().getTags()` | `string[]` | Tags associated with the group in the conversation | + ### 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` @@ -228,6 +258,13 @@ conversationRequest: CometChat.ConversationsRequest = new CometChat.Conversation + +Relevant fields to access on returned conversations: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| tags | `getTags()` | `string[]` | Tags associated with the conversation | + ### Set Tags This method helps you fetch the conversations based on the specified tags. @@ -258,6 +295,13 @@ let limit: number = 30, + +Relevant fields to access on returned conversations: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| tags | `getTags()` | `string[]` | Tags associated with the conversation | + ### Include Blocked Users This method helps you fetch the conversations of users whom the logged-in user has blocked. @@ -316,6 +360,16 @@ let limit: number = 30, + +Relevant fields to access on returned conversations: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| blockedByMe | `getConversationWith().getBlockedByMe()` | `boolean` | Whether the logged-in user has blocked this user | +| hasBlockedMe | `getConversationWith().getHasBlockedMe()` | `boolean` | Whether this user has blocked the logged-in user | +| blockedByMeAt | `getConversationWith().blockedByMeAt` | `number` | Timestamp when the logged-in user blocked this user | +| blockedAt | `getConversationWith().blockedAt` | `number` | Timestamp when this user was blocked | + ### Search Conversations This method helps you search a conversation based on User or Group name. @@ -499,30 +553,7 @@ conversationsRequest.fetchNext().then( -The `Conversation` Object consists of the following fields: - -| 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`). | - -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`) | +The `fetchNext()` method returns an array of [`Conversation`](/sdk/reference/entities#conversation) objects. ## Tag Conversation @@ -583,6 +614,15 @@ 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. + +The `tagConversation()` method returns a [`Conversation`](/sdk/reference/entities#conversation) object with the `tags` field populated. + +Relevant fields to access on returned conversation: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| tags | `getTags()` | `string[]` | Tags applied to the conversation | + ## Retrieve Single Conversation *In other words, as a logged-in user, how do I retrieve a specific conversation?* @@ -631,16 +671,8 @@ 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`) | +The `getConversation()` method returns a single [`Conversation`](/sdk/reference/entities#conversation) object. ## Convert Messages to Conversations @@ -682,6 +714,9 @@ 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. + +The `getConversationFromMessage()` method returns a [`Conversation`](/sdk/reference/entities#conversation) object. + --- ## Next Steps From 933bc89fe013be9deddd07623f85bc92e3f962cd Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 25 Mar 2026 11:59:45 +0530 Subject: [PATCH 048/139] updates the typescript first and then javascript for examples --- .../additional-message-filtering.mdx | 16 +- sdk/javascript/ai-agents.mdx | 42 +-- .../ai-integration-quick-reference.mdx | 64 ++-- sdk/javascript/ai-moderation.mdx | 44 +-- sdk/javascript/all-real-time-listeners.mdx | 286 +++++++++--------- sdk/javascript/authentication-overview.mdx | 84 ++--- sdk/javascript/block-users.mdx | 94 +++--- sdk/javascript/call-logs.mdx | 20 +- sdk/javascript/calling-setup.mdx | 16 +- sdk/javascript/create-group.mdx | 84 ++--- sdk/javascript/default-call.mdx | 206 ++++++------- sdk/javascript/delete-group.mdx | 30 +- sdk/javascript/delete-message.mdx | 30 +- sdk/javascript/delivery-read-receipts.mdx | 88 +++--- sdk/javascript/direct-call.mdx | 236 +++++++-------- sdk/javascript/flag-message.mdx | 48 +-- sdk/javascript/initialization.mdx | 32 +- sdk/javascript/interactive-messages.mdx | 136 ++++----- sdk/javascript/login-listener.mdx | 78 ++--- ...aging-web-sockets-connections-manually.mdx | 28 +- .../message-structure-and-hierarchy.mdx | 46 +-- sdk/javascript/rate-limits.mdx | 32 +- sdk/javascript/reactions.mdx | 200 ++++++------ sdk/javascript/recording.mdx | 8 +- sdk/javascript/retrieve-conversations.mdx | 168 +++++----- sdk/javascript/retrieve-users.mdx | 102 +++---- sdk/javascript/send-message.mdx | 40 +-- sdk/javascript/standalone-calling.mdx | 224 +++++++------- sdk/javascript/user-management.mdx | 100 +++--- sdk/javascript/user-presence.mdx | 32 +- sdk/javascript/video-view-customisation.mdx | 12 +- sdk/javascript/virtual-background.mdx | 40 +-- 32 files changed, 1333 insertions(+), 1333 deletions(-) diff --git a/sdk/javascript/additional-message-filtering.mdx b/sdk/javascript/additional-message-filtering.mdx index 7f89e548a..d4db9dd74 100644 --- a/sdk/javascript/additional-message-filtering.mdx +++ b/sdk/javascript/additional-message-filtering.mdx @@ -58,6 +58,14 @@ Messages are paginated with a maximum of 100 per request. Call `fetchPrevious()` Set the number of messages to fetch per request using `setLimit()`. Maximum is 100. + +```typescript +let messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder().setLimit(50).build(); +``` + + + ```js let messagesRequest = new CometChat.MessagesRequestBuilder() @@ -67,14 +75,6 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - -```typescript -let messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder().setLimit(50).build(); -``` - - - ## Messages for a user conversation diff --git a/sdk/javascript/ai-agents.mdx b/sdk/javascript/ai-agents.mdx index d3d998e32..80e5da475 100644 --- a/sdk/javascript/ai-agents.mdx +++ b/sdk/javascript/ai-agents.mdx @@ -63,13 +63,13 @@ Events arrive via `onAIAssistantEventReceived` in this order:
- - ```js - const listnerId = "unique_listener_id"; + + ```ts + const listnerId: string = "unique_listener_id"; // Adding the AIAssistantListener CometChat.addAIAssistantListener(listnerId, { - onAIAssistantEventReceived: (message) => { + onAIAssistantEventReceived: (message: CometChat.AIAssistantBaseEvent) => { console.log("AIAssistant event received successfully", message); } }); @@ -78,13 +78,13 @@ Events arrive via `onAIAssistantEventReceived` in this order: CometChat.removeAIAssistantListener(listnerId); ``` - - ```ts - const listnerId: string = "unique_listener_id"; + + ```js + const listnerId = "unique_listener_id"; // Adding the AIAssistantListener CometChat.addAIAssistantListener(listnerId, { - onAIAssistantEventReceived: (message: CometChat.AIAssistantBaseEvent) => { + onAIAssistantEventReceived: (message) => { console.log("AIAssistant event received successfully", message); } }); @@ -106,19 +106,20 @@ After the run completes, these messages arrive via `MessageListener`: | `AIToolArgumentMessage` | The arguments passed to a tool | - - ```js - const listnerId = "unique_listener_id"; + + + ```ts + const listnerId: string = "unique_listener_id"; // Adding the MessageListener CometChat.addMessageListener(listnerId, { - onAIAssistantMessageReceived: (message) => { + onAIAssistantMessageReceived: (message: CometChat.AIAssistantMessage) => { console.log("AI Assistant message received successfully", message); }, - onAIToolResultReceived: (message) => { + onAIToolResultReceived: (message: CometChat.AIToolResultMessage) => { console.log("AI Tool result message received successfully", message); }, - onAIToolArgumentsReceived: (message) => { + onAIToolArgumentsReceived: (message: CometChat.AIToolArgumentMessage) => { console.log("AI Tool argument message received successfully", message); }, }); @@ -127,20 +128,19 @@ After the run completes, these messages arrive via `MessageListener`: CometChat.removeMessageListener(listnerId); ``` - - - ```ts - const listnerId: string = "unique_listener_id"; + + ```js + const listnerId = "unique_listener_id"; // Adding the MessageListener CometChat.addMessageListener(listnerId, { - onAIAssistantMessageReceived: (message: CometChat.AIAssistantMessage) => { + onAIAssistantMessageReceived: (message) => { console.log("AI Assistant message received successfully", message); }, - onAIToolResultReceived: (message: CometChat.AIToolResultMessage) => { + onAIToolResultReceived: (message) => { console.log("AI Tool result message received successfully", message); }, - onAIToolArgumentsReceived: (message: CometChat.AIToolArgumentMessage) => { + onAIToolArgumentsReceived: (message) => { console.log("AI Tool argument message received successfully", message); }, }); diff --git a/sdk/javascript/ai-integration-quick-reference.mdx b/sdk/javascript/ai-integration-quick-reference.mdx index 3f3af5c23..e2ce6b1dd 100644 --- a/sdk/javascript/ai-integration-quick-reference.mdx +++ b/sdk/javascript/ai-integration-quick-reference.mdx @@ -41,26 +41,26 @@ AI Agents enable intelligent, automated interactions. They process user messages - Event flow: Run Start → Tool Call(s) → Text Message Stream → Run Finished - - ```javascript - const listnerId = "unique_listener_id"; + + ```typescript + const listnerId: string = "unique_listener_id"; // Adding the AIAssistantListener for real-time events CometChat.addAIAssistantListener(listnerId, { - onAIAssistantEventReceived: (message) => { + onAIAssistantEventReceived: (message: CometChat.AIAssistantBaseEvent) => { console.log("AIAssistant event received successfully", message); } }); // Adding the MessageListener for persisted agentic messages CometChat.addMessageListener(listnerId, { - onAIAssistantMessageReceived: (message) => { + onAIAssistantMessageReceived: (message: CometChat.AIAssistantMessage) => { console.log("AI Assistant message received successfully", message); }, - onAIToolResultReceived: (message) => { + onAIToolResultReceived: (message: CometChat.AIToolResultMessage) => { console.log("AI Tool result message received successfully", message); }, - onAIToolArgumentsReceived: (message) => { + onAIToolArgumentsReceived: (message: CometChat.AIToolArgumentMessage) => { console.log("AI Tool argument message received successfully", message); }, }); @@ -70,26 +70,26 @@ AI Agents enable intelligent, automated interactions. They process user messages CometChat.removeMessageListener(listnerId); ``` - - ```typescript - const listnerId: string = "unique_listener_id"; + + ```javascript + const listnerId = "unique_listener_id"; // Adding the AIAssistantListener for real-time events CometChat.addAIAssistantListener(listnerId, { - onAIAssistantEventReceived: (message: CometChat.AIAssistantBaseEvent) => { + onAIAssistantEventReceived: (message) => { console.log("AIAssistant event received successfully", message); } }); // Adding the MessageListener for persisted agentic messages CometChat.addMessageListener(listnerId, { - onAIAssistantMessageReceived: (message: CometChat.AIAssistantMessage) => { + onAIAssistantMessageReceived: (message) => { console.log("AI Assistant message received successfully", message); }, - onAIToolResultReceived: (message: CometChat.AIToolResultMessage) => { + onAIToolResultReceived: (message) => { console.log("AI Tool result message received successfully", message); }, - onAIToolArgumentsReceived: (message: CometChat.AIToolArgumentMessage) => { + onAIToolArgumentsReceived: (message) => { console.log("AI Tool argument message received successfully", message); }, }); @@ -111,8 +111,8 @@ AI Moderation automatically reviews messages for inappropriate content in real-t - Enable and configure rules in the CometChat Dashboard - - ```javascript + + ```typescript // Send message and check initial moderation status const textMessage = new CometChat.TextMessage( receiverUID, @@ -121,27 +121,27 @@ AI Moderation automatically reviews messages for inappropriate content in real-t ); CometChat.sendMessage(textMessage).then( - (message) => { - const status = message.getModerationStatus(); + (message: CometChat.TextMessage) => { + const status: string = message.getModerationStatus(); if (status === CometChat.ModerationStatus.PENDING) { console.log("Message is under moderation review"); } }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Message sending failed:", error); } ); // Listen for moderation results - const listenerID = "MODERATION_LISTENER"; + const listenerID: string = "MODERATION_LISTENER"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onMessageModerated: (message) => { - const status = message.getModerationStatus(); - const messageId = message.getId(); + onMessageModerated: (message: CometChat.BaseMessage) => { + const status: string = message.getModerationStatus(); + const messageId: number = message.getId(); switch (status) { case CometChat.ModerationStatus.APPROVED: @@ -156,8 +156,8 @@ AI Moderation automatically reviews messages for inappropriate content in real-t ); ``` - - ```typescript + + ```javascript // Send message and check initial moderation status const textMessage = new CometChat.TextMessage( receiverUID, @@ -166,27 +166,27 @@ AI Moderation automatically reviews messages for inappropriate content in real-t ); CometChat.sendMessage(textMessage).then( - (message: CometChat.TextMessage) => { - const status: string = message.getModerationStatus(); + (message) => { + const status = message.getModerationStatus(); if (status === CometChat.ModerationStatus.PENDING) { console.log("Message is under moderation review"); } }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Message sending failed:", error); } ); // Listen for moderation results - const listenerID: string = "MODERATION_LISTENER"; + const listenerID = "MODERATION_LISTENER"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onMessageModerated: (message: CometChat.BaseMessage) => { - const status: string = message.getModerationStatus(); - const messageId: number = message.getId(); + onMessageModerated: (message) => { + const status = message.getModerationStatus(); + const messageId = message.getId(); switch (status) { case CometChat.ModerationStatus.APPROVED: diff --git a/sdk/javascript/ai-moderation.mdx b/sdk/javascript/ai-moderation.mdx index 3222af96a..44f8a4482 100644 --- a/sdk/javascript/ai-moderation.mdx +++ b/sdk/javascript/ai-moderation.mdx @@ -96,8 +96,8 @@ The `getModerationStatus()` method returns one of the following values: When you send a text, image, or video message, check the initial moderation status: - - ```javascript + + ```typescript const textMessage = new CometChat.TextMessage( receiverUID, "Hello, how are you?", @@ -105,23 +105,23 @@ When you send a text, image, or video message, check the initial moderation stat ); CometChat.sendMessage(textMessage).then( - (message) => { + (message: CometChat.TextMessage) => { // Check moderation status - const status = message.getModerationStatus(); + const status: string = message.getModerationStatus(); if (status === CometChat.ModerationStatus.PENDING) { console.log("Message is under moderation review"); // Show pending indicator in UI } }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Message sending failed:", error); } ); ``` - - ```typescript + + ```javascript const textMessage = new CometChat.TextMessage( receiverUID, "Hello, how are you?", @@ -129,16 +129,16 @@ When you send a text, image, or video message, check the initial moderation stat ); CometChat.sendMessage(textMessage).then( - (message: CometChat.TextMessage) => { + (message) => { // Check moderation status - const status: string = message.getModerationStatus(); + const status = message.getModerationStatus(); if (status === CometChat.ModerationStatus.PENDING) { console.log("Message is under moderation review"); // Show pending indicator in UI } }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Message sending failed:", error); } ); @@ -151,20 +151,20 @@ When you send a text, image, or video message, check the initial moderation stat Register a message listener to receive moderation results in real-time: - - ```javascript - const listenerID = "MODERATION_LISTENER"; + + ```typescript + const listenerID: string = "MODERATION_LISTENER"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onMessageModerated: (message) => { + onMessageModerated: (message: CometChat.BaseMessage) => { if ( message instanceof CometChat.TextMessage || message instanceof CometChat.MediaMessage ) { - const status = message.getModerationStatus(); - const messageId = message.getId(); + const status: string = message.getModerationStatus(); + const messageId: number = message.getId(); switch (status) { case CometChat.ModerationStatus.APPROVED: @@ -187,20 +187,20 @@ Register a message listener to receive moderation results in real-time: // CometChat.removeMessageListener(listenerID); ``` - - ```typescript - const listenerID: string = "MODERATION_LISTENER"; + + ```javascript + const listenerID = "MODERATION_LISTENER"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onMessageModerated: (message: CometChat.BaseMessage) => { + onMessageModerated: (message) => { if ( message instanceof CometChat.TextMessage || message instanceof CometChat.MediaMessage ) { - const status: string = message.getModerationStatus(); - const messageId: number = message.getId(); + const status = message.getModerationStatus(); + const messageId = message.getId(); switch (status) { case CometChat.ModerationStatus.APPROVED: diff --git a/sdk/javascript/all-real-time-listeners.mdx b/sdk/javascript/all-real-time-listeners.mdx index a33575498..e2c92ddbc 100644 --- a/sdk/javascript/all-real-time-listeners.mdx +++ b/sdk/javascript/all-real-time-listeners.mdx @@ -58,16 +58,18 @@ The `UserListener` class provides you with live events related to users. Below a To add the `UserListener`, you need to use the `addUserListener()` method provided by the `CometChat` class. - -```js -const listenerID = "UNIQUE_LISTENER_ID"; + +```typescript +const listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addUserListener( listenerID, new CometChat.UserListener({ - onUserOnline: (onlineUser) => { + onUserOnline: (onlineUser: CometChat.User) => { + /* when someuser/friend comes online, user will be received here */ console.log("On User Online:", { onlineUser }); }, - onUserOffline: (offlineUser) => { + onUserOffline: (offlineUser: CometChat.User) => { + /* when someuser/friend went offline, user will be received here */ console.log("On User Offline:", { offlineUser }); }, }) @@ -76,18 +78,16 @@ CometChat.addUserListener( - -```typescript -const listenerID: string = "UNIQUE_LISTENER_ID"; + +```js +const listenerID = "UNIQUE_LISTENER_ID"; CometChat.addUserListener( listenerID, new CometChat.UserListener({ - onUserOnline: (onlineUser: CometChat.User) => { - /* when someuser/friend comes online, user will be received here */ + onUserOnline: (onlineUser) => { console.log("On User Online:", { onlineUser }); }, - onUserOffline: (offlineUser: CometChat.User) => { - /* when someuser/friend went offline, user will be received here */ + onUserOffline: (offlineUser) => { console.log("On User Offline:", { offlineUser }); }, }) @@ -103,13 +103,6 @@ where `UNIQUE_LISTENER_ID` is the unique identifier for the listener. Please mak Once the `UserListener` is not in use, you need to remove the listener using the `removeUserListener()` method which takes the id of the listener to be removed as the parameter. - -```js -CometChat.removeUserListener(UNIQUE_LISTENER_ID); -``` - - - ```typescript let listenerID: string = "UNIQUE_LISTENER_ID"; @@ -118,6 +111,13 @@ CometChat.removeUserListener(listenerID); + +```js +CometChat.removeUserListener(UNIQUE_LISTENER_ID); +``` + + + ## Group Listener @@ -137,18 +137,31 @@ The `GroupListener` class provides you with all the real-time events related to To add the `GroupListener`, you need to use the `addGroupListener()` method provided by the `CometChat` class. - -```js + +```typescript CometChat.addGroupListener( "UNIQUE_LISTENER_ID", new CometChat.GroupListener({ - onGroupMemberJoined: (message, joinedUser, joinedGroup) => { + onGroupMemberJoined: ( + message: CometChat.Action, + joinedUser: CometChat.User, + joinedGroup: CometChat.Group + ) => { console.log("onGroupMemberJoined", { message, joinedUser, joinedGroup }); }, - onGroupMemberLeft: (message, leftUser, leftGroup) => { + onGroupMemberLeft: ( + message: CometChat.Action, + leftUser: CometChat.User, + leftGroup: CometChat.Group + ) => { console.log("onGroupMemberLeft", { message, leftUser, leftGroup }); }, - onGroupMemberKicked: (message, kickedUser, kickedBy, kickedFrom) => { + onGroupMemberKicked: ( + message: CometChat.Action, + kickedUser: CometChat.User, + kickedBy: CometChat.User, + kickedFrom: CometChat.Group + ) => { console.log("onGroupMemberKicked", { message, kickedUser, @@ -156,7 +169,12 @@ CometChat.addGroupListener( kickedFrom, }); }, - onGroupMemberBanned: (message, bannedUser, bannedBy, bannedFrom) => { + onGroupMemberBanned: ( + message: CometChat.Action, + bannedUser: CometChat.User, + bannedBy: CometChat.User, + bannedFrom: CometChat.Group + ) => { console.log("onGroupMemberBanned", { message, bannedUser, @@ -165,10 +183,10 @@ CometChat.addGroupListener( }); }, onGroupMemberUnbanned: ( - message, - unbannedUser, - unbannedBy, - unbannedFrom + message: CometChat.Action, + unbannedUser: CometChat.User, + unbannedBy: CometChat.User, + unbannedFrom: CometChat.Group ) => { console.log("onGroupMemberUnbanned", { message, @@ -178,11 +196,11 @@ CometChat.addGroupListener( }); }, onGroupMemberScopeChanged: ( - message, - changedUser, - newScope, - oldScope, - changedGroup + message: CometChat.Action, + changedUser: CometChat.User, + newScope: string, + oldScope: string, + changedGroup: CometChat.Group ) => { console.log("onGroupMemberScopeChanged", { message, @@ -192,7 +210,12 @@ CometChat.addGroupListener( changedGroup, }); }, - onMemberAddedToGroup: (message, userAdded, addedby, addedTo) => { + onMemberAddedToGroup: ( + message: CometChat.Action, + userAdded: CometChat.User, + addedby: CometChat.User, + addedTo: CometChat.Group + ) => { console.log("onMemberAddedToGroup", { message, userAdded, @@ -206,31 +229,18 @@ CometChat.addGroupListener( - -```typescript + +```js CometChat.addGroupListener( "UNIQUE_LISTENER_ID", new CometChat.GroupListener({ - onGroupMemberJoined: ( - message: CometChat.Action, - joinedUser: CometChat.User, - joinedGroup: CometChat.Group - ) => { + onGroupMemberJoined: (message, joinedUser, joinedGroup) => { console.log("onGroupMemberJoined", { message, joinedUser, joinedGroup }); }, - onGroupMemberLeft: ( - message: CometChat.Action, - leftUser: CometChat.User, - leftGroup: CometChat.Group - ) => { + onGroupMemberLeft: (message, leftUser, leftGroup) => { console.log("onGroupMemberLeft", { message, leftUser, leftGroup }); }, - onGroupMemberKicked: ( - message: CometChat.Action, - kickedUser: CometChat.User, - kickedBy: CometChat.User, - kickedFrom: CometChat.Group - ) => { + onGroupMemberKicked: (message, kickedUser, kickedBy, kickedFrom) => { console.log("onGroupMemberKicked", { message, kickedUser, @@ -238,12 +248,7 @@ CometChat.addGroupListener( kickedFrom, }); }, - onGroupMemberBanned: ( - message: CometChat.Action, - bannedUser: CometChat.User, - bannedBy: CometChat.User, - bannedFrom: CometChat.Group - ) => { + onGroupMemberBanned: (message, bannedUser, bannedBy, bannedFrom) => { console.log("onGroupMemberBanned", { message, bannedUser, @@ -252,10 +257,10 @@ CometChat.addGroupListener( }); }, onGroupMemberUnbanned: ( - message: CometChat.Action, - unbannedUser: CometChat.User, - unbannedBy: CometChat.User, - unbannedFrom: CometChat.Group + message, + unbannedUser, + unbannedBy, + unbannedFrom ) => { console.log("onGroupMemberUnbanned", { message, @@ -265,11 +270,11 @@ CometChat.addGroupListener( }); }, onGroupMemberScopeChanged: ( - message: CometChat.Action, - changedUser: CometChat.User, - newScope: string, - oldScope: string, - changedGroup: CometChat.Group + message, + changedUser, + newScope, + oldScope, + changedGroup ) => { console.log("onGroupMemberScopeChanged", { message, @@ -279,12 +284,7 @@ CometChat.addGroupListener( changedGroup, }); }, - onMemberAddedToGroup: ( - message: CometChat.Action, - userAdded: CometChat.User, - addedby: CometChat.User, - addedTo: CometChat.Group - ) => { + onMemberAddedToGroup: (message, userAdded, addedby, addedTo) => { console.log("onMemberAddedToGroup", { message, userAdded, @@ -305,13 +305,6 @@ where `UNIQUE_LISTENER_ID` is the unique identifier for the listener. Please mak Once the `GroupListener` is not in use, you need to remove the listener using the `removeGroupListener()` method which takes the id of the listener to be removed as the parameter. - -```js -CometChat.removeGroupListener(UNIQUE_LISTENER_ID); -``` - - - ```typescript let listenerID: string = "UNIQUE_LISTENER_ID"; @@ -320,6 +313,13 @@ CometChat.removeGroupListener(listenerID); + +```js +CometChat.removeGroupListener(UNIQUE_LISTENER_ID); +``` + + + ## Message Listener @@ -346,54 +346,54 @@ The `MessageListener` class provides you with live events related to messages. B To add the `MessageListener`, you need to use the `addMessageListener()` method provided by the `CometChat` class. - -```js + +```typescript CometChat.addMessageListener( "UNIQUE_LISTENER_ID", new CometChat.MessageListener({ - onTextMessageReceived: (textMessage) => { + onTextMessageReceived: (textMessage: CometChat.TextMessage) => { console.log("Text message received successfully", textMessage); }, - onMediaMessageReceived: (mediaMessage) => { + onMediaMessageReceived: (mediaMessage: CometChat.MediaMessage) => { console.log("Media message received successfully", mediaMessage); }, - onCustomMessageReceived: (customMessage) => { + onCustomMessageReceived: (customMessage: CometChat.CustomMessage) => { console.log("Custom message received successfully", customMessage); }, - onMessagesDelivered: (messageReceipt) => { + onMessagesDelivered: (messageReceipt: CometChat.MessageReceipt) => { console.log("Message Delivered", messageReceipt); }, - onMessagesRead: (messageReceipt) => { + onMessagesRead: (messageReceipt: CometChat.MessageReceipt) => { console.log("Message Read", messageReceipt); }, - onTypingStarted: (typingIndicator) => { + onTypingStarted: (typingIndicator: CometChat.TypingIndicator) => { console.log("Typing Started", typingIndicator); }, - onTypingEnded: (typingIndicator) => { + onTypingEnded: (typingIndicator: CometChat.TypingIndicator) => { console.log("Typing Ended", typingIndicator); }, - onMessagesDeleted: (message) => { - console.log("Message Deleted", message); + onMessageDeleted: (message: CometChat.BaseMessage) => { + console.log("Message Delted", message); }, - onMessageEdited: (message) => { + onMessageEdited: (message: CometChat.BaseMessage) => { console.log("Message Edited", message); }, - onInteractiveMessageReceived: (message) => { + onInteractiveMessageReceived: (message: CometChat.InteractiveMessage) => { console.log("interactive Message received", message); }, - onInteractionGoalCompleted: (message) => { + onInteractionGoalCompleted: (receipt: CometChat.InteractionReceipt) => { console.log("Message interaction goal completed", message); }, - onTransientMessageReceived: (message) => { + onTransientMessageReceived: (message: CometChat.TransientMessage) => { console.log("Transient Message received", message); }, - onMessageReactionAdded: (reaction) => { + onMessageReactionAdded: (reaction: CometChat.ReactionEvent) => { console.log("Message Reaction added", reaction); }, - onMessageReactionRemoved: (reaction) => { + onMessageReactionRemoved: (reaction: CometChat.ReactionEvent) => { console.log("Message Reaction removed", reaction); }, - onMessageModerated: (message) => { + onMessageModerated: (message: CometChat.BaseMessage) => { console.log("Message Moderated", message); }, }) @@ -402,54 +402,54 @@ CometChat.addMessageListener( - -```typescript + +```js CometChat.addMessageListener( "UNIQUE_LISTENER_ID", new CometChat.MessageListener({ - onTextMessageReceived: (textMessage: CometChat.TextMessage) => { + onTextMessageReceived: (textMessage) => { console.log("Text message received successfully", textMessage); }, - onMediaMessageReceived: (mediaMessage: CometChat.MediaMessage) => { + onMediaMessageReceived: (mediaMessage) => { console.log("Media message received successfully", mediaMessage); }, - onCustomMessageReceived: (customMessage: CometChat.CustomMessage) => { + onCustomMessageReceived: (customMessage) => { console.log("Custom message received successfully", customMessage); }, - onMessagesDelivered: (messageReceipt: CometChat.MessageReceipt) => { + onMessagesDelivered: (messageReceipt) => { console.log("Message Delivered", messageReceipt); }, - onMessagesRead: (messageReceipt: CometChat.MessageReceipt) => { + onMessagesRead: (messageReceipt) => { console.log("Message Read", messageReceipt); }, - onTypingStarted: (typingIndicator: CometChat.TypingIndicator) => { + onTypingStarted: (typingIndicator) => { console.log("Typing Started", typingIndicator); }, - onTypingEnded: (typingIndicator: CometChat.TypingIndicator) => { + onTypingEnded: (typingIndicator) => { console.log("Typing Ended", typingIndicator); }, - onMessageDeleted: (message: CometChat.BaseMessage) => { - console.log("Message Delted", message); + onMessagesDeleted: (message) => { + console.log("Message Deleted", message); }, - onMessageEdited: (message: CometChat.BaseMessage) => { + onMessageEdited: (message) => { console.log("Message Edited", message); }, - onInteractiveMessageReceived: (message: CometChat.InteractiveMessage) => { + onInteractiveMessageReceived: (message) => { console.log("interactive Message received", message); }, - onInteractionGoalCompleted: (receipt: CometChat.InteractionReceipt) => { + onInteractionGoalCompleted: (message) => { console.log("Message interaction goal completed", message); }, - onTransientMessageReceived: (message: CometChat.TransientMessage) => { + onTransientMessageReceived: (message) => { console.log("Transient Message received", message); }, - onMessageReactionAdded: (reaction: CometChat.ReactionEvent) => { + onMessageReactionAdded: (reaction) => { console.log("Message Reaction added", reaction); }, - onMessageReactionRemoved: (reaction: CometChat.ReactionEvent) => { + onMessageReactionRemoved: (reaction) => { console.log("Message Reaction removed", reaction); }, - onMessageModerated: (message: CometChat.BaseMessage) => { + onMessageModerated: (message) => { console.log("Message Moderated", message); }, }) @@ -465,13 +465,6 @@ where `UNIQUE_LISTENER_ID` is the unique identifier for the listener. Please mak Once the `MessageListener` is not in use, you need to remove the listener using the `removeMessageListener()` method which takes the id of the listener to be removed as the parameter. - -```js -CometChat.removeMessageListener(UNIQUE_LISTENER_ID); -``` - - - ```typescript let listenerID: string = "UNIQUE_LISTENER_ID"; @@ -480,6 +473,13 @@ CometChat.removeMessageListener(listenerID); + +```js +CometChat.removeMessageListener(UNIQUE_LISTENER_ID); +``` + + + ## Call Listener @@ -496,21 +496,21 @@ The `CallListener` class provides you with live events related to calls. Below a To add the `CallListener`, you need to use the `addCallListener()` method provided by the `CometChat` class. - -```js + +```typescript CometChat.addCallListener( "UNIQUE_LISTENER_ID", new CometChat.CallListener({ - onIncomingCallReceived(call) { + onIncomingCallReceived: (call: CometChat.Call) => { console.log("Incoming call:", call); }, - onOutgoingCallAccepted(call) { + onOutgoingCallAccepted: (call: CometChat.Call) => { console.log("Outgoing call accepted:", call); }, - onOutgoingCallRejected(call) { + onOutgoingCallRejected: (call: CometChat.Call) => { console.log("Outgoing call rejected:", call); }, - onIncomingCallCancelled(call) { + onIncomingCallCancelled: (call: CometChat.Call) => { console.log("Incoming call canceled:", call); }, }) @@ -519,21 +519,21 @@ CometChat.addCallListener( - -```typescript + +```js CometChat.addCallListener( "UNIQUE_LISTENER_ID", new CometChat.CallListener({ - onIncomingCallReceived: (call: CometChat.Call) => { + onIncomingCallReceived(call) { console.log("Incoming call:", call); }, - onOutgoingCallAccepted: (call: CometChat.Call) => { + onOutgoingCallAccepted(call) { console.log("Outgoing call accepted:", call); }, - onOutgoingCallRejected: (call: CometChat.Call) => { + onOutgoingCallRejected(call) { console.log("Outgoing call rejected:", call); }, - onIncomingCallCancelled: (call: CometChat.Call) => { + onIncomingCallCancelled(call) { console.log("Incoming call canceled:", call); }, }) @@ -549,13 +549,6 @@ where `UNIQUE_LISTENER_ID` is the unique identifier for the listener. Please mak Once the `CallListener` is not in use, you need to remove the listener using the `removeCallListener()` method which takes the id of the listener to be removed as the parameter. - -```js -CometChat.removeCallListener(UNIQUE_LISTENER_ID); -``` - - - ```typescript let listenerID: string = "UNIQUE_LISTENER_ID"; @@ -564,6 +557,13 @@ CometChat.removeCallListener(listenerID); + +```js +CometChat.removeCallListener(UNIQUE_LISTENER_ID); +``` + + + diff --git a/sdk/javascript/authentication-overview.mdx b/sdk/javascript/authentication-overview.mdx index 03756f7db..9b6a07ebb 100644 --- a/sdk/javascript/authentication-overview.mdx +++ b/sdk/javascript/authentication-overview.mdx @@ -77,52 +77,52 @@ This straightforward authentication method is ideal for proof-of-concept (POC) d - -```js -const UID = "UID"; -const authKey = "AUTH_KEY"; + +```typescript +const UID: string = "cometchat-uid-1"; +const authKey: string = "AUTH_KEY"; CometChat.getLoggedinUser().then( - (user) => { + (user: CometChat.User) => { if (!user) { CometChat.login(UID, authKey).then( - (user) => { + (user: CometChat.User) => { console.log("Login Successful:", { user }); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Login failed with exception:", { error }); } ); } }, - (error) => { - console.log("Something went wrong", error); + (error: CometChat.CometChatException) => { + console.log("Some Error Occured", { error }); } ); ``` - -```typescript -const UID: string = "cometchat-uid-1"; -const authKey: string = "AUTH_KEY"; + +```js +const UID = "UID"; +const authKey = "AUTH_KEY"; CometChat.getLoggedinUser().then( - (user: CometChat.User) => { + (user) => { if (!user) { CometChat.login(UID, authKey).then( - (user: CometChat.User) => { + (user) => { console.log("Login Successful:", { user }); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Login failed with exception:", { error }); } ); } }, - (error: CometChat.CometChatException) => { - console.log("Some Error Occured", { error }); + (error) => { + console.log("Something went wrong", error); } ); ``` @@ -165,50 +165,50 @@ This advanced authentication procedure does not use the Auth Key directly in you 3. Load the Auth Token in your client and pass it to the `login()` method. - -```js -const authToken = "AUTH_TOKEN"; + +```typescript +const authToken: string = "AUTH_TOKEN"; CometChat.getLoggedinUser().then( - (user) => { + (user: CometChat.User) => { if (!user) { CometChat.login(authToken).then( - (user) => { + (user: CometChat.User) => { console.log("Login Successful:", { user }); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Login failed with exception:", { error }); } ); } }, - (error) => { - console.log("Something went wrong", error); + (error: CometChat.CometChatException) => { + console.log("Some Error Occured", { error }); } ); ``` - -```typescript -const authToken: string = "AUTH_TOKEN"; + +```js +const authToken = "AUTH_TOKEN"; CometChat.getLoggedinUser().then( - (user: CometChat.User) => { + (user) => { if (!user) { CometChat.login(authToken).then( - (user: CometChat.User) => { + (user) => { console.log("Login Successful:", { user }); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Login failed with exception:", { error }); } ); } }, - (error: CometChat.CometChatException) => { - console.log("Some Error Occured", { error }); + (error) => { + console.log("Something went wrong", error); } ); ``` @@ -245,13 +245,13 @@ After the user logs in, their information is returned in the `User` object on th You can use the `logout()` method to log out the user from CometChat. We suggest you call this method once your user has been successfully logged out from your app. - -```js + +```typescript CometChat.logout().then( - () => { + (loggedOut: Object) => { console.log("Logout completed successfully"); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Logout failed with exception:", { error }); } ); @@ -259,13 +259,13 @@ CometChat.logout().then( - -```typescript + +```js CometChat.logout().then( - (loggedOut: Object) => { + () => { console.log("Logout completed successfully"); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Logout failed with exception:", { error }); } ); diff --git a/sdk/javascript/block-users.mdx b/sdk/javascript/block-users.mdx index 5fd991ef8..b27f83d12 100644 --- a/sdk/javascript/block-users.mdx +++ b/sdk/javascript/block-users.mdx @@ -27,21 +27,6 @@ let blockedUsers = await request.fetchNext(); Block users to prevent all communication with them. Use `blockUsers()` with an array of UIDs. - -```javascript -const usersList = ["UID1", "UID2", "UID3"]; - -CometChat.blockUsers(usersList).then( -list => { - console.log("users list blocked", { list }); -}, error => { - console.log("Blocking user fails with error", error); -} -); -``` - - - ```typescript const usersList: String[] = ["UID1", "UID2", "UID3"]; @@ -57,6 +42,21 @@ CometChat.blockUsers(usersList).then( + +```javascript +const usersList = ["UID1", "UID2", "UID3"]; + +CometChat.blockUsers(usersList).then( +list => { + console.log("users list blocked", { list }); +}, error => { + console.log("Blocking user fails with error", error); +} +); +``` + + + ```javascript const usersList = ["UID1", "UID2", "UID3"]; @@ -89,21 +89,6 @@ The method returns an array of [`User`](/sdk/reference/entities#user) objects wi Unblock previously blocked users using `unblockUsers()` with an array of UIDs. - -```javascript -const usersList = ["UID1", "UID2", "UID3"]; - -CometChat.unblockUsers(usersList).then( -list => { - console.log("users list unblocked", { list }); -}, error => { - console.log("unblocking user fails with error", error); -} -); -``` - - - ```typescript const usersList: String[] = ["UID1", "UID2", "UID3"]; @@ -119,6 +104,21 @@ CometChat.unblockUsers(usersList).then( + +```javascript +const usersList = ["UID1", "UID2", "UID3"]; + +CometChat.unblockUsers(usersList).then( +list => { + console.log("users list unblocked", { list }); +}, error => { + console.log("unblocking user fails with error", error); +} +); +``` + + + ```javascript const usersList = ["UID1", "UID2", "UID3"]; @@ -244,23 +244,6 @@ let blockedUsersRequest: CometChat.BlockedUsersRequest = new CometChat.BlockedUs After configuring the builder, call `build()` to get the `BlockedUsersRequest` object, then call `fetchNext()` to retrieve blocked users. - -```javascript -const limit = 30; -const blockedUsersRequest = new CometChat.BlockedUsersRequestBuilder() - .setLimit(limit) - .build(); -blockedUsersRequest.fetchNext().then( -userList => { - console.log("Blocked user list received:", userList); -}, error => { - console.log("Blocked user list fetching failed with error:", error); -} -); -``` - - - ```typescript let limit: number = 30; @@ -279,6 +262,23 @@ blockedUsersRequest.fetchNext().then( + +```javascript +const limit = 30; +const blockedUsersRequest = new CometChat.BlockedUsersRequestBuilder() + .setLimit(limit) + .build(); +blockedUsersRequest.fetchNext().then( +userList => { + console.log("Blocked user list received:", userList); +}, error => { + console.log("Blocked user list fetching failed with error:", error); +} +); +``` + + + --- diff --git a/sdk/javascript/call-logs.mdx b/sdk/javascript/call-logs.mdx index deeac9afd..41277a847 100644 --- a/sdk/javascript/call-logs.mdx +++ b/sdk/javascript/call-logs.mdx @@ -110,27 +110,27 @@ The `fetchNext()` and `fetchPrevious()` methods return an array of [`Call`](/sdk Retrieve details for a specific call session using `getCallDetails()`: - -```javascript -const sessionID = "SESSION_ID"; + +```typescript +const sessionID: string = "SESSION_ID"; CometChatCalls.getCallDetails(sessionID, authToken).then( - (callLogs) => { + (callLogs: Array) => { console.log("Call details:", callLogs); }, - (error) => { + (error: any) => { console.log("Error fetching call details:", error); } ); ``` - -```typescript -const sessionID: string = "SESSION_ID"; + +```javascript +const sessionID = "SESSION_ID"; CometChatCalls.getCallDetails(sessionID, authToken).then( - (callLogs: Array) => { + (callLogs) => { console.log("Call details:", callLogs); }, - (error: any) => { + (error) => { console.log("Error fetching call details:", error); } ); diff --git a/sdk/javascript/calling-setup.mdx b/sdk/javascript/calling-setup.mdx index 96ffa72cb..e0c160bbb 100644 --- a/sdk/javascript/calling-setup.mdx +++ b/sdk/javascript/calling-setup.mdx @@ -61,15 +61,15 @@ yarn add @cometchat/calls-sdk-javascript Then, import the `CometChatCalls` class wherever you want to use `CometChatCalls`. - -```js + +```typescript import { CometChatCalls } from "@cometchat/calls-sdk-javascript"; ``` - -```typescript + +```js import { CometChatCalls } from "@cometchat/calls-sdk-javascript"; ``` @@ -92,8 +92,8 @@ The `init()` method initializes the Calls SDK. It takes a `CallAppSettings` inst Call `init()` before any other `CometChatCalls` method — ideally on app startup. - -```js + +```typescript let appID = "APP_ID"; let region = "REGION"; @@ -114,8 +114,8 @@ CometChatCalls.init(callAppSetting).then( - -```typescript + +```js let appID = "APP_ID"; let region = "REGION"; diff --git a/sdk/javascript/create-group.mdx b/sdk/javascript/create-group.mdx index e288bb58b..65366f087 100644 --- a/sdk/javascript/create-group.mdx +++ b/sdk/javascript/create-group.mdx @@ -35,26 +35,6 @@ Group types: - `CometChat.GROUP_TYPE.PRIVATE` - -```javascript -const GUID = "GUID"; -const groupName = "Hello Group!"; -const groupType = CometChat.GROUP_TYPE.PUBLIC; -const password = ""; - -const group = new CometChat.Group(GUID, groupName, groupType, password); - -CometChat.createGroup(group).then( - group => { - console.log("Group created successfully:", group); - }, error => { - console.log("Group creation failed with exception:", error); - } -); -``` - - - ```typescript const GUID: string = "GUID"; @@ -75,6 +55,26 @@ CometChat.createGroup(group).then( + +```javascript +const GUID = "GUID"; +const groupName = "Hello Group!"; +const groupType = CometChat.GROUP_TYPE.PUBLIC; +const password = ""; + +const group = new CometChat.Group(GUID, groupName, groupType, password); + +CometChat.createGroup(group).then( + group => { + console.log("Group created successfully:", group); + }, error => { + console.log("Group creation failed with exception:", error); + } +); +``` + + + ```javascript const GUID = "GUID"; @@ -131,23 +131,23 @@ Parameters: Create a `GroupMember` with: `new CometChat.GroupMember(UID, scope)` - -```js -let GUID = "cometchat-guid-11"; -let UID = "cometchat-uid-1"; -let groupName = "Hello Group!"; -let groupType = CometChat.GROUP_TYPE.PUBLIC; + +```typescript +let GUID: string = "cometchat-guid-11"; +let UID: string = "cometchat-uid-1"; +let groupName: string = "Hello Group!"; +let groupType: string = CometChat.GROUP_TYPE.PUBLIC; -let group = new CometChat.Group(GUID, groupName, groupType); -let members = [ +let group: CometChat.Group = new CometChat.Group(GUID, groupName, groupType); +let members: Array = [ new CometChat.GroupMember(UID, CometChat.GROUP_MEMBER_SCOPE.PARTICIPANT) ]; -let banMembers = ["cometchat-uid-2"]; +let banMembers: Array = ["cometchat-uid-2"]; CometChat.createGroupWithMembers(group, members, banMembers).then( - response => { + (response: Object) => { console.log("Group created successfully", response); - }, error => { + }, (error: CometChat.CometChatException) => { console.log("Some error occured while creating group", error) } ); @@ -155,23 +155,23 @@ CometChat.createGroupWithMembers(group, members, banMembers).then( - -```typescript -let GUID: string = "cometchat-guid-11"; -let UID: string = "cometchat-uid-1"; -let groupName: string = "Hello Group!"; -let groupType: string = CometChat.GROUP_TYPE.PUBLIC; + +```js +let GUID = "cometchat-guid-11"; +let UID = "cometchat-uid-1"; +let groupName = "Hello Group!"; +let groupType = CometChat.GROUP_TYPE.PUBLIC; -let group: CometChat.Group = new CometChat.Group(GUID, groupName, groupType); -let members: Array = [ +let group = new CometChat.Group(GUID, groupName, groupType); +let members = [ new CometChat.GroupMember(UID, CometChat.GROUP_MEMBER_SCOPE.PARTICIPANT) ]; -let banMembers: Array = ["cometchat-uid-2"]; +let banMembers = ["cometchat-uid-2"]; CometChat.createGroupWithMembers(group, members, banMembers).then( - (response: Object) => { + response => { console.log("Group created successfully", response); - }, (error: CometChat.CometChatException) => { + }, error => { console.log("Some error occured while creating group", error) } ); diff --git a/sdk/javascript/default-call.mdx b/sdk/javascript/default-call.mdx index 6dff0e20e..5926d7575 100644 --- a/sdk/javascript/default-call.mdx +++ b/sdk/javascript/default-call.mdx @@ -153,33 +153,28 @@ The `initiateCall()` method returns a [`Call`](/sdk/reference/messages#call) obj Register the `CallListener` to receive real-time call events. Each listener requires a unique `listenerId` string to prevent duplicate registrations and enable targeted removal. - -```javascript -const listenerId = "UNIQUE_LISTENER_ID"; + +```typescript +const listenerId: string = "UNIQUE_LISTENER_ID"; // Register listener CometChat.addCallListener( listenerId, new CometChat.CallListener({ - onIncomingCallReceived: (call) => { + onIncomingCallReceived: (call: CometChat.Call) => { console.log("Incoming call:", call); - // Show incoming call UI }, - onOutgoingCallAccepted: (call) => { + onOutgoingCallAccepted: (call: CometChat.Call) => { console.log("Outgoing call accepted:", call); - // Receiver accepted, start the call session }, - onOutgoingCallRejected: (call) => { + onOutgoingCallRejected: (call: CometChat.Call) => { console.log("Outgoing call rejected:", call); - // Receiver rejected, dismiss outgoing call UI }, - onIncomingCallCancelled: (call) => { + onIncomingCallCancelled: (call: CometChat.Call) => { console.log("Incoming call cancelled:", call); - // Caller cancelled, dismiss incoming call UI }, - onCallEndedMessageReceived: (call) => { + onCallEndedMessageReceived: (call: CometChat.Call) => { console.log("Call ended message:", call); - // Call ended by remote participant } }) ); @@ -188,28 +183,33 @@ CometChat.addCallListener( CometChat.removeCallListener(listenerId); ``` - -```typescript -const listenerId: string = "UNIQUE_LISTENER_ID"; + +```javascript +const listenerId = "UNIQUE_LISTENER_ID"; // Register listener CometChat.addCallListener( listenerId, new CometChat.CallListener({ - onIncomingCallReceived: (call: CometChat.Call) => { + onIncomingCallReceived: (call) => { console.log("Incoming call:", call); + // Show incoming call UI }, - onOutgoingCallAccepted: (call: CometChat.Call) => { + onOutgoingCallAccepted: (call) => { console.log("Outgoing call accepted:", call); + // Receiver accepted, start the call session }, - onOutgoingCallRejected: (call: CometChat.Call) => { + onOutgoingCallRejected: (call) => { console.log("Outgoing call rejected:", call); + // Receiver rejected, dismiss outgoing call UI }, - onIncomingCallCancelled: (call: CometChat.Call) => { + onIncomingCallCancelled: (call) => { console.log("Incoming call cancelled:", call); + // Caller cancelled, dismiss incoming call UI }, - onCallEndedMessageReceived: (call: CometChat.Call) => { + onCallEndedMessageReceived: (call) => { console.log("Call ended message:", call); + // Call ended by remote participant } }) ); @@ -245,6 +245,20 @@ All call listener callbacks receive a [`Call`](/sdk/reference/messages#call) obj When an incoming call is received via `onIncomingCallReceived()`, use `acceptCall()` to accept it. On success, start the call session. + +```typescript +const sessionId: string = call.getSessionId(); // From onIncomingCallReceived + +CometChat.acceptCall(sessionId).then( + (call: CometChat.Call) => { + console.log("Call accepted:", call); + }, + (error: CometChat.CometChatException) => { + console.log("Accept call failed:", error); + } +); +``` + ```javascript const sessionId = call.getSessionId(); // From onIncomingCallReceived @@ -261,27 +275,28 @@ CometChat.acceptCall(sessionId).then( ); ``` + + +## Reject Call + +Use `rejectCall()` to reject an incoming call. Set the status to `CALL_STATUS_REJECTED`. + + ```typescript -const sessionId: string = call.getSessionId(); // From onIncomingCallReceived +const sessionId: string = call.getSessionId(); +const status: string = CometChat.CALL_STATUS.REJECTED; -CometChat.acceptCall(sessionId).then( +CometChat.rejectCall(sessionId, status).then( (call: CometChat.Call) => { - console.log("Call accepted:", call); + console.log("Call rejected:", call); }, (error: CometChat.CometChatException) => { - console.log("Accept call failed:", error); + console.log("Reject call failed:", error); } ); ``` - - -## Reject Call - -Use `rejectCall()` to reject an incoming call. Set the status to `CALL_STATUS_REJECTED`. - - ```javascript const sessionId = call.getSessionId(); @@ -298,28 +313,28 @@ CometChat.rejectCall(sessionId, status).then( ); ``` + + +## Cancel Call + +The caller can cancel an outgoing call before it's answered using `rejectCall()` with status `CALL_STATUS_CANCELLED`. + + ```typescript const sessionId: string = call.getSessionId(); -const status: string = CometChat.CALL_STATUS.REJECTED; +const status: string = CometChat.CALL_STATUS.CANCELLED; CometChat.rejectCall(sessionId, status).then( (call: CometChat.Call) => { - console.log("Call rejected:", call); + console.log("Call cancelled:", call); }, (error: CometChat.CometChatException) => { - console.log("Reject call failed:", error); + console.log("Cancel call failed:", error); } ); ``` - - -## Cancel Call - -The caller can cancel an outgoing call before it's answered using `rejectCall()` with status `CALL_STATUS_CANCELLED`. - - ```javascript const sessionId = call.getSessionId(); @@ -336,21 +351,6 @@ CometChat.rejectCall(sessionId, status).then( ); ``` - -```typescript -const sessionId: string = call.getSessionId(); -const status: string = CometChat.CALL_STATUS.CANCELLED; - -CometChat.rejectCall(sessionId, status).then( - (call: CometChat.Call) => { - console.log("Call cancelled:", call); - }, - (error: CometChat.CometChatException) => { - console.log("Cancel call failed:", error); - } -); -``` - ## Start Call Session @@ -362,15 +362,15 @@ Once the call is accepted, both participants need to start the call session. **Receiver flow:** In the `acceptCall()` success callback, generate a token and start the session. - -```javascript -const sessionId = call.getSessionId(); + +```typescript +const sessionId: string = call.getSessionId(); const loggedInUser = await CometChat.getLoggedinUser(); -const authToken = loggedInUser.getAuthToken(); +const authToken: string = loggedInUser.getAuthToken(); // Step 1: Generate call token CometChatCalls.generateToken(sessionId, authToken).then( - (callToken) => { + (callToken: any) => { // Step 2: Configure call settings const callListener = new CometChatCalls.OngoingCallListener({ onCallEnded: () => { @@ -385,12 +385,12 @@ CometChatCalls.generateToken(sessionId, authToken).then( CometChatCalls.endSession(); // Close calling screen }, - (error) => console.log("End call failed:", error) + (error: CometChat.CometChatException) => console.log("End call failed:", error) ); }, - onUserJoined: (user) => console.log("User joined:", user), - onUserLeft: (user) => console.log("User left:", user), - onError: (error) => console.log("Call error:", error) + onUserJoined: (user: any) => console.log("User joined:", user), + onUserLeft: (user: any) => console.log("User left:", user), + onError: (error: any) => console.log("Call error:", error) }); const callSettings = new CometChatCalls.CallSettingsBuilder() @@ -400,24 +400,24 @@ CometChatCalls.generateToken(sessionId, authToken).then( .build(); // Step 3: Start the session - const htmlElement = document.getElementById("call-container"); + const htmlElement = document.getElementById("call-container") as HTMLElement; CometChatCalls.startSession(callToken, callSettings, htmlElement); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Token generation failed:", error); } ); ``` - -```typescript -const sessionId: string = call.getSessionId(); + +```javascript +const sessionId = call.getSessionId(); const loggedInUser = await CometChat.getLoggedinUser(); -const authToken: string = loggedInUser.getAuthToken(); +const authToken = loggedInUser.getAuthToken(); // Step 1: Generate call token CometChatCalls.generateToken(sessionId, authToken).then( - (callToken: any) => { + (callToken) => { // Step 2: Configure call settings const callListener = new CometChatCalls.OngoingCallListener({ onCallEnded: () => { @@ -432,12 +432,12 @@ CometChatCalls.generateToken(sessionId, authToken).then( CometChatCalls.endSession(); // Close calling screen }, - (error: CometChat.CometChatException) => console.log("End call failed:", error) + (error) => console.log("End call failed:", error) ); }, - onUserJoined: (user: any) => console.log("User joined:", user), - onUserLeft: (user: any) => console.log("User left:", user), - onError: (error: any) => console.log("Call error:", error) + onUserJoined: (user) => console.log("User joined:", user), + onUserLeft: (user) => console.log("User left:", user), + onError: (error) => console.log("Call error:", error) }); const callSettings = new CometChatCalls.CallSettingsBuilder() @@ -447,10 +447,10 @@ CometChatCalls.generateToken(sessionId, authToken).then( .build(); // Step 3: Start the session - const htmlElement = document.getElementById("call-container") as HTMLElement; + const htmlElement = document.getElementById("call-container"); CometChatCalls.startSession(callToken, callSettings, htmlElement); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Token generation failed:", error); } ); @@ -469,34 +469,34 @@ To end an active call in the ringing flow, the process differs based on who ends When the user clicks the end call button, the `onCallEndButtonPressed()` callback is triggered. Inside this callback, call `CometChat.endCall()` to notify other participants. On success, call `CometChat.clearActiveCall()` and `CometChatCalls.endSession()` to release resources. - -```javascript + +```typescript onCallEndButtonPressed: () => { CometChat.endCall(sessionId).then( - (call) => { + (call: CometChat.Call) => { console.log("Call ended successfully"); CometChat.clearActiveCall(); CometChatCalls.endSession(); // Close the calling screen }, - (error) => { + (error: CometChat.CometChatException) => { console.log("End call failed:", error); } ); } ``` - -```typescript + +```javascript onCallEndButtonPressed: () => { CometChat.endCall(sessionId).then( - (call: CometChat.Call) => { + (call) => { console.log("Call ended successfully"); CometChat.clearActiveCall(); CometChatCalls.endSession(); // Close the calling screen }, - (error: CometChat.CometChatException) => { + (error) => { console.log("End call failed:", error); } ); @@ -508,8 +508,8 @@ onCallEndButtonPressed: () => { **Remote participant** (receives `onCallEnded()` callback): - -```javascript + +```typescript onCallEnded: () => { CometChat.clearActiveCall(); CometChatCalls.endSession(); @@ -517,8 +517,8 @@ onCallEnded: () => { } ``` - -```typescript + +```javascript onCallEnded: () => { CometChat.clearActiveCall(); CometChatCalls.endSession(); @@ -535,31 +535,31 @@ For more details, see the [End Call Session](/sdk/javascript/direct-call#end-cal If the receiver is already on another call, you can reject the incoming call with `CALL_STATUS_BUSY` status. - -```javascript -const sessionId = call.getSessionId(); -const status = CometChat.CALL_STATUS.BUSY; + +```typescript +const sessionId: string = call.getSessionId(); +const status: string = CometChat.CALL_STATUS.BUSY; CometChat.rejectCall(sessionId, status).then( - (call) => { + (call: CometChat.Call) => { console.log("Busy status sent:", call); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Busy rejection failed:", error); } ); ``` - -```typescript -const sessionId: string = call.getSessionId(); -const status: string = CometChat.CALL_STATUS.BUSY; + +```javascript +const sessionId = call.getSessionId(); +const status = CometChat.CALL_STATUS.BUSY; CometChat.rejectCall(sessionId, status).then( - (call: CometChat.Call) => { + (call) => { console.log("Busy status sent:", call); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Busy rejection failed:", error); } ); diff --git a/sdk/javascript/delete-group.mdx b/sdk/javascript/delete-group.mdx index 643324371..b2b25382d 100644 --- a/sdk/javascript/delete-group.mdx +++ b/sdk/javascript/delete-group.mdx @@ -24,21 +24,6 @@ This operation is irreversible. Deleted groups and their messages cannot be reco Use `deleteGroup()` to permanently delete a group. Only group admins can perform this operation. - -```javascript -const GUID = "GUID"; - -CometChat.deleteGroup(GUID).then( -response => { - console.log("Groups deleted successfully:", response); -}, error => { - console.log("Group delete failed with exception:", error); -} -); -``` - - - ```typescript const GUID: string = "GUID"; @@ -54,6 +39,21 @@ CometChat.deleteGroup(GUID).then( + +```javascript +const GUID = "GUID"; + +CometChat.deleteGroup(GUID).then( +response => { + console.log("Groups deleted successfully:", response); +}, error => { + console.log("Group delete failed with exception:", error); +} +); +``` + + + ```javascript const GUID = "GUID"; diff --git a/sdk/javascript/delete-message.mdx b/sdk/javascript/delete-message.mdx index 12757717c..2e9780c40 100644 --- a/sdk/javascript/delete-message.mdx +++ b/sdk/javascript/delete-message.mdx @@ -37,21 +37,6 @@ Deleting a message is straightforward. Receiving delete events has two parts: Use `deleteMessage()` with the message ID. - -```javascript -let messageId = "ID_OF_THE_MESSAGE_YOU_WANT_TO_DELETE"; - -CometChat.deleteMessage(messageId).then( -message => { - console.log("Message deleted", message); -}, error => { - console.log("Message delete failed with error:", error); -} -); -``` - - - ```typescript let messageId: number = 1; @@ -67,6 +52,21 @@ CometChat.deleteMessage(messageId).then( + +```javascript +let messageId = "ID_OF_THE_MESSAGE_YOU_WANT_TO_DELETE"; + +CometChat.deleteMessage(messageId).then( +message => { + console.log("Message deleted", message); +}, error => { + console.log("Message delete failed with error:", error); +} +); +``` + + + ```javascript let messageId = "ID_OF_THE_MESSAGE_YOU_WANT_TO_DELETE"; diff --git a/sdk/javascript/delivery-read-receipts.mdx b/sdk/javascript/delivery-read-receipts.mdx index 3d42ec12d..fc5f9c78d 100644 --- a/sdk/javascript/delivery-read-receipts.mdx +++ b/sdk/javascript/delivery-read-receipts.mdx @@ -42,25 +42,25 @@ Use `markAsDelivered()` to mark messages as delivered. You can pass either a mes ### Using Message Object - -```javascript + +```typescript CometChat.markAsDelivered(message).then( () => { console.log("Marked as delivered successfully"); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Error marking as delivered:", error); } ); ``` - -```typescript + +```javascript CometChat.markAsDelivered(message).then( () => { console.log("Marked as delivered successfully"); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Error marking as delivered:", error); } ); @@ -222,25 +222,25 @@ Use `markAsRead()` to mark messages as read. You can pass either a message objec ### Using Message Object - -```javascript + +```typescript CometChat.markAsRead(message).then( () => { console.log("Marked as read successfully"); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Error marking as read:", error); } ); ``` - -```typescript + +```javascript CometChat.markAsRead(message).then( () => { console.log("Marked as read successfully"); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Error marking as read:", error); } ); @@ -397,27 +397,27 @@ You cannot mark your own messages as unread. This method only works for messages
- -```javascript + +```typescript CometChat.markMessageAsUnread(message).then( - (conversation) => { + (conversation: CometChat.Conversation) => { console.log("Marked as unread successfully", conversation); console.log("Unread count:", conversation.getUnreadMessageCount()); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Error marking as unread:", error); } ); ``` - -```typescript + +```javascript CometChat.markMessageAsUnread(message).then( - (conversation: CometChat.Conversation) => { + (conversation) => { console.log("Marked as unread successfully", conversation); console.log("Unread count:", conversation.getUnreadMessageCount()); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Error marking as unread:", error); } ); @@ -439,46 +439,46 @@ Register a `MessageListener` to receive delivery and read receipt events. | `onMessagesReadByAll` | Group message read by all members | - -```javascript -let listenerID = "UNIQUE_LISTENER_ID"; + +```typescript +let listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onMessagesDelivered: (messageReceipt) => { + onMessagesDelivered: (messageReceipt: CometChat.MessageReceipt) => { console.log("Message delivered:", messageReceipt); }, - onMessagesRead: (messageReceipt) => { + onMessagesRead: (messageReceipt: CometChat.MessageReceipt) => { console.log("Message read:", messageReceipt); }, - onMessagesDeliveredToAll: (messageReceipt) => { + onMessagesDeliveredToAll: (messageReceipt: CometChat.MessageReceipt) => { console.log("Message delivered to all group members:", messageReceipt); }, - onMessagesReadByAll: (messageReceipt) => { + onMessagesReadByAll: (messageReceipt: CometChat.MessageReceipt) => { console.log("Message read by all group members:", messageReceipt); } }) ); ``` - -```typescript -let listenerID: string = "UNIQUE_LISTENER_ID"; + +```javascript +let listenerID = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onMessagesDelivered: (messageReceipt: CometChat.MessageReceipt) => { + onMessagesDelivered: (messageReceipt) => { console.log("Message delivered:", messageReceipt); }, - onMessagesRead: (messageReceipt: CometChat.MessageReceipt) => { + onMessagesRead: (messageReceipt) => { console.log("Message read:", messageReceipt); }, - onMessagesDeliveredToAll: (messageReceipt: CometChat.MessageReceipt) => { + onMessagesDeliveredToAll: (messageReceipt) => { console.log("Message delivered to all group members:", messageReceipt); }, - onMessagesReadByAll: (messageReceipt: CometChat.MessageReceipt) => { + onMessagesReadByAll: (messageReceipt) => { console.log("Message read by all group members:", messageReceipt); } }) @@ -514,29 +514,29 @@ The listener callbacks receive a [`MessageReceipt`](/sdk/reference/auxiliary#mes 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 = 123; + +```typescript +let messageId: number = 123; CometChat.getMessageReceipts(messageId).then( - (receipts) => { + (receipts: CometChat.MessageReceipt[]) => { console.log("Message receipts:", receipts); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Error fetching receipts:", error); } ); ``` - -```typescript -let messageId: number = 123; + +```javascript +let messageId = 123; CometChat.getMessageReceipts(messageId).then( - (receipts: CometChat.MessageReceipt[]) => { + (receipts) => { console.log("Message receipts:", receipts); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Error fetching receipts:", error); } ); diff --git a/sdk/javascript/direct-call.mdx b/sdk/javascript/direct-call.mdx index 110a9d887..dcaa9aec5 100644 --- a/sdk/javascript/direct-call.mdx +++ b/sdk/javascript/direct-call.mdx @@ -47,35 +47,35 @@ You can generate the token just before starting the call, or generate and store Use the `generateToken()` method to create a call token: - -```javascript + +```typescript const loggedInUser = await CometChat.getLoggedinUser(); const authToken = loggedInUser.getAuthToken(); -const sessionId = "SESSION_ID"; // Random or from Call object in ringing flow +const sessionId: string = "SESSION_ID"; // Random or from Call object in ringing flow CometChatCalls.generateToken(sessionId, authToken).then( - (callToken) => { + (callToken: any) => { console.log("Call token generated:", callToken.token); // Use callToken to start the session }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Token generation failed:", error); } ); ``` - -```typescript + +```javascript const loggedInUser = await CometChat.getLoggedinUser(); const authToken = loggedInUser.getAuthToken(); -const sessionId: string = "SESSION_ID"; // Random or from Call object in ringing flow +const sessionId = "SESSION_ID"; // Random or from Call object in ringing flow CometChatCalls.generateToken(sessionId, authToken).then( - (callToken: any) => { + (callToken) => { console.log("Call token generated:", callToken.token); // Use callToken to start the session }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Token generation failed:", error); } ); @@ -96,16 +96,16 @@ Use the `startSession()` method to join a call session. This method requires: 3. An HTML element where the call UI will be rendered - -```javascript + +```typescript const callListener = new CometChatCalls.OngoingCallListener({ - onUserJoined: (user) => { + onUserJoined: (user: any) => { console.log("User joined:", user); }, - onUserLeft: (user) => { + onUserLeft: (user: any) => { console.log("User left:", user); }, - onUserListUpdated: (userList) => { + onUserListUpdated: (userList: any[]) => { console.log("User list updated:", userList); }, onCallEnded: () => { @@ -115,13 +115,13 @@ const callListener = new CometChatCalls.OngoingCallListener({ console.log("End call button pressed"); // Handle end call - see End Call Session section }, - onError: (error) => { + onError: (error: any) => { console.log("Call error:", error); }, - onMediaDeviceListUpdated: (deviceList) => { + onMediaDeviceListUpdated: (deviceList: any[]) => { console.log("Device list updated:", deviceList); }, - onUserMuted: (event) => { + onUserMuted: (event: any) => { console.log("User muted:", event); }, onScreenShareStarted: () => { @@ -130,7 +130,7 @@ const callListener = new CometChatCalls.OngoingCallListener({ onScreenShareStopped: () => { console.log("Screen sharing stopped"); }, - onCallSwitchedToVideo: (event) => { + onCallSwitchedToVideo: (event: any) => { console.log("Call switched to video:", event); }, onSessionTimeout: () => { @@ -144,20 +144,20 @@ const callSettings = new CometChatCalls.CallSettingsBuilder() .setCallListener(callListener) .build(); -const htmlElement = document.getElementById("call-container"); +const htmlElement = document.getElementById("call-container") as HTMLElement; CometChatCalls.startSession(callToken, callSettings, htmlElement); ``` - -```typescript + +```javascript const callListener = new CometChatCalls.OngoingCallListener({ - onUserJoined: (user: any) => { + onUserJoined: (user) => { console.log("User joined:", user); }, - onUserLeft: (user: any) => { + onUserLeft: (user) => { console.log("User left:", user); }, - onUserListUpdated: (userList: any[]) => { + onUserListUpdated: (userList) => { console.log("User list updated:", userList); }, onCallEnded: () => { @@ -167,13 +167,13 @@ const callListener = new CometChatCalls.OngoingCallListener({ console.log("End call button pressed"); // Handle end call - see End Call Session section }, - onError: (error: any) => { + onError: (error) => { console.log("Call error:", error); }, - onMediaDeviceListUpdated: (deviceList: any[]) => { + onMediaDeviceListUpdated: (deviceList) => { console.log("Device list updated:", deviceList); }, - onUserMuted: (event: any) => { + onUserMuted: (event) => { console.log("User muted:", event); }, onScreenShareStarted: () => { @@ -182,7 +182,7 @@ const callListener = new CometChatCalls.OngoingCallListener({ onScreenShareStopped: () => { console.log("Screen sharing stopped"); }, - onCallSwitchedToVideo: (event: any) => { + onCallSwitchedToVideo: (event) => { console.log("Call switched to video:", event); }, onSessionTimeout: () => { @@ -196,7 +196,7 @@ const callSettings = new CometChatCalls.CallSettingsBuilder() .setCallListener(callListener) .build(); -const htmlElement = document.getElementById("call-container") as HTMLElement; +const htmlElement = document.getElementById("call-container"); CometChatCalls.startSession(callToken, callSettings, htmlElement); ``` @@ -243,18 +243,18 @@ Each listener requires a unique `listenerId` string. This ID is used to: - **Enable targeted removal** — Remove specific listeners without affecting others - -```javascript -const listenerId = "UNIQUE_LISTENER_ID"; + +```typescript +const listenerId: string = "UNIQUE_LISTENER_ID"; CometChatCalls.addCallEventListener(listenerId, { - onUserJoined: (user) => { + onUserJoined: (user: any) => { console.log("User joined:", user); }, - onUserLeft: (user) => { + onUserLeft: (user: any) => { console.log("User left:", user); }, - onUserListUpdated: (userList) => { + onUserListUpdated: (userList: any[]) => { console.log("User list updated:", userList); }, onCallEnded: () => { @@ -263,13 +263,13 @@ CometChatCalls.addCallEventListener(listenerId, { onCallEndButtonPressed: () => { console.log("End call button pressed"); }, - onError: (error) => { + onError: (error: any) => { console.log("Call error:", error); }, - onMediaDeviceListUpdated: (deviceList) => { + onMediaDeviceListUpdated: (deviceList: any[]) => { console.log("Device list updated:", deviceList); }, - onUserMuted: (event) => { + onUserMuted: (event: any) => { console.log("User muted:", event); }, onScreenShareStarted: () => { @@ -278,7 +278,7 @@ CometChatCalls.addCallEventListener(listenerId, { onScreenShareStopped: () => { console.log("Screen sharing stopped"); }, - onCallSwitchedToVideo: (event) => { + onCallSwitchedToVideo: (event: any) => { console.log("Call switched to video:", event); }, onSessionTimeout: () => { @@ -290,18 +290,18 @@ CometChatCalls.addCallEventListener(listenerId, { CometChatCalls.removeCallEventListener(listenerId); ``` - -```typescript -const listenerId: string = "UNIQUE_LISTENER_ID"; + +```javascript +const listenerId = "UNIQUE_LISTENER_ID"; CometChatCalls.addCallEventListener(listenerId, { - onUserJoined: (user: any) => { + onUserJoined: (user) => { console.log("User joined:", user); }, - onUserLeft: (user: any) => { + onUserLeft: (user) => { console.log("User left:", user); }, - onUserListUpdated: (userList: any[]) => { + onUserListUpdated: (userList) => { console.log("User list updated:", userList); }, onCallEnded: () => { @@ -310,13 +310,13 @@ CometChatCalls.addCallEventListener(listenerId, { onCallEndButtonPressed: () => { console.log("End call button pressed"); }, - onError: (error: any) => { + onError: (error) => { console.log("Call error:", error); }, - onMediaDeviceListUpdated: (deviceList: any[]) => { + onMediaDeviceListUpdated: (deviceList) => { console.log("Device list updated:", deviceList); }, - onUserMuted: (event: any) => { + onUserMuted: (event) => { console.log("User muted:", event); }, onScreenShareStarted: () => { @@ -325,7 +325,7 @@ CometChatCalls.addCallEventListener(listenerId, { onScreenShareStopped: () => { console.log("Screen sharing stopped"); }, - onCallSwitchedToVideo: (event: any) => { + onCallSwitchedToVideo: (event) => { console.log("Call switched to video:", event); }, onSessionTimeout: () => { @@ -389,34 +389,34 @@ The Ringing flow requires calling methods from both the Chat SDK (`CometChat.end When the user clicks the end call button in the UI, the `onCallEndButtonPressed()` callback is triggered. You must call `CometChat.endCall()` inside this callback to properly terminate the call and notify other participants. On success, call `CometChat.clearActiveCall()` and `CometChatCalls.endSession()` to release resources. - -```javascript + +```typescript onCallEndButtonPressed: () => { CometChat.endCall(sessionId).then( - (call) => { + (call: CometChat.Call) => { console.log("Call ended successfully"); CometChat.clearActiveCall(); CometChatCalls.endSession(); // Close the calling screen }, - (error) => { + (error: CometChat.CometChatException) => { console.log("End call failed:", error); } ); } ``` - -```typescript + +```javascript onCallEndButtonPressed: () => { CometChat.endCall(sessionId).then( - (call: CometChat.Call) => { + (call) => { console.log("Call ended successfully"); CometChat.clearActiveCall(); CometChatCalls.endSession(); // Close the calling screen }, - (error: CometChat.CometChatException) => { + (error) => { console.log("End call failed:", error); } ); @@ -430,8 +430,8 @@ onCallEndButtonPressed: () => { Call `CometChat.clearActiveCall()` to clear the local call state, then call `CometChatCalls.endSession()` to release media resources. - -```javascript + +```typescript onCallEnded: () => { CometChat.clearActiveCall(); CometChatCalls.endSession(); @@ -439,8 +439,8 @@ onCallEnded: () => { } ``` - -```typescript + +```javascript onCallEnded: () => { CometChat.clearActiveCall(); CometChatCalls.endSession(); @@ -457,16 +457,16 @@ When using the Session Only flow (direct call without ringing), you only need to Call `CometChatCalls.endSession()` in the `onCallEndButtonPressed()` callback to release all media resources and disconnect from the call session. - -```javascript + +```typescript onCallEndButtonPressed: () => { CometChatCalls.endSession(); // Close the calling screen } ``` - -```typescript + +```javascript onCallEndButtonPressed: () => { CometChatCalls.endSession(); // Close the calling screen @@ -488,13 +488,13 @@ These methods can only be called when a call session is active. Toggles between the front and rear camera during a video call. Only supported on mobile browsers. - -```javascript + +```typescript CometChatCalls.switchCamera(); ``` - -```typescript + +```javascript CometChatCalls.switchCamera(); ``` @@ -512,13 +512,13 @@ Controls the local audio stream transmission. When muted, other participants can - `false` — Unmutes the microphone, resumes audio transmission - -```javascript + +```typescript CometChatCalls.muteAudio(true); ``` - -```typescript + +```javascript CometChatCalls.muteAudio(true); ``` @@ -532,13 +532,13 @@ Controls the local video stream transmission. When paused, other participants se - `false` — Resumes the camera, continues video transmission - -```javascript + +```typescript CometChatCalls.pauseVideo(true); ``` - -```typescript + +```javascript CometChatCalls.pauseVideo(true); ``` @@ -549,13 +549,13 @@ CometChatCalls.pauseVideo(true); Starts sharing your screen or a specific application window with other participants. - -```javascript + +```typescript CometChatCalls.startScreenShare(); ``` - -```typescript + +```javascript CometChatCalls.startScreenShare(); ``` @@ -566,13 +566,13 @@ CometChatCalls.startScreenShare(); Stops the current screen sharing session. - -```javascript + +```typescript CometChatCalls.stopScreenShare(); ``` - -```typescript + +```javascript CometChatCalls.stopScreenShare(); ``` @@ -587,13 +587,13 @@ Changes the call UI layout mode dynamically during the call. - `CometChat.CALL_MODE.SPOTLIGHT` — Focus on the active speaker - -```javascript + +```typescript CometChatCalls.setMode(CometChat.CALL_MODE.SPOTLIGHT); ``` - -```typescript + +```javascript CometChatCalls.setMode(CometChat.CALL_MODE.SPOTLIGHT); ``` @@ -604,14 +604,14 @@ CometChatCalls.setMode(CometChat.CALL_MODE.SPOTLIGHT); Returns a list of available audio input devices (microphones). - -```javascript + +```typescript const audioInputDevices = CometChatCalls.getAudioInputDevices(); console.log("Available microphones:", audioInputDevices); ``` - -```typescript + +```javascript const audioInputDevices = CometChatCalls.getAudioInputDevices(); console.log("Available microphones:", audioInputDevices); ``` @@ -623,14 +623,14 @@ console.log("Available microphones:", audioInputDevices); Returns a list of available audio output devices (speakers/headphones). - -```javascript + +```typescript const audioOutputDevices = CometChatCalls.getAudioOutputDevices(); console.log("Available speakers:", audioOutputDevices); ``` - -```typescript + +```javascript const audioOutputDevices = CometChatCalls.getAudioOutputDevices(); console.log("Available speakers:", audioOutputDevices); ``` @@ -642,14 +642,14 @@ console.log("Available speakers:", audioOutputDevices); Returns a list of available video input devices (cameras). - -```javascript + +```typescript const videoInputDevices = CometChatCalls.getVideoInputDevices(); console.log("Available cameras:", videoInputDevices); ``` - -```typescript + +```javascript const videoInputDevices = CometChatCalls.getVideoInputDevices(); console.log("Available cameras:", videoInputDevices); ``` @@ -661,13 +661,13 @@ console.log("Available cameras:", videoInputDevices); Sets the active audio input device (microphone) by device ID. - -```javascript + +```typescript CometChatCalls.setAudioInputDevice(deviceId); ``` - -```typescript + +```javascript CometChatCalls.setAudioInputDevice(deviceId); ``` @@ -678,13 +678,13 @@ CometChatCalls.setAudioInputDevice(deviceId); Sets the active audio output device (speaker/headphones) by device ID. - -```javascript + +```typescript CometChatCalls.setAudioOutputDevice(deviceId); ``` - -```typescript + +```javascript CometChatCalls.setAudioOutputDevice(deviceId); ``` @@ -695,13 +695,13 @@ CometChatCalls.setAudioOutputDevice(deviceId); Sets the active video input device (camera) by device ID. - -```javascript + +```typescript CometChatCalls.setVideoInputDevice(deviceId); ``` - -```typescript + +```javascript CometChatCalls.setVideoInputDevice(deviceId); ``` @@ -712,13 +712,13 @@ CometChatCalls.setVideoInputDevice(deviceId); Upgrades an ongoing audio call to a video call. This enables the camera and starts transmitting video to other participants. The remote participant receives the `onCallSwitchedToVideo()` callback. - -```javascript + +```typescript CometChatCalls.switchToVideoCall(); ``` - -```typescript + +```javascript CometChatCalls.switchToVideoCall(); ``` diff --git a/sdk/javascript/flag-message.mdx b/sdk/javascript/flag-message.mdx index 3e310ff16..959dd8c41 100644 --- a/sdk/javascript/flag-message.mdx +++ b/sdk/javascript/flag-message.mdx @@ -61,29 +61,29 @@ sequenceDiagram Before flagging a message, retrieve the list of available flag reasons configured in your Dashboard: - - ```javascript + + ```typescript CometChat.getFlagReasons().then( - (reasons) => { + (reasons: CometChat.FlagReason[]) => { console.log("Flag reasons retrieved:", reasons); // reasons is an array of { id, reason } objects // Use these to populate your report dialog UI }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Failed to get flag reasons:", error); } ); ``` - - ```typescript + + ```javascript CometChat.getFlagReasons().then( - (reasons: CometChat.FlagReason[]) => { + (reasons) => { console.log("Flag reasons retrieved:", reasons); // reasons is an array of { id, reason } objects // Use these to populate your report dialog UI }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Failed to get flag reasons:", error); } ); @@ -111,37 +111,37 @@ The response is an array of flag reason objects: To flag a message, use the `flagMessage()` method with the message ID and a payload containing the reason: - - ```javascript - const messageId = "MESSAGE_ID_TO_FLAG"; - const payload = { - reasonId: "spam", // Required: ID from getFlagReasons() - remark: "This message contains promotional content" // Optional + + ```typescript + const messageId: string = "MESSAGE_ID_TO_FLAG"; + const payload: { reasonId: string; remark?: string } = { + reasonId: "spam", + remark: "This message contains promotional content" }; CometChat.flagMessage(messageId, payload).then( - (response) => { + (response: CometChat.FlagMessageResponse) => { console.log("Message flagged successfully:", response); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Message flagging failed:", error); } ); ``` - - ```typescript - const messageId: string = "MESSAGE_ID_TO_FLAG"; - const payload: { reasonId: string; remark?: string } = { - reasonId: "spam", - remark: "This message contains promotional content" + + ```javascript + const messageId = "MESSAGE_ID_TO_FLAG"; + const payload = { + reasonId: "spam", // Required: ID from getFlagReasons() + remark: "This message contains promotional content" // Optional }; CometChat.flagMessage(messageId, payload).then( - (response: CometChat.FlagMessageResponse) => { + (response) => { console.log("Message flagged successfully:", response); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Message flagging failed:", error); } ); diff --git a/sdk/javascript/initialization.mdx b/sdk/javascript/initialization.mdx index bc918d41a..f66032036 100644 --- a/sdk/javascript/initialization.mdx +++ b/sdk/javascript/initialization.mdx @@ -8,22 +8,22 @@ The `init()` method initializes the SDK and must be called before any other Come ## Basic Initialization - -```javascript -let appID = "APP_ID"; -let region = "APP_REGION"; + +```typescript +let appID: string = "APP_ID"; +let region: string = "APP_REGION"; -let appSetting = new CometChat.AppSettingsBuilder() +let appSetting: CometChat.AppSettings = new CometChat.AppSettingsBuilder() .subscribePresenceForAllUsers() .setRegion(region) .autoEstablishSocketConnection(true) .build(); CometChat.init(appID, appSetting).then( - () => { - console.log("Initialization completed successfully"); + (initialized: boolean) => { + console.log("Initialization completed successfully", initialized); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Initialization failed with error:", error); } ); @@ -31,22 +31,22 @@ CometChat.init(appID, appSetting).then( - -```typescript -let appID: string = "APP_ID"; -let region: string = "APP_REGION"; + +```javascript +let appID = "APP_ID"; +let region = "APP_REGION"; -let appSetting: CometChat.AppSettings = new CometChat.AppSettingsBuilder() +let appSetting = new CometChat.AppSettingsBuilder() .subscribePresenceForAllUsers() .setRegion(region) .autoEstablishSocketConnection(true) .build(); CometChat.init(appID, appSetting).then( - (initialized: boolean) => { - console.log("Initialization completed successfully", initialized); + () => { + console.log("Initialization completed successfully"); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Initialization failed with error:", error); } ); diff --git a/sdk/javascript/interactive-messages.mdx b/sdk/javascript/interactive-messages.mdx index db180414d..3570fb421 100644 --- a/sdk/javascript/interactive-messages.mdx +++ b/sdk/javascript/interactive-messages.mdx @@ -50,12 +50,12 @@ The [`InteractiveMessage`](/sdk/reference/messages#interactivemessage) class rep Use `sendInteractiveMessage()` to send an interactive message. - -```javascript -let receiverId = "UID"; -let receiverType = CometChat.RECEIVER_TYPE.USER; + +```typescript +let receiverId: string = "UID"; +let receiverType: string = CometChat.RECEIVER_TYPE.USER; -let interactiveData = { +let interactiveData: Object = { title: "Survey", formFields: [ { @@ -109,7 +109,7 @@ let interactiveData = { } }; -let interactiveMessage = new CometChat.InteractiveMessage( +let interactiveMessage: CometChat.InteractiveMessage = new CometChat.InteractiveMessage( receiverId, receiverType, "form", @@ -117,21 +117,21 @@ let interactiveMessage = new CometChat.InteractiveMessage( ); CometChat.sendInteractiveMessage(interactiveMessage).then( - (message) => { + (message: CometChat.InteractiveMessage) => { console.log("Interactive message sent successfully", message); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Interactive message sending failed with error:", error); } ); ``` - -```typescript -let receiverId: string = "UID"; -let receiverType: string = CometChat.RECEIVER_TYPE.USER; + +```javascript +let receiverId = "UID"; +let receiverType = CometChat.RECEIVER_TYPE.USER; -let interactiveData: Object = { +let interactiveData = { title: "Survey", formFields: [ { @@ -185,7 +185,7 @@ let interactiveData: Object = { } }; -let interactiveMessage: CometChat.InteractiveMessage = new CometChat.InteractiveMessage( +let interactiveMessage = new CometChat.InteractiveMessage( receiverId, receiverType, "form", @@ -193,10 +193,10 @@ let interactiveMessage: CometChat.InteractiveMessage = new CometChat.Interactive ); CometChat.sendInteractiveMessage(interactiveMessage).then( - (message: CometChat.InteractiveMessage) => { + (message) => { console.log("Interactive message sent successfully", message); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Interactive message sending failed with error:", error); } ); @@ -300,15 +300,15 @@ An `InteractionGoal` defines when the user's interaction with the message is con ### Set an Interaction Goal - -```javascript -let elementIds = ["name", "gender", "submitButton"]; -let interactionGoal = new CometChat.InteractionGoal( + +```typescript +let elementIds: Array = ["name", "gender", "submitButton"]; +let interactionGoal: CometChat.InteractionGoal = new CometChat.InteractionGoal( CometChat.GoalType.ALL_OF, elementIds ); -let interactiveMessage = new CometChat.InteractiveMessage( +let interactiveMessage: CometChat.InteractiveMessage = new CometChat.InteractiveMessage( receiverId, receiverType, "form", @@ -317,24 +317,24 @@ let interactiveMessage = new CometChat.InteractiveMessage( interactiveMessage.setInteractionGoal(interactionGoal); CometChat.sendInteractiveMessage(interactiveMessage).then( - (message) => { + (message: CometChat.InteractiveMessage) => { console.log("Interactive message sent successfully", message); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Interactive message sending failed with error:", error); } ); ``` - -```typescript -let elementIds: Array = ["name", "gender", "submitButton"]; -let interactionGoal: CometChat.InteractionGoal = new CometChat.InteractionGoal( + +```javascript +let elementIds = ["name", "gender", "submitButton"]; +let interactionGoal = new CometChat.InteractionGoal( CometChat.GoalType.ALL_OF, elementIds ); -let interactiveMessage: CometChat.InteractiveMessage = new CometChat.InteractiveMessage( +let interactiveMessage = new CometChat.InteractiveMessage( receiverId, receiverType, "form", @@ -343,10 +343,10 @@ let interactiveMessage: CometChat.InteractiveMessage = new CometChat.Interactive interactiveMessage.setInteractionGoal(interactionGoal); CometChat.sendInteractiveMessage(interactiveMessage).then( - (message: CometChat.InteractiveMessage) => { + (message) => { console.log("Interactive message sent successfully", message); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Interactive message sending failed with error:", error); } ); @@ -368,31 +368,31 @@ An `Interaction` represents a single user action on an interactive element. Use `markAsInteracted()` to record when a user interacts with an element. - -```javascript -let messageId = 123; -let elementId = "submitButton"; + +```typescript +let messageId: number = 123; +let elementId: string = "submitButton"; CometChat.markAsInteracted(messageId, elementId).then( - (response) => { + (response: string) => { console.log("Marked as interacted successfully", response); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Failed to mark as interacted:", error); } ); ``` - -```typescript -let messageId: number = 123; -let elementId: string = "submitButton"; + +```javascript +let messageId = 123; +let elementId = "submitButton"; CometChat.markAsInteracted(messageId, elementId).then( - (response: string) => { + (response) => { console.log("Marked as interacted successfully", response); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Failed to mark as interacted:", error); } ); @@ -407,14 +407,14 @@ Register a `MessageListener` to receive interactive message events. ### Receive Interactive Messages - -```javascript -let listenerID = "UNIQUE_LISTENER_ID"; + +```typescript +let listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onInteractiveMessageReceived: (message) => { + onInteractiveMessageReceived: (message: CometChat.InteractiveMessage) => { console.log("Interactive message received", message); // Render the interactive UI based on message.getInteractiveData() } @@ -422,14 +422,14 @@ CometChat.addMessageListener( ); ``` - -```typescript -let listenerID: string = "UNIQUE_LISTENER_ID"; + +```javascript +let listenerID = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onInteractiveMessageReceived: (message: CometChat.InteractiveMessage) => { + onInteractiveMessageReceived: (message) => { console.log("Interactive message received", message); // Render the interactive UI based on message.getInteractiveData() } @@ -444,14 +444,14 @@ CometChat.addMessageListener( Triggered when a user's interactions satisfy the defined `InteractionGoal`. - -```javascript -let listenerID = "UNIQUE_LISTENER_ID"; + +```typescript +let listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onInteractionGoalCompleted: (receipt) => { + onInteractionGoalCompleted: (receipt: CometChat.InteractionReceipt) => { console.log("Interaction goal completed", receipt); // Handle goal completion (e.g., show confirmation, trigger next step) } @@ -459,14 +459,14 @@ CometChat.addMessageListener( ); ``` - -```typescript -let listenerID: string = "UNIQUE_LISTENER_ID"; + +```javascript +let listenerID = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onInteractionGoalCompleted: (receipt: CometChat.InteractionReceipt) => { + onInteractionGoalCompleted: (receipt) => { console.log("Interaction goal completed", receipt); // Handle goal completion (e.g., show confirmation, trigger next step) } @@ -489,9 +489,9 @@ CometChat.removeMessageListener("UNIQUE_LISTENER_ID"); By default, the sender cannot interact with their own interactive message. Enable sender interaction: - -```javascript -let interactiveMessage = new CometChat.InteractiveMessage( + +```typescript +let interactiveMessage: CometChat.InteractiveMessage = new CometChat.InteractiveMessage( receiverId, receiverType, "form", @@ -500,18 +500,18 @@ let interactiveMessage = new CometChat.InteractiveMessage( interactiveMessage.setIsSenderInteractionAllowed(true); CometChat.sendInteractiveMessage(interactiveMessage).then( - (message) => { + (message: CometChat.InteractiveMessage) => { console.log("Interactive message sent successfully", message); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Interactive message sending failed with error:", error); } ); ``` - -```typescript -let interactiveMessage: CometChat.InteractiveMessage = new CometChat.InteractiveMessage( + +```javascript +let interactiveMessage = new CometChat.InteractiveMessage( receiverId, receiverType, "form", @@ -520,10 +520,10 @@ let interactiveMessage: CometChat.InteractiveMessage = new CometChat.Interactive interactiveMessage.setIsSenderInteractionAllowed(true); CometChat.sendInteractiveMessage(interactiveMessage).then( - (message: CometChat.InteractiveMessage) => { + (message) => { console.log("Interactive message sent successfully", message); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Interactive message sending failed with error:", error); } ); diff --git a/sdk/javascript/login-listener.mdx b/sdk/javascript/login-listener.mdx index 5a103fd20..47dbcaf45 100644 --- a/sdk/javascript/login-listener.mdx +++ b/sdk/javascript/login-listener.mdx @@ -32,23 +32,23 @@ The CometChat SDK provides you with real-time updates for the `login` and `logou To add the `LoginListener`, you need to use the `addLoginListener()` method provided by the SDK which takes a unique identifier for the listener and of the the `LoginListener` class itself. - -```js - let listenerID = "UNIQUE_LISTENER_ID"; + +```typescript + const listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addLoginListener( listenerID, new CometChat.LoginListener({ - loginSuccess: (e) => { - console.log("LoginListener :: loginSuccess", e); + loginSuccess: (user: CometChat.User) => { + console.log("LoginListener :: loginSuccess", user); }, - loginFailure: (e) => { - console.log("LoginListener :: loginFailure", e); + loginFailure: (error: CometChat.CometChatException) => { + console.log("LoginListener :: loginFailure", error); }, logoutSuccess: () => { console.log("LoginListener :: logoutSuccess"); }, - logoutFailure: (e) => { - console.log("LoginListener :: logoutFailure", e); + logoutFailure: (error: CometChat.CometChatException) => { + console.log("LoginListener :: logoutFailure", error); } }) ); @@ -56,23 +56,23 @@ To add the `LoginListener`, you need to use the `addLoginListener()` method prov - -```typescript - const listenerID: string = "UNIQUE_LISTENER_ID"; + +```js + let listenerID = "UNIQUE_LISTENER_ID"; CometChat.addLoginListener( listenerID, new CometChat.LoginListener({ - loginSuccess: (user: CometChat.User) => { - console.log("LoginListener :: loginSuccess", user); + loginSuccess: (e) => { + console.log("LoginListener :: loginSuccess", e); }, - loginFailure: (error: CometChat.CometChatException) => { - console.log("LoginListener :: loginFailure", error); + loginFailure: (e) => { + console.log("LoginListener :: loginFailure", e); }, logoutSuccess: () => { console.log("LoginListener :: logoutSuccess"); }, - logoutFailure: (error: CometChat.CometChatException) => { - console.log("LoginListener :: logoutFailure", error); + logoutFailure: (e) => { + console.log("LoginListener :: logoutFailure", e); } }) ); @@ -87,28 +87,27 @@ To add the `LoginListener`, you need to use the `addLoginListener()` method prov If you're using React, register the listener inside a `useEffect` hook and clean it up on unmount: - -```javascript + +```typescript import { useEffect } from "react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; -function useLoginListener() { +function useLoginListener(): void { useEffect(() => { - const listenerID = "LOGIN_LISTENER"; + const listenerID: string = "LOGIN_LISTENER"; CometChat.addLoginListener( listenerID, new CometChat.LoginListener({ - loginSuccess: (user) => { + loginSuccess: (user: CometChat.User) => { console.log("User logged in:", user); }, - loginFailure: (error) => { + loginFailure: (error: CometChat.CometChatException) => { console.log("Login failed:", error); }, logoutSuccess: () => { console.log("User logged out"); - // Redirect to login page, clear app state, etc. }, - logoutFailure: (error) => { + logoutFailure: (error: CometChat.CometChatException) => { console.log("Logout failed:", error); }, }) @@ -121,27 +120,28 @@ function useLoginListener() { } ``` - -```typescript + +```javascript import { useEffect } from "react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; -function useLoginListener(): void { +function useLoginListener() { useEffect(() => { - const listenerID: string = "LOGIN_LISTENER"; + const listenerID = "LOGIN_LISTENER"; CometChat.addLoginListener( listenerID, new CometChat.LoginListener({ - loginSuccess: (user: CometChat.User) => { + loginSuccess: (user) => { console.log("User logged in:", user); }, - loginFailure: (error: CometChat.CometChatException) => { + loginFailure: (error) => { console.log("Login failed:", error); }, logoutSuccess: () => { console.log("User logged out"); + // Redirect to login page, clear app state, etc. }, - logoutFailure: (error: CometChat.CometChatException) => { + logoutFailure: (error) => { console.log("Logout failed:", error); }, }) @@ -159,17 +159,17 @@ function useLoginListener(): void { 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 - const listenerID = "UNIQUE_LISTENER_ID"; + +```typescript + const listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.removeLoginListener(listenerID); ``` - -```typescript - const listenerID: string = "UNIQUE_LISTENER_ID"; + +```js + const listenerID = "UNIQUE_LISTENER_ID"; CometChat.removeLoginListener(listenerID); ``` diff --git a/sdk/javascript/managing-web-sockets-connections-manually.mdx b/sdk/javascript/managing-web-sockets-connections-manually.mdx index 6cd7a7380..27215fbf6 100644 --- a/sdk/javascript/managing-web-sockets-connections-manually.mdx +++ b/sdk/javascript/managing-web-sockets-connections-manually.mdx @@ -41,20 +41,20 @@ The CometChat SDK also allows you to modify the above default behaviour of the S 1. While calling the init() function on the app startup, you need to inform the SDK that you will be managing the web socket connect. You can do so by using the `autoEstablishSocketConnection()` method provided by the `AppSettingsBuilder` class. This method takes a boolean value as an input. If set to `true` , the SDK will manage the web-socket connection internally based on the default behaviour mentioned above. If set to `false` , the web socket connection can will not be managed by the SDK and you will have to handle it manually. You can refer to the below code snippet for the same: - -```js -let appID = "APP_ID"; -let region = "APP_REGION"; -let appSetting = new CometChat.AppSettingsBuilder() + +```typescript +let appID: string = "APP_ID"; +let region: string = "APP_REGION"; +let appSetting: CometChat.AppSettings = new CometChat.AppSettingsBuilder() .subscribePresenceForAllUsers() .setRegion(region) .autoEstablishSocketConnection(false) .build(); CometChat.init(appID, appSetting).then( - () => { + (isInitialized: boolean) => { console.log("Initialization completed successfully"); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Initialization failed with error:", error); } ); @@ -62,20 +62,20 @@ CometChat.init(appID, appSetting).then( - -```typescript -let appID: string = "APP_ID"; -let region: string = "APP_REGION"; -let appSetting: CometChat.AppSettings = new CometChat.AppSettingsBuilder() + +```js +let appID = "APP_ID"; +let region = "APP_REGION"; +let appSetting = new CometChat.AppSettingsBuilder() .subscribePresenceForAllUsers() .setRegion(region) .autoEstablishSocketConnection(false) .build(); CometChat.init(appID, appSetting).then( - (isInitialized: boolean) => { + () => { console.log("Initialization completed successfully"); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Initialization failed with error:", error); } ); diff --git a/sdk/javascript/message-structure-and-hierarchy.mdx b/sdk/javascript/message-structure-and-hierarchy.mdx index 1f93fc379..17b27315b 100644 --- a/sdk/javascript/message-structure-and-hierarchy.mdx +++ b/sdk/javascript/message-structure-and-hierarchy.mdx @@ -37,57 +37,57 @@ Every message in CometChat belongs to a category and has a specific type. Unders Use `getCategory()` and `getType()` to determine how to handle a received message: - -```javascript -const category = message.getCategory(); -const type = message.getType(); + +```typescript +const category: string = message.getCategory(); +const type: string = message.getType(); switch (category) { case CometChat.CATEGORY_MESSAGE: if (type === CometChat.MESSAGE_TYPE.TEXT) { - console.log("Text:", message.getText()); + const textMsg = message as CometChat.TextMessage; + console.log("Text:", textMsg.getText()); } else if (type === CometChat.MESSAGE_TYPE.IMAGE) { - console.log("Image URL:", message.getData().url); + const mediaMsg = message as CometChat.MediaMessage; + console.log("Image URL:", mediaMsg.getData().url); } break; case CometChat.CATEGORY_CUSTOM: - console.log("Custom type:", type, "data:", message.getData()); + const customMsg = message as CometChat.CustomMessage; + console.log("Custom type:", type, "data:", customMsg.getData()); break; case CometChat.CATEGORY_ACTION: - console.log("Action:", message.getAction()); + const actionMsg = message as CometChat.Action; + console.log("Action:", actionMsg.getAction()); break; case CometChat.CATEGORY_CALL: - console.log("Call status:", message.getStatus()); + const callMsg = message as CometChat.Call; + console.log("Call status:", callMsg.getStatus()); break; } ``` - -```typescript -const category: string = message.getCategory(); -const type: string = message.getType(); + +```javascript +const category = message.getCategory(); +const type = message.getType(); switch (category) { case CometChat.CATEGORY_MESSAGE: if (type === CometChat.MESSAGE_TYPE.TEXT) { - const textMsg = message as CometChat.TextMessage; - console.log("Text:", textMsg.getText()); + console.log("Text:", message.getText()); } else if (type === CometChat.MESSAGE_TYPE.IMAGE) { - const mediaMsg = message as CometChat.MediaMessage; - console.log("Image URL:", mediaMsg.getData().url); + console.log("Image URL:", message.getData().url); } break; case CometChat.CATEGORY_CUSTOM: - const customMsg = message as CometChat.CustomMessage; - console.log("Custom type:", type, "data:", customMsg.getData()); + console.log("Custom type:", type, "data:", message.getData()); break; case CometChat.CATEGORY_ACTION: - const actionMsg = message as CometChat.Action; - console.log("Action:", actionMsg.getAction()); + console.log("Action:", message.getAction()); break; case CometChat.CATEGORY_CALL: - const callMsg = message as CometChat.Call; - console.log("Call status:", callMsg.getStatus()); + console.log("Call status:", message.getStatus()); break; } ``` diff --git a/sdk/javascript/rate-limits.mdx b/sdk/javascript/rate-limits.mdx index 1d8a4a86c..c7689f4ef 100644 --- a/sdk/javascript/rate-limits.mdx +++ b/sdk/javascript/rate-limits.mdx @@ -40,15 +40,18 @@ CometChat includes rate limit information in response headers: When you exceed the rate limit, CometChat returns HTTP `429 Too Many Requests`. Implement exponential backoff to handle this gracefully: - -```javascript -async function callWithRetry(apiCall, maxRetries = 3) { + +```typescript +async function callWithRetry( + apiCall: () => Promise, + maxRetries: number = 3 +): Promise { for (let attempt = 0; attempt < maxRetries; attempt++) { try { return await apiCall(); - } catch (error) { + } catch (error: any) { if (error.code === "ERR_TOO_MANY_REQUESTS" && attempt < maxRetries - 1) { - const waitTime = Math.pow(2, attempt) * 1000; // 1s, 2s, 4s + const waitTime = Math.pow(2, attempt) * 1000; console.log(`Rate limited. Retrying in ${waitTime / 1000}s...`); await new Promise((resolve) => setTimeout(resolve, waitTime)); } else { @@ -56,26 +59,24 @@ async function callWithRetry(apiCall, maxRetries = 3) { } } } + throw new Error("Max retries exceeded"); } // Usage -const users = await callWithRetry(() => +const users: CometChat.User[] = await callWithRetry(() => new CometChat.UsersRequestBuilder().setLimit(30).build().fetchNext() ); ``` - -```typescript -async function callWithRetry( - apiCall: () => Promise, - maxRetries: number = 3 -): Promise { + +```javascript +async function callWithRetry(apiCall, maxRetries = 3) { for (let attempt = 0; attempt < maxRetries; attempt++) { try { return await apiCall(); - } catch (error: any) { + } catch (error) { if (error.code === "ERR_TOO_MANY_REQUESTS" && attempt < maxRetries - 1) { - const waitTime = Math.pow(2, attempt) * 1000; + 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 { @@ -83,11 +84,10 @@ async function callWithRetry( } } } - throw new Error("Max retries exceeded"); } // Usage -const users: CometChat.User[] = await callWithRetry(() => +const users = await callWithRetry(() => new CometChat.UsersRequestBuilder().setLimit(30).build().fetchNext() ); ``` diff --git a/sdk/javascript/reactions.mdx b/sdk/javascript/reactions.mdx index 82e226f6e..12c22fd34 100644 --- a/sdk/javascript/reactions.mdx +++ b/sdk/javascript/reactions.mdx @@ -34,32 +34,32 @@ Enhance user engagement in your chat application with message reactions. Users c Users can add a reaction to a message by calling `addReaction` with the message ID and the reaction emoji. - -```js -let messageId = "1"; -let emoji = "😊"; + +```typescript +let messageId:string = "1"; +let emoji:string = "😊"; CometChat.addReaction(messageId, emoji) -.then((res) => { +.then((res:CometChat.BaseMessage) => { console.log('response', res); -}).catch(err => { +}).catch((err:CometChat.CometChatException) => { console.log('err', err); -}) +}) ``` - -```typescript -let messageId:string = "1"; -let emoji:string = "😊"; + +```js +let messageId = "1"; +let emoji = "😊"; CometChat.addReaction(messageId, emoji) -.then((res:CometChat.BaseMessage) => { +.then((res) => { console.log('response', res); -}).catch((err:CometChat.CometChatException) => { +}).catch(err => { console.log('err', err); -}) +}) ``` @@ -77,32 +77,32 @@ You can react on text message, media message and custom message Removing a reaction from a message can be done using the `removeReaction` method. - -```js -let messageId = "1"; -let emoji = "😊"; + +```typescript +let messageId:string = "1"; +let emoji:string = "😊"; CometChat.removeReaction(messageId, emoji) -.then((res) => { +.then((res:CometChat.BaseMessage) => { console.log('response', res); -}).catch(err => { +}).catch((err:CometChat.CometChatException) => { console.log('err', err); -}) +}) ``` - -```typescript -let messageId:string = "1"; -let emoji:string = "😊"; + +```js +let messageId = "1"; +let emoji = "😊"; CometChat.removeReaction(messageId, emoji) -.then((res:CometChat.BaseMessage) => { +.then((res) => { console.log('response', res); -}).catch((err:CometChat.CometChatException) => { +}).catch(err => { console.log('err', err); -}) +}) ``` @@ -133,10 +133,10 @@ To get all reactions for a specific message, first create a `ReactionRequest` us The `fetchNext()` method fetches the next set of reactions for the message. - -```js -let limit = 10; -let messageId = 1; + +```typescript +let limit:number = 10; +let messageId:number = 1; let reactionRequest = new CometChat.ReactionRequestBuilder() .setMessageId(messageId) @@ -144,21 +144,21 @@ let reactionRequest = new CometChat.ReactionRequestBuilder() .build(); reactionRequest.fetchNext().then( - messages => { + (messages: MessageReaction[]) => { console.log("list fetched:", messages); }, - error => {a + (error: CometChat.CometChatException) => { console.log('list fetching failed with error:', error); }, - ); + ); ``` - -```typescript -let limit:number = 10; -let messageId:number = 1; + +```js +let limit = 10; +let messageId = 1; let reactionRequest = new CometChat.ReactionRequestBuilder() .setMessageId(messageId) @@ -166,13 +166,13 @@ let reactionRequest = new CometChat.ReactionRequestBuilder() .build(); reactionRequest.fetchNext().then( - (messages: MessageReaction[]) => { + messages => { console.log("list fetched:", messages); }, - (error: CometChat.CometChatException) => { + error => {a console.log('list fetching failed with error:', error); }, - ); + ); ``` @@ -182,10 +182,10 @@ reactionRequest.fetchNext().then( Fetch Previous The `fetchPrevious()` method fetches the previous set of reactions for the message. - -```js -let limit = 10; -let messageId = 1; + +```typescript +let limit:number = 10; +let messageId:number = 1; let reactionRequest = new CometChat.ReactionRequestBuilder() .setMessageId(messageId) @@ -193,21 +193,21 @@ let reactionRequest = new CometChat.ReactionRequestBuilder() .build(); reactionRequest.fetchPrevious().then( - messages => { + (messages: MessageReaction[]) => { console.log("list fetched:", messages); }, - error => {a + (error: CometChat.CometChatException) => { console.log('list fetching failed with error:', error); }, - ); + ); ``` - -```typescript -let limit:number = 10; -let messageId:number = 1; + +```js +let limit = 10; +let messageId = 1; let reactionRequest = new CometChat.ReactionRequestBuilder() .setMessageId(messageId) @@ -215,13 +215,13 @@ let reactionRequest = new CometChat.ReactionRequestBuilder() .build(); reactionRequest.fetchPrevious().then( - (messages: MessageReaction[]) => { + messages => { console.log("list fetched:", messages); }, - (error: CometChat.CometChatException) => { + error => {a console.log('list fetching failed with error:', error); }, - ); + ); ``` @@ -237,34 +237,34 @@ Always remove listeners when they're no longer needed (e.g., on component unmoun - -```js -let listenerID = "UNIQUE_LISTENER_ID"; + +```typescript +let listenerID:string = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener(listenerID, { - onMessageReactionAdded:(message) => { + onMessageReactionAdded:(message: Object) => { console.log("Reaction added", message); }, - onMessageReactionRemoved:(message) => { + onMessageReactionRemoved:(message: Object) => { console.log("Reaction removed", message); } - }) + }) ``` - -```typescript -let listenerID:string = "UNIQUE_LISTENER_ID"; + +```js +let listenerID = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener(listenerID, { - onMessageReactionAdded:(message: Object) => { + onMessageReactionAdded:(message) => { console.log("Reaction added", message); }, - onMessageReactionRemoved:(message: Object) => { + onMessageReactionRemoved:(message) => { console.log("Reaction removed", message); } - }) + }) ``` @@ -286,20 +286,20 @@ Each reaction listener callback receives a [`ReactionEvent`](/sdk/reference/auxi To stop listening for reaction events, remove the listener as follows: - -```js -let listenerID = "UNIQUE_LISTENER_ID"; + +```typescript +let listenerID:string = "UNIQUE_LISTENER_ID"; -CometChat.removeMessageListener(listenerID); +CometChat.removeMessageReactionListener(listenerID); ``` - -```typescript -let listenerID:string = "UNIQUE_LISTENER_ID"; + +```js +let listenerID = "UNIQUE_LISTENER_ID"; -CometChat.removeMessageReactionListener(listenerID); +CometChat.removeMessageListener(listenerID); ``` @@ -311,16 +311,16 @@ CometChat.removeMessageReactionListener(listenerID); To retrieve the list of reactions reacted on particular message, you can use the `message.getReactions()` method. This method will return an array containing the reactions, or an empty array if no one reacted on the message. - -```js -message.getReactions() + +```typescript +message.getReactions() ``` - -```typescript -message.getReactions() + +```js +message.getReactions() ``` @@ -332,22 +332,22 @@ message.getReactions() 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. - -```js + +```typescript let reactions = message.getReactions(); reactions.forEach((reaction) => { reaction.getReactedByMe(); //Return true is logged-in user reacted on that message, otherwise false -}) +}) ``` - -```typescript + +```js let reactions = message.getReactions(); reactions.forEach((reaction) => { reaction.getReactedByMe(); //Return true is logged-in user reacted on that message, otherwise false -}) +}) ``` @@ -363,42 +363,42 @@ The `updateMessageWithReactionInfo()` method provides a seamless way to update t 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. - -```js + +```typescript // The message to which the reaction is related -let message = ...; +let message: CometChat.BaseMessage = ...; // The reaction event data received in real-time -let messageReaction = ...; +let messageReaction: CometChat.MessageReaction = ...; // The recieved reaction event real-time action type. Can be CometChatConstants.REACTION_ADDED or CometChatConstants.REACTION_REMOVED -let action = CometChat.REACTION_ACTION.REACTION_ADDED; +let action: CometChat.REACTION_ACTION = CometChat.REACTION_ACTION.REACTION_ADDED; let modifiedBaseMessage = CometChat.CometChatHelper.updateMessageWithReactionInfo( baseMessage, messageReaction, action -); +); ``` - -```typescript + +```js // The message to which the reaction is related -let message: CometChat.BaseMessage = ...; +let message = ...; // The reaction event data received in real-time -let messageReaction: CometChat.MessageReaction = ...; +let messageReaction = ...; // The recieved reaction event real-time action type. Can be CometChatConstants.REACTION_ADDED or CometChatConstants.REACTION_REMOVED -let action: CometChat.REACTION_ACTION = CometChat.REACTION_ACTION.REACTION_ADDED; +let action = CometChat.REACTION_ACTION.REACTION_ADDED; let modifiedBaseMessage = CometChat.CometChatHelper.updateMessageWithReactionInfo( baseMessage, messageReaction, action -); +); ``` diff --git a/sdk/javascript/recording.mdx b/sdk/javascript/recording.mdx index 1f8b119be..10ea137b7 100644 --- a/sdk/javascript/recording.mdx +++ b/sdk/javascript/recording.mdx @@ -37,8 +37,8 @@ Always remove listeners when they're no longer needed (e.g., on component unmoun - -```js + +```typescript // Add listeners onRecordingStarted and onRecordingStopped to the startCall method const defaultLayout = true; const audioOnly = false; @@ -62,8 +62,8 @@ CometChatCalls.startSession(callToken, callSettings, htmlElement); - -```typescript + +```js // Add listeners onRecordingStarted and onRecordingStopped to the startCall method const defaultLayout = true; const audioOnly = false; diff --git a/sdk/javascript/retrieve-conversations.mdx b/sdk/javascript/retrieve-conversations.mdx index f8be2187d..ad43cc898 100644 --- a/sdk/javascript/retrieve-conversations.mdx +++ b/sdk/javascript/retrieve-conversations.mdx @@ -130,18 +130,6 @@ When conversations are fetched successfully, the response includes `tags` arrays Fetch user conversations where the user has specific tags. - -```js -let limit = 30; -let userTags = ["tag1"]; -let conversationRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setUserTags(userTags) - .build(); -``` - - - ```typescript let limit: number = 30, @@ -154,27 +142,27 @@ let limit: number = 30, - - -When conversations are fetched successfully, the response includes only user conversations where the user has the specified tags. - -### Set Group Tags - -Fetch group conversations where the group has specific tags. - - ```js let limit = 30; -let groupTags = ["tag1"]; +let userTags = ["tag1"]; let conversationRequest = new CometChat.ConversationsRequestBuilder() .setLimit(limit) - .setGroupTags(groupTags) - .build(); + .setUserTags(userTags) + .build(); ``` + + +When conversations are fetched successfully, the response includes only user conversations where the user has the specified tags. + +### Set Group Tags + +Fetch group conversations where the group has specific tags. + + ```typescript let limit: number = 30, @@ -187,6 +175,18 @@ let limit: number = 30, + +```js +let limit = 30; +let groupTags = ["tag1"]; +let conversationRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setGroupTags(groupTags) + .build(); +``` + + + When conversations are fetched successfully, the response includes only group conversations where the group has the specified tags. @@ -254,17 +254,6 @@ let limit: number = 30, Use `setIncludeBlockedUsers(true)` to include conversations with users you've blocked. - -```js -let limit = 30; -let conversationRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setIncludeBlockedUsers(true) - .build(); -``` - - - ```typescript let limit: number = 30, @@ -276,26 +265,26 @@ let limit: number = 30, - - -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 - -Use `setWithBlockedInfo(true)` to include blocked user information in the response. - - ```js let limit = 30; let conversationRequest = new CometChat.ConversationsRequestBuilder() .setLimit(limit) - .setWithBlockedInfo(true) + .setIncludeBlockedUsers(true) .build(); ``` + + +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 + +Use `setWithBlockedInfo(true)` to include blocked user information in the response. + + ```typescript let limit: number = 30, @@ -307,6 +296,17 @@ let limit: number = 30, + +```js +let limit = 30; +let conversationRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setWithBlockedInfo(true) + .build(); +``` + + + ### Search Conversations @@ -319,17 +319,6 @@ This feature is only available with `Conversation & Advanced Search`. The `Conve - -```js -let limit = 30; -let conversationRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setSearchKeyword("Hiking") - .build(); -``` - - - ```typescript let limit: number = 30, @@ -341,6 +330,17 @@ let limit: number = 30, + +```js +let limit = 30; +let conversationRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setSearchKeyword("Hiking") + .build(); +``` + + + When conversations are fetched successfully, the response includes conversations where the user or group name matches the search keyword. @@ -356,17 +356,6 @@ This feature is only available with `Conversation & Advanced Search`. The `Conve - -```js -let limit = 30; -let conversationRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setUnread(true) - .build(); -``` - - - ```typescript let limit: number = 30, @@ -378,26 +367,26 @@ let limit: number = 30, - - -When conversations are fetched successfully, the response includes only conversations with unread messages (`unreadMessageCount` > 0). - -### Hide Agentic Conversations - -Use `setHideAgentic(true)` to exclude AI agent conversations from the list. - - ```js let limit = 30; let conversationRequest = new CometChat.ConversationsRequestBuilder() .setLimit(limit) - .setHideAgentic(true) + .setUnread(true) .build(); ``` + + +When conversations are fetched successfully, the response includes only conversations with unread messages (`unreadMessageCount` > 0). + +### Hide Agentic Conversations + +Use `setHideAgentic(true)` to exclude AI agent conversations from the list. + + ```typescript let limit: number = 30, @@ -409,23 +398,23 @@ let limit: number = 30, - -### Only Agentic Conversations - -Use `setOnlyAgentic(true)` to fetch only AI agent conversations. - - ```js let limit = 30; let conversationRequest = new CometChat.ConversationsRequestBuilder() .setLimit(limit) - .setOnlyAgentic(true) + .setHideAgentic(true) .build(); ``` + +### Only Agentic Conversations + +Use `setOnlyAgentic(true)` to fetch only AI agent conversations. + + ```typescript let limit: number = 30, @@ -437,6 +426,17 @@ let limit: number = 30, + +```js +let limit = 30; +let conversationRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setOnlyAgentic(true) + .build(); +``` + + + diff --git a/sdk/javascript/retrieve-users.mdx b/sdk/javascript/retrieve-users.mdx index e7f27204a..736ddd6ec 100644 --- a/sdk/javascript/retrieve-users.mdx +++ b/sdk/javascript/retrieve-users.mdx @@ -137,20 +137,6 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() Specifies which user properties to search. Works with `setSearchKeyword()`. By default, searches both UID and name. - -```js -let limit = 30; -let searchKeyword = "super"; -let searchIn = ["uid", "name"]; -let usersRequest = new CometChat.UsersRequestBuilder() - .setLimit(limit) - .setSearchKeyword(searchKeyword) - .searchIn(searchIn) - .build(); -``` - - - ```typescript let limit: number = 30; @@ -165,6 +151,20 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() + +```js +let limit = 30; +let searchKeyword = "super"; +let searchIn = ["uid", "name"]; +let usersRequest = new CometChat.UsersRequestBuilder() + .setLimit(limit) + .setSearchKeyword(searchKeyword) + .searchIn(searchIn) + .build(); +``` + + + ### Set Status @@ -386,6 +386,18 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() Sorts the user list by a specific property. Default sort order: `status → name → UID`. Pass `"name"` to sort by `name → UID`. + +```typescript +let limit: number = 30; +let sortBy: string = "name"; +let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() + .setLimit(limit) + .sortBy(sortBy) + .build(); +``` + + + ```js let limit = 30; @@ -399,25 +411,25 @@ let usersRequest = new CometChat.UsersRequestBuilder() + + +### Sort By Order + +Sets the sort order. Default is ascending (`"asc"`). Use `"desc"` for descending. + + ```typescript let limit: number = 30; -let sortBy: string = "name"; +let sortOrder: string = "desc"; let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() .setLimit(limit) - .sortBy(sortBy) - .build(); + .sortOrder(sortOrder) + .build(); ``` - - -### Sort By Order - -Sets the sort order. Default is ascending (`"asc"`). Use `"desc"` for descending. - - ```js let limit = 30; @@ -430,23 +442,29 @@ let usersReques = new CometChat.UsersRequestBuilder() + + +After configuring the builder, call `build()` to get the `UsersRequest` object, then call `fetchNext()` to retrieve users. + + ```typescript let limit: number = 30; -let sortOrder: string = "desc"; let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() - .setLimit(limit) - .sortOrder(sortOrder) - .build(); +.setLimit(limit) +.build(); + +usersRequest.fetchNext().then( + (userList: CometChat.User[]) => { + console.log("User list received:", userList); + }, (error: CometChat.CometChatException) => { + console.log("User list fetching failed with error:", error); + } +); ``` - - -After configuring the builder, call `build()` to get the `UsersRequest` object, then call `fetchNext()` to retrieve users. - - ```javascript const limit = 30; @@ -465,24 +483,6 @@ userList => { - -```typescript -let limit: number = 30; -let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() -.setLimit(limit) -.build(); - -usersRequest.fetchNext().then( - (userList: CometChat.User[]) => { - console.log("User list received:", userList); - }, (error: CometChat.CometChatException) => { - console.log("User list fetching failed with error:", error); - } -); -``` - - - The `fetchNext()` method returns an array of [`User`](/sdk/reference/entities#user) objects. Access the response data using getter methods: diff --git a/sdk/javascript/send-message.mdx b/sdk/javascript/send-message.mdx index 0d8458111..034d6030b 100644 --- a/sdk/javascript/send-message.mdx +++ b/sdk/javascript/send-message.mdx @@ -151,9 +151,9 @@ On success, `sendMessage()` returns a [TextMessage](/sdk/reference/messages#text Attach custom JSON data to the message: - -```javascript -let metadata = { + +```typescript +let metadata: Object = { latitude: "50.6192171633316", longitude: "-72.68182268750002", }; @@ -161,9 +161,9 @@ let metadata = { textMessage.setMetadata(metadata); ``` - -```typescript -let metadata: Object = { + +```javascript +let metadata = { latitude: "50.6192171633316", longitude: "-72.68182268750002", }; @@ -178,16 +178,16 @@ textMessage.setMetadata(metadata); Tag messages for easy filtering later: - -```javascript -let tags = ["starredMessage"]; + +```typescript +let tags: Array = ["starredMessage"]; textMessage.setTags(tags); ``` - -```typescript -let tags: Array = ["starredMessage"]; + +```javascript +let tags = ["starredMessage"]; textMessage.setTags(tags); ``` @@ -199,13 +199,13 @@ textMessage.setTags(tags); Reply to a specific message by setting its ID: - -```javascript + +```typescript textMessage.setQuotedMessageId(10); ``` - -```typescript + +```javascript textMessage.setQuotedMessageId(10); ``` @@ -477,13 +477,13 @@ On success, `sendMediaMessage()` returns a [MediaMessage](/sdk/reference/message Add text along with the media: - -```javascript + +```typescript mediaMessage.setCaption("Check out this photo!"); ``` - -```typescript + +```javascript mediaMessage.setCaption("Check out this photo!"); ``` diff --git a/sdk/javascript/standalone-calling.mdx b/sdk/javascript/standalone-calling.mdx index 54db56dca..a9bbb772a 100644 --- a/sdk/javascript/standalone-calling.mdx +++ b/sdk/javascript/standalone-calling.mdx @@ -59,33 +59,33 @@ You can generate the token just before starting the call, or generate and store Use the `generateToken()` method to create a call token: - -```javascript -const sessionId = "UNIQUE_SESSION_ID"; // Generate a unique session ID -const userAuthToken = "USER_AUTH_TOKEN"; // Obtained from REST API + +```typescript +const sessionId: string = "UNIQUE_SESSION_ID"; // Generate a unique session ID +const userAuthToken: string = "USER_AUTH_TOKEN"; // Obtained from REST API CometChatCalls.generateToken(sessionId, userAuthToken).then( - (callToken) => { + (callToken: any) => { console.log("Call token generated:", callToken.token); // Use callToken to start the session }, - (error) => { + (error: any) => { console.log("Token generation failed:", error); } ); ``` - -```typescript -const sessionId: string = "UNIQUE_SESSION_ID"; // Generate a unique session ID -const userAuthToken: string = "USER_AUTH_TOKEN"; // Obtained from REST API + +```javascript +const sessionId = "UNIQUE_SESSION_ID"; // Generate a unique session ID +const userAuthToken = "USER_AUTH_TOKEN"; // Obtained from REST API CometChatCalls.generateToken(sessionId, userAuthToken).then( - (callToken: any) => { + (callToken) => { console.log("Call token generated:", callToken.token); // Use callToken to start the session }, - (error: any) => { + (error) => { console.log("Token generation failed:", error); } ); @@ -106,16 +106,16 @@ Use the `startSession()` method to join a call session. This method requires: 3. An HTML element where the call UI will be rendered - -```javascript + +```typescript const callListener = new CometChatCalls.OngoingCallListener({ - onUserJoined: (user) => { + onUserJoined: (user: any) => { console.log("User joined:", user); }, - onUserLeft: (user) => { + onUserLeft: (user: any) => { console.log("User left:", user); }, - onUserListUpdated: (userList) => { + onUserListUpdated: (userList: any[]) => { console.log("User list updated:", userList); }, onCallEnded: () => { @@ -128,13 +128,13 @@ const callListener = new CometChatCalls.OngoingCallListener({ CometChatCalls.endSession(); // Close calling screen }, - onError: (error) => { + onError: (error: any) => { console.log("Call error:", error); }, - onMediaDeviceListUpdated: (deviceList) => { + onMediaDeviceListUpdated: (deviceList: any[]) => { console.log("Device list updated:", deviceList); }, - onUserMuted: (event) => { + onUserMuted: (event: any) => { console.log("User muted:", event); }, onScreenShareStarted: () => { @@ -143,7 +143,7 @@ const callListener = new CometChatCalls.OngoingCallListener({ onScreenShareStopped: () => { console.log("Screen sharing stopped"); }, - onCallSwitchedToVideo: (event) => { + onCallSwitchedToVideo: (event: any) => { console.log("Call switched to video:", event); }, onSessionTimeout: () => { @@ -157,20 +157,20 @@ const callSettings = new CometChatCalls.CallSettingsBuilder() .setCallListener(callListener) .build(); -const htmlElement = document.getElementById("call-container"); +const htmlElement = document.getElementById("call-container") as HTMLElement; CometChatCalls.startSession(callToken, callSettings, htmlElement); ``` - -```typescript + +```javascript const callListener = new CometChatCalls.OngoingCallListener({ - onUserJoined: (user: any) => { + onUserJoined: (user) => { console.log("User joined:", user); }, - onUserLeft: (user: any) => { + onUserLeft: (user) => { console.log("User left:", user); }, - onUserListUpdated: (userList: any[]) => { + onUserListUpdated: (userList) => { console.log("User list updated:", userList); }, onCallEnded: () => { @@ -183,13 +183,13 @@ const callListener = new CometChatCalls.OngoingCallListener({ CometChatCalls.endSession(); // Close calling screen }, - onError: (error: any) => { + onError: (error) => { console.log("Call error:", error); }, - onMediaDeviceListUpdated: (deviceList: any[]) => { + onMediaDeviceListUpdated: (deviceList) => { console.log("Device list updated:", deviceList); }, - onUserMuted: (event: any) => { + onUserMuted: (event) => { console.log("User muted:", event); }, onScreenShareStarted: () => { @@ -198,7 +198,7 @@ const callListener = new CometChatCalls.OngoingCallListener({ onScreenShareStopped: () => { console.log("Screen sharing stopped"); }, - onCallSwitchedToVideo: (event: any) => { + onCallSwitchedToVideo: (event) => { console.log("Call switched to video:", event); }, onSessionTimeout: () => { @@ -212,7 +212,7 @@ const callSettings = new CometChatCalls.CallSettingsBuilder() .setCallListener(callListener) .build(); -const htmlElement = document.getElementById("call-container") as HTMLElement; +const htmlElement = document.getElementById("call-container"); CometChatCalls.startSession(callToken, callSettings, htmlElement); ``` @@ -263,18 +263,18 @@ Each listener requires a unique `listenerId` string. This ID is used to: - **Enable targeted removal** — Remove specific listeners without affecting others - -```javascript -const listenerId = "UNIQUE_LISTENER_ID"; + +```typescript +const listenerId: string = "UNIQUE_LISTENER_ID"; CometChatCalls.addCallEventListener(listenerId, { - onUserJoined: (user) => { + onUserJoined: (user: any) => { console.log("User joined:", user); }, - onUserLeft: (user) => { + onUserLeft: (user: any) => { console.log("User left:", user); }, - onUserListUpdated: (userList) => { + onUserListUpdated: (userList: any[]) => { console.log("User list updated:", userList); }, onCallEnded: () => { @@ -287,13 +287,13 @@ CometChatCalls.addCallEventListener(listenerId, { CometChatCalls.endSession(); // Close calling screen }, - onError: (error) => { + onError: (error: any) => { console.log("Call error:", error); }, - onMediaDeviceListUpdated: (deviceList) => { + onMediaDeviceListUpdated: (deviceList: any[]) => { console.log("Device list updated:", deviceList); }, - onUserMuted: (event) => { + onUserMuted: (event: any) => { console.log("User muted:", event); }, onScreenShareStarted: () => { @@ -302,7 +302,7 @@ CometChatCalls.addCallEventListener(listenerId, { onScreenShareStopped: () => { console.log("Screen sharing stopped"); }, - onCallSwitchedToVideo: (event) => { + onCallSwitchedToVideo: (event: any) => { console.log("Call switched to video:", event); }, onSessionTimeout: () => { @@ -314,18 +314,18 @@ CometChatCalls.addCallEventListener(listenerId, { CometChatCalls.removeCallEventListener(listenerId); ``` - -```typescript -const listenerId: string = "UNIQUE_LISTENER_ID"; + +```javascript +const listenerId = "UNIQUE_LISTENER_ID"; CometChatCalls.addCallEventListener(listenerId, { - onUserJoined: (user: any) => { + onUserJoined: (user) => { console.log("User joined:", user); }, - onUserLeft: (user: any) => { + onUserLeft: (user) => { console.log("User left:", user); }, - onUserListUpdated: (userList: any[]) => { + onUserListUpdated: (userList) => { console.log("User list updated:", userList); }, onCallEnded: () => { @@ -338,13 +338,13 @@ CometChatCalls.addCallEventListener(listenerId, { CometChatCalls.endSession(); // Close calling screen }, - onError: (error: any) => { + onError: (error) => { console.log("Call error:", error); }, - onMediaDeviceListUpdated: (deviceList: any[]) => { + onMediaDeviceListUpdated: (deviceList) => { console.log("Device list updated:", deviceList); }, - onUserMuted: (event: any) => { + onUserMuted: (event) => { console.log("User muted:", event); }, onScreenShareStarted: () => { @@ -353,7 +353,7 @@ CometChatCalls.addCallEventListener(listenerId, { onScreenShareStopped: () => { console.log("Screen sharing stopped"); }, - onCallSwitchedToVideo: (event: any) => { + onCallSwitchedToVideo: (event) => { console.log("Call switched to video:", event); }, onSessionTimeout: () => { @@ -389,16 +389,16 @@ CometChatCalls.removeCallEventListener(listenerId); To end the call session and release all media resources (camera, microphone, network connections), call `CometChatCalls.endSession()` in the `onCallEndButtonPressed()` callback. - -```javascript + +```typescript onCallEndButtonPressed: () => { CometChatCalls.endSession(); // Close the calling screen } ``` - -```typescript + +```javascript onCallEndButtonPressed: () => { CometChatCalls.endSession(); // Close the calling screen @@ -420,13 +420,13 @@ These methods can only be called when a call session is active. Toggles between the front and rear camera during a video call. Only supported on mobile browsers. - -```javascript + +```typescript CometChatCalls.switchCamera(); ``` - -```typescript + +```javascript CometChatCalls.switchCamera(); ``` @@ -444,13 +444,13 @@ Controls the local audio stream transmission. When muted, other participants can - `false` — Unmutes the microphone, resumes audio transmission - -```javascript + +```typescript CometChatCalls.muteAudio(true); ``` - -```typescript + +```javascript CometChatCalls.muteAudio(true); ``` @@ -464,13 +464,13 @@ Controls the local video stream transmission. When paused, other participants se - `false` — Resumes the camera, continues video transmission - -```javascript + +```typescript CometChatCalls.pauseVideo(true); ``` - -```typescript + +```javascript CometChatCalls.pauseVideo(true); ``` @@ -481,13 +481,13 @@ CometChatCalls.pauseVideo(true); Starts sharing your screen or a specific application window with other participants. - -```javascript + +```typescript CometChatCalls.startScreenShare(); ``` - -```typescript + +```javascript CometChatCalls.startScreenShare(); ``` @@ -498,13 +498,13 @@ CometChatCalls.startScreenShare(); Stops the current screen sharing session. - -```javascript + +```typescript CometChatCalls.stopScreenShare(); ``` - -```typescript + +```javascript CometChatCalls.stopScreenShare(); ``` @@ -519,13 +519,13 @@ Changes the call UI layout mode dynamically during the call. - `CometChat.CALL_MODE.SPOTLIGHT` — Focus on the active speaker - -```javascript + +```typescript CometChatCalls.setMode(CometChat.CALL_MODE.SPOTLIGHT); ``` - -```typescript + +```javascript CometChatCalls.setMode(CometChat.CALL_MODE.SPOTLIGHT); ``` @@ -536,14 +536,14 @@ CometChatCalls.setMode(CometChat.CALL_MODE.SPOTLIGHT); Returns a list of available audio input devices (microphones). - -```javascript + +```typescript const audioInputDevices = CometChatCalls.getAudioInputDevices(); console.log("Available microphones:", audioInputDevices); ``` - -```typescript + +```javascript const audioInputDevices = CometChatCalls.getAudioInputDevices(); console.log("Available microphones:", audioInputDevices); ``` @@ -555,14 +555,14 @@ console.log("Available microphones:", audioInputDevices); Returns a list of available audio output devices (speakers/headphones). - -```javascript + +```typescript const audioOutputDevices = CometChatCalls.getAudioOutputDevices(); console.log("Available speakers:", audioOutputDevices); ``` - -```typescript + +```javascript const audioOutputDevices = CometChatCalls.getAudioOutputDevices(); console.log("Available speakers:", audioOutputDevices); ``` @@ -574,14 +574,14 @@ console.log("Available speakers:", audioOutputDevices); Returns a list of available video input devices (cameras). - -```javascript + +```typescript const videoInputDevices = CometChatCalls.getVideoInputDevices(); console.log("Available cameras:", videoInputDevices); ``` - -```typescript + +```javascript const videoInputDevices = CometChatCalls.getVideoInputDevices(); console.log("Available cameras:", videoInputDevices); ``` @@ -593,13 +593,13 @@ console.log("Available cameras:", videoInputDevices); Sets the active audio input device (microphone) by device ID. - -```javascript + +```typescript CometChatCalls.setAudioInputDevice(deviceId); ``` - -```typescript + +```javascript CometChatCalls.setAudioInputDevice(deviceId); ``` @@ -610,13 +610,13 @@ CometChatCalls.setAudioInputDevice(deviceId); Sets the active audio output device (speaker/headphones) by device ID. - -```javascript + +```typescript CometChatCalls.setAudioOutputDevice(deviceId); ``` - -```typescript + +```javascript CometChatCalls.setAudioOutputDevice(deviceId); ``` @@ -627,13 +627,13 @@ CometChatCalls.setAudioOutputDevice(deviceId); Sets the active video input device (camera) by device ID. - -```javascript + +```typescript CometChatCalls.setVideoInputDevice(deviceId); ``` - -```typescript + +```javascript CometChatCalls.setVideoInputDevice(deviceId); ``` @@ -644,13 +644,13 @@ CometChatCalls.setVideoInputDevice(deviceId); Upgrades an ongoing audio call to a video call. This enables the camera and starts transmitting video to other participants. The remote participant receives the `onCallSwitchedToVideo()` callback. - -```javascript + +```typescript CometChatCalls.switchToVideoCall(); ``` - -```typescript + +```javascript CometChatCalls.switchToVideoCall(); ``` @@ -661,13 +661,13 @@ 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 + +```typescript CometChatCalls.endSession(); ``` - -```typescript + +```javascript CometChatCalls.endSession(); ``` diff --git a/sdk/javascript/user-management.mdx b/sdk/javascript/user-management.mdx index a5625c047..5d87d92f1 100644 --- a/sdk/javascript/user-management.mdx +++ b/sdk/javascript/user-management.mdx @@ -40,42 +40,42 @@ User creation should ideally happen on your backend via the [REST API](https://a For client-side creation (development only), use `createUser()`: - -```javascript -let authKey = "AUTH_KEY"; -let uid = "user1"; -let name = "Kevin"; + +```typescript +let authKey: string = "AUTH_KEY"; +let uid: string = "user1"; +let name: string = "Kevin"; -let user = new CometChat.User(uid); +let user: CometChat.User = new CometChat.User(uid); user.setName(name); CometChat.createUser(user, authKey).then( - user => { + (user: CometChat.User) => { console.log("user created", user); - }, error => { + }, (error: CometChat.CometChatException) => { console.log("error", error); } -) +); ``` - -```typescript -let authKey: string = "AUTH_KEY"; -let uid: string = "user1"; -let name: string = "Kevin"; + +```javascript +let authKey = "AUTH_KEY"; +let uid = "user1"; +let name = "Kevin"; -let user: CometChat.User = new CometChat.User(uid); +let user = new CometChat.User(uid); user.setName(name); CometChat.createUser(user, authKey).then( - (user: CometChat.User) => { + user => { console.log("user created", user); - }, (error: CometChat.CometChatException) => { + }, error => { console.log("error", error); } -); +) ``` @@ -103,39 +103,39 @@ Like creation, user updates should ideally happen on your backend via the [REST For client-side updates (development only), use `updateUser()`: - -```javascript -let authKey = "AUTH_KEY"; -let uid = "user1"; -let name = "Kevin Fernandez"; + +```typescript +let authKey: string = "AUTH_KEY"; +let uid: string = "user1"; +let name: string = "Kevin Fernandez"; -let user = new CometChat.User(uid); +let user: CometChat.User = new CometChat.User(uid); user.setName(name); CometChat.updateUser(user, authKey).then( - user => { + (user: CometChat.User) => { console.log("user updated", user); - }, error => { + }, (error: CometChat.CometChatException) => { console.log("error", error); } ) ``` - -```typescript -let authKey: string = "AUTH_KEY"; -let uid: string = "user1"; -let name: string = "Kevin Fernandez"; + +```javascript +let authKey = "AUTH_KEY"; +let uid = "user1"; +let name = "Kevin Fernandez"; -let user: CometChat.User = new CometChat.User(uid); +let user = new CometChat.User(uid); user.setName(name); CometChat.updateUser(user, authKey).then( - (user: CometChat.User) => { + user => { console.log("user updated", user); - }, (error: CometChat.CometChatException) => { + }, error => { console.log("error", error); } ) @@ -160,40 +160,40 @@ The method returns a [`User`](/sdk/reference/entities#user) object. Access the r Use `updateCurrentUserDetails()` to update the current user without an Auth Key. Note: You cannot update the user's role with this method. - -```javascript -let uid = "user1"; -let name = "Kevin Fernandez"; + +```typescript +let uid: string = "user1"; +let name: string = "Kevin Fernandez"; -let user = new CometChat.User(uid); +let user: CometChat.User = new CometChat.User(uid); user.setName(name); CometChat.updateCurrentUserDetails(user).then( - user => { + (user: CometChat.User) => { console.log("user updated", user); - }, error => { + }, (error: CometChat.CometChatException) => { console.log("error", error); } -) +); ``` - -```typescript -let uid: string = "user1"; -let name: string = "Kevin Fernandez"; + +```javascript +let uid = "user1"; +let name = "Kevin Fernandez"; -let user: CometChat.User = new CometChat.User(uid); +let user = new CometChat.User(uid); user.setName(name); CometChat.updateCurrentUserDetails(user).then( - (user: CometChat.User) => { + user => { console.log("user updated", user); - }, (error: CometChat.CometChatException) => { + }, error => { console.log("error", error); } -); +) ``` diff --git a/sdk/javascript/user-presence.mdx b/sdk/javascript/user-presence.mdx index 0b62bf35c..f85b09166 100644 --- a/sdk/javascript/user-presence.mdx +++ b/sdk/javascript/user-presence.mdx @@ -45,34 +45,34 @@ You must configure presence subscription in `AppSettings` during `CometChat.init Register a `UserListener` to receive presence events: - -```javascript -let listenerID = "UNIQUE_LISTENER_ID"; + +```typescript +let listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addUserListener( listenerID, new CometChat.UserListener({ - onUserOnline: onlineUser => { + onUserOnline: (onlineUser: CometChat.User) => { console.log("On User Online:", { onlineUser }); }, - onUserOffline: offlineUser => { + onUserOffline: (offlineUser: CometChat.User) => { console.log("On User Offline:", { offlineUser }); } }) ); ``` - -```typescript -let listenerID: string = "UNIQUE_LISTENER_ID"; + +```javascript +let listenerID = "UNIQUE_LISTENER_ID"; CometChat.addUserListener( listenerID, new CometChat.UserListener({ - onUserOnline: (onlineUser: CometChat.User) => { + onUserOnline: onlineUser => { console.log("On User Online:", { onlineUser }); }, - onUserOffline: (offlineUser: CometChat.User) => { + onUserOffline: offlineUser => { console.log("On User Offline:", { offlineUser }); } }) @@ -99,18 +99,18 @@ The listener callbacks provide a [`User`](/sdk/reference/entities#user) object w Remove the listener when no longer needed: - -```javascript -let listenerID = "UNIQUE_LISTENER_ID"; -CometChat.removeUserListener(listenerID); -``` - ```typescript let listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.removeUserListener(listenerID); ``` + +```javascript +let listenerID = "UNIQUE_LISTENER_ID"; +CometChat.removeUserListener(listenerID); +``` + diff --git a/sdk/javascript/video-view-customisation.mdx b/sdk/javascript/video-view-customisation.mdx index 84e242291..c02eccfc2 100644 --- a/sdk/javascript/video-view-customisation.mdx +++ b/sdk/javascript/video-view-customisation.mdx @@ -33,9 +33,9 @@ The `MainVideoContainerSetting` class customizes the main video view. Pass a `Ma Example: - -```javascript -let videoSettings = new CometChat.MainVideoContainerSetting(); + +```typescript +let videoSettings: CometChat.MainVideoContainerSetting = new CometChat.MainVideoContainerSetting(); videoSettings.setMainVideoAspectRatio(CometChat.CallSettings.ASPECT_RATIO_CONTAIN); videoSettings.setFullScreenButtonParams(CometChat.CallSettings.POSITION_BOTTOM_RIGHT, true); @@ -43,9 +43,9 @@ videoSettings.setNameLabelParams(CometChat.CallSettings.POSITION_BOTTOM_LEFT, tr videoSettings.setNetworkLabelParams(CometChat.CallSettings.POSITION_BOTTOM_RIGHT, true); ``` - -```typescript -let videoSettings: CometChat.MainVideoContainerSetting = new CometChat.MainVideoContainerSetting(); + +```javascript +let videoSettings = new CometChat.MainVideoContainerSetting(); videoSettings.setMainVideoAspectRatio(CometChat.CallSettings.ASPECT_RATIO_CONTAIN); videoSettings.setFullScreenButtonParams(CometChat.CallSettings.POSITION_BOTTOM_RIGHT, true); diff --git a/sdk/javascript/virtual-background.mdx b/sdk/javascript/virtual-background.mdx index f3f7a2a74..86bbc1e07 100644 --- a/sdk/javascript/virtual-background.mdx +++ b/sdk/javascript/virtual-background.mdx @@ -35,18 +35,18 @@ For custom UI without the default layout, use these methods to control virtual b You can use the `openVirtualBackground()` method to open the virtual background settings pop-up. - -```javascript -let callController = CometChat.CallController.getInstance(); -callController.openVirtualBackground(); -``` - ```typescript let callController: CometChat.CallController = CometChat.CallController.getInstance(); callController.openVirtualBackground(); ``` + +```javascript +let callController = CometChat.CallController.getInstance(); +callController.openVirtualBackground(); +``` + ### Set Background Blur @@ -54,13 +54,6 @@ callController.openVirtualBackground(); You can use the `setBackgroundBlur()` method to apply background blur on the video stream. This method accepts a number which decides the level of blur to be applied. - -```javascript -let callController = CometChat.CallController.getInstance(); -let blurLevel = 1; -callController.setBackgroundBlur(blurLevel); -``` - ```typescript let callController: CometChat.CallController = CometChat.CallController.getInstance(); @@ -68,6 +61,13 @@ let blurLevel: number = 1; callController.setBackgroundBlur(blurLevel); ``` + +```javascript +let callController = CometChat.CallController.getInstance(); +let blurLevel = 1; +callController.setBackgroundBlur(blurLevel); +``` + ### Set Background Image @@ -75,13 +75,6 @@ callController.setBackgroundBlur(blurLevel); You can use the `setBackgroundImage()`method to set the background image. This method takes either a URL or file Object & sets that image as the background. - -```javascript -let callController = CometChat.CallController.getInstance(); -let imageURL = "URL_OF_BACKGROUND_IMAGE"; -callController.setBackgroundImage(imageURL); -``` - ```typescript let callController: CometChat.CallController = CometChat.CallController.getInstance(); @@ -89,6 +82,13 @@ let imageURL: string = "URL_OF_BACKGROUND_IMAGE"; callController.setBackgroundImage(imageURL); ``` + +```javascript +let callController = CometChat.CallController.getInstance(); +let imageURL = "URL_OF_BACKGROUND_IMAGE"; +callController.setBackgroundImage(imageURL); +``` + ## Virtual Background Settings From 60b649289b746c3dc70568e1bc4e03eda478fb6c Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 25 Mar 2026 12:09:04 +0530 Subject: [PATCH 049/139] Revert "updates the typescript first and then javascript for examples" This reverts commit 933bc89fe013be9deddd07623f85bc92e3f962cd. --- .../additional-message-filtering.mdx | 16 +- sdk/javascript/ai-agents.mdx | 42 +-- .../ai-integration-quick-reference.mdx | 64 ++-- sdk/javascript/ai-moderation.mdx | 44 +-- sdk/javascript/all-real-time-listeners.mdx | 286 +++++++++--------- sdk/javascript/authentication-overview.mdx | 84 ++--- sdk/javascript/block-users.mdx | 94 +++--- sdk/javascript/call-logs.mdx | 20 +- sdk/javascript/calling-setup.mdx | 16 +- sdk/javascript/create-group.mdx | 84 ++--- sdk/javascript/default-call.mdx | 206 ++++++------- sdk/javascript/delete-group.mdx | 30 +- sdk/javascript/delete-message.mdx | 30 +- sdk/javascript/delivery-read-receipts.mdx | 88 +++--- sdk/javascript/direct-call.mdx | 236 +++++++-------- sdk/javascript/flag-message.mdx | 48 +-- sdk/javascript/initialization.mdx | 32 +- sdk/javascript/interactive-messages.mdx | 136 ++++----- sdk/javascript/login-listener.mdx | 78 ++--- ...aging-web-sockets-connections-manually.mdx | 28 +- .../message-structure-and-hierarchy.mdx | 46 +-- sdk/javascript/rate-limits.mdx | 32 +- sdk/javascript/reactions.mdx | 200 ++++++------ sdk/javascript/recording.mdx | 8 +- sdk/javascript/retrieve-conversations.mdx | 168 +++++----- sdk/javascript/retrieve-users.mdx | 102 +++---- sdk/javascript/send-message.mdx | 40 +-- sdk/javascript/standalone-calling.mdx | 224 +++++++------- sdk/javascript/user-management.mdx | 100 +++--- sdk/javascript/user-presence.mdx | 32 +- sdk/javascript/video-view-customisation.mdx | 12 +- sdk/javascript/virtual-background.mdx | 40 +-- 32 files changed, 1333 insertions(+), 1333 deletions(-) diff --git a/sdk/javascript/additional-message-filtering.mdx b/sdk/javascript/additional-message-filtering.mdx index d4db9dd74..7f89e548a 100644 --- a/sdk/javascript/additional-message-filtering.mdx +++ b/sdk/javascript/additional-message-filtering.mdx @@ -58,14 +58,6 @@ Messages are paginated with a maximum of 100 per request. Call `fetchPrevious()` Set the number of messages to fetch per request using `setLimit()`. Maximum is 100. - -```typescript -let messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder().setLimit(50).build(); -``` - - - ```js let messagesRequest = new CometChat.MessagesRequestBuilder() @@ -75,6 +67,14 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() + +```typescript +let messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder().setLimit(50).build(); +``` + + + ## Messages for a user conversation diff --git a/sdk/javascript/ai-agents.mdx b/sdk/javascript/ai-agents.mdx index 80e5da475..d3d998e32 100644 --- a/sdk/javascript/ai-agents.mdx +++ b/sdk/javascript/ai-agents.mdx @@ -63,13 +63,13 @@ Events arrive via `onAIAssistantEventReceived` in this order: - - ```ts - const listnerId: string = "unique_listener_id"; + + ```js + const listnerId = "unique_listener_id"; // Adding the AIAssistantListener CometChat.addAIAssistantListener(listnerId, { - onAIAssistantEventReceived: (message: CometChat.AIAssistantBaseEvent) => { + onAIAssistantEventReceived: (message) => { console.log("AIAssistant event received successfully", message); } }); @@ -78,13 +78,13 @@ Events arrive via `onAIAssistantEventReceived` in this order: CometChat.removeAIAssistantListener(listnerId); ``` - - ```js - const listnerId = "unique_listener_id"; + + ```ts + const listnerId: string = "unique_listener_id"; // Adding the AIAssistantListener CometChat.addAIAssistantListener(listnerId, { - onAIAssistantEventReceived: (message) => { + onAIAssistantEventReceived: (message: CometChat.AIAssistantBaseEvent) => { console.log("AIAssistant event received successfully", message); } }); @@ -106,20 +106,19 @@ After the run completes, these messages arrive via `MessageListener`: | `AIToolArgumentMessage` | The arguments passed to a tool | - - - ```ts - const listnerId: string = "unique_listener_id"; + + ```js + const listnerId = "unique_listener_id"; // Adding the MessageListener CometChat.addMessageListener(listnerId, { - onAIAssistantMessageReceived: (message: CometChat.AIAssistantMessage) => { + onAIAssistantMessageReceived: (message) => { console.log("AI Assistant message received successfully", message); }, - onAIToolResultReceived: (message: CometChat.AIToolResultMessage) => { + onAIToolResultReceived: (message) => { console.log("AI Tool result message received successfully", message); }, - onAIToolArgumentsReceived: (message: CometChat.AIToolArgumentMessage) => { + onAIToolArgumentsReceived: (message) => { console.log("AI Tool argument message received successfully", message); }, }); @@ -128,19 +127,20 @@ After the run completes, these messages arrive via `MessageListener`: CometChat.removeMessageListener(listnerId); ``` - - ```js - const listnerId = "unique_listener_id"; + + + ```ts + const listnerId: string = "unique_listener_id"; // Adding the MessageListener CometChat.addMessageListener(listnerId, { - onAIAssistantMessageReceived: (message) => { + onAIAssistantMessageReceived: (message: CometChat.AIAssistantMessage) => { console.log("AI Assistant message received successfully", message); }, - onAIToolResultReceived: (message) => { + onAIToolResultReceived: (message: CometChat.AIToolResultMessage) => { console.log("AI Tool result message received successfully", message); }, - onAIToolArgumentsReceived: (message) => { + onAIToolArgumentsReceived: (message: CometChat.AIToolArgumentMessage) => { console.log("AI Tool argument message received successfully", message); }, }); diff --git a/sdk/javascript/ai-integration-quick-reference.mdx b/sdk/javascript/ai-integration-quick-reference.mdx index e2ce6b1dd..3f3af5c23 100644 --- a/sdk/javascript/ai-integration-quick-reference.mdx +++ b/sdk/javascript/ai-integration-quick-reference.mdx @@ -41,26 +41,26 @@ AI Agents enable intelligent, automated interactions. They process user messages - Event flow: Run Start → Tool Call(s) → Text Message Stream → Run Finished - - ```typescript - const listnerId: string = "unique_listener_id"; + + ```javascript + const listnerId = "unique_listener_id"; // Adding the AIAssistantListener for real-time events CometChat.addAIAssistantListener(listnerId, { - onAIAssistantEventReceived: (message: CometChat.AIAssistantBaseEvent) => { + onAIAssistantEventReceived: (message) => { console.log("AIAssistant event received successfully", message); } }); // Adding the MessageListener for persisted agentic messages CometChat.addMessageListener(listnerId, { - onAIAssistantMessageReceived: (message: CometChat.AIAssistantMessage) => { + onAIAssistantMessageReceived: (message) => { console.log("AI Assistant message received successfully", message); }, - onAIToolResultReceived: (message: CometChat.AIToolResultMessage) => { + onAIToolResultReceived: (message) => { console.log("AI Tool result message received successfully", message); }, - onAIToolArgumentsReceived: (message: CometChat.AIToolArgumentMessage) => { + onAIToolArgumentsReceived: (message) => { console.log("AI Tool argument message received successfully", message); }, }); @@ -70,26 +70,26 @@ AI Agents enable intelligent, automated interactions. They process user messages CometChat.removeMessageListener(listnerId); ``` - - ```javascript - const listnerId = "unique_listener_id"; + + ```typescript + const listnerId: string = "unique_listener_id"; // Adding the AIAssistantListener for real-time events CometChat.addAIAssistantListener(listnerId, { - onAIAssistantEventReceived: (message) => { + onAIAssistantEventReceived: (message: CometChat.AIAssistantBaseEvent) => { console.log("AIAssistant event received successfully", message); } }); // Adding the MessageListener for persisted agentic messages CometChat.addMessageListener(listnerId, { - onAIAssistantMessageReceived: (message) => { + onAIAssistantMessageReceived: (message: CometChat.AIAssistantMessage) => { console.log("AI Assistant message received successfully", message); }, - onAIToolResultReceived: (message) => { + onAIToolResultReceived: (message: CometChat.AIToolResultMessage) => { console.log("AI Tool result message received successfully", message); }, - onAIToolArgumentsReceived: (message) => { + onAIToolArgumentsReceived: (message: CometChat.AIToolArgumentMessage) => { console.log("AI Tool argument message received successfully", message); }, }); @@ -111,8 +111,8 @@ AI Moderation automatically reviews messages for inappropriate content in real-t - Enable and configure rules in the CometChat Dashboard - - ```typescript + + ```javascript // Send message and check initial moderation status const textMessage = new CometChat.TextMessage( receiverUID, @@ -121,27 +121,27 @@ AI Moderation automatically reviews messages for inappropriate content in real-t ); CometChat.sendMessage(textMessage).then( - (message: CometChat.TextMessage) => { - const status: string = message.getModerationStatus(); + (message) => { + const status = message.getModerationStatus(); if (status === CometChat.ModerationStatus.PENDING) { console.log("Message is under moderation review"); } }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Message sending failed:", error); } ); // Listen for moderation results - const listenerID: string = "MODERATION_LISTENER"; + const listenerID = "MODERATION_LISTENER"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onMessageModerated: (message: CometChat.BaseMessage) => { - const status: string = message.getModerationStatus(); - const messageId: number = message.getId(); + onMessageModerated: (message) => { + const status = message.getModerationStatus(); + const messageId = message.getId(); switch (status) { case CometChat.ModerationStatus.APPROVED: @@ -156,8 +156,8 @@ AI Moderation automatically reviews messages for inappropriate content in real-t ); ``` - - ```javascript + + ```typescript // Send message and check initial moderation status const textMessage = new CometChat.TextMessage( receiverUID, @@ -166,27 +166,27 @@ AI Moderation automatically reviews messages for inappropriate content in real-t ); CometChat.sendMessage(textMessage).then( - (message) => { - const status = message.getModerationStatus(); + (message: CometChat.TextMessage) => { + const status: string = message.getModerationStatus(); if (status === CometChat.ModerationStatus.PENDING) { console.log("Message is under moderation review"); } }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Message sending failed:", error); } ); // Listen for moderation results - const listenerID = "MODERATION_LISTENER"; + const listenerID: string = "MODERATION_LISTENER"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onMessageModerated: (message) => { - const status = message.getModerationStatus(); - const messageId = message.getId(); + onMessageModerated: (message: CometChat.BaseMessage) => { + const status: string = message.getModerationStatus(); + const messageId: number = message.getId(); switch (status) { case CometChat.ModerationStatus.APPROVED: diff --git a/sdk/javascript/ai-moderation.mdx b/sdk/javascript/ai-moderation.mdx index 44f8a4482..3222af96a 100644 --- a/sdk/javascript/ai-moderation.mdx +++ b/sdk/javascript/ai-moderation.mdx @@ -96,8 +96,8 @@ The `getModerationStatus()` method returns one of the following values: When you send a text, image, or video message, check the initial moderation status: - - ```typescript + + ```javascript const textMessage = new CometChat.TextMessage( receiverUID, "Hello, how are you?", @@ -105,23 +105,23 @@ When you send a text, image, or video message, check the initial moderation stat ); CometChat.sendMessage(textMessage).then( - (message: CometChat.TextMessage) => { + (message) => { // Check moderation status - const status: string = message.getModerationStatus(); + const status = message.getModerationStatus(); if (status === CometChat.ModerationStatus.PENDING) { console.log("Message is under moderation review"); // Show pending indicator in UI } }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Message sending failed:", error); } ); ``` - - ```javascript + + ```typescript const textMessage = new CometChat.TextMessage( receiverUID, "Hello, how are you?", @@ -129,16 +129,16 @@ When you send a text, image, or video message, check the initial moderation stat ); CometChat.sendMessage(textMessage).then( - (message) => { + (message: CometChat.TextMessage) => { // Check moderation status - const status = message.getModerationStatus(); + const status: string = message.getModerationStatus(); if (status === CometChat.ModerationStatus.PENDING) { console.log("Message is under moderation review"); // Show pending indicator in UI } }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Message sending failed:", error); } ); @@ -151,20 +151,20 @@ When you send a text, image, or video message, check the initial moderation stat Register a message listener to receive moderation results in real-time: - - ```typescript - const listenerID: string = "MODERATION_LISTENER"; + + ```javascript + const listenerID = "MODERATION_LISTENER"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onMessageModerated: (message: CometChat.BaseMessage) => { + onMessageModerated: (message) => { if ( message instanceof CometChat.TextMessage || message instanceof CometChat.MediaMessage ) { - const status: string = message.getModerationStatus(); - const messageId: number = message.getId(); + const status = message.getModerationStatus(); + const messageId = message.getId(); switch (status) { case CometChat.ModerationStatus.APPROVED: @@ -187,20 +187,20 @@ Register a message listener to receive moderation results in real-time: // CometChat.removeMessageListener(listenerID); ``` - - ```javascript - const listenerID = "MODERATION_LISTENER"; + + ```typescript + const listenerID: string = "MODERATION_LISTENER"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onMessageModerated: (message) => { + onMessageModerated: (message: CometChat.BaseMessage) => { if ( message instanceof CometChat.TextMessage || message instanceof CometChat.MediaMessage ) { - const status = message.getModerationStatus(); - const messageId = message.getId(); + const status: string = message.getModerationStatus(); + const messageId: number = message.getId(); switch (status) { case CometChat.ModerationStatus.APPROVED: diff --git a/sdk/javascript/all-real-time-listeners.mdx b/sdk/javascript/all-real-time-listeners.mdx index e2c92ddbc..a33575498 100644 --- a/sdk/javascript/all-real-time-listeners.mdx +++ b/sdk/javascript/all-real-time-listeners.mdx @@ -58,18 +58,16 @@ The `UserListener` class provides you with live events related to users. Below a To add the `UserListener`, you need to use the `addUserListener()` method provided by the `CometChat` class. - -```typescript -const listenerID: string = "UNIQUE_LISTENER_ID"; + +```js +const listenerID = "UNIQUE_LISTENER_ID"; CometChat.addUserListener( listenerID, new CometChat.UserListener({ - onUserOnline: (onlineUser: CometChat.User) => { - /* when someuser/friend comes online, user will be received here */ + onUserOnline: (onlineUser) => { console.log("On User Online:", { onlineUser }); }, - onUserOffline: (offlineUser: CometChat.User) => { - /* when someuser/friend went offline, user will be received here */ + onUserOffline: (offlineUser) => { console.log("On User Offline:", { offlineUser }); }, }) @@ -78,16 +76,18 @@ CometChat.addUserListener( - -```js -const listenerID = "UNIQUE_LISTENER_ID"; + +```typescript +const listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addUserListener( listenerID, new CometChat.UserListener({ - onUserOnline: (onlineUser) => { + onUserOnline: (onlineUser: CometChat.User) => { + /* when someuser/friend comes online, user will be received here */ console.log("On User Online:", { onlineUser }); }, - onUserOffline: (offlineUser) => { + onUserOffline: (offlineUser: CometChat.User) => { + /* when someuser/friend went offline, user will be received here */ console.log("On User Offline:", { offlineUser }); }, }) @@ -103,17 +103,17 @@ where `UNIQUE_LISTENER_ID` is the unique identifier for the listener. Please mak Once the `UserListener` is not in use, you need to remove the listener using the `removeUserListener()` method which takes the id of the listener to be removed as the parameter. - -```typescript -let listenerID: string = "UNIQUE_LISTENER_ID"; -CometChat.removeUserListener(listenerID); + +```js +CometChat.removeUserListener(UNIQUE_LISTENER_ID); ``` - -```js -CometChat.removeUserListener(UNIQUE_LISTENER_ID); + +```typescript +let listenerID: string = "UNIQUE_LISTENER_ID"; +CometChat.removeUserListener(listenerID); ``` @@ -137,31 +137,18 @@ The `GroupListener` class provides you with all the real-time events related to To add the `GroupListener`, you need to use the `addGroupListener()` method provided by the `CometChat` class. - -```typescript + +```js CometChat.addGroupListener( "UNIQUE_LISTENER_ID", new CometChat.GroupListener({ - onGroupMemberJoined: ( - message: CometChat.Action, - joinedUser: CometChat.User, - joinedGroup: CometChat.Group - ) => { + onGroupMemberJoined: (message, joinedUser, joinedGroup) => { console.log("onGroupMemberJoined", { message, joinedUser, joinedGroup }); }, - onGroupMemberLeft: ( - message: CometChat.Action, - leftUser: CometChat.User, - leftGroup: CometChat.Group - ) => { + onGroupMemberLeft: (message, leftUser, leftGroup) => { console.log("onGroupMemberLeft", { message, leftUser, leftGroup }); }, - onGroupMemberKicked: ( - message: CometChat.Action, - kickedUser: CometChat.User, - kickedBy: CometChat.User, - kickedFrom: CometChat.Group - ) => { + onGroupMemberKicked: (message, kickedUser, kickedBy, kickedFrom) => { console.log("onGroupMemberKicked", { message, kickedUser, @@ -169,12 +156,7 @@ CometChat.addGroupListener( kickedFrom, }); }, - onGroupMemberBanned: ( - message: CometChat.Action, - bannedUser: CometChat.User, - bannedBy: CometChat.User, - bannedFrom: CometChat.Group - ) => { + onGroupMemberBanned: (message, bannedUser, bannedBy, bannedFrom) => { console.log("onGroupMemberBanned", { message, bannedUser, @@ -183,10 +165,10 @@ CometChat.addGroupListener( }); }, onGroupMemberUnbanned: ( - message: CometChat.Action, - unbannedUser: CometChat.User, - unbannedBy: CometChat.User, - unbannedFrom: CometChat.Group + message, + unbannedUser, + unbannedBy, + unbannedFrom ) => { console.log("onGroupMemberUnbanned", { message, @@ -196,11 +178,11 @@ CometChat.addGroupListener( }); }, onGroupMemberScopeChanged: ( - message: CometChat.Action, - changedUser: CometChat.User, - newScope: string, - oldScope: string, - changedGroup: CometChat.Group + message, + changedUser, + newScope, + oldScope, + changedGroup ) => { console.log("onGroupMemberScopeChanged", { message, @@ -210,12 +192,7 @@ CometChat.addGroupListener( changedGroup, }); }, - onMemberAddedToGroup: ( - message: CometChat.Action, - userAdded: CometChat.User, - addedby: CometChat.User, - addedTo: CometChat.Group - ) => { + onMemberAddedToGroup: (message, userAdded, addedby, addedTo) => { console.log("onMemberAddedToGroup", { message, userAdded, @@ -229,18 +206,31 @@ CometChat.addGroupListener( - -```js + +```typescript CometChat.addGroupListener( "UNIQUE_LISTENER_ID", new CometChat.GroupListener({ - onGroupMemberJoined: (message, joinedUser, joinedGroup) => { + onGroupMemberJoined: ( + message: CometChat.Action, + joinedUser: CometChat.User, + joinedGroup: CometChat.Group + ) => { console.log("onGroupMemberJoined", { message, joinedUser, joinedGroup }); }, - onGroupMemberLeft: (message, leftUser, leftGroup) => { + onGroupMemberLeft: ( + message: CometChat.Action, + leftUser: CometChat.User, + leftGroup: CometChat.Group + ) => { console.log("onGroupMemberLeft", { message, leftUser, leftGroup }); }, - onGroupMemberKicked: (message, kickedUser, kickedBy, kickedFrom) => { + onGroupMemberKicked: ( + message: CometChat.Action, + kickedUser: CometChat.User, + kickedBy: CometChat.User, + kickedFrom: CometChat.Group + ) => { console.log("onGroupMemberKicked", { message, kickedUser, @@ -248,7 +238,12 @@ CometChat.addGroupListener( kickedFrom, }); }, - onGroupMemberBanned: (message, bannedUser, bannedBy, bannedFrom) => { + onGroupMemberBanned: ( + message: CometChat.Action, + bannedUser: CometChat.User, + bannedBy: CometChat.User, + bannedFrom: CometChat.Group + ) => { console.log("onGroupMemberBanned", { message, bannedUser, @@ -257,10 +252,10 @@ CometChat.addGroupListener( }); }, onGroupMemberUnbanned: ( - message, - unbannedUser, - unbannedBy, - unbannedFrom + message: CometChat.Action, + unbannedUser: CometChat.User, + unbannedBy: CometChat.User, + unbannedFrom: CometChat.Group ) => { console.log("onGroupMemberUnbanned", { message, @@ -270,11 +265,11 @@ CometChat.addGroupListener( }); }, onGroupMemberScopeChanged: ( - message, - changedUser, - newScope, - oldScope, - changedGroup + message: CometChat.Action, + changedUser: CometChat.User, + newScope: string, + oldScope: string, + changedGroup: CometChat.Group ) => { console.log("onGroupMemberScopeChanged", { message, @@ -284,7 +279,12 @@ CometChat.addGroupListener( changedGroup, }); }, - onMemberAddedToGroup: (message, userAdded, addedby, addedTo) => { + onMemberAddedToGroup: ( + message: CometChat.Action, + userAdded: CometChat.User, + addedby: CometChat.User, + addedTo: CometChat.Group + ) => { console.log("onMemberAddedToGroup", { message, userAdded, @@ -305,17 +305,17 @@ where `UNIQUE_LISTENER_ID` is the unique identifier for the listener. Please mak Once the `GroupListener` is not in use, you need to remove the listener using the `removeGroupListener()` method which takes the id of the listener to be removed as the parameter. - -```typescript -let listenerID: string = "UNIQUE_LISTENER_ID"; -CometChat.removeGroupListener(listenerID); + +```js +CometChat.removeGroupListener(UNIQUE_LISTENER_ID); ``` - -```js -CometChat.removeGroupListener(UNIQUE_LISTENER_ID); + +```typescript +let listenerID: string = "UNIQUE_LISTENER_ID"; +CometChat.removeGroupListener(listenerID); ``` @@ -346,54 +346,54 @@ The `MessageListener` class provides you with live events related to messages. B To add the `MessageListener`, you need to use the `addMessageListener()` method provided by the `CometChat` class. - -```typescript + +```js CometChat.addMessageListener( "UNIQUE_LISTENER_ID", new CometChat.MessageListener({ - onTextMessageReceived: (textMessage: CometChat.TextMessage) => { + onTextMessageReceived: (textMessage) => { console.log("Text message received successfully", textMessage); }, - onMediaMessageReceived: (mediaMessage: CometChat.MediaMessage) => { + onMediaMessageReceived: (mediaMessage) => { console.log("Media message received successfully", mediaMessage); }, - onCustomMessageReceived: (customMessage: CometChat.CustomMessage) => { + onCustomMessageReceived: (customMessage) => { console.log("Custom message received successfully", customMessage); }, - onMessagesDelivered: (messageReceipt: CometChat.MessageReceipt) => { + onMessagesDelivered: (messageReceipt) => { console.log("Message Delivered", messageReceipt); }, - onMessagesRead: (messageReceipt: CometChat.MessageReceipt) => { + onMessagesRead: (messageReceipt) => { console.log("Message Read", messageReceipt); }, - onTypingStarted: (typingIndicator: CometChat.TypingIndicator) => { + onTypingStarted: (typingIndicator) => { console.log("Typing Started", typingIndicator); }, - onTypingEnded: (typingIndicator: CometChat.TypingIndicator) => { + onTypingEnded: (typingIndicator) => { console.log("Typing Ended", typingIndicator); }, - onMessageDeleted: (message: CometChat.BaseMessage) => { - console.log("Message Delted", message); + onMessagesDeleted: (message) => { + console.log("Message Deleted", message); }, - onMessageEdited: (message: CometChat.BaseMessage) => { + onMessageEdited: (message) => { console.log("Message Edited", message); }, - onInteractiveMessageReceived: (message: CometChat.InteractiveMessage) => { + onInteractiveMessageReceived: (message) => { console.log("interactive Message received", message); }, - onInteractionGoalCompleted: (receipt: CometChat.InteractionReceipt) => { + onInteractionGoalCompleted: (message) => { console.log("Message interaction goal completed", message); }, - onTransientMessageReceived: (message: CometChat.TransientMessage) => { + onTransientMessageReceived: (message) => { console.log("Transient Message received", message); }, - onMessageReactionAdded: (reaction: CometChat.ReactionEvent) => { + onMessageReactionAdded: (reaction) => { console.log("Message Reaction added", reaction); }, - onMessageReactionRemoved: (reaction: CometChat.ReactionEvent) => { + onMessageReactionRemoved: (reaction) => { console.log("Message Reaction removed", reaction); }, - onMessageModerated: (message: CometChat.BaseMessage) => { + onMessageModerated: (message) => { console.log("Message Moderated", message); }, }) @@ -402,54 +402,54 @@ CometChat.addMessageListener( - -```js + +```typescript CometChat.addMessageListener( "UNIQUE_LISTENER_ID", new CometChat.MessageListener({ - onTextMessageReceived: (textMessage) => { + onTextMessageReceived: (textMessage: CometChat.TextMessage) => { console.log("Text message received successfully", textMessage); }, - onMediaMessageReceived: (mediaMessage) => { + onMediaMessageReceived: (mediaMessage: CometChat.MediaMessage) => { console.log("Media message received successfully", mediaMessage); }, - onCustomMessageReceived: (customMessage) => { + onCustomMessageReceived: (customMessage: CometChat.CustomMessage) => { console.log("Custom message received successfully", customMessage); }, - onMessagesDelivered: (messageReceipt) => { + onMessagesDelivered: (messageReceipt: CometChat.MessageReceipt) => { console.log("Message Delivered", messageReceipt); }, - onMessagesRead: (messageReceipt) => { + onMessagesRead: (messageReceipt: CometChat.MessageReceipt) => { console.log("Message Read", messageReceipt); }, - onTypingStarted: (typingIndicator) => { + onTypingStarted: (typingIndicator: CometChat.TypingIndicator) => { console.log("Typing Started", typingIndicator); }, - onTypingEnded: (typingIndicator) => { + onTypingEnded: (typingIndicator: CometChat.TypingIndicator) => { console.log("Typing Ended", typingIndicator); }, - onMessagesDeleted: (message) => { - console.log("Message Deleted", message); + onMessageDeleted: (message: CometChat.BaseMessage) => { + console.log("Message Delted", message); }, - onMessageEdited: (message) => { + onMessageEdited: (message: CometChat.BaseMessage) => { console.log("Message Edited", message); }, - onInteractiveMessageReceived: (message) => { + onInteractiveMessageReceived: (message: CometChat.InteractiveMessage) => { console.log("interactive Message received", message); }, - onInteractionGoalCompleted: (message) => { + onInteractionGoalCompleted: (receipt: CometChat.InteractionReceipt) => { console.log("Message interaction goal completed", message); }, - onTransientMessageReceived: (message) => { + onTransientMessageReceived: (message: CometChat.TransientMessage) => { console.log("Transient Message received", message); }, - onMessageReactionAdded: (reaction) => { + onMessageReactionAdded: (reaction: CometChat.ReactionEvent) => { console.log("Message Reaction added", reaction); }, - onMessageReactionRemoved: (reaction) => { + onMessageReactionRemoved: (reaction: CometChat.ReactionEvent) => { console.log("Message Reaction removed", reaction); }, - onMessageModerated: (message) => { + onMessageModerated: (message: CometChat.BaseMessage) => { console.log("Message Moderated", message); }, }) @@ -465,17 +465,17 @@ where `UNIQUE_LISTENER_ID` is the unique identifier for the listener. Please mak Once the `MessageListener` is not in use, you need to remove the listener using the `removeMessageListener()` method which takes the id of the listener to be removed as the parameter. - -```typescript -let listenerID: string = "UNIQUE_LISTENER_ID"; -CometChat.removeMessageListener(listenerID); + +```js +CometChat.removeMessageListener(UNIQUE_LISTENER_ID); ``` - -```js -CometChat.removeMessageListener(UNIQUE_LISTENER_ID); + +```typescript +let listenerID: string = "UNIQUE_LISTENER_ID"; +CometChat.removeMessageListener(listenerID); ``` @@ -496,21 +496,21 @@ The `CallListener` class provides you with live events related to calls. Below a To add the `CallListener`, you need to use the `addCallListener()` method provided by the `CometChat` class. - -```typescript + +```js CometChat.addCallListener( "UNIQUE_LISTENER_ID", new CometChat.CallListener({ - onIncomingCallReceived: (call: CometChat.Call) => { + onIncomingCallReceived(call) { console.log("Incoming call:", call); }, - onOutgoingCallAccepted: (call: CometChat.Call) => { + onOutgoingCallAccepted(call) { console.log("Outgoing call accepted:", call); }, - onOutgoingCallRejected: (call: CometChat.Call) => { + onOutgoingCallRejected(call) { console.log("Outgoing call rejected:", call); }, - onIncomingCallCancelled: (call: CometChat.Call) => { + onIncomingCallCancelled(call) { console.log("Incoming call canceled:", call); }, }) @@ -519,21 +519,21 @@ CometChat.addCallListener( - -```js + +```typescript CometChat.addCallListener( "UNIQUE_LISTENER_ID", new CometChat.CallListener({ - onIncomingCallReceived(call) { + onIncomingCallReceived: (call: CometChat.Call) => { console.log("Incoming call:", call); }, - onOutgoingCallAccepted(call) { + onOutgoingCallAccepted: (call: CometChat.Call) => { console.log("Outgoing call accepted:", call); }, - onOutgoingCallRejected(call) { + onOutgoingCallRejected: (call: CometChat.Call) => { console.log("Outgoing call rejected:", call); }, - onIncomingCallCancelled(call) { + onIncomingCallCancelled: (call: CometChat.Call) => { console.log("Incoming call canceled:", call); }, }) @@ -549,17 +549,17 @@ where `UNIQUE_LISTENER_ID` is the unique identifier for the listener. Please mak Once the `CallListener` is not in use, you need to remove the listener using the `removeCallListener()` method which takes the id of the listener to be removed as the parameter. - -```typescript -let listenerID: string = "UNIQUE_LISTENER_ID"; -CometChat.removeCallListener(listenerID); + +```js +CometChat.removeCallListener(UNIQUE_LISTENER_ID); ``` - -```js -CometChat.removeCallListener(UNIQUE_LISTENER_ID); + +```typescript +let listenerID: string = "UNIQUE_LISTENER_ID"; +CometChat.removeCallListener(listenerID); ``` diff --git a/sdk/javascript/authentication-overview.mdx b/sdk/javascript/authentication-overview.mdx index 9b6a07ebb..03756f7db 100644 --- a/sdk/javascript/authentication-overview.mdx +++ b/sdk/javascript/authentication-overview.mdx @@ -77,52 +77,52 @@ This straightforward authentication method is ideal for proof-of-concept (POC) d - -```typescript -const UID: string = "cometchat-uid-1"; -const authKey: string = "AUTH_KEY"; + +```js +const UID = "UID"; +const authKey = "AUTH_KEY"; CometChat.getLoggedinUser().then( - (user: CometChat.User) => { + (user) => { if (!user) { CometChat.login(UID, authKey).then( - (user: CometChat.User) => { + (user) => { console.log("Login Successful:", { user }); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Login failed with exception:", { error }); } ); } }, - (error: CometChat.CometChatException) => { - console.log("Some Error Occured", { error }); + (error) => { + console.log("Something went wrong", error); } ); ``` - -```js -const UID = "UID"; -const authKey = "AUTH_KEY"; + +```typescript +const UID: string = "cometchat-uid-1"; +const authKey: string = "AUTH_KEY"; CometChat.getLoggedinUser().then( - (user) => { + (user: CometChat.User) => { if (!user) { CometChat.login(UID, authKey).then( - (user) => { + (user: CometChat.User) => { console.log("Login Successful:", { user }); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Login failed with exception:", { error }); } ); } }, - (error) => { - console.log("Something went wrong", error); + (error: CometChat.CometChatException) => { + console.log("Some Error Occured", { error }); } ); ``` @@ -165,50 +165,50 @@ This advanced authentication procedure does not use the Auth Key directly in you 3. Load the Auth Token in your client and pass it to the `login()` method. - -```typescript -const authToken: string = "AUTH_TOKEN"; + +```js +const authToken = "AUTH_TOKEN"; CometChat.getLoggedinUser().then( - (user: CometChat.User) => { + (user) => { if (!user) { CometChat.login(authToken).then( - (user: CometChat.User) => { + (user) => { console.log("Login Successful:", { user }); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Login failed with exception:", { error }); } ); } }, - (error: CometChat.CometChatException) => { - console.log("Some Error Occured", { error }); + (error) => { + console.log("Something went wrong", error); } ); ``` - -```js -const authToken = "AUTH_TOKEN"; + +```typescript +const authToken: string = "AUTH_TOKEN"; CometChat.getLoggedinUser().then( - (user) => { + (user: CometChat.User) => { if (!user) { CometChat.login(authToken).then( - (user) => { + (user: CometChat.User) => { console.log("Login Successful:", { user }); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Login failed with exception:", { error }); } ); } }, - (error) => { - console.log("Something went wrong", error); + (error: CometChat.CometChatException) => { + console.log("Some Error Occured", { error }); } ); ``` @@ -245,13 +245,13 @@ After the user logs in, their information is returned in the `User` object on th You can use the `logout()` method to log out the user from CometChat. We suggest you call this method once your user has been successfully logged out from your app. - -```typescript + +```js CometChat.logout().then( - (loggedOut: Object) => { + () => { console.log("Logout completed successfully"); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Logout failed with exception:", { error }); } ); @@ -259,13 +259,13 @@ CometChat.logout().then( - -```js + +```typescript CometChat.logout().then( - () => { + (loggedOut: Object) => { console.log("Logout completed successfully"); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Logout failed with exception:", { error }); } ); diff --git a/sdk/javascript/block-users.mdx b/sdk/javascript/block-users.mdx index b27f83d12..5fd991ef8 100644 --- a/sdk/javascript/block-users.mdx +++ b/sdk/javascript/block-users.mdx @@ -27,21 +27,6 @@ let blockedUsers = await request.fetchNext(); Block users to prevent all communication with them. Use `blockUsers()` with an array of UIDs. - -```typescript -const usersList: String[] = ["UID1", "UID2", "UID3"]; - -CometChat.blockUsers(usersList).then( - (list: Object) => { - console.log("users list blocked", { list }); - }, (error: CometChat.CometChatException) => { - console.log("Blocking user fails with error", error); - } -); -``` - - - ```javascript const usersList = ["UID1", "UID2", "UID3"]; @@ -57,6 +42,21 @@ list => { + +```typescript +const usersList: String[] = ["UID1", "UID2", "UID3"]; + +CometChat.blockUsers(usersList).then( + (list: Object) => { + console.log("users list blocked", { list }); + }, (error: CometChat.CometChatException) => { + console.log("Blocking user fails with error", error); + } +); +``` + + + ```javascript const usersList = ["UID1", "UID2", "UID3"]; @@ -89,21 +89,6 @@ The method returns an array of [`User`](/sdk/reference/entities#user) objects wi Unblock previously blocked users using `unblockUsers()` with an array of UIDs. - -```typescript -const usersList: String[] = ["UID1", "UID2", "UID3"]; - -CometChat.unblockUsers(usersList).then( - (list: Object) => { - console.log("users list blocked", { list }); - }, (error: CometChat.CometChatException) => { - console.log("Blocking user fails with error", error); - } -); -``` - - - ```javascript const usersList = ["UID1", "UID2", "UID3"]; @@ -119,6 +104,21 @@ list => { + +```typescript +const usersList: String[] = ["UID1", "UID2", "UID3"]; + +CometChat.unblockUsers(usersList).then( + (list: Object) => { + console.log("users list blocked", { list }); + }, (error: CometChat.CometChatException) => { + console.log("Blocking user fails with error", error); + } +); +``` + + + ```javascript const usersList = ["UID1", "UID2", "UID3"]; @@ -244,6 +244,23 @@ let blockedUsersRequest: CometChat.BlockedUsersRequest = new CometChat.BlockedUs After configuring the builder, call `build()` to get the `BlockedUsersRequest` object, then call `fetchNext()` to retrieve blocked users. + +```javascript +const limit = 30; +const blockedUsersRequest = new CometChat.BlockedUsersRequestBuilder() + .setLimit(limit) + .build(); +blockedUsersRequest.fetchNext().then( +userList => { + console.log("Blocked user list received:", userList); +}, error => { + console.log("Blocked user list fetching failed with error:", error); +} +); +``` + + + ```typescript let limit: number = 30; @@ -262,23 +279,6 @@ blockedUsersRequest.fetchNext().then( - -```javascript -const limit = 30; -const blockedUsersRequest = new CometChat.BlockedUsersRequestBuilder() - .setLimit(limit) - .build(); -blockedUsersRequest.fetchNext().then( -userList => { - console.log("Blocked user list received:", userList); -}, error => { - console.log("Blocked user list fetching failed with error:", error); -} -); -``` - - - --- diff --git a/sdk/javascript/call-logs.mdx b/sdk/javascript/call-logs.mdx index 41277a847..deeac9afd 100644 --- a/sdk/javascript/call-logs.mdx +++ b/sdk/javascript/call-logs.mdx @@ -110,27 +110,27 @@ The `fetchNext()` and `fetchPrevious()` methods return an array of [`Call`](/sdk Retrieve details for a specific call session using `getCallDetails()`: - -```typescript -const sessionID: string = "SESSION_ID"; + +```javascript +const sessionID = "SESSION_ID"; CometChatCalls.getCallDetails(sessionID, authToken).then( - (callLogs: Array) => { + (callLogs) => { console.log("Call details:", callLogs); }, - (error: any) => { + (error) => { console.log("Error fetching call details:", error); } ); ``` - -```javascript -const sessionID = "SESSION_ID"; + +```typescript +const sessionID: string = "SESSION_ID"; CometChatCalls.getCallDetails(sessionID, authToken).then( - (callLogs) => { + (callLogs: Array) => { console.log("Call details:", callLogs); }, - (error) => { + (error: any) => { console.log("Error fetching call details:", error); } ); diff --git a/sdk/javascript/calling-setup.mdx b/sdk/javascript/calling-setup.mdx index e0c160bbb..96ffa72cb 100644 --- a/sdk/javascript/calling-setup.mdx +++ b/sdk/javascript/calling-setup.mdx @@ -61,15 +61,15 @@ yarn add @cometchat/calls-sdk-javascript Then, import the `CometChatCalls` class wherever you want to use `CometChatCalls`. - -```typescript + +```js import { CometChatCalls } from "@cometchat/calls-sdk-javascript"; ``` - -```js + +```typescript import { CometChatCalls } from "@cometchat/calls-sdk-javascript"; ``` @@ -92,8 +92,8 @@ The `init()` method initializes the Calls SDK. It takes a `CallAppSettings` inst Call `init()` before any other `CometChatCalls` method — ideally on app startup. - -```typescript + +```js let appID = "APP_ID"; let region = "REGION"; @@ -114,8 +114,8 @@ CometChatCalls.init(callAppSetting).then( - -```js + +```typescript let appID = "APP_ID"; let region = "REGION"; diff --git a/sdk/javascript/create-group.mdx b/sdk/javascript/create-group.mdx index 65366f087..e288bb58b 100644 --- a/sdk/javascript/create-group.mdx +++ b/sdk/javascript/create-group.mdx @@ -35,26 +35,6 @@ Group types: - `CometChat.GROUP_TYPE.PRIVATE` - -```typescript -const GUID: string = "GUID"; -const groupName: string = "Hello Group!"; -const groupType: string = CometChat.GROUP_TYPE.PUBLIC; -const password: string = ""; - -const group: CometChat.Group = new CometChat.Group(GUID, groupName, groupType, password); - -CometChat.createGroup(group).then( - (group: CometChat.Group) => { - console.log("Group created successfully:", group); - }, (error: CometChat.CometChatException) => { - console.log("Group creation failed with exception:", error); - } -); -``` - - - ```javascript const GUID = "GUID"; @@ -75,6 +55,26 @@ CometChat.createGroup(group).then( + +```typescript +const GUID: string = "GUID"; +const groupName: string = "Hello Group!"; +const groupType: string = CometChat.GROUP_TYPE.PUBLIC; +const password: string = ""; + +const group: CometChat.Group = new CometChat.Group(GUID, groupName, groupType, password); + +CometChat.createGroup(group).then( + (group: CometChat.Group) => { + console.log("Group created successfully:", group); + }, (error: CometChat.CometChatException) => { + console.log("Group creation failed with exception:", error); + } +); +``` + + + ```javascript const GUID = "GUID"; @@ -131,23 +131,23 @@ Parameters: Create a `GroupMember` with: `new CometChat.GroupMember(UID, scope)` - -```typescript -let GUID: string = "cometchat-guid-11"; -let UID: string = "cometchat-uid-1"; -let groupName: string = "Hello Group!"; -let groupType: string = CometChat.GROUP_TYPE.PUBLIC; + +```js +let GUID = "cometchat-guid-11"; +let UID = "cometchat-uid-1"; +let groupName = "Hello Group!"; +let groupType = CometChat.GROUP_TYPE.PUBLIC; -let group: CometChat.Group = new CometChat.Group(GUID, groupName, groupType); -let members: Array = [ +let group = new CometChat.Group(GUID, groupName, groupType); +let members = [ new CometChat.GroupMember(UID, CometChat.GROUP_MEMBER_SCOPE.PARTICIPANT) ]; -let banMembers: Array = ["cometchat-uid-2"]; +let banMembers = ["cometchat-uid-2"]; CometChat.createGroupWithMembers(group, members, banMembers).then( - (response: Object) => { + response => { console.log("Group created successfully", response); - }, (error: CometChat.CometChatException) => { + }, error => { console.log("Some error occured while creating group", error) } ); @@ -155,23 +155,23 @@ CometChat.createGroupWithMembers(group, members, banMembers).then( - -```js -let GUID = "cometchat-guid-11"; -let UID = "cometchat-uid-1"; -let groupName = "Hello Group!"; -let groupType = CometChat.GROUP_TYPE.PUBLIC; + +```typescript +let GUID: string = "cometchat-guid-11"; +let UID: string = "cometchat-uid-1"; +let groupName: string = "Hello Group!"; +let groupType: string = CometChat.GROUP_TYPE.PUBLIC; -let group = new CometChat.Group(GUID, groupName, groupType); -let members = [ +let group: CometChat.Group = new CometChat.Group(GUID, groupName, groupType); +let members: Array = [ new CometChat.GroupMember(UID, CometChat.GROUP_MEMBER_SCOPE.PARTICIPANT) ]; -let banMembers = ["cometchat-uid-2"]; +let banMembers: Array = ["cometchat-uid-2"]; CometChat.createGroupWithMembers(group, members, banMembers).then( - response => { + (response: Object) => { console.log("Group created successfully", response); - }, error => { + }, (error: CometChat.CometChatException) => { console.log("Some error occured while creating group", error) } ); diff --git a/sdk/javascript/default-call.mdx b/sdk/javascript/default-call.mdx index 5926d7575..6dff0e20e 100644 --- a/sdk/javascript/default-call.mdx +++ b/sdk/javascript/default-call.mdx @@ -153,28 +153,33 @@ The `initiateCall()` method returns a [`Call`](/sdk/reference/messages#call) obj Register the `CallListener` to receive real-time call events. Each listener requires a unique `listenerId` string to prevent duplicate registrations and enable targeted removal. - -```typescript -const listenerId: string = "UNIQUE_LISTENER_ID"; + +```javascript +const listenerId = "UNIQUE_LISTENER_ID"; // Register listener CometChat.addCallListener( listenerId, new CometChat.CallListener({ - onIncomingCallReceived: (call: CometChat.Call) => { + onIncomingCallReceived: (call) => { console.log("Incoming call:", call); + // Show incoming call UI }, - onOutgoingCallAccepted: (call: CometChat.Call) => { + onOutgoingCallAccepted: (call) => { console.log("Outgoing call accepted:", call); + // Receiver accepted, start the call session }, - onOutgoingCallRejected: (call: CometChat.Call) => { + onOutgoingCallRejected: (call) => { console.log("Outgoing call rejected:", call); + // Receiver rejected, dismiss outgoing call UI }, - onIncomingCallCancelled: (call: CometChat.Call) => { + onIncomingCallCancelled: (call) => { console.log("Incoming call cancelled:", call); + // Caller cancelled, dismiss incoming call UI }, - onCallEndedMessageReceived: (call: CometChat.Call) => { + onCallEndedMessageReceived: (call) => { console.log("Call ended message:", call); + // Call ended by remote participant } }) ); @@ -183,33 +188,28 @@ CometChat.addCallListener( CometChat.removeCallListener(listenerId); ``` - -```javascript -const listenerId = "UNIQUE_LISTENER_ID"; + +```typescript +const listenerId: string = "UNIQUE_LISTENER_ID"; // Register listener CometChat.addCallListener( listenerId, new CometChat.CallListener({ - onIncomingCallReceived: (call) => { + onIncomingCallReceived: (call: CometChat.Call) => { console.log("Incoming call:", call); - // Show incoming call UI }, - onOutgoingCallAccepted: (call) => { + onOutgoingCallAccepted: (call: CometChat.Call) => { console.log("Outgoing call accepted:", call); - // Receiver accepted, start the call session }, - onOutgoingCallRejected: (call) => { + onOutgoingCallRejected: (call: CometChat.Call) => { console.log("Outgoing call rejected:", call); - // Receiver rejected, dismiss outgoing call UI }, - onIncomingCallCancelled: (call) => { + onIncomingCallCancelled: (call: CometChat.Call) => { console.log("Incoming call cancelled:", call); - // Caller cancelled, dismiss incoming call UI }, - onCallEndedMessageReceived: (call) => { + onCallEndedMessageReceived: (call: CometChat.Call) => { console.log("Call ended message:", call); - // Call ended by remote participant } }) ); @@ -245,20 +245,6 @@ All call listener callbacks receive a [`Call`](/sdk/reference/messages#call) obj When an incoming call is received via `onIncomingCallReceived()`, use `acceptCall()` to accept it. On success, start the call session. - -```typescript -const sessionId: string = call.getSessionId(); // From onIncomingCallReceived - -CometChat.acceptCall(sessionId).then( - (call: CometChat.Call) => { - console.log("Call accepted:", call); - }, - (error: CometChat.CometChatException) => { - console.log("Accept call failed:", error); - } -); -``` - ```javascript const sessionId = call.getSessionId(); // From onIncomingCallReceived @@ -275,28 +261,27 @@ CometChat.acceptCall(sessionId).then( ); ``` - - -## Reject Call - -Use `rejectCall()` to reject an incoming call. Set the status to `CALL_STATUS_REJECTED`. - - ```typescript -const sessionId: string = call.getSessionId(); -const status: string = CometChat.CALL_STATUS.REJECTED; +const sessionId: string = call.getSessionId(); // From onIncomingCallReceived -CometChat.rejectCall(sessionId, status).then( +CometChat.acceptCall(sessionId).then( (call: CometChat.Call) => { - console.log("Call rejected:", call); + console.log("Call accepted:", call); }, (error: CometChat.CometChatException) => { - console.log("Reject call failed:", error); + console.log("Accept call failed:", error); } ); ``` + + +## Reject Call + +Use `rejectCall()` to reject an incoming call. Set the status to `CALL_STATUS_REJECTED`. + + ```javascript const sessionId = call.getSessionId(); @@ -313,28 +298,28 @@ CometChat.rejectCall(sessionId, status).then( ); ``` - - -## Cancel Call - -The caller can cancel an outgoing call before it's answered using `rejectCall()` with status `CALL_STATUS_CANCELLED`. - - ```typescript const sessionId: string = call.getSessionId(); -const status: string = CometChat.CALL_STATUS.CANCELLED; +const status: string = CometChat.CALL_STATUS.REJECTED; CometChat.rejectCall(sessionId, status).then( (call: CometChat.Call) => { - console.log("Call cancelled:", call); + console.log("Call rejected:", call); }, (error: CometChat.CometChatException) => { - console.log("Cancel call failed:", error); + console.log("Reject call failed:", error); } ); ``` + + +## Cancel Call + +The caller can cancel an outgoing call before it's answered using `rejectCall()` with status `CALL_STATUS_CANCELLED`. + + ```javascript const sessionId = call.getSessionId(); @@ -351,6 +336,21 @@ CometChat.rejectCall(sessionId, status).then( ); ``` + +```typescript +const sessionId: string = call.getSessionId(); +const status: string = CometChat.CALL_STATUS.CANCELLED; + +CometChat.rejectCall(sessionId, status).then( + (call: CometChat.Call) => { + console.log("Call cancelled:", call); + }, + (error: CometChat.CometChatException) => { + console.log("Cancel call failed:", error); + } +); +``` + ## Start Call Session @@ -362,15 +362,15 @@ Once the call is accepted, both participants need to start the call session. **Receiver flow:** In the `acceptCall()` success callback, generate a token and start the session. - -```typescript -const sessionId: string = call.getSessionId(); + +```javascript +const sessionId = call.getSessionId(); const loggedInUser = await CometChat.getLoggedinUser(); -const authToken: string = loggedInUser.getAuthToken(); +const authToken = loggedInUser.getAuthToken(); // Step 1: Generate call token CometChatCalls.generateToken(sessionId, authToken).then( - (callToken: any) => { + (callToken) => { // Step 2: Configure call settings const callListener = new CometChatCalls.OngoingCallListener({ onCallEnded: () => { @@ -385,12 +385,12 @@ CometChatCalls.generateToken(sessionId, authToken).then( CometChatCalls.endSession(); // Close calling screen }, - (error: CometChat.CometChatException) => console.log("End call failed:", error) + (error) => console.log("End call failed:", error) ); }, - onUserJoined: (user: any) => console.log("User joined:", user), - onUserLeft: (user: any) => console.log("User left:", user), - onError: (error: any) => console.log("Call error:", error) + onUserJoined: (user) => console.log("User joined:", user), + onUserLeft: (user) => console.log("User left:", user), + onError: (error) => console.log("Call error:", error) }); const callSettings = new CometChatCalls.CallSettingsBuilder() @@ -400,24 +400,24 @@ CometChatCalls.generateToken(sessionId, authToken).then( .build(); // Step 3: Start the session - const htmlElement = document.getElementById("call-container") as HTMLElement; + const htmlElement = document.getElementById("call-container"); CometChatCalls.startSession(callToken, callSettings, htmlElement); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Token generation failed:", error); } ); ``` - -```javascript -const sessionId = call.getSessionId(); + +```typescript +const sessionId: string = call.getSessionId(); const loggedInUser = await CometChat.getLoggedinUser(); -const authToken = loggedInUser.getAuthToken(); +const authToken: string = loggedInUser.getAuthToken(); // Step 1: Generate call token CometChatCalls.generateToken(sessionId, authToken).then( - (callToken) => { + (callToken: any) => { // Step 2: Configure call settings const callListener = new CometChatCalls.OngoingCallListener({ onCallEnded: () => { @@ -432,12 +432,12 @@ CometChatCalls.generateToken(sessionId, authToken).then( CometChatCalls.endSession(); // Close calling screen }, - (error) => console.log("End call failed:", error) + (error: CometChat.CometChatException) => console.log("End call failed:", error) ); }, - onUserJoined: (user) => console.log("User joined:", user), - onUserLeft: (user) => console.log("User left:", user), - onError: (error) => console.log("Call error:", error) + onUserJoined: (user: any) => console.log("User joined:", user), + onUserLeft: (user: any) => console.log("User left:", user), + onError: (error: any) => console.log("Call error:", error) }); const callSettings = new CometChatCalls.CallSettingsBuilder() @@ -447,10 +447,10 @@ CometChatCalls.generateToken(sessionId, authToken).then( .build(); // Step 3: Start the session - const htmlElement = document.getElementById("call-container"); + const htmlElement = document.getElementById("call-container") as HTMLElement; CometChatCalls.startSession(callToken, callSettings, htmlElement); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Token generation failed:", error); } ); @@ -469,34 +469,34 @@ To end an active call in the ringing flow, the process differs based on who ends When the user clicks the end call button, the `onCallEndButtonPressed()` callback is triggered. Inside this callback, call `CometChat.endCall()` to notify other participants. On success, call `CometChat.clearActiveCall()` and `CometChatCalls.endSession()` to release resources. - -```typescript + +```javascript onCallEndButtonPressed: () => { CometChat.endCall(sessionId).then( - (call: CometChat.Call) => { + (call) => { console.log("Call ended successfully"); CometChat.clearActiveCall(); CometChatCalls.endSession(); // Close the calling screen }, - (error: CometChat.CometChatException) => { + (error) => { console.log("End call failed:", error); } ); } ``` - -```javascript + +```typescript onCallEndButtonPressed: () => { CometChat.endCall(sessionId).then( - (call) => { + (call: CometChat.Call) => { console.log("Call ended successfully"); CometChat.clearActiveCall(); CometChatCalls.endSession(); // Close the calling screen }, - (error) => { + (error: CometChat.CometChatException) => { console.log("End call failed:", error); } ); @@ -508,8 +508,8 @@ onCallEndButtonPressed: () => { **Remote participant** (receives `onCallEnded()` callback): - -```typescript + +```javascript onCallEnded: () => { CometChat.clearActiveCall(); CometChatCalls.endSession(); @@ -517,8 +517,8 @@ onCallEnded: () => { } ``` - -```javascript + +```typescript onCallEnded: () => { CometChat.clearActiveCall(); CometChatCalls.endSession(); @@ -535,31 +535,31 @@ For more details, see the [End Call Session](/sdk/javascript/direct-call#end-cal If the receiver is already on another call, you can reject the incoming call with `CALL_STATUS_BUSY` status. - -```typescript -const sessionId: string = call.getSessionId(); -const status: string = CometChat.CALL_STATUS.BUSY; + +```javascript +const sessionId = call.getSessionId(); +const status = CometChat.CALL_STATUS.BUSY; CometChat.rejectCall(sessionId, status).then( - (call: CometChat.Call) => { + (call) => { console.log("Busy status sent:", call); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Busy rejection failed:", error); } ); ``` - -```javascript -const sessionId = call.getSessionId(); -const status = CometChat.CALL_STATUS.BUSY; + +```typescript +const sessionId: string = call.getSessionId(); +const status: string = CometChat.CALL_STATUS.BUSY; CometChat.rejectCall(sessionId, status).then( - (call) => { + (call: CometChat.Call) => { console.log("Busy status sent:", call); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Busy rejection failed:", error); } ); diff --git a/sdk/javascript/delete-group.mdx b/sdk/javascript/delete-group.mdx index b2b25382d..643324371 100644 --- a/sdk/javascript/delete-group.mdx +++ b/sdk/javascript/delete-group.mdx @@ -24,21 +24,6 @@ This operation is irreversible. Deleted groups and their messages cannot be reco Use `deleteGroup()` to permanently delete a group. Only group admins can perform this operation. - -```typescript -const GUID: string = "GUID"; - -CometChat.deleteGroup(GUID).then( - (response: boolean) => { - console.log("Group deleted successfully:", response); - }, (error: CometChat.CometChatException) => { - console.log("Group delete failed with exception:", error); - } -); -``` - - - ```javascript const GUID = "GUID"; @@ -54,6 +39,21 @@ response => { + +```typescript +const GUID: string = "GUID"; + +CometChat.deleteGroup(GUID).then( + (response: boolean) => { + console.log("Group deleted successfully:", response); + }, (error: CometChat.CometChatException) => { + console.log("Group delete failed with exception:", error); + } +); +``` + + + ```javascript const GUID = "GUID"; diff --git a/sdk/javascript/delete-message.mdx b/sdk/javascript/delete-message.mdx index 2e9780c40..12757717c 100644 --- a/sdk/javascript/delete-message.mdx +++ b/sdk/javascript/delete-message.mdx @@ -37,21 +37,6 @@ Deleting a message is straightforward. Receiving delete events has two parts: Use `deleteMessage()` with the message ID. - -```typescript -let messageId: number = 1; - -CometChat.deleteMessage(messageId).then( - (message: CometChat.BaseMessage) => { - console.log("Message deleted", message); - }, (error: CometChat.CometChatException) => { - console.log("Message delete failed with error:", error); - } -); -``` - - - ```javascript let messageId = "ID_OF_THE_MESSAGE_YOU_WANT_TO_DELETE"; @@ -67,6 +52,21 @@ message => { + +```typescript +let messageId: number = 1; + +CometChat.deleteMessage(messageId).then( + (message: CometChat.BaseMessage) => { + console.log("Message deleted", message); + }, (error: CometChat.CometChatException) => { + console.log("Message delete failed with error:", error); + } +); +``` + + + ```javascript let messageId = "ID_OF_THE_MESSAGE_YOU_WANT_TO_DELETE"; diff --git a/sdk/javascript/delivery-read-receipts.mdx b/sdk/javascript/delivery-read-receipts.mdx index fc5f9c78d..3d42ec12d 100644 --- a/sdk/javascript/delivery-read-receipts.mdx +++ b/sdk/javascript/delivery-read-receipts.mdx @@ -42,25 +42,25 @@ Use `markAsDelivered()` to mark messages as delivered. You can pass either a mes ### Using Message Object - -```typescript + +```javascript CometChat.markAsDelivered(message).then( () => { console.log("Marked as delivered successfully"); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Error marking as delivered:", error); } ); ``` - -```javascript + +```typescript CometChat.markAsDelivered(message).then( () => { console.log("Marked as delivered successfully"); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Error marking as delivered:", error); } ); @@ -222,25 +222,25 @@ Use `markAsRead()` to mark messages as read. You can pass either a message objec ### Using Message Object - -```typescript + +```javascript CometChat.markAsRead(message).then( () => { console.log("Marked as read successfully"); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Error marking as read:", error); } ); ``` - -```javascript + +```typescript CometChat.markAsRead(message).then( () => { console.log("Marked as read successfully"); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Error marking as read:", error); } ); @@ -397,27 +397,27 @@ You cannot mark your own messages as unread. This method only works for messages - -```typescript + +```javascript CometChat.markMessageAsUnread(message).then( - (conversation: CometChat.Conversation) => { + (conversation) => { console.log("Marked as unread successfully", conversation); console.log("Unread count:", conversation.getUnreadMessageCount()); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Error marking as unread:", error); } ); ``` - -```javascript + +```typescript CometChat.markMessageAsUnread(message).then( - (conversation) => { + (conversation: CometChat.Conversation) => { console.log("Marked as unread successfully", conversation); console.log("Unread count:", conversation.getUnreadMessageCount()); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Error marking as unread:", error); } ); @@ -439,46 +439,46 @@ Register a `MessageListener` to receive delivery and read receipt events. | `onMessagesReadByAll` | Group message read by all members | - -```typescript -let listenerID: string = "UNIQUE_LISTENER_ID"; + +```javascript +let listenerID = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onMessagesDelivered: (messageReceipt: CometChat.MessageReceipt) => { + onMessagesDelivered: (messageReceipt) => { console.log("Message delivered:", messageReceipt); }, - onMessagesRead: (messageReceipt: CometChat.MessageReceipt) => { + onMessagesRead: (messageReceipt) => { console.log("Message read:", messageReceipt); }, - onMessagesDeliveredToAll: (messageReceipt: CometChat.MessageReceipt) => { + onMessagesDeliveredToAll: (messageReceipt) => { console.log("Message delivered to all group members:", messageReceipt); }, - onMessagesReadByAll: (messageReceipt: CometChat.MessageReceipt) => { + onMessagesReadByAll: (messageReceipt) => { console.log("Message read by all group members:", messageReceipt); } }) ); ``` - -```javascript -let listenerID = "UNIQUE_LISTENER_ID"; + +```typescript +let listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onMessagesDelivered: (messageReceipt) => { + onMessagesDelivered: (messageReceipt: CometChat.MessageReceipt) => { console.log("Message delivered:", messageReceipt); }, - onMessagesRead: (messageReceipt) => { + onMessagesRead: (messageReceipt: CometChat.MessageReceipt) => { console.log("Message read:", messageReceipt); }, - onMessagesDeliveredToAll: (messageReceipt) => { + onMessagesDeliveredToAll: (messageReceipt: CometChat.MessageReceipt) => { console.log("Message delivered to all group members:", messageReceipt); }, - onMessagesReadByAll: (messageReceipt) => { + onMessagesReadByAll: (messageReceipt: CometChat.MessageReceipt) => { console.log("Message read by all group members:", messageReceipt); } }) @@ -514,29 +514,29 @@ The listener callbacks receive a [`MessageReceipt`](/sdk/reference/auxiliary#mes 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. - -```typescript -let messageId: number = 123; + +```javascript +let messageId = 123; CometChat.getMessageReceipts(messageId).then( - (receipts: CometChat.MessageReceipt[]) => { + (receipts) => { console.log("Message receipts:", receipts); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Error fetching receipts:", error); } ); ``` - -```javascript -let messageId = 123; + +```typescript +let messageId: number = 123; CometChat.getMessageReceipts(messageId).then( - (receipts) => { + (receipts: CometChat.MessageReceipt[]) => { console.log("Message receipts:", receipts); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Error fetching receipts:", error); } ); diff --git a/sdk/javascript/direct-call.mdx b/sdk/javascript/direct-call.mdx index dcaa9aec5..110a9d887 100644 --- a/sdk/javascript/direct-call.mdx +++ b/sdk/javascript/direct-call.mdx @@ -47,35 +47,35 @@ You can generate the token just before starting the call, or generate and store Use the `generateToken()` method to create a call token: - -```typescript + +```javascript const loggedInUser = await CometChat.getLoggedinUser(); const authToken = loggedInUser.getAuthToken(); -const sessionId: string = "SESSION_ID"; // Random or from Call object in ringing flow +const sessionId = "SESSION_ID"; // Random or from Call object in ringing flow CometChatCalls.generateToken(sessionId, authToken).then( - (callToken: any) => { + (callToken) => { console.log("Call token generated:", callToken.token); // Use callToken to start the session }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Token generation failed:", error); } ); ``` - -```javascript + +```typescript const loggedInUser = await CometChat.getLoggedinUser(); const authToken = loggedInUser.getAuthToken(); -const sessionId = "SESSION_ID"; // Random or from Call object in ringing flow +const sessionId: string = "SESSION_ID"; // Random or from Call object in ringing flow CometChatCalls.generateToken(sessionId, authToken).then( - (callToken) => { + (callToken: any) => { console.log("Call token generated:", callToken.token); // Use callToken to start the session }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Token generation failed:", error); } ); @@ -96,16 +96,16 @@ Use the `startSession()` method to join a call session. This method requires: 3. An HTML element where the call UI will be rendered - -```typescript + +```javascript const callListener = new CometChatCalls.OngoingCallListener({ - onUserJoined: (user: any) => { + onUserJoined: (user) => { console.log("User joined:", user); }, - onUserLeft: (user: any) => { + onUserLeft: (user) => { console.log("User left:", user); }, - onUserListUpdated: (userList: any[]) => { + onUserListUpdated: (userList) => { console.log("User list updated:", userList); }, onCallEnded: () => { @@ -115,13 +115,13 @@ const callListener = new CometChatCalls.OngoingCallListener({ console.log("End call button pressed"); // Handle end call - see End Call Session section }, - onError: (error: any) => { + onError: (error) => { console.log("Call error:", error); }, - onMediaDeviceListUpdated: (deviceList: any[]) => { + onMediaDeviceListUpdated: (deviceList) => { console.log("Device list updated:", deviceList); }, - onUserMuted: (event: any) => { + onUserMuted: (event) => { console.log("User muted:", event); }, onScreenShareStarted: () => { @@ -130,7 +130,7 @@ const callListener = new CometChatCalls.OngoingCallListener({ onScreenShareStopped: () => { console.log("Screen sharing stopped"); }, - onCallSwitchedToVideo: (event: any) => { + onCallSwitchedToVideo: (event) => { console.log("Call switched to video:", event); }, onSessionTimeout: () => { @@ -144,20 +144,20 @@ const callSettings = new CometChatCalls.CallSettingsBuilder() .setCallListener(callListener) .build(); -const htmlElement = document.getElementById("call-container") as HTMLElement; +const htmlElement = document.getElementById("call-container"); CometChatCalls.startSession(callToken, callSettings, htmlElement); ``` - -```javascript + +```typescript const callListener = new CometChatCalls.OngoingCallListener({ - onUserJoined: (user) => { + onUserJoined: (user: any) => { console.log("User joined:", user); }, - onUserLeft: (user) => { + onUserLeft: (user: any) => { console.log("User left:", user); }, - onUserListUpdated: (userList) => { + onUserListUpdated: (userList: any[]) => { console.log("User list updated:", userList); }, onCallEnded: () => { @@ -167,13 +167,13 @@ const callListener = new CometChatCalls.OngoingCallListener({ console.log("End call button pressed"); // Handle end call - see End Call Session section }, - onError: (error) => { + onError: (error: any) => { console.log("Call error:", error); }, - onMediaDeviceListUpdated: (deviceList) => { + onMediaDeviceListUpdated: (deviceList: any[]) => { console.log("Device list updated:", deviceList); }, - onUserMuted: (event) => { + onUserMuted: (event: any) => { console.log("User muted:", event); }, onScreenShareStarted: () => { @@ -182,7 +182,7 @@ const callListener = new CometChatCalls.OngoingCallListener({ onScreenShareStopped: () => { console.log("Screen sharing stopped"); }, - onCallSwitchedToVideo: (event) => { + onCallSwitchedToVideo: (event: any) => { console.log("Call switched to video:", event); }, onSessionTimeout: () => { @@ -196,7 +196,7 @@ const callSettings = new CometChatCalls.CallSettingsBuilder() .setCallListener(callListener) .build(); -const htmlElement = document.getElementById("call-container"); +const htmlElement = document.getElementById("call-container") as HTMLElement; CometChatCalls.startSession(callToken, callSettings, htmlElement); ``` @@ -243,18 +243,18 @@ Each listener requires a unique `listenerId` string. This ID is used to: - **Enable targeted removal** — Remove specific listeners without affecting others - -```typescript -const listenerId: string = "UNIQUE_LISTENER_ID"; + +```javascript +const listenerId = "UNIQUE_LISTENER_ID"; CometChatCalls.addCallEventListener(listenerId, { - onUserJoined: (user: any) => { + onUserJoined: (user) => { console.log("User joined:", user); }, - onUserLeft: (user: any) => { + onUserLeft: (user) => { console.log("User left:", user); }, - onUserListUpdated: (userList: any[]) => { + onUserListUpdated: (userList) => { console.log("User list updated:", userList); }, onCallEnded: () => { @@ -263,13 +263,13 @@ CometChatCalls.addCallEventListener(listenerId, { onCallEndButtonPressed: () => { console.log("End call button pressed"); }, - onError: (error: any) => { + onError: (error) => { console.log("Call error:", error); }, - onMediaDeviceListUpdated: (deviceList: any[]) => { + onMediaDeviceListUpdated: (deviceList) => { console.log("Device list updated:", deviceList); }, - onUserMuted: (event: any) => { + onUserMuted: (event) => { console.log("User muted:", event); }, onScreenShareStarted: () => { @@ -278,7 +278,7 @@ CometChatCalls.addCallEventListener(listenerId, { onScreenShareStopped: () => { console.log("Screen sharing stopped"); }, - onCallSwitchedToVideo: (event: any) => { + onCallSwitchedToVideo: (event) => { console.log("Call switched to video:", event); }, onSessionTimeout: () => { @@ -290,18 +290,18 @@ CometChatCalls.addCallEventListener(listenerId, { CometChatCalls.removeCallEventListener(listenerId); ``` - -```javascript -const listenerId = "UNIQUE_LISTENER_ID"; + +```typescript +const listenerId: string = "UNIQUE_LISTENER_ID"; CometChatCalls.addCallEventListener(listenerId, { - onUserJoined: (user) => { + onUserJoined: (user: any) => { console.log("User joined:", user); }, - onUserLeft: (user) => { + onUserLeft: (user: any) => { console.log("User left:", user); }, - onUserListUpdated: (userList) => { + onUserListUpdated: (userList: any[]) => { console.log("User list updated:", userList); }, onCallEnded: () => { @@ -310,13 +310,13 @@ CometChatCalls.addCallEventListener(listenerId, { onCallEndButtonPressed: () => { console.log("End call button pressed"); }, - onError: (error) => { + onError: (error: any) => { console.log("Call error:", error); }, - onMediaDeviceListUpdated: (deviceList) => { + onMediaDeviceListUpdated: (deviceList: any[]) => { console.log("Device list updated:", deviceList); }, - onUserMuted: (event) => { + onUserMuted: (event: any) => { console.log("User muted:", event); }, onScreenShareStarted: () => { @@ -325,7 +325,7 @@ CometChatCalls.addCallEventListener(listenerId, { onScreenShareStopped: () => { console.log("Screen sharing stopped"); }, - onCallSwitchedToVideo: (event) => { + onCallSwitchedToVideo: (event: any) => { console.log("Call switched to video:", event); }, onSessionTimeout: () => { @@ -389,34 +389,34 @@ The Ringing flow requires calling methods from both the Chat SDK (`CometChat.end When the user clicks the end call button in the UI, the `onCallEndButtonPressed()` callback is triggered. You must call `CometChat.endCall()` inside this callback to properly terminate the call and notify other participants. On success, call `CometChat.clearActiveCall()` and `CometChatCalls.endSession()` to release resources. - -```typescript + +```javascript onCallEndButtonPressed: () => { CometChat.endCall(sessionId).then( - (call: CometChat.Call) => { + (call) => { console.log("Call ended successfully"); CometChat.clearActiveCall(); CometChatCalls.endSession(); // Close the calling screen }, - (error: CometChat.CometChatException) => { + (error) => { console.log("End call failed:", error); } ); } ``` - -```javascript + +```typescript onCallEndButtonPressed: () => { CometChat.endCall(sessionId).then( - (call) => { + (call: CometChat.Call) => { console.log("Call ended successfully"); CometChat.clearActiveCall(); CometChatCalls.endSession(); // Close the calling screen }, - (error) => { + (error: CometChat.CometChatException) => { console.log("End call failed:", error); } ); @@ -430,8 +430,8 @@ onCallEndButtonPressed: () => { Call `CometChat.clearActiveCall()` to clear the local call state, then call `CometChatCalls.endSession()` to release media resources. - -```typescript + +```javascript onCallEnded: () => { CometChat.clearActiveCall(); CometChatCalls.endSession(); @@ -439,8 +439,8 @@ onCallEnded: () => { } ``` - -```javascript + +```typescript onCallEnded: () => { CometChat.clearActiveCall(); CometChatCalls.endSession(); @@ -457,16 +457,16 @@ When using the Session Only flow (direct call without ringing), you only need to Call `CometChatCalls.endSession()` in the `onCallEndButtonPressed()` callback to release all media resources and disconnect from the call session. - -```typescript + +```javascript onCallEndButtonPressed: () => { CometChatCalls.endSession(); // Close the calling screen } ``` - -```javascript + +```typescript onCallEndButtonPressed: () => { CometChatCalls.endSession(); // Close the calling screen @@ -488,13 +488,13 @@ These methods can only be called when a call session is active. Toggles between the front and rear camera during a video call. Only supported on mobile browsers. - -```typescript + +```javascript CometChatCalls.switchCamera(); ``` - -```javascript + +```typescript CometChatCalls.switchCamera(); ``` @@ -512,13 +512,13 @@ Controls the local audio stream transmission. When muted, other participants can - `false` — Unmutes the microphone, resumes audio transmission - -```typescript + +```javascript CometChatCalls.muteAudio(true); ``` - -```javascript + +```typescript CometChatCalls.muteAudio(true); ``` @@ -532,13 +532,13 @@ Controls the local video stream transmission. When paused, other participants se - `false` — Resumes the camera, continues video transmission - -```typescript + +```javascript CometChatCalls.pauseVideo(true); ``` - -```javascript + +```typescript CometChatCalls.pauseVideo(true); ``` @@ -549,13 +549,13 @@ CometChatCalls.pauseVideo(true); Starts sharing your screen or a specific application window with other participants. - -```typescript + +```javascript CometChatCalls.startScreenShare(); ``` - -```javascript + +```typescript CometChatCalls.startScreenShare(); ``` @@ -566,13 +566,13 @@ CometChatCalls.startScreenShare(); Stops the current screen sharing session. - -```typescript + +```javascript CometChatCalls.stopScreenShare(); ``` - -```javascript + +```typescript CometChatCalls.stopScreenShare(); ``` @@ -587,13 +587,13 @@ Changes the call UI layout mode dynamically during the call. - `CometChat.CALL_MODE.SPOTLIGHT` — Focus on the active speaker - -```typescript + +```javascript CometChatCalls.setMode(CometChat.CALL_MODE.SPOTLIGHT); ``` - -```javascript + +```typescript CometChatCalls.setMode(CometChat.CALL_MODE.SPOTLIGHT); ``` @@ -604,14 +604,14 @@ CometChatCalls.setMode(CometChat.CALL_MODE.SPOTLIGHT); Returns a list of available audio input devices (microphones). - -```typescript + +```javascript const audioInputDevices = CometChatCalls.getAudioInputDevices(); console.log("Available microphones:", audioInputDevices); ``` - -```javascript + +```typescript const audioInputDevices = CometChatCalls.getAudioInputDevices(); console.log("Available microphones:", audioInputDevices); ``` @@ -623,14 +623,14 @@ console.log("Available microphones:", audioInputDevices); Returns a list of available audio output devices (speakers/headphones). - -```typescript + +```javascript const audioOutputDevices = CometChatCalls.getAudioOutputDevices(); console.log("Available speakers:", audioOutputDevices); ``` - -```javascript + +```typescript const audioOutputDevices = CometChatCalls.getAudioOutputDevices(); console.log("Available speakers:", audioOutputDevices); ``` @@ -642,14 +642,14 @@ console.log("Available speakers:", audioOutputDevices); Returns a list of available video input devices (cameras). - -```typescript + +```javascript const videoInputDevices = CometChatCalls.getVideoInputDevices(); console.log("Available cameras:", videoInputDevices); ``` - -```javascript + +```typescript const videoInputDevices = CometChatCalls.getVideoInputDevices(); console.log("Available cameras:", videoInputDevices); ``` @@ -661,13 +661,13 @@ console.log("Available cameras:", videoInputDevices); Sets the active audio input device (microphone) by device ID. - -```typescript + +```javascript CometChatCalls.setAudioInputDevice(deviceId); ``` - -```javascript + +```typescript CometChatCalls.setAudioInputDevice(deviceId); ``` @@ -678,13 +678,13 @@ CometChatCalls.setAudioInputDevice(deviceId); Sets the active audio output device (speaker/headphones) by device ID. - -```typescript + +```javascript CometChatCalls.setAudioOutputDevice(deviceId); ``` - -```javascript + +```typescript CometChatCalls.setAudioOutputDevice(deviceId); ``` @@ -695,13 +695,13 @@ CometChatCalls.setAudioOutputDevice(deviceId); Sets the active video input device (camera) by device ID. - -```typescript + +```javascript CometChatCalls.setVideoInputDevice(deviceId); ``` - -```javascript + +```typescript CometChatCalls.setVideoInputDevice(deviceId); ``` @@ -712,13 +712,13 @@ CometChatCalls.setVideoInputDevice(deviceId); Upgrades an ongoing audio call to a video call. This enables the camera and starts transmitting video to other participants. The remote participant receives the `onCallSwitchedToVideo()` callback. - -```typescript + +```javascript CometChatCalls.switchToVideoCall(); ``` - -```javascript + +```typescript CometChatCalls.switchToVideoCall(); ``` diff --git a/sdk/javascript/flag-message.mdx b/sdk/javascript/flag-message.mdx index 959dd8c41..3e310ff16 100644 --- a/sdk/javascript/flag-message.mdx +++ b/sdk/javascript/flag-message.mdx @@ -61,29 +61,29 @@ sequenceDiagram Before flagging a message, retrieve the list of available flag reasons configured in your Dashboard: - - ```typescript + + ```javascript CometChat.getFlagReasons().then( - (reasons: CometChat.FlagReason[]) => { + (reasons) => { console.log("Flag reasons retrieved:", reasons); // reasons is an array of { id, reason } objects // Use these to populate your report dialog UI }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Failed to get flag reasons:", error); } ); ``` - - ```javascript + + ```typescript CometChat.getFlagReasons().then( - (reasons) => { + (reasons: CometChat.FlagReason[]) => { console.log("Flag reasons retrieved:", reasons); // reasons is an array of { id, reason } objects // Use these to populate your report dialog UI }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Failed to get flag reasons:", error); } ); @@ -111,37 +111,37 @@ The response is an array of flag reason objects: To flag a message, use the `flagMessage()` method with the message ID and a payload containing the reason: - - ```typescript - const messageId: string = "MESSAGE_ID_TO_FLAG"; - const payload: { reasonId: string; remark?: string } = { - reasonId: "spam", - remark: "This message contains promotional content" + + ```javascript + const messageId = "MESSAGE_ID_TO_FLAG"; + const payload = { + reasonId: "spam", // Required: ID from getFlagReasons() + remark: "This message contains promotional content" // Optional }; CometChat.flagMessage(messageId, payload).then( - (response: CometChat.FlagMessageResponse) => { + (response) => { console.log("Message flagged successfully:", response); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Message flagging failed:", error); } ); ``` - - ```javascript - const messageId = "MESSAGE_ID_TO_FLAG"; - const payload = { - reasonId: "spam", // Required: ID from getFlagReasons() - remark: "This message contains promotional content" // Optional + + ```typescript + const messageId: string = "MESSAGE_ID_TO_FLAG"; + const payload: { reasonId: string; remark?: string } = { + reasonId: "spam", + remark: "This message contains promotional content" }; CometChat.flagMessage(messageId, payload).then( - (response) => { + (response: CometChat.FlagMessageResponse) => { console.log("Message flagged successfully:", response); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Message flagging failed:", error); } ); diff --git a/sdk/javascript/initialization.mdx b/sdk/javascript/initialization.mdx index f66032036..bc918d41a 100644 --- a/sdk/javascript/initialization.mdx +++ b/sdk/javascript/initialization.mdx @@ -8,22 +8,22 @@ The `init()` method initializes the SDK and must be called before any other Come ## Basic Initialization - -```typescript -let appID: string = "APP_ID"; -let region: string = "APP_REGION"; + +```javascript +let appID = "APP_ID"; +let region = "APP_REGION"; -let appSetting: CometChat.AppSettings = new CometChat.AppSettingsBuilder() +let appSetting = new CometChat.AppSettingsBuilder() .subscribePresenceForAllUsers() .setRegion(region) .autoEstablishSocketConnection(true) .build(); CometChat.init(appID, appSetting).then( - (initialized: boolean) => { - console.log("Initialization completed successfully", initialized); + () => { + console.log("Initialization completed successfully"); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Initialization failed with error:", error); } ); @@ -31,22 +31,22 @@ CometChat.init(appID, appSetting).then( - -```javascript -let appID = "APP_ID"; -let region = "APP_REGION"; + +```typescript +let appID: string = "APP_ID"; +let region: string = "APP_REGION"; -let appSetting = new CometChat.AppSettingsBuilder() +let appSetting: CometChat.AppSettings = new CometChat.AppSettingsBuilder() .subscribePresenceForAllUsers() .setRegion(region) .autoEstablishSocketConnection(true) .build(); CometChat.init(appID, appSetting).then( - () => { - console.log("Initialization completed successfully"); + (initialized: boolean) => { + console.log("Initialization completed successfully", initialized); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Initialization failed with error:", error); } ); diff --git a/sdk/javascript/interactive-messages.mdx b/sdk/javascript/interactive-messages.mdx index 3570fb421..db180414d 100644 --- a/sdk/javascript/interactive-messages.mdx +++ b/sdk/javascript/interactive-messages.mdx @@ -50,12 +50,12 @@ The [`InteractiveMessage`](/sdk/reference/messages#interactivemessage) class rep Use `sendInteractiveMessage()` to send an interactive message. - -```typescript -let receiverId: string = "UID"; -let receiverType: string = CometChat.RECEIVER_TYPE.USER; + +```javascript +let receiverId = "UID"; +let receiverType = CometChat.RECEIVER_TYPE.USER; -let interactiveData: Object = { +let interactiveData = { title: "Survey", formFields: [ { @@ -109,7 +109,7 @@ let interactiveData: Object = { } }; -let interactiveMessage: CometChat.InteractiveMessage = new CometChat.InteractiveMessage( +let interactiveMessage = new CometChat.InteractiveMessage( receiverId, receiverType, "form", @@ -117,21 +117,21 @@ let interactiveMessage: CometChat.InteractiveMessage = new CometChat.Interactive ); CometChat.sendInteractiveMessage(interactiveMessage).then( - (message: CometChat.InteractiveMessage) => { + (message) => { console.log("Interactive message sent successfully", message); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Interactive message sending failed with error:", error); } ); ``` - -```javascript -let receiverId = "UID"; -let receiverType = CometChat.RECEIVER_TYPE.USER; + +```typescript +let receiverId: string = "UID"; +let receiverType: string = CometChat.RECEIVER_TYPE.USER; -let interactiveData = { +let interactiveData: Object = { title: "Survey", formFields: [ { @@ -185,7 +185,7 @@ let interactiveData = { } }; -let interactiveMessage = new CometChat.InteractiveMessage( +let interactiveMessage: CometChat.InteractiveMessage = new CometChat.InteractiveMessage( receiverId, receiverType, "form", @@ -193,10 +193,10 @@ let interactiveMessage = new CometChat.InteractiveMessage( ); CometChat.sendInteractiveMessage(interactiveMessage).then( - (message) => { + (message: CometChat.InteractiveMessage) => { console.log("Interactive message sent successfully", message); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Interactive message sending failed with error:", error); } ); @@ -300,15 +300,15 @@ An `InteractionGoal` defines when the user's interaction with the message is con ### Set an Interaction Goal - -```typescript -let elementIds: Array = ["name", "gender", "submitButton"]; -let interactionGoal: CometChat.InteractionGoal = new CometChat.InteractionGoal( + +```javascript +let elementIds = ["name", "gender", "submitButton"]; +let interactionGoal = new CometChat.InteractionGoal( CometChat.GoalType.ALL_OF, elementIds ); -let interactiveMessage: CometChat.InteractiveMessage = new CometChat.InteractiveMessage( +let interactiveMessage = new CometChat.InteractiveMessage( receiverId, receiverType, "form", @@ -317,24 +317,24 @@ let interactiveMessage: CometChat.InteractiveMessage = new CometChat.Interactive interactiveMessage.setInteractionGoal(interactionGoal); CometChat.sendInteractiveMessage(interactiveMessage).then( - (message: CometChat.InteractiveMessage) => { + (message) => { console.log("Interactive message sent successfully", message); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Interactive message sending failed with error:", error); } ); ``` - -```javascript -let elementIds = ["name", "gender", "submitButton"]; -let interactionGoal = new CometChat.InteractionGoal( + +```typescript +let elementIds: Array = ["name", "gender", "submitButton"]; +let interactionGoal: CometChat.InteractionGoal = new CometChat.InteractionGoal( CometChat.GoalType.ALL_OF, elementIds ); -let interactiveMessage = new CometChat.InteractiveMessage( +let interactiveMessage: CometChat.InteractiveMessage = new CometChat.InteractiveMessage( receiverId, receiverType, "form", @@ -343,10 +343,10 @@ let interactiveMessage = new CometChat.InteractiveMessage( interactiveMessage.setInteractionGoal(interactionGoal); CometChat.sendInteractiveMessage(interactiveMessage).then( - (message) => { + (message: CometChat.InteractiveMessage) => { console.log("Interactive message sent successfully", message); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Interactive message sending failed with error:", error); } ); @@ -368,31 +368,31 @@ An `Interaction` represents a single user action on an interactive element. Use `markAsInteracted()` to record when a user interacts with an element. - -```typescript -let messageId: number = 123; -let elementId: string = "submitButton"; + +```javascript +let messageId = 123; +let elementId = "submitButton"; CometChat.markAsInteracted(messageId, elementId).then( - (response: string) => { + (response) => { console.log("Marked as interacted successfully", response); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Failed to mark as interacted:", error); } ); ``` - -```javascript -let messageId = 123; -let elementId = "submitButton"; + +```typescript +let messageId: number = 123; +let elementId: string = "submitButton"; CometChat.markAsInteracted(messageId, elementId).then( - (response) => { + (response: string) => { console.log("Marked as interacted successfully", response); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Failed to mark as interacted:", error); } ); @@ -407,14 +407,14 @@ Register a `MessageListener` to receive interactive message events. ### Receive Interactive Messages - -```typescript -let listenerID: string = "UNIQUE_LISTENER_ID"; + +```javascript +let listenerID = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onInteractiveMessageReceived: (message: CometChat.InteractiveMessage) => { + onInteractiveMessageReceived: (message) => { console.log("Interactive message received", message); // Render the interactive UI based on message.getInteractiveData() } @@ -422,14 +422,14 @@ CometChat.addMessageListener( ); ``` - -```javascript -let listenerID = "UNIQUE_LISTENER_ID"; + +```typescript +let listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onInteractiveMessageReceived: (message) => { + onInteractiveMessageReceived: (message: CometChat.InteractiveMessage) => { console.log("Interactive message received", message); // Render the interactive UI based on message.getInteractiveData() } @@ -444,14 +444,14 @@ CometChat.addMessageListener( Triggered when a user's interactions satisfy the defined `InteractionGoal`. - -```typescript -let listenerID: string = "UNIQUE_LISTENER_ID"; + +```javascript +let listenerID = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onInteractionGoalCompleted: (receipt: CometChat.InteractionReceipt) => { + onInteractionGoalCompleted: (receipt) => { console.log("Interaction goal completed", receipt); // Handle goal completion (e.g., show confirmation, trigger next step) } @@ -459,14 +459,14 @@ CometChat.addMessageListener( ); ``` - -```javascript -let listenerID = "UNIQUE_LISTENER_ID"; + +```typescript +let listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onInteractionGoalCompleted: (receipt) => { + onInteractionGoalCompleted: (receipt: CometChat.InteractionReceipt) => { console.log("Interaction goal completed", receipt); // Handle goal completion (e.g., show confirmation, trigger next step) } @@ -489,9 +489,9 @@ CometChat.removeMessageListener("UNIQUE_LISTENER_ID"); By default, the sender cannot interact with their own interactive message. Enable sender interaction: - -```typescript -let interactiveMessage: CometChat.InteractiveMessage = new CometChat.InteractiveMessage( + +```javascript +let interactiveMessage = new CometChat.InteractiveMessage( receiverId, receiverType, "form", @@ -500,18 +500,18 @@ let interactiveMessage: CometChat.InteractiveMessage = new CometChat.Interactive interactiveMessage.setIsSenderInteractionAllowed(true); CometChat.sendInteractiveMessage(interactiveMessage).then( - (message: CometChat.InteractiveMessage) => { + (message) => { console.log("Interactive message sent successfully", message); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Interactive message sending failed with error:", error); } ); ``` - -```javascript -let interactiveMessage = new CometChat.InteractiveMessage( + +```typescript +let interactiveMessage: CometChat.InteractiveMessage = new CometChat.InteractiveMessage( receiverId, receiverType, "form", @@ -520,10 +520,10 @@ let interactiveMessage = new CometChat.InteractiveMessage( interactiveMessage.setIsSenderInteractionAllowed(true); CometChat.sendInteractiveMessage(interactiveMessage).then( - (message) => { + (message: CometChat.InteractiveMessage) => { console.log("Interactive message sent successfully", message); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Interactive message sending failed with error:", error); } ); diff --git a/sdk/javascript/login-listener.mdx b/sdk/javascript/login-listener.mdx index 47dbcaf45..5a103fd20 100644 --- a/sdk/javascript/login-listener.mdx +++ b/sdk/javascript/login-listener.mdx @@ -32,23 +32,23 @@ The CometChat SDK provides you with real-time updates for the `login` and `logou To add the `LoginListener`, you need to use the `addLoginListener()` method provided by the SDK which takes a unique identifier for the listener and of the the `LoginListener` class itself. - -```typescript - const listenerID: string = "UNIQUE_LISTENER_ID"; + +```js + let listenerID = "UNIQUE_LISTENER_ID"; CometChat.addLoginListener( listenerID, new CometChat.LoginListener({ - loginSuccess: (user: CometChat.User) => { - console.log("LoginListener :: loginSuccess", user); + loginSuccess: (e) => { + console.log("LoginListener :: loginSuccess", e); }, - loginFailure: (error: CometChat.CometChatException) => { - console.log("LoginListener :: loginFailure", error); + loginFailure: (e) => { + console.log("LoginListener :: loginFailure", e); }, logoutSuccess: () => { console.log("LoginListener :: logoutSuccess"); }, - logoutFailure: (error: CometChat.CometChatException) => { - console.log("LoginListener :: logoutFailure", error); + logoutFailure: (e) => { + console.log("LoginListener :: logoutFailure", e); } }) ); @@ -56,23 +56,23 @@ To add the `LoginListener`, you need to use the `addLoginListener()` method prov - -```js - let listenerID = "UNIQUE_LISTENER_ID"; + +```typescript + const listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addLoginListener( listenerID, new CometChat.LoginListener({ - loginSuccess: (e) => { - console.log("LoginListener :: loginSuccess", e); + loginSuccess: (user: CometChat.User) => { + console.log("LoginListener :: loginSuccess", user); }, - loginFailure: (e) => { - console.log("LoginListener :: loginFailure", e); + loginFailure: (error: CometChat.CometChatException) => { + console.log("LoginListener :: loginFailure", error); }, logoutSuccess: () => { console.log("LoginListener :: logoutSuccess"); }, - logoutFailure: (e) => { - console.log("LoginListener :: logoutFailure", e); + logoutFailure: (error: CometChat.CometChatException) => { + console.log("LoginListener :: logoutFailure", error); } }) ); @@ -87,27 +87,28 @@ To add the `LoginListener`, you need to use the `addLoginListener()` method prov If you're using React, register the listener inside a `useEffect` hook and clean it up on unmount: - -```typescript + +```javascript import { useEffect } from "react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; -function useLoginListener(): void { +function useLoginListener() { useEffect(() => { - const listenerID: string = "LOGIN_LISTENER"; + const listenerID = "LOGIN_LISTENER"; CometChat.addLoginListener( listenerID, new CometChat.LoginListener({ - loginSuccess: (user: CometChat.User) => { + loginSuccess: (user) => { console.log("User logged in:", user); }, - loginFailure: (error: CometChat.CometChatException) => { + loginFailure: (error) => { console.log("Login failed:", error); }, logoutSuccess: () => { console.log("User logged out"); + // Redirect to login page, clear app state, etc. }, - logoutFailure: (error: CometChat.CometChatException) => { + logoutFailure: (error) => { console.log("Logout failed:", error); }, }) @@ -120,28 +121,27 @@ function useLoginListener(): void { } ``` - -```javascript + +```typescript import { useEffect } from "react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; -function useLoginListener() { +function useLoginListener(): void { useEffect(() => { - const listenerID = "LOGIN_LISTENER"; + const listenerID: string = "LOGIN_LISTENER"; CometChat.addLoginListener( listenerID, new CometChat.LoginListener({ - loginSuccess: (user) => { + loginSuccess: (user: CometChat.User) => { console.log("User logged in:", user); }, - loginFailure: (error) => { + loginFailure: (error: CometChat.CometChatException) => { console.log("Login failed:", error); }, logoutSuccess: () => { console.log("User logged out"); - // Redirect to login page, clear app state, etc. }, - logoutFailure: (error) => { + logoutFailure: (error: CometChat.CometChatException) => { console.log("Logout failed:", error); }, }) @@ -159,17 +159,17 @@ function useLoginListener() { 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. - -```typescript - const listenerID: string = "UNIQUE_LISTENER_ID"; + +```js + const listenerID = "UNIQUE_LISTENER_ID"; CometChat.removeLoginListener(listenerID); ``` - -```js - const listenerID = "UNIQUE_LISTENER_ID"; + +```typescript + const listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.removeLoginListener(listenerID); ``` diff --git a/sdk/javascript/managing-web-sockets-connections-manually.mdx b/sdk/javascript/managing-web-sockets-connections-manually.mdx index 27215fbf6..6cd7a7380 100644 --- a/sdk/javascript/managing-web-sockets-connections-manually.mdx +++ b/sdk/javascript/managing-web-sockets-connections-manually.mdx @@ -41,20 +41,20 @@ The CometChat SDK also allows you to modify the above default behaviour of the S 1. While calling the init() function on the app startup, you need to inform the SDK that you will be managing the web socket connect. You can do so by using the `autoEstablishSocketConnection()` method provided by the `AppSettingsBuilder` class. This method takes a boolean value as an input. If set to `true` , the SDK will manage the web-socket connection internally based on the default behaviour mentioned above. If set to `false` , the web socket connection can will not be managed by the SDK and you will have to handle it manually. You can refer to the below code snippet for the same: - -```typescript -let appID: string = "APP_ID"; -let region: string = "APP_REGION"; -let appSetting: CometChat.AppSettings = new CometChat.AppSettingsBuilder() + +```js +let appID = "APP_ID"; +let region = "APP_REGION"; +let appSetting = new CometChat.AppSettingsBuilder() .subscribePresenceForAllUsers() .setRegion(region) .autoEstablishSocketConnection(false) .build(); CometChat.init(appID, appSetting).then( - (isInitialized: boolean) => { + () => { console.log("Initialization completed successfully"); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Initialization failed with error:", error); } ); @@ -62,20 +62,20 @@ CometChat.init(appID, appSetting).then( - -```js -let appID = "APP_ID"; -let region = "APP_REGION"; -let appSetting = new CometChat.AppSettingsBuilder() + +```typescript +let appID: string = "APP_ID"; +let region: string = "APP_REGION"; +let appSetting: CometChat.AppSettings = new CometChat.AppSettingsBuilder() .subscribePresenceForAllUsers() .setRegion(region) .autoEstablishSocketConnection(false) .build(); CometChat.init(appID, appSetting).then( - () => { + (isInitialized: boolean) => { console.log("Initialization completed successfully"); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Initialization failed with error:", error); } ); diff --git a/sdk/javascript/message-structure-and-hierarchy.mdx b/sdk/javascript/message-structure-and-hierarchy.mdx index 17b27315b..1f93fc379 100644 --- a/sdk/javascript/message-structure-and-hierarchy.mdx +++ b/sdk/javascript/message-structure-and-hierarchy.mdx @@ -37,57 +37,57 @@ Every message in CometChat belongs to a category and has a specific type. Unders Use `getCategory()` and `getType()` to determine how to handle a received message: - -```typescript -const category: string = message.getCategory(); -const type: string = message.getType(); + +```javascript +const category = message.getCategory(); +const type = message.getType(); switch (category) { case CometChat.CATEGORY_MESSAGE: if (type === CometChat.MESSAGE_TYPE.TEXT) { - const textMsg = message as CometChat.TextMessage; - console.log("Text:", textMsg.getText()); + console.log("Text:", message.getText()); } else if (type === CometChat.MESSAGE_TYPE.IMAGE) { - const mediaMsg = message as CometChat.MediaMessage; - console.log("Image URL:", mediaMsg.getData().url); + console.log("Image URL:", message.getData().url); } break; case CometChat.CATEGORY_CUSTOM: - const customMsg = message as CometChat.CustomMessage; - console.log("Custom type:", type, "data:", customMsg.getData()); + console.log("Custom type:", type, "data:", message.getData()); break; case CometChat.CATEGORY_ACTION: - const actionMsg = message as CometChat.Action; - console.log("Action:", actionMsg.getAction()); + console.log("Action:", message.getAction()); break; case CometChat.CATEGORY_CALL: - const callMsg = message as CometChat.Call; - console.log("Call status:", callMsg.getStatus()); + console.log("Call status:", message.getStatus()); break; } ``` - -```javascript -const category = message.getCategory(); -const type = message.getType(); + +```typescript +const category: string = message.getCategory(); +const type: string = message.getType(); switch (category) { case CometChat.CATEGORY_MESSAGE: if (type === CometChat.MESSAGE_TYPE.TEXT) { - console.log("Text:", message.getText()); + const textMsg = message as CometChat.TextMessage; + console.log("Text:", textMsg.getText()); } else if (type === CometChat.MESSAGE_TYPE.IMAGE) { - console.log("Image URL:", message.getData().url); + const mediaMsg = message as CometChat.MediaMessage; + console.log("Image URL:", mediaMsg.getData().url); } break; case CometChat.CATEGORY_CUSTOM: - console.log("Custom type:", type, "data:", message.getData()); + const customMsg = message as CometChat.CustomMessage; + console.log("Custom type:", type, "data:", customMsg.getData()); break; case CometChat.CATEGORY_ACTION: - console.log("Action:", message.getAction()); + const actionMsg = message as CometChat.Action; + console.log("Action:", actionMsg.getAction()); break; case CometChat.CATEGORY_CALL: - console.log("Call status:", message.getStatus()); + const callMsg = message as CometChat.Call; + console.log("Call status:", callMsg.getStatus()); break; } ``` diff --git a/sdk/javascript/rate-limits.mdx b/sdk/javascript/rate-limits.mdx index c7689f4ef..1d8a4a86c 100644 --- a/sdk/javascript/rate-limits.mdx +++ b/sdk/javascript/rate-limits.mdx @@ -40,18 +40,15 @@ CometChat includes rate limit information in response headers: When you exceed the rate limit, CometChat returns HTTP `429 Too Many Requests`. Implement exponential backoff to handle this gracefully: - -```typescript -async function callWithRetry( - apiCall: () => Promise, - maxRetries: number = 3 -): Promise { + +```javascript +async function callWithRetry(apiCall, maxRetries = 3) { for (let attempt = 0; attempt < maxRetries; attempt++) { try { return await apiCall(); - } catch (error: any) { + } catch (error) { if (error.code === "ERR_TOO_MANY_REQUESTS" && attempt < maxRetries - 1) { - const waitTime = Math.pow(2, attempt) * 1000; + 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 { @@ -59,24 +56,26 @@ async function callWithRetry( } } } - throw new Error("Max retries exceeded"); } // Usage -const users: CometChat.User[] = await callWithRetry(() => +const users = await callWithRetry(() => new CometChat.UsersRequestBuilder().setLimit(30).build().fetchNext() ); ``` - -```javascript -async function callWithRetry(apiCall, maxRetries = 3) { + +```typescript +async function callWithRetry( + apiCall: () => Promise, + maxRetries: number = 3 +): Promise { for (let attempt = 0; attempt < maxRetries; attempt++) { try { return await apiCall(); - } catch (error) { + } catch (error: any) { if (error.code === "ERR_TOO_MANY_REQUESTS" && attempt < maxRetries - 1) { - const waitTime = Math.pow(2, attempt) * 1000; // 1s, 2s, 4s + const waitTime = Math.pow(2, attempt) * 1000; console.log(`Rate limited. Retrying in ${waitTime / 1000}s...`); await new Promise((resolve) => setTimeout(resolve, waitTime)); } else { @@ -84,10 +83,11 @@ async function callWithRetry(apiCall, maxRetries = 3) { } } } + throw new Error("Max retries exceeded"); } // Usage -const users = await callWithRetry(() => +const users: CometChat.User[] = await callWithRetry(() => new CometChat.UsersRequestBuilder().setLimit(30).build().fetchNext() ); ``` diff --git a/sdk/javascript/reactions.mdx b/sdk/javascript/reactions.mdx index 12c22fd34..82e226f6e 100644 --- a/sdk/javascript/reactions.mdx +++ b/sdk/javascript/reactions.mdx @@ -34,32 +34,32 @@ Enhance user engagement in your chat application with message reactions. Users c Users can add a reaction to a message by calling `addReaction` with the message ID and the reaction emoji. - -```typescript -let messageId:string = "1"; -let emoji:string = "😊"; + +```js +let messageId = "1"; +let emoji = "😊"; CometChat.addReaction(messageId, emoji) -.then((res:CometChat.BaseMessage) => { +.then((res) => { console.log('response', res); -}).catch((err:CometChat.CometChatException) => { +}).catch(err => { console.log('err', err); -}) +}) ``` - -```js -let messageId = "1"; -let emoji = "😊"; + +```typescript +let messageId:string = "1"; +let emoji:string = "😊"; CometChat.addReaction(messageId, emoji) -.then((res) => { +.then((res:CometChat.BaseMessage) => { console.log('response', res); -}).catch(err => { +}).catch((err:CometChat.CometChatException) => { console.log('err', err); -}) +}) ``` @@ -77,32 +77,32 @@ You can react on text message, media message and custom message Removing a reaction from a message can be done using the `removeReaction` method. - -```typescript -let messageId:string = "1"; -let emoji:string = "😊"; + +```js +let messageId = "1"; +let emoji = "😊"; CometChat.removeReaction(messageId, emoji) -.then((res:CometChat.BaseMessage) => { +.then((res) => { console.log('response', res); -}).catch((err:CometChat.CometChatException) => { +}).catch(err => { console.log('err', err); -}) +}) ``` - -```js -let messageId = "1"; -let emoji = "😊"; + +```typescript +let messageId:string = "1"; +let emoji:string = "😊"; CometChat.removeReaction(messageId, emoji) -.then((res) => { +.then((res:CometChat.BaseMessage) => { console.log('response', res); -}).catch(err => { +}).catch((err:CometChat.CometChatException) => { console.log('err', err); -}) +}) ``` @@ -133,10 +133,10 @@ To get all reactions for a specific message, first create a `ReactionRequest` us The `fetchNext()` method fetches the next set of reactions for the message. - -```typescript -let limit:number = 10; -let messageId:number = 1; + +```js +let limit = 10; +let messageId = 1; let reactionRequest = new CometChat.ReactionRequestBuilder() .setMessageId(messageId) @@ -144,21 +144,21 @@ let reactionRequest = new CometChat.ReactionRequestBuilder() .build(); reactionRequest.fetchNext().then( - (messages: MessageReaction[]) => { + messages => { console.log("list fetched:", messages); }, - (error: CometChat.CometChatException) => { + error => {a console.log('list fetching failed with error:', error); }, - ); + ); ``` - -```js -let limit = 10; -let messageId = 1; + +```typescript +let limit:number = 10; +let messageId:number = 1; let reactionRequest = new CometChat.ReactionRequestBuilder() .setMessageId(messageId) @@ -166,13 +166,13 @@ let reactionRequest = new CometChat.ReactionRequestBuilder() .build(); reactionRequest.fetchNext().then( - messages => { + (messages: MessageReaction[]) => { console.log("list fetched:", messages); }, - error => {a + (error: CometChat.CometChatException) => { console.log('list fetching failed with error:', error); }, - ); + ); ``` @@ -182,10 +182,10 @@ reactionRequest.fetchNext().then( Fetch Previous The `fetchPrevious()` method fetches the previous set of reactions for the message. - -```typescript -let limit:number = 10; -let messageId:number = 1; + +```js +let limit = 10; +let messageId = 1; let reactionRequest = new CometChat.ReactionRequestBuilder() .setMessageId(messageId) @@ -193,21 +193,21 @@ let reactionRequest = new CometChat.ReactionRequestBuilder() .build(); reactionRequest.fetchPrevious().then( - (messages: MessageReaction[]) => { + messages => { console.log("list fetched:", messages); }, - (error: CometChat.CometChatException) => { + error => {a console.log('list fetching failed with error:', error); }, - ); + ); ``` - -```js -let limit = 10; -let messageId = 1; + +```typescript +let limit:number = 10; +let messageId:number = 1; let reactionRequest = new CometChat.ReactionRequestBuilder() .setMessageId(messageId) @@ -215,13 +215,13 @@ let reactionRequest = new CometChat.ReactionRequestBuilder() .build(); reactionRequest.fetchPrevious().then( - messages => { + (messages: MessageReaction[]) => { console.log("list fetched:", messages); }, - error => {a + (error: CometChat.CometChatException) => { console.log('list fetching failed with error:', error); }, - ); + ); ``` @@ -237,34 +237,34 @@ Always remove listeners when they're no longer needed (e.g., on component unmoun - -```typescript -let listenerID:string = "UNIQUE_LISTENER_ID"; + +```js +let listenerID = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener(listenerID, { - onMessageReactionAdded:(message: Object) => { + onMessageReactionAdded:(message) => { console.log("Reaction added", message); }, - onMessageReactionRemoved:(message: Object) => { + onMessageReactionRemoved:(message) => { console.log("Reaction removed", message); } - }) + }) ``` - -```js -let listenerID = "UNIQUE_LISTENER_ID"; + +```typescript +let listenerID:string = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener(listenerID, { - onMessageReactionAdded:(message) => { + onMessageReactionAdded:(message: Object) => { console.log("Reaction added", message); }, - onMessageReactionRemoved:(message) => { + onMessageReactionRemoved:(message: Object) => { console.log("Reaction removed", message); } - }) + }) ``` @@ -286,20 +286,20 @@ Each reaction listener callback receives a [`ReactionEvent`](/sdk/reference/auxi To stop listening for reaction events, remove the listener as follows: - -```typescript -let listenerID:string = "UNIQUE_LISTENER_ID"; + +```js +let listenerID = "UNIQUE_LISTENER_ID"; -CometChat.removeMessageReactionListener(listenerID); +CometChat.removeMessageListener(listenerID); ``` - -```js -let listenerID = "UNIQUE_LISTENER_ID"; + +```typescript +let listenerID:string = "UNIQUE_LISTENER_ID"; -CometChat.removeMessageListener(listenerID); +CometChat.removeMessageReactionListener(listenerID); ``` @@ -311,16 +311,16 @@ CometChat.removeMessageListener(listenerID); To retrieve the list of reactions reacted on particular message, you can use the `message.getReactions()` method. This method will return an array containing the reactions, or an empty array if no one reacted on the message. - -```typescript -message.getReactions() + +```js +message.getReactions() ``` - -```js -message.getReactions() + +```typescript +message.getReactions() ``` @@ -332,22 +332,22 @@ message.getReactions() 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. - -```typescript + +```js let reactions = message.getReactions(); reactions.forEach((reaction) => { reaction.getReactedByMe(); //Return true is logged-in user reacted on that message, otherwise false -}) +}) ``` - -```js + +```typescript let reactions = message.getReactions(); reactions.forEach((reaction) => { reaction.getReactedByMe(); //Return true is logged-in user reacted on that message, otherwise false -}) +}) ``` @@ -363,42 +363,42 @@ The `updateMessageWithReactionInfo()` method provides a seamless way to update t 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. - -```typescript + +```js // The message to which the reaction is related -let message: CometChat.BaseMessage = ...; +let message = ...; // The reaction event data received in real-time -let messageReaction: CometChat.MessageReaction = ...; +let messageReaction = ...; // The recieved reaction event real-time action type. Can be CometChatConstants.REACTION_ADDED or CometChatConstants.REACTION_REMOVED -let action: CometChat.REACTION_ACTION = CometChat.REACTION_ACTION.REACTION_ADDED; +let action = CometChat.REACTION_ACTION.REACTION_ADDED; let modifiedBaseMessage = CometChat.CometChatHelper.updateMessageWithReactionInfo( baseMessage, messageReaction, action -); +); ``` - -```js + +```typescript // The message to which the reaction is related -let message = ...; +let message: CometChat.BaseMessage = ...; // The reaction event data received in real-time -let messageReaction = ...; +let messageReaction: CometChat.MessageReaction = ...; // The recieved reaction event real-time action type. Can be CometChatConstants.REACTION_ADDED or CometChatConstants.REACTION_REMOVED -let action = CometChat.REACTION_ACTION.REACTION_ADDED; +let action: CometChat.REACTION_ACTION = CometChat.REACTION_ACTION.REACTION_ADDED; let modifiedBaseMessage = CometChat.CometChatHelper.updateMessageWithReactionInfo( baseMessage, messageReaction, action -); +); ``` diff --git a/sdk/javascript/recording.mdx b/sdk/javascript/recording.mdx index 10ea137b7..1f8b119be 100644 --- a/sdk/javascript/recording.mdx +++ b/sdk/javascript/recording.mdx @@ -37,8 +37,8 @@ Always remove listeners when they're no longer needed (e.g., on component unmoun - -```typescript + +```js // Add listeners onRecordingStarted and onRecordingStopped to the startCall method const defaultLayout = true; const audioOnly = false; @@ -62,8 +62,8 @@ CometChatCalls.startSession(callToken, callSettings, htmlElement); - -```js + +```typescript // Add listeners onRecordingStarted and onRecordingStopped to the startCall method const defaultLayout = true; const audioOnly = false; diff --git a/sdk/javascript/retrieve-conversations.mdx b/sdk/javascript/retrieve-conversations.mdx index ad43cc898..f8be2187d 100644 --- a/sdk/javascript/retrieve-conversations.mdx +++ b/sdk/javascript/retrieve-conversations.mdx @@ -130,18 +130,6 @@ When conversations are fetched successfully, the response includes `tags` arrays Fetch user conversations where the user has specific tags. - -```typescript -let limit: number = 30, - userTags: Array = ["tag1"], - conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setUserTags(userTags) - .build(); -``` - - - ```js let limit = 30; @@ -154,27 +142,27 @@ let conversationRequest = new CometChat.ConversationsRequestBuilder() - - -When conversations are fetched successfully, the response includes only user conversations where the user has the specified tags. - -### Set Group Tags - -Fetch group conversations where the group has specific tags. - - ```typescript let limit: number = 30, - groupTags: Array = ["tag1"], + userTags: Array = ["tag1"], conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() .setLimit(limit) - .setGroupTags(groupTags) - .build(); + .setUserTags(userTags) + .build(); ``` + + +When conversations are fetched successfully, the response includes only user conversations where the user has the specified tags. + +### Set Group Tags + +Fetch group conversations where the group has specific tags. + + ```js let limit = 30; @@ -187,6 +175,18 @@ let conversationRequest = new CometChat.ConversationsRequestBuilder() + +```typescript +let limit: number = 30, + groupTags: Array = ["tag1"], + conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setGroupTags(groupTags) + .build(); +``` + + + When conversations are fetched successfully, the response includes only group conversations where the group has the specified tags. @@ -254,17 +254,6 @@ let limit: number = 30, Use `setIncludeBlockedUsers(true)` to include conversations with users you've blocked. - -```typescript -let limit: number = 30, - conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setIncludeBlockedUsers(true) - .build(); -``` - - - ```js let limit = 30; @@ -276,6 +265,17 @@ let conversationRequest = new CometChat.ConversationsRequestBuilder() + +```typescript +let limit: number = 30, + conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setIncludeBlockedUsers(true) + .build(); +``` + + + 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`. @@ -285,24 +285,24 @@ When conversations are fetched successfully, the response includes conversations Use `setWithBlockedInfo(true)` to include blocked user information in the response. - -```typescript -let limit: number = 30, - conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() + +```js +let limit = 30; +let conversationRequest = new CometChat.ConversationsRequestBuilder() .setLimit(limit) .setWithBlockedInfo(true) - .build(); + .build(); ``` - -```js -let limit = 30; -let conversationRequest = new CometChat.ConversationsRequestBuilder() + +```typescript +let limit: number = 30, + conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() .setLimit(limit) .setWithBlockedInfo(true) - .build(); + .build(); ``` @@ -319,17 +319,6 @@ This feature is only available with `Conversation & Advanced Search`. The `Conve - -```typescript -let limit: number = 30, - conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setSearchKeyword("Hiking") - .build(); -``` - - - ```js let limit = 30; @@ -341,6 +330,17 @@ let conversationRequest = new CometChat.ConversationsRequestBuilder() + +```typescript +let limit: number = 30, + conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setSearchKeyword("Hiking") + .build(); +``` + + + When conversations are fetched successfully, the response includes conversations where the user or group name matches the search keyword. @@ -356,17 +356,6 @@ This feature is only available with `Conversation & Advanced Search`. The `Conve - -```typescript -let limit: number = 30, - conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setUnread(true) - .build(); -``` - - - ```js let limit = 30; @@ -378,26 +367,26 @@ let conversationRequest = new CometChat.ConversationsRequestBuilder() - - -When conversations are fetched successfully, the response includes only conversations with unread messages (`unreadMessageCount` > 0). - -### Hide Agentic Conversations - -Use `setHideAgentic(true)` to exclude AI agent conversations from the list. - - ```typescript let limit: number = 30, conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() .setLimit(limit) - .setHideAgentic(true) + .setUnread(true) .build(); ``` + + +When conversations are fetched successfully, the response includes only conversations with unread messages (`unreadMessageCount` > 0). + +### Hide Agentic Conversations + +Use `setHideAgentic(true)` to exclude AI agent conversations from the list. + + ```js let limit = 30; @@ -409,23 +398,23 @@ let conversationRequest = new CometChat.ConversationsRequestBuilder() - -### Only Agentic Conversations - -Use `setOnlyAgentic(true)` to fetch only AI agent conversations. - - ```typescript let limit: number = 30, conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() .setLimit(limit) - .setOnlyAgentic(true) + .setHideAgentic(true) .build(); ``` + +### Only Agentic Conversations + +Use `setOnlyAgentic(true)` to fetch only AI agent conversations. + + ```js let limit = 30; @@ -437,6 +426,17 @@ let conversationRequest = new CometChat.ConversationsRequestBuilder() + +```typescript +let limit: number = 30, + conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setOnlyAgentic(true) + .build(); +``` + + + diff --git a/sdk/javascript/retrieve-users.mdx b/sdk/javascript/retrieve-users.mdx index 736ddd6ec..e7f27204a 100644 --- a/sdk/javascript/retrieve-users.mdx +++ b/sdk/javascript/retrieve-users.mdx @@ -137,20 +137,6 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() Specifies which user properties to search. Works with `setSearchKeyword()`. By default, searches both UID and name. - -```typescript -let limit: number = 30; -let searchKeyword: string = "super"; -let searchIn: Array = ["uid", "name"]; -let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() - .setLimit(limit) - .setSearchKeyword(searchKeyword) - .searchIn(searchIn) - .build(); -``` - - - ```js let limit = 30; @@ -165,6 +151,20 @@ let usersRequest = new CometChat.UsersRequestBuilder() + +```typescript +let limit: number = 30; +let searchKeyword: string = "super"; +let searchIn: Array = ["uid", "name"]; +let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() + .setLimit(limit) + .setSearchKeyword(searchKeyword) + .searchIn(searchIn) + .build(); +``` + + + ### Set Status @@ -386,18 +386,6 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() Sorts the user list by a specific property. Default sort order: `status → name → UID`. Pass `"name"` to sort by `name → UID`. - -```typescript -let limit: number = 30; -let sortBy: string = "name"; -let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() - .setLimit(limit) - .sortBy(sortBy) - .build(); -``` - - - ```js let limit = 30; @@ -411,25 +399,25 @@ let usersRequest = new CometChat.UsersRequestBuilder() - - -### Sort By Order - -Sets the sort order. Default is ascending (`"asc"`). Use `"desc"` for descending. - - ```typescript let limit: number = 30; -let sortOrder: string = "desc"; +let sortBy: string = "name"; let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() .setLimit(limit) - .sortOrder(sortOrder) - .build(); + .sortBy(sortBy) + .build(); ``` + + +### Sort By Order + +Sets the sort order. Default is ascending (`"asc"`). Use `"desc"` for descending. + + ```js let limit = 30; @@ -442,29 +430,23 @@ let usersReques = new CometChat.UsersRequestBuilder() - - -After configuring the builder, call `build()` to get the `UsersRequest` object, then call `fetchNext()` to retrieve users. - - ```typescript let limit: number = 30; +let sortOrder: string = "desc"; let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() -.setLimit(limit) -.build(); - -usersRequest.fetchNext().then( - (userList: CometChat.User[]) => { - console.log("User list received:", userList); - }, (error: CometChat.CometChatException) => { - console.log("User list fetching failed with error:", error); - } -); + .setLimit(limit) + .sortOrder(sortOrder) + .build(); ``` + + +After configuring the builder, call `build()` to get the `UsersRequest` object, then call `fetchNext()` to retrieve users. + + ```javascript const limit = 30; @@ -483,6 +465,24 @@ userList => { + +```typescript +let limit: number = 30; +let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() +.setLimit(limit) +.build(); + +usersRequest.fetchNext().then( + (userList: CometChat.User[]) => { + console.log("User list received:", userList); + }, (error: CometChat.CometChatException) => { + console.log("User list fetching failed with error:", error); + } +); +``` + + + The `fetchNext()` method returns an array of [`User`](/sdk/reference/entities#user) objects. Access the response data using getter methods: diff --git a/sdk/javascript/send-message.mdx b/sdk/javascript/send-message.mdx index 034d6030b..0d8458111 100644 --- a/sdk/javascript/send-message.mdx +++ b/sdk/javascript/send-message.mdx @@ -151,9 +151,9 @@ On success, `sendMessage()` returns a [TextMessage](/sdk/reference/messages#text Attach custom JSON data to the message: - -```typescript -let metadata: Object = { + +```javascript +let metadata = { latitude: "50.6192171633316", longitude: "-72.68182268750002", }; @@ -161,9 +161,9 @@ let metadata: Object = { textMessage.setMetadata(metadata); ``` - -```javascript -let metadata = { + +```typescript +let metadata: Object = { latitude: "50.6192171633316", longitude: "-72.68182268750002", }; @@ -178,16 +178,16 @@ textMessage.setMetadata(metadata); Tag messages for easy filtering later: - -```typescript -let tags: Array = ["starredMessage"]; + +```javascript +let tags = ["starredMessage"]; textMessage.setTags(tags); ``` - -```javascript -let tags = ["starredMessage"]; + +```typescript +let tags: Array = ["starredMessage"]; textMessage.setTags(tags); ``` @@ -199,13 +199,13 @@ textMessage.setTags(tags); Reply to a specific message by setting its ID: - -```typescript + +```javascript textMessage.setQuotedMessageId(10); ``` - -```javascript + +```typescript textMessage.setQuotedMessageId(10); ``` @@ -477,13 +477,13 @@ On success, `sendMediaMessage()` returns a [MediaMessage](/sdk/reference/message Add text along with the media: - -```typescript + +```javascript mediaMessage.setCaption("Check out this photo!"); ``` - -```javascript + +```typescript mediaMessage.setCaption("Check out this photo!"); ``` diff --git a/sdk/javascript/standalone-calling.mdx b/sdk/javascript/standalone-calling.mdx index a9bbb772a..54db56dca 100644 --- a/sdk/javascript/standalone-calling.mdx +++ b/sdk/javascript/standalone-calling.mdx @@ -59,33 +59,33 @@ You can generate the token just before starting the call, or generate and store Use the `generateToken()` method to create a call token: - -```typescript -const sessionId: string = "UNIQUE_SESSION_ID"; // Generate a unique session ID -const userAuthToken: string = "USER_AUTH_TOKEN"; // Obtained from REST API + +```javascript +const sessionId = "UNIQUE_SESSION_ID"; // Generate a unique session ID +const userAuthToken = "USER_AUTH_TOKEN"; // Obtained from REST API CometChatCalls.generateToken(sessionId, userAuthToken).then( - (callToken: any) => { + (callToken) => { console.log("Call token generated:", callToken.token); // Use callToken to start the session }, - (error: any) => { + (error) => { console.log("Token generation failed:", error); } ); ``` - -```javascript -const sessionId = "UNIQUE_SESSION_ID"; // Generate a unique session ID -const userAuthToken = "USER_AUTH_TOKEN"; // Obtained from REST API + +```typescript +const sessionId: string = "UNIQUE_SESSION_ID"; // Generate a unique session ID +const userAuthToken: string = "USER_AUTH_TOKEN"; // Obtained from REST API CometChatCalls.generateToken(sessionId, userAuthToken).then( - (callToken) => { + (callToken: any) => { console.log("Call token generated:", callToken.token); // Use callToken to start the session }, - (error) => { + (error: any) => { console.log("Token generation failed:", error); } ); @@ -106,16 +106,16 @@ Use the `startSession()` method to join a call session. This method requires: 3. An HTML element where the call UI will be rendered - -```typescript + +```javascript const callListener = new CometChatCalls.OngoingCallListener({ - onUserJoined: (user: any) => { + onUserJoined: (user) => { console.log("User joined:", user); }, - onUserLeft: (user: any) => { + onUserLeft: (user) => { console.log("User left:", user); }, - onUserListUpdated: (userList: any[]) => { + onUserListUpdated: (userList) => { console.log("User list updated:", userList); }, onCallEnded: () => { @@ -128,13 +128,13 @@ const callListener = new CometChatCalls.OngoingCallListener({ CometChatCalls.endSession(); // Close calling screen }, - onError: (error: any) => { + onError: (error) => { console.log("Call error:", error); }, - onMediaDeviceListUpdated: (deviceList: any[]) => { + onMediaDeviceListUpdated: (deviceList) => { console.log("Device list updated:", deviceList); }, - onUserMuted: (event: any) => { + onUserMuted: (event) => { console.log("User muted:", event); }, onScreenShareStarted: () => { @@ -143,7 +143,7 @@ const callListener = new CometChatCalls.OngoingCallListener({ onScreenShareStopped: () => { console.log("Screen sharing stopped"); }, - onCallSwitchedToVideo: (event: any) => { + onCallSwitchedToVideo: (event) => { console.log("Call switched to video:", event); }, onSessionTimeout: () => { @@ -157,20 +157,20 @@ const callSettings = new CometChatCalls.CallSettingsBuilder() .setCallListener(callListener) .build(); -const htmlElement = document.getElementById("call-container") as HTMLElement; +const htmlElement = document.getElementById("call-container"); CometChatCalls.startSession(callToken, callSettings, htmlElement); ``` - -```javascript + +```typescript const callListener = new CometChatCalls.OngoingCallListener({ - onUserJoined: (user) => { + onUserJoined: (user: any) => { console.log("User joined:", user); }, - onUserLeft: (user) => { + onUserLeft: (user: any) => { console.log("User left:", user); }, - onUserListUpdated: (userList) => { + onUserListUpdated: (userList: any[]) => { console.log("User list updated:", userList); }, onCallEnded: () => { @@ -183,13 +183,13 @@ const callListener = new CometChatCalls.OngoingCallListener({ CometChatCalls.endSession(); // Close calling screen }, - onError: (error) => { + onError: (error: any) => { console.log("Call error:", error); }, - onMediaDeviceListUpdated: (deviceList) => { + onMediaDeviceListUpdated: (deviceList: any[]) => { console.log("Device list updated:", deviceList); }, - onUserMuted: (event) => { + onUserMuted: (event: any) => { console.log("User muted:", event); }, onScreenShareStarted: () => { @@ -198,7 +198,7 @@ const callListener = new CometChatCalls.OngoingCallListener({ onScreenShareStopped: () => { console.log("Screen sharing stopped"); }, - onCallSwitchedToVideo: (event) => { + onCallSwitchedToVideo: (event: any) => { console.log("Call switched to video:", event); }, onSessionTimeout: () => { @@ -212,7 +212,7 @@ const callSettings = new CometChatCalls.CallSettingsBuilder() .setCallListener(callListener) .build(); -const htmlElement = document.getElementById("call-container"); +const htmlElement = document.getElementById("call-container") as HTMLElement; CometChatCalls.startSession(callToken, callSettings, htmlElement); ``` @@ -263,18 +263,18 @@ Each listener requires a unique `listenerId` string. This ID is used to: - **Enable targeted removal** — Remove specific listeners without affecting others - -```typescript -const listenerId: string = "UNIQUE_LISTENER_ID"; + +```javascript +const listenerId = "UNIQUE_LISTENER_ID"; CometChatCalls.addCallEventListener(listenerId, { - onUserJoined: (user: any) => { + onUserJoined: (user) => { console.log("User joined:", user); }, - onUserLeft: (user: any) => { + onUserLeft: (user) => { console.log("User left:", user); }, - onUserListUpdated: (userList: any[]) => { + onUserListUpdated: (userList) => { console.log("User list updated:", userList); }, onCallEnded: () => { @@ -287,13 +287,13 @@ CometChatCalls.addCallEventListener(listenerId, { CometChatCalls.endSession(); // Close calling screen }, - onError: (error: any) => { + onError: (error) => { console.log("Call error:", error); }, - onMediaDeviceListUpdated: (deviceList: any[]) => { + onMediaDeviceListUpdated: (deviceList) => { console.log("Device list updated:", deviceList); }, - onUserMuted: (event: any) => { + onUserMuted: (event) => { console.log("User muted:", event); }, onScreenShareStarted: () => { @@ -302,7 +302,7 @@ CometChatCalls.addCallEventListener(listenerId, { onScreenShareStopped: () => { console.log("Screen sharing stopped"); }, - onCallSwitchedToVideo: (event: any) => { + onCallSwitchedToVideo: (event) => { console.log("Call switched to video:", event); }, onSessionTimeout: () => { @@ -314,18 +314,18 @@ CometChatCalls.addCallEventListener(listenerId, { CometChatCalls.removeCallEventListener(listenerId); ``` - -```javascript -const listenerId = "UNIQUE_LISTENER_ID"; + +```typescript +const listenerId: string = "UNIQUE_LISTENER_ID"; CometChatCalls.addCallEventListener(listenerId, { - onUserJoined: (user) => { + onUserJoined: (user: any) => { console.log("User joined:", user); }, - onUserLeft: (user) => { + onUserLeft: (user: any) => { console.log("User left:", user); }, - onUserListUpdated: (userList) => { + onUserListUpdated: (userList: any[]) => { console.log("User list updated:", userList); }, onCallEnded: () => { @@ -338,13 +338,13 @@ CometChatCalls.addCallEventListener(listenerId, { CometChatCalls.endSession(); // Close calling screen }, - onError: (error) => { + onError: (error: any) => { console.log("Call error:", error); }, - onMediaDeviceListUpdated: (deviceList) => { + onMediaDeviceListUpdated: (deviceList: any[]) => { console.log("Device list updated:", deviceList); }, - onUserMuted: (event) => { + onUserMuted: (event: any) => { console.log("User muted:", event); }, onScreenShareStarted: () => { @@ -353,7 +353,7 @@ CometChatCalls.addCallEventListener(listenerId, { onScreenShareStopped: () => { console.log("Screen sharing stopped"); }, - onCallSwitchedToVideo: (event) => { + onCallSwitchedToVideo: (event: any) => { console.log("Call switched to video:", event); }, onSessionTimeout: () => { @@ -389,16 +389,16 @@ CometChatCalls.removeCallEventListener(listenerId); To end the call session and release all media resources (camera, microphone, network connections), call `CometChatCalls.endSession()` in the `onCallEndButtonPressed()` callback. - -```typescript + +```javascript onCallEndButtonPressed: () => { CometChatCalls.endSession(); // Close the calling screen } ``` - -```javascript + +```typescript onCallEndButtonPressed: () => { CometChatCalls.endSession(); // Close the calling screen @@ -420,13 +420,13 @@ These methods can only be called when a call session is active. Toggles between the front and rear camera during a video call. Only supported on mobile browsers. - -```typescript + +```javascript CometChatCalls.switchCamera(); ``` - -```javascript + +```typescript CometChatCalls.switchCamera(); ``` @@ -444,13 +444,13 @@ Controls the local audio stream transmission. When muted, other participants can - `false` — Unmutes the microphone, resumes audio transmission - -```typescript + +```javascript CometChatCalls.muteAudio(true); ``` - -```javascript + +```typescript CometChatCalls.muteAudio(true); ``` @@ -464,13 +464,13 @@ Controls the local video stream transmission. When paused, other participants se - `false` — Resumes the camera, continues video transmission - -```typescript + +```javascript CometChatCalls.pauseVideo(true); ``` - -```javascript + +```typescript CometChatCalls.pauseVideo(true); ``` @@ -481,13 +481,13 @@ CometChatCalls.pauseVideo(true); Starts sharing your screen or a specific application window with other participants. - -```typescript + +```javascript CometChatCalls.startScreenShare(); ``` - -```javascript + +```typescript CometChatCalls.startScreenShare(); ``` @@ -498,13 +498,13 @@ CometChatCalls.startScreenShare(); Stops the current screen sharing session. - -```typescript + +```javascript CometChatCalls.stopScreenShare(); ``` - -```javascript + +```typescript CometChatCalls.stopScreenShare(); ``` @@ -519,13 +519,13 @@ Changes the call UI layout mode dynamically during the call. - `CometChat.CALL_MODE.SPOTLIGHT` — Focus on the active speaker - -```typescript + +```javascript CometChatCalls.setMode(CometChat.CALL_MODE.SPOTLIGHT); ``` - -```javascript + +```typescript CometChatCalls.setMode(CometChat.CALL_MODE.SPOTLIGHT); ``` @@ -536,14 +536,14 @@ CometChatCalls.setMode(CometChat.CALL_MODE.SPOTLIGHT); Returns a list of available audio input devices (microphones). - -```typescript + +```javascript const audioInputDevices = CometChatCalls.getAudioInputDevices(); console.log("Available microphones:", audioInputDevices); ``` - -```javascript + +```typescript const audioInputDevices = CometChatCalls.getAudioInputDevices(); console.log("Available microphones:", audioInputDevices); ``` @@ -555,14 +555,14 @@ console.log("Available microphones:", audioInputDevices); Returns a list of available audio output devices (speakers/headphones). - -```typescript + +```javascript const audioOutputDevices = CometChatCalls.getAudioOutputDevices(); console.log("Available speakers:", audioOutputDevices); ``` - -```javascript + +```typescript const audioOutputDevices = CometChatCalls.getAudioOutputDevices(); console.log("Available speakers:", audioOutputDevices); ``` @@ -574,14 +574,14 @@ console.log("Available speakers:", audioOutputDevices); Returns a list of available video input devices (cameras). - -```typescript + +```javascript const videoInputDevices = CometChatCalls.getVideoInputDevices(); console.log("Available cameras:", videoInputDevices); ``` - -```javascript + +```typescript const videoInputDevices = CometChatCalls.getVideoInputDevices(); console.log("Available cameras:", videoInputDevices); ``` @@ -593,13 +593,13 @@ console.log("Available cameras:", videoInputDevices); Sets the active audio input device (microphone) by device ID. - -```typescript + +```javascript CometChatCalls.setAudioInputDevice(deviceId); ``` - -```javascript + +```typescript CometChatCalls.setAudioInputDevice(deviceId); ``` @@ -610,13 +610,13 @@ CometChatCalls.setAudioInputDevice(deviceId); Sets the active audio output device (speaker/headphones) by device ID. - -```typescript + +```javascript CometChatCalls.setAudioOutputDevice(deviceId); ``` - -```javascript + +```typescript CometChatCalls.setAudioOutputDevice(deviceId); ``` @@ -627,13 +627,13 @@ CometChatCalls.setAudioOutputDevice(deviceId); Sets the active video input device (camera) by device ID. - -```typescript + +```javascript CometChatCalls.setVideoInputDevice(deviceId); ``` - -```javascript + +```typescript CometChatCalls.setVideoInputDevice(deviceId); ``` @@ -644,13 +644,13 @@ CometChatCalls.setVideoInputDevice(deviceId); Upgrades an ongoing audio call to a video call. This enables the camera and starts transmitting video to other participants. The remote participant receives the `onCallSwitchedToVideo()` callback. - -```typescript + +```javascript CometChatCalls.switchToVideoCall(); ``` - -```javascript + +```typescript CometChatCalls.switchToVideoCall(); ``` @@ -661,13 +661,13 @@ 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. - -```typescript + +```javascript CometChatCalls.endSession(); ``` - -```javascript + +```typescript CometChatCalls.endSession(); ``` diff --git a/sdk/javascript/user-management.mdx b/sdk/javascript/user-management.mdx index 5d87d92f1..a5625c047 100644 --- a/sdk/javascript/user-management.mdx +++ b/sdk/javascript/user-management.mdx @@ -40,42 +40,42 @@ User creation should ideally happen on your backend via the [REST API](https://a For client-side creation (development only), use `createUser()`: - -```typescript -let authKey: string = "AUTH_KEY"; -let uid: string = "user1"; -let name: string = "Kevin"; + +```javascript +let authKey = "AUTH_KEY"; +let uid = "user1"; +let name = "Kevin"; -let user: CometChat.User = new CometChat.User(uid); +let user = new CometChat.User(uid); user.setName(name); CometChat.createUser(user, authKey).then( - (user: CometChat.User) => { + user => { console.log("user created", user); - }, (error: CometChat.CometChatException) => { + }, error => { console.log("error", error); } -); +) ``` - -```javascript -let authKey = "AUTH_KEY"; -let uid = "user1"; -let name = "Kevin"; + +```typescript +let authKey: string = "AUTH_KEY"; +let uid: string = "user1"; +let name: string = "Kevin"; -let user = new CometChat.User(uid); +let user: CometChat.User = new CometChat.User(uid); user.setName(name); CometChat.createUser(user, authKey).then( - user => { + (user: CometChat.User) => { console.log("user created", user); - }, error => { + }, (error: CometChat.CometChatException) => { console.log("error", error); } -) +); ``` @@ -103,39 +103,39 @@ Like creation, user updates should ideally happen on your backend via the [REST For client-side updates (development only), use `updateUser()`: - -```typescript -let authKey: string = "AUTH_KEY"; -let uid: string = "user1"; -let name: string = "Kevin Fernandez"; + +```javascript +let authKey = "AUTH_KEY"; +let uid = "user1"; +let name = "Kevin Fernandez"; -let user: CometChat.User = new CometChat.User(uid); +let user = new CometChat.User(uid); user.setName(name); CometChat.updateUser(user, authKey).then( - (user: CometChat.User) => { + user => { console.log("user updated", user); - }, (error: CometChat.CometChatException) => { + }, error => { console.log("error", error); } ) ``` - -```javascript -let authKey = "AUTH_KEY"; -let uid = "user1"; -let name = "Kevin Fernandez"; + +```typescript +let authKey: string = "AUTH_KEY"; +let uid: string = "user1"; +let name: string = "Kevin Fernandez"; -let user = new CometChat.User(uid); +let user: CometChat.User = new CometChat.User(uid); user.setName(name); CometChat.updateUser(user, authKey).then( - user => { + (user: CometChat.User) => { console.log("user updated", user); - }, error => { + }, (error: CometChat.CometChatException) => { console.log("error", error); } ) @@ -160,40 +160,40 @@ The method returns a [`User`](/sdk/reference/entities#user) object. Access the r Use `updateCurrentUserDetails()` to update the current user without an Auth Key. Note: You cannot update the user's role with this method. - -```typescript -let uid: string = "user1"; -let name: string = "Kevin Fernandez"; + +```javascript +let uid = "user1"; +let name = "Kevin Fernandez"; -let user: CometChat.User = new CometChat.User(uid); +let user = new CometChat.User(uid); user.setName(name); CometChat.updateCurrentUserDetails(user).then( - (user: CometChat.User) => { + user => { console.log("user updated", user); - }, (error: CometChat.CometChatException) => { + }, error => { console.log("error", error); } -); +) ``` - -```javascript -let uid = "user1"; -let name = "Kevin Fernandez"; + +```typescript +let uid: string = "user1"; +let name: string = "Kevin Fernandez"; -let user = new CometChat.User(uid); +let user: CometChat.User = new CometChat.User(uid); user.setName(name); CometChat.updateCurrentUserDetails(user).then( - user => { + (user: CometChat.User) => { console.log("user updated", user); - }, error => { + }, (error: CometChat.CometChatException) => { console.log("error", error); } -) +); ``` diff --git a/sdk/javascript/user-presence.mdx b/sdk/javascript/user-presence.mdx index f85b09166..0b62bf35c 100644 --- a/sdk/javascript/user-presence.mdx +++ b/sdk/javascript/user-presence.mdx @@ -45,34 +45,34 @@ You must configure presence subscription in `AppSettings` during `CometChat.init Register a `UserListener` to receive presence events: - -```typescript -let listenerID: string = "UNIQUE_LISTENER_ID"; + +```javascript +let listenerID = "UNIQUE_LISTENER_ID"; CometChat.addUserListener( listenerID, new CometChat.UserListener({ - onUserOnline: (onlineUser: CometChat.User) => { + onUserOnline: onlineUser => { console.log("On User Online:", { onlineUser }); }, - onUserOffline: (offlineUser: CometChat.User) => { + onUserOffline: offlineUser => { console.log("On User Offline:", { offlineUser }); } }) ); ``` - -```javascript -let listenerID = "UNIQUE_LISTENER_ID"; + +```typescript +let listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addUserListener( listenerID, new CometChat.UserListener({ - onUserOnline: onlineUser => { + onUserOnline: (onlineUser: CometChat.User) => { console.log("On User Online:", { onlineUser }); }, - onUserOffline: offlineUser => { + onUserOffline: (offlineUser: CometChat.User) => { console.log("On User Offline:", { offlineUser }); } }) @@ -99,18 +99,18 @@ The listener callbacks provide a [`User`](/sdk/reference/entities#user) object w Remove the listener when no longer needed: - -```typescript -let listenerID: string = "UNIQUE_LISTENER_ID"; -CometChat.removeUserListener(listenerID); -``` - ```javascript let listenerID = "UNIQUE_LISTENER_ID"; CometChat.removeUserListener(listenerID); ``` + +```typescript +let listenerID: string = "UNIQUE_LISTENER_ID"; +CometChat.removeUserListener(listenerID); +``` + diff --git a/sdk/javascript/video-view-customisation.mdx b/sdk/javascript/video-view-customisation.mdx index c02eccfc2..84e242291 100644 --- a/sdk/javascript/video-view-customisation.mdx +++ b/sdk/javascript/video-view-customisation.mdx @@ -33,9 +33,9 @@ The `MainVideoContainerSetting` class customizes the main video view. Pass a `Ma Example: - -```typescript -let videoSettings: CometChat.MainVideoContainerSetting = new CometChat.MainVideoContainerSetting(); + +```javascript +let videoSettings = new CometChat.MainVideoContainerSetting(); videoSettings.setMainVideoAspectRatio(CometChat.CallSettings.ASPECT_RATIO_CONTAIN); videoSettings.setFullScreenButtonParams(CometChat.CallSettings.POSITION_BOTTOM_RIGHT, true); @@ -43,9 +43,9 @@ videoSettings.setNameLabelParams(CometChat.CallSettings.POSITION_BOTTOM_LEFT, tr videoSettings.setNetworkLabelParams(CometChat.CallSettings.POSITION_BOTTOM_RIGHT, true); ``` - -```javascript -let videoSettings = new CometChat.MainVideoContainerSetting(); + +```typescript +let videoSettings: CometChat.MainVideoContainerSetting = new CometChat.MainVideoContainerSetting(); videoSettings.setMainVideoAspectRatio(CometChat.CallSettings.ASPECT_RATIO_CONTAIN); videoSettings.setFullScreenButtonParams(CometChat.CallSettings.POSITION_BOTTOM_RIGHT, true); diff --git a/sdk/javascript/virtual-background.mdx b/sdk/javascript/virtual-background.mdx index 86bbc1e07..f3f7a2a74 100644 --- a/sdk/javascript/virtual-background.mdx +++ b/sdk/javascript/virtual-background.mdx @@ -35,18 +35,18 @@ For custom UI without the default layout, use these methods to control virtual b You can use the `openVirtualBackground()` method to open the virtual background settings pop-up. - -```typescript -let callController: CometChat.CallController = CometChat.CallController.getInstance(); -callController.openVirtualBackground(); -``` - ```javascript let callController = CometChat.CallController.getInstance(); callController.openVirtualBackground(); ``` + +```typescript +let callController: CometChat.CallController = CometChat.CallController.getInstance(); +callController.openVirtualBackground(); +``` + ### Set Background Blur @@ -54,13 +54,6 @@ callController.openVirtualBackground(); You can use the `setBackgroundBlur()` method to apply background blur on the video stream. This method accepts a number which decides the level of blur to be applied. - -```typescript -let callController: CometChat.CallController = CometChat.CallController.getInstance(); -let blurLevel: number = 1; -callController.setBackgroundBlur(blurLevel); -``` - ```javascript let callController = CometChat.CallController.getInstance(); @@ -68,6 +61,13 @@ let blurLevel = 1; callController.setBackgroundBlur(blurLevel); ``` + +```typescript +let callController: CometChat.CallController = CometChat.CallController.getInstance(); +let blurLevel: number = 1; +callController.setBackgroundBlur(blurLevel); +``` + ### Set Background Image @@ -75,13 +75,6 @@ callController.setBackgroundBlur(blurLevel); You can use the `setBackgroundImage()`method to set the background image. This method takes either a URL or file Object & sets that image as the background. - -```typescript -let callController: CometChat.CallController = CometChat.CallController.getInstance(); -let imageURL: string = "URL_OF_BACKGROUND_IMAGE"; -callController.setBackgroundImage(imageURL); -``` - ```javascript let callController = CometChat.CallController.getInstance(); @@ -89,6 +82,13 @@ let imageURL = "URL_OF_BACKGROUND_IMAGE"; callController.setBackgroundImage(imageURL); ``` + +```typescript +let callController: CometChat.CallController = CometChat.CallController.getInstance(); +let imageURL: string = "URL_OF_BACKGROUND_IMAGE"; +callController.setBackgroundImage(imageURL); +``` + ## Virtual Background Settings From f9130ff1971cd3c014827554eb526adcc85c4c5c Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 25 Mar 2026 14:35:37 +0530 Subject: [PATCH 050/139] TypeScript and JavaScript - Examples --- .../additional-message-filtering.mdx | 56 +- sdk/javascript/ai-agents.mdx | 42 +- .../ai-integration-quick-reference.mdx | 64 +-- sdk/javascript/ai-moderation.mdx | 44 +- sdk/javascript/all-real-time-listeners.mdx | 286 +++++------ sdk/javascript/authentication-overview.mdx | 84 +-- sdk/javascript/block-users.mdx | 150 +++--- sdk/javascript/call-logs.mdx | 20 +- sdk/javascript/calling-setup.mdx | 16 +- sdk/javascript/connection-status.mdx | 24 +- sdk/javascript/create-group.mdx | 84 +-- sdk/javascript/default-call.mdx | 206 ++++---- sdk/javascript/delete-group.mdx | 30 +- sdk/javascript/delete-message.mdx | 62 +-- sdk/javascript/delivery-read-receipts.mdx | 88 ++-- sdk/javascript/direct-call.mdx | 236 ++++----- sdk/javascript/edit-message.mdx | 58 +-- sdk/javascript/flag-message.mdx | 48 +- sdk/javascript/group-add-members.mdx | 54 +- sdk/javascript/group-change-member-scope.mdx | 66 +-- sdk/javascript/group-kick-ban-members.mdx | 212 ++++---- sdk/javascript/initialization.mdx | 32 +- sdk/javascript/interactive-messages.mdx | 136 ++--- sdk/javascript/join-group.mdx | 44 +- sdk/javascript/leave-group.mdx | 42 +- sdk/javascript/login-listener.mdx | 78 +-- ...aging-web-sockets-connections-manually.mdx | 28 +- .../message-structure-and-hierarchy.mdx | 46 +- sdk/javascript/rate-limits.mdx | 32 +- sdk/javascript/reactions.mdx | 200 ++++---- sdk/javascript/receive-message.mdx | 484 +++++++++--------- sdk/javascript/recording.mdx | 24 +- sdk/javascript/retrieve-conversations.mdx | 370 ++++++------- sdk/javascript/retrieve-group-members.mdx | 118 ++--- sdk/javascript/retrieve-groups.mdx | 182 +++---- sdk/javascript/retrieve-users.mdx | 351 ++++++------- sdk/javascript/send-message.mdx | 40 +- sdk/javascript/standalone-calling.mdx | 224 ++++---- sdk/javascript/threaded-messages.mdx | 130 ++--- sdk/javascript/transfer-group-ownership.mdx | 24 +- sdk/javascript/transient-messages.mdx | 32 +- sdk/javascript/typing-indicators.mdx | 38 +- sdk/javascript/update-group.mdx | 36 +- sdk/javascript/user-management.mdx | 100 ++-- sdk/javascript/user-presence.mdx | 32 +- sdk/javascript/video-view-customisation.mdx | 12 +- sdk/javascript/virtual-background.mdx | 40 +- 47 files changed, 2405 insertions(+), 2400 deletions(-) diff --git a/sdk/javascript/additional-message-filtering.mdx b/sdk/javascript/additional-message-filtering.mdx index 7f89e548a..8145670dd 100644 --- a/sdk/javascript/additional-message-filtering.mdx +++ b/sdk/javascript/additional-message-filtering.mdx @@ -58,6 +58,14 @@ Messages are paginated with a maximum of 100 per request. Call `fetchPrevious()` Set the number of messages to fetch per request using `setLimit()`. Maximum is 100. + +```typescript +let messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder().setLimit(50).build(); +``` + + + ```js let messagesRequest = new CometChat.MessagesRequestBuilder() @@ -67,14 +75,6 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - -```typescript -let messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder().setLimit(50).build(); -``` - - - ## Messages for a user conversation @@ -82,22 +82,22 @@ let messagesRequest: CometChat.MessagesRequest = Use `setUID()` to fetch messages between the logged-in user and a specific user. - -```javascript + +```typescript let UID = "UID"; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setLimit(50) - .build(); +let messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder().setUID(UID).setLimit(50).build(); ``` - -```typescript + +```javascript let UID = "UID"; -let messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder().setUID(UID).setLimit(50).build(); +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setLimit(50) + .build(); ``` @@ -115,7 +115,16 @@ The examples on this page use a small `setLimit()` value for brevity. In product Use `setGUID()` to fetch messages from a group. The logged-in user must be a member of the group. - + +```typescript +let GUID: string = "GUID"; +let messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder().setGUID(GUID).setLimit(50).build(); +``` + + + + ```javascript let GUID = "GUID"; let messagesRequest = new CometChat.MessagesRequestBuilder() @@ -126,15 +135,6 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - -```typescript -let GUID: string = "GUID"; -let messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder().setGUID(GUID).setLimit(50).build(); -``` - - - When messages are fetched successfully, the response includes an array of message objects. diff --git a/sdk/javascript/ai-agents.mdx b/sdk/javascript/ai-agents.mdx index d3d998e32..80e5da475 100644 --- a/sdk/javascript/ai-agents.mdx +++ b/sdk/javascript/ai-agents.mdx @@ -63,13 +63,13 @@ Events arrive via `onAIAssistantEventReceived` in this order: - - ```js - const listnerId = "unique_listener_id"; + + ```ts + const listnerId: string = "unique_listener_id"; // Adding the AIAssistantListener CometChat.addAIAssistantListener(listnerId, { - onAIAssistantEventReceived: (message) => { + onAIAssistantEventReceived: (message: CometChat.AIAssistantBaseEvent) => { console.log("AIAssistant event received successfully", message); } }); @@ -78,13 +78,13 @@ Events arrive via `onAIAssistantEventReceived` in this order: CometChat.removeAIAssistantListener(listnerId); ``` - - ```ts - const listnerId: string = "unique_listener_id"; + + ```js + const listnerId = "unique_listener_id"; // Adding the AIAssistantListener CometChat.addAIAssistantListener(listnerId, { - onAIAssistantEventReceived: (message: CometChat.AIAssistantBaseEvent) => { + onAIAssistantEventReceived: (message) => { console.log("AIAssistant event received successfully", message); } }); @@ -106,19 +106,20 @@ After the run completes, these messages arrive via `MessageListener`: | `AIToolArgumentMessage` | The arguments passed to a tool | - - ```js - const listnerId = "unique_listener_id"; + + + ```ts + const listnerId: string = "unique_listener_id"; // Adding the MessageListener CometChat.addMessageListener(listnerId, { - onAIAssistantMessageReceived: (message) => { + onAIAssistantMessageReceived: (message: CometChat.AIAssistantMessage) => { console.log("AI Assistant message received successfully", message); }, - onAIToolResultReceived: (message) => { + onAIToolResultReceived: (message: CometChat.AIToolResultMessage) => { console.log("AI Tool result message received successfully", message); }, - onAIToolArgumentsReceived: (message) => { + onAIToolArgumentsReceived: (message: CometChat.AIToolArgumentMessage) => { console.log("AI Tool argument message received successfully", message); }, }); @@ -127,20 +128,19 @@ After the run completes, these messages arrive via `MessageListener`: CometChat.removeMessageListener(listnerId); ``` - - - ```ts - const listnerId: string = "unique_listener_id"; + + ```js + const listnerId = "unique_listener_id"; // Adding the MessageListener CometChat.addMessageListener(listnerId, { - onAIAssistantMessageReceived: (message: CometChat.AIAssistantMessage) => { + onAIAssistantMessageReceived: (message) => { console.log("AI Assistant message received successfully", message); }, - onAIToolResultReceived: (message: CometChat.AIToolResultMessage) => { + onAIToolResultReceived: (message) => { console.log("AI Tool result message received successfully", message); }, - onAIToolArgumentsReceived: (message: CometChat.AIToolArgumentMessage) => { + onAIToolArgumentsReceived: (message) => { console.log("AI Tool argument message received successfully", message); }, }); diff --git a/sdk/javascript/ai-integration-quick-reference.mdx b/sdk/javascript/ai-integration-quick-reference.mdx index 3f3af5c23..e2ce6b1dd 100644 --- a/sdk/javascript/ai-integration-quick-reference.mdx +++ b/sdk/javascript/ai-integration-quick-reference.mdx @@ -41,26 +41,26 @@ AI Agents enable intelligent, automated interactions. They process user messages - Event flow: Run Start → Tool Call(s) → Text Message Stream → Run Finished - - ```javascript - const listnerId = "unique_listener_id"; + + ```typescript + const listnerId: string = "unique_listener_id"; // Adding the AIAssistantListener for real-time events CometChat.addAIAssistantListener(listnerId, { - onAIAssistantEventReceived: (message) => { + onAIAssistantEventReceived: (message: CometChat.AIAssistantBaseEvent) => { console.log("AIAssistant event received successfully", message); } }); // Adding the MessageListener for persisted agentic messages CometChat.addMessageListener(listnerId, { - onAIAssistantMessageReceived: (message) => { + onAIAssistantMessageReceived: (message: CometChat.AIAssistantMessage) => { console.log("AI Assistant message received successfully", message); }, - onAIToolResultReceived: (message) => { + onAIToolResultReceived: (message: CometChat.AIToolResultMessage) => { console.log("AI Tool result message received successfully", message); }, - onAIToolArgumentsReceived: (message) => { + onAIToolArgumentsReceived: (message: CometChat.AIToolArgumentMessage) => { console.log("AI Tool argument message received successfully", message); }, }); @@ -70,26 +70,26 @@ AI Agents enable intelligent, automated interactions. They process user messages CometChat.removeMessageListener(listnerId); ``` - - ```typescript - const listnerId: string = "unique_listener_id"; + + ```javascript + const listnerId = "unique_listener_id"; // Adding the AIAssistantListener for real-time events CometChat.addAIAssistantListener(listnerId, { - onAIAssistantEventReceived: (message: CometChat.AIAssistantBaseEvent) => { + onAIAssistantEventReceived: (message) => { console.log("AIAssistant event received successfully", message); } }); // Adding the MessageListener for persisted agentic messages CometChat.addMessageListener(listnerId, { - onAIAssistantMessageReceived: (message: CometChat.AIAssistantMessage) => { + onAIAssistantMessageReceived: (message) => { console.log("AI Assistant message received successfully", message); }, - onAIToolResultReceived: (message: CometChat.AIToolResultMessage) => { + onAIToolResultReceived: (message) => { console.log("AI Tool result message received successfully", message); }, - onAIToolArgumentsReceived: (message: CometChat.AIToolArgumentMessage) => { + onAIToolArgumentsReceived: (message) => { console.log("AI Tool argument message received successfully", message); }, }); @@ -111,8 +111,8 @@ AI Moderation automatically reviews messages for inappropriate content in real-t - Enable and configure rules in the CometChat Dashboard - - ```javascript + + ```typescript // Send message and check initial moderation status const textMessage = new CometChat.TextMessage( receiverUID, @@ -121,27 +121,27 @@ AI Moderation automatically reviews messages for inappropriate content in real-t ); CometChat.sendMessage(textMessage).then( - (message) => { - const status = message.getModerationStatus(); + (message: CometChat.TextMessage) => { + const status: string = message.getModerationStatus(); if (status === CometChat.ModerationStatus.PENDING) { console.log("Message is under moderation review"); } }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Message sending failed:", error); } ); // Listen for moderation results - const listenerID = "MODERATION_LISTENER"; + const listenerID: string = "MODERATION_LISTENER"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onMessageModerated: (message) => { - const status = message.getModerationStatus(); - const messageId = message.getId(); + onMessageModerated: (message: CometChat.BaseMessage) => { + const status: string = message.getModerationStatus(); + const messageId: number = message.getId(); switch (status) { case CometChat.ModerationStatus.APPROVED: @@ -156,8 +156,8 @@ AI Moderation automatically reviews messages for inappropriate content in real-t ); ``` - - ```typescript + + ```javascript // Send message and check initial moderation status const textMessage = new CometChat.TextMessage( receiverUID, @@ -166,27 +166,27 @@ AI Moderation automatically reviews messages for inappropriate content in real-t ); CometChat.sendMessage(textMessage).then( - (message: CometChat.TextMessage) => { - const status: string = message.getModerationStatus(); + (message) => { + const status = message.getModerationStatus(); if (status === CometChat.ModerationStatus.PENDING) { console.log("Message is under moderation review"); } }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Message sending failed:", error); } ); // Listen for moderation results - const listenerID: string = "MODERATION_LISTENER"; + const listenerID = "MODERATION_LISTENER"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onMessageModerated: (message: CometChat.BaseMessage) => { - const status: string = message.getModerationStatus(); - const messageId: number = message.getId(); + onMessageModerated: (message) => { + const status = message.getModerationStatus(); + const messageId = message.getId(); switch (status) { case CometChat.ModerationStatus.APPROVED: diff --git a/sdk/javascript/ai-moderation.mdx b/sdk/javascript/ai-moderation.mdx index 3222af96a..44f8a4482 100644 --- a/sdk/javascript/ai-moderation.mdx +++ b/sdk/javascript/ai-moderation.mdx @@ -96,8 +96,8 @@ The `getModerationStatus()` method returns one of the following values: When you send a text, image, or video message, check the initial moderation status: - - ```javascript + + ```typescript const textMessage = new CometChat.TextMessage( receiverUID, "Hello, how are you?", @@ -105,23 +105,23 @@ When you send a text, image, or video message, check the initial moderation stat ); CometChat.sendMessage(textMessage).then( - (message) => { + (message: CometChat.TextMessage) => { // Check moderation status - const status = message.getModerationStatus(); + const status: string = message.getModerationStatus(); if (status === CometChat.ModerationStatus.PENDING) { console.log("Message is under moderation review"); // Show pending indicator in UI } }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Message sending failed:", error); } ); ``` - - ```typescript + + ```javascript const textMessage = new CometChat.TextMessage( receiverUID, "Hello, how are you?", @@ -129,16 +129,16 @@ When you send a text, image, or video message, check the initial moderation stat ); CometChat.sendMessage(textMessage).then( - (message: CometChat.TextMessage) => { + (message) => { // Check moderation status - const status: string = message.getModerationStatus(); + const status = message.getModerationStatus(); if (status === CometChat.ModerationStatus.PENDING) { console.log("Message is under moderation review"); // Show pending indicator in UI } }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Message sending failed:", error); } ); @@ -151,20 +151,20 @@ When you send a text, image, or video message, check the initial moderation stat Register a message listener to receive moderation results in real-time: - - ```javascript - const listenerID = "MODERATION_LISTENER"; + + ```typescript + const listenerID: string = "MODERATION_LISTENER"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onMessageModerated: (message) => { + onMessageModerated: (message: CometChat.BaseMessage) => { if ( message instanceof CometChat.TextMessage || message instanceof CometChat.MediaMessage ) { - const status = message.getModerationStatus(); - const messageId = message.getId(); + const status: string = message.getModerationStatus(); + const messageId: number = message.getId(); switch (status) { case CometChat.ModerationStatus.APPROVED: @@ -187,20 +187,20 @@ Register a message listener to receive moderation results in real-time: // CometChat.removeMessageListener(listenerID); ``` - - ```typescript - const listenerID: string = "MODERATION_LISTENER"; + + ```javascript + const listenerID = "MODERATION_LISTENER"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onMessageModerated: (message: CometChat.BaseMessage) => { + onMessageModerated: (message) => { if ( message instanceof CometChat.TextMessage || message instanceof CometChat.MediaMessage ) { - const status: string = message.getModerationStatus(); - const messageId: number = message.getId(); + const status = message.getModerationStatus(); + const messageId = message.getId(); switch (status) { case CometChat.ModerationStatus.APPROVED: diff --git a/sdk/javascript/all-real-time-listeners.mdx b/sdk/javascript/all-real-time-listeners.mdx index a33575498..e2c92ddbc 100644 --- a/sdk/javascript/all-real-time-listeners.mdx +++ b/sdk/javascript/all-real-time-listeners.mdx @@ -58,16 +58,18 @@ The `UserListener` class provides you with live events related to users. Below a To add the `UserListener`, you need to use the `addUserListener()` method provided by the `CometChat` class. - -```js -const listenerID = "UNIQUE_LISTENER_ID"; + +```typescript +const listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addUserListener( listenerID, new CometChat.UserListener({ - onUserOnline: (onlineUser) => { + onUserOnline: (onlineUser: CometChat.User) => { + /* when someuser/friend comes online, user will be received here */ console.log("On User Online:", { onlineUser }); }, - onUserOffline: (offlineUser) => { + onUserOffline: (offlineUser: CometChat.User) => { + /* when someuser/friend went offline, user will be received here */ console.log("On User Offline:", { offlineUser }); }, }) @@ -76,18 +78,16 @@ CometChat.addUserListener( - -```typescript -const listenerID: string = "UNIQUE_LISTENER_ID"; + +```js +const listenerID = "UNIQUE_LISTENER_ID"; CometChat.addUserListener( listenerID, new CometChat.UserListener({ - onUserOnline: (onlineUser: CometChat.User) => { - /* when someuser/friend comes online, user will be received here */ + onUserOnline: (onlineUser) => { console.log("On User Online:", { onlineUser }); }, - onUserOffline: (offlineUser: CometChat.User) => { - /* when someuser/friend went offline, user will be received here */ + onUserOffline: (offlineUser) => { console.log("On User Offline:", { offlineUser }); }, }) @@ -103,13 +103,6 @@ where `UNIQUE_LISTENER_ID` is the unique identifier for the listener. Please mak Once the `UserListener` is not in use, you need to remove the listener using the `removeUserListener()` method which takes the id of the listener to be removed as the parameter. - -```js -CometChat.removeUserListener(UNIQUE_LISTENER_ID); -``` - - - ```typescript let listenerID: string = "UNIQUE_LISTENER_ID"; @@ -118,6 +111,13 @@ CometChat.removeUserListener(listenerID); + +```js +CometChat.removeUserListener(UNIQUE_LISTENER_ID); +``` + + + ## Group Listener @@ -137,18 +137,31 @@ The `GroupListener` class provides you with all the real-time events related to To add the `GroupListener`, you need to use the `addGroupListener()` method provided by the `CometChat` class. - -```js + +```typescript CometChat.addGroupListener( "UNIQUE_LISTENER_ID", new CometChat.GroupListener({ - onGroupMemberJoined: (message, joinedUser, joinedGroup) => { + onGroupMemberJoined: ( + message: CometChat.Action, + joinedUser: CometChat.User, + joinedGroup: CometChat.Group + ) => { console.log("onGroupMemberJoined", { message, joinedUser, joinedGroup }); }, - onGroupMemberLeft: (message, leftUser, leftGroup) => { + onGroupMemberLeft: ( + message: CometChat.Action, + leftUser: CometChat.User, + leftGroup: CometChat.Group + ) => { console.log("onGroupMemberLeft", { message, leftUser, leftGroup }); }, - onGroupMemberKicked: (message, kickedUser, kickedBy, kickedFrom) => { + onGroupMemberKicked: ( + message: CometChat.Action, + kickedUser: CometChat.User, + kickedBy: CometChat.User, + kickedFrom: CometChat.Group + ) => { console.log("onGroupMemberKicked", { message, kickedUser, @@ -156,7 +169,12 @@ CometChat.addGroupListener( kickedFrom, }); }, - onGroupMemberBanned: (message, bannedUser, bannedBy, bannedFrom) => { + onGroupMemberBanned: ( + message: CometChat.Action, + bannedUser: CometChat.User, + bannedBy: CometChat.User, + bannedFrom: CometChat.Group + ) => { console.log("onGroupMemberBanned", { message, bannedUser, @@ -165,10 +183,10 @@ CometChat.addGroupListener( }); }, onGroupMemberUnbanned: ( - message, - unbannedUser, - unbannedBy, - unbannedFrom + message: CometChat.Action, + unbannedUser: CometChat.User, + unbannedBy: CometChat.User, + unbannedFrom: CometChat.Group ) => { console.log("onGroupMemberUnbanned", { message, @@ -178,11 +196,11 @@ CometChat.addGroupListener( }); }, onGroupMemberScopeChanged: ( - message, - changedUser, - newScope, - oldScope, - changedGroup + message: CometChat.Action, + changedUser: CometChat.User, + newScope: string, + oldScope: string, + changedGroup: CometChat.Group ) => { console.log("onGroupMemberScopeChanged", { message, @@ -192,7 +210,12 @@ CometChat.addGroupListener( changedGroup, }); }, - onMemberAddedToGroup: (message, userAdded, addedby, addedTo) => { + onMemberAddedToGroup: ( + message: CometChat.Action, + userAdded: CometChat.User, + addedby: CometChat.User, + addedTo: CometChat.Group + ) => { console.log("onMemberAddedToGroup", { message, userAdded, @@ -206,31 +229,18 @@ CometChat.addGroupListener( - -```typescript + +```js CometChat.addGroupListener( "UNIQUE_LISTENER_ID", new CometChat.GroupListener({ - onGroupMemberJoined: ( - message: CometChat.Action, - joinedUser: CometChat.User, - joinedGroup: CometChat.Group - ) => { + onGroupMemberJoined: (message, joinedUser, joinedGroup) => { console.log("onGroupMemberJoined", { message, joinedUser, joinedGroup }); }, - onGroupMemberLeft: ( - message: CometChat.Action, - leftUser: CometChat.User, - leftGroup: CometChat.Group - ) => { + onGroupMemberLeft: (message, leftUser, leftGroup) => { console.log("onGroupMemberLeft", { message, leftUser, leftGroup }); }, - onGroupMemberKicked: ( - message: CometChat.Action, - kickedUser: CometChat.User, - kickedBy: CometChat.User, - kickedFrom: CometChat.Group - ) => { + onGroupMemberKicked: (message, kickedUser, kickedBy, kickedFrom) => { console.log("onGroupMemberKicked", { message, kickedUser, @@ -238,12 +248,7 @@ CometChat.addGroupListener( kickedFrom, }); }, - onGroupMemberBanned: ( - message: CometChat.Action, - bannedUser: CometChat.User, - bannedBy: CometChat.User, - bannedFrom: CometChat.Group - ) => { + onGroupMemberBanned: (message, bannedUser, bannedBy, bannedFrom) => { console.log("onGroupMemberBanned", { message, bannedUser, @@ -252,10 +257,10 @@ CometChat.addGroupListener( }); }, onGroupMemberUnbanned: ( - message: CometChat.Action, - unbannedUser: CometChat.User, - unbannedBy: CometChat.User, - unbannedFrom: CometChat.Group + message, + unbannedUser, + unbannedBy, + unbannedFrom ) => { console.log("onGroupMemberUnbanned", { message, @@ -265,11 +270,11 @@ CometChat.addGroupListener( }); }, onGroupMemberScopeChanged: ( - message: CometChat.Action, - changedUser: CometChat.User, - newScope: string, - oldScope: string, - changedGroup: CometChat.Group + message, + changedUser, + newScope, + oldScope, + changedGroup ) => { console.log("onGroupMemberScopeChanged", { message, @@ -279,12 +284,7 @@ CometChat.addGroupListener( changedGroup, }); }, - onMemberAddedToGroup: ( - message: CometChat.Action, - userAdded: CometChat.User, - addedby: CometChat.User, - addedTo: CometChat.Group - ) => { + onMemberAddedToGroup: (message, userAdded, addedby, addedTo) => { console.log("onMemberAddedToGroup", { message, userAdded, @@ -305,13 +305,6 @@ where `UNIQUE_LISTENER_ID` is the unique identifier for the listener. Please mak Once the `GroupListener` is not in use, you need to remove the listener using the `removeGroupListener()` method which takes the id of the listener to be removed as the parameter. - -```js -CometChat.removeGroupListener(UNIQUE_LISTENER_ID); -``` - - - ```typescript let listenerID: string = "UNIQUE_LISTENER_ID"; @@ -320,6 +313,13 @@ CometChat.removeGroupListener(listenerID); + +```js +CometChat.removeGroupListener(UNIQUE_LISTENER_ID); +``` + + + ## Message Listener @@ -346,54 +346,54 @@ The `MessageListener` class provides you with live events related to messages. B To add the `MessageListener`, you need to use the `addMessageListener()` method provided by the `CometChat` class. - -```js + +```typescript CometChat.addMessageListener( "UNIQUE_LISTENER_ID", new CometChat.MessageListener({ - onTextMessageReceived: (textMessage) => { + onTextMessageReceived: (textMessage: CometChat.TextMessage) => { console.log("Text message received successfully", textMessage); }, - onMediaMessageReceived: (mediaMessage) => { + onMediaMessageReceived: (mediaMessage: CometChat.MediaMessage) => { console.log("Media message received successfully", mediaMessage); }, - onCustomMessageReceived: (customMessage) => { + onCustomMessageReceived: (customMessage: CometChat.CustomMessage) => { console.log("Custom message received successfully", customMessage); }, - onMessagesDelivered: (messageReceipt) => { + onMessagesDelivered: (messageReceipt: CometChat.MessageReceipt) => { console.log("Message Delivered", messageReceipt); }, - onMessagesRead: (messageReceipt) => { + onMessagesRead: (messageReceipt: CometChat.MessageReceipt) => { console.log("Message Read", messageReceipt); }, - onTypingStarted: (typingIndicator) => { + onTypingStarted: (typingIndicator: CometChat.TypingIndicator) => { console.log("Typing Started", typingIndicator); }, - onTypingEnded: (typingIndicator) => { + onTypingEnded: (typingIndicator: CometChat.TypingIndicator) => { console.log("Typing Ended", typingIndicator); }, - onMessagesDeleted: (message) => { - console.log("Message Deleted", message); + onMessageDeleted: (message: CometChat.BaseMessage) => { + console.log("Message Delted", message); }, - onMessageEdited: (message) => { + onMessageEdited: (message: CometChat.BaseMessage) => { console.log("Message Edited", message); }, - onInteractiveMessageReceived: (message) => { + onInteractiveMessageReceived: (message: CometChat.InteractiveMessage) => { console.log("interactive Message received", message); }, - onInteractionGoalCompleted: (message) => { + onInteractionGoalCompleted: (receipt: CometChat.InteractionReceipt) => { console.log("Message interaction goal completed", message); }, - onTransientMessageReceived: (message) => { + onTransientMessageReceived: (message: CometChat.TransientMessage) => { console.log("Transient Message received", message); }, - onMessageReactionAdded: (reaction) => { + onMessageReactionAdded: (reaction: CometChat.ReactionEvent) => { console.log("Message Reaction added", reaction); }, - onMessageReactionRemoved: (reaction) => { + onMessageReactionRemoved: (reaction: CometChat.ReactionEvent) => { console.log("Message Reaction removed", reaction); }, - onMessageModerated: (message) => { + onMessageModerated: (message: CometChat.BaseMessage) => { console.log("Message Moderated", message); }, }) @@ -402,54 +402,54 @@ CometChat.addMessageListener( - -```typescript + +```js CometChat.addMessageListener( "UNIQUE_LISTENER_ID", new CometChat.MessageListener({ - onTextMessageReceived: (textMessage: CometChat.TextMessage) => { + onTextMessageReceived: (textMessage) => { console.log("Text message received successfully", textMessage); }, - onMediaMessageReceived: (mediaMessage: CometChat.MediaMessage) => { + onMediaMessageReceived: (mediaMessage) => { console.log("Media message received successfully", mediaMessage); }, - onCustomMessageReceived: (customMessage: CometChat.CustomMessage) => { + onCustomMessageReceived: (customMessage) => { console.log("Custom message received successfully", customMessage); }, - onMessagesDelivered: (messageReceipt: CometChat.MessageReceipt) => { + onMessagesDelivered: (messageReceipt) => { console.log("Message Delivered", messageReceipt); }, - onMessagesRead: (messageReceipt: CometChat.MessageReceipt) => { + onMessagesRead: (messageReceipt) => { console.log("Message Read", messageReceipt); }, - onTypingStarted: (typingIndicator: CometChat.TypingIndicator) => { + onTypingStarted: (typingIndicator) => { console.log("Typing Started", typingIndicator); }, - onTypingEnded: (typingIndicator: CometChat.TypingIndicator) => { + onTypingEnded: (typingIndicator) => { console.log("Typing Ended", typingIndicator); }, - onMessageDeleted: (message: CometChat.BaseMessage) => { - console.log("Message Delted", message); + onMessagesDeleted: (message) => { + console.log("Message Deleted", message); }, - onMessageEdited: (message: CometChat.BaseMessage) => { + onMessageEdited: (message) => { console.log("Message Edited", message); }, - onInteractiveMessageReceived: (message: CometChat.InteractiveMessage) => { + onInteractiveMessageReceived: (message) => { console.log("interactive Message received", message); }, - onInteractionGoalCompleted: (receipt: CometChat.InteractionReceipt) => { + onInteractionGoalCompleted: (message) => { console.log("Message interaction goal completed", message); }, - onTransientMessageReceived: (message: CometChat.TransientMessage) => { + onTransientMessageReceived: (message) => { console.log("Transient Message received", message); }, - onMessageReactionAdded: (reaction: CometChat.ReactionEvent) => { + onMessageReactionAdded: (reaction) => { console.log("Message Reaction added", reaction); }, - onMessageReactionRemoved: (reaction: CometChat.ReactionEvent) => { + onMessageReactionRemoved: (reaction) => { console.log("Message Reaction removed", reaction); }, - onMessageModerated: (message: CometChat.BaseMessage) => { + onMessageModerated: (message) => { console.log("Message Moderated", message); }, }) @@ -465,13 +465,6 @@ where `UNIQUE_LISTENER_ID` is the unique identifier for the listener. Please mak Once the `MessageListener` is not in use, you need to remove the listener using the `removeMessageListener()` method which takes the id of the listener to be removed as the parameter. - -```js -CometChat.removeMessageListener(UNIQUE_LISTENER_ID); -``` - - - ```typescript let listenerID: string = "UNIQUE_LISTENER_ID"; @@ -480,6 +473,13 @@ CometChat.removeMessageListener(listenerID); + +```js +CometChat.removeMessageListener(UNIQUE_LISTENER_ID); +``` + + + ## Call Listener @@ -496,21 +496,21 @@ The `CallListener` class provides you with live events related to calls. Below a To add the `CallListener`, you need to use the `addCallListener()` method provided by the `CometChat` class. - -```js + +```typescript CometChat.addCallListener( "UNIQUE_LISTENER_ID", new CometChat.CallListener({ - onIncomingCallReceived(call) { + onIncomingCallReceived: (call: CometChat.Call) => { console.log("Incoming call:", call); }, - onOutgoingCallAccepted(call) { + onOutgoingCallAccepted: (call: CometChat.Call) => { console.log("Outgoing call accepted:", call); }, - onOutgoingCallRejected(call) { + onOutgoingCallRejected: (call: CometChat.Call) => { console.log("Outgoing call rejected:", call); }, - onIncomingCallCancelled(call) { + onIncomingCallCancelled: (call: CometChat.Call) => { console.log("Incoming call canceled:", call); }, }) @@ -519,21 +519,21 @@ CometChat.addCallListener( - -```typescript + +```js CometChat.addCallListener( "UNIQUE_LISTENER_ID", new CometChat.CallListener({ - onIncomingCallReceived: (call: CometChat.Call) => { + onIncomingCallReceived(call) { console.log("Incoming call:", call); }, - onOutgoingCallAccepted: (call: CometChat.Call) => { + onOutgoingCallAccepted(call) { console.log("Outgoing call accepted:", call); }, - onOutgoingCallRejected: (call: CometChat.Call) => { + onOutgoingCallRejected(call) { console.log("Outgoing call rejected:", call); }, - onIncomingCallCancelled: (call: CometChat.Call) => { + onIncomingCallCancelled(call) { console.log("Incoming call canceled:", call); }, }) @@ -549,13 +549,6 @@ where `UNIQUE_LISTENER_ID` is the unique identifier for the listener. Please mak Once the `CallListener` is not in use, you need to remove the listener using the `removeCallListener()` method which takes the id of the listener to be removed as the parameter. - -```js -CometChat.removeCallListener(UNIQUE_LISTENER_ID); -``` - - - ```typescript let listenerID: string = "UNIQUE_LISTENER_ID"; @@ -564,6 +557,13 @@ CometChat.removeCallListener(listenerID); + +```js +CometChat.removeCallListener(UNIQUE_LISTENER_ID); +``` + + + diff --git a/sdk/javascript/authentication-overview.mdx b/sdk/javascript/authentication-overview.mdx index 03756f7db..9b6a07ebb 100644 --- a/sdk/javascript/authentication-overview.mdx +++ b/sdk/javascript/authentication-overview.mdx @@ -77,52 +77,52 @@ This straightforward authentication method is ideal for proof-of-concept (POC) d - -```js -const UID = "UID"; -const authKey = "AUTH_KEY"; + +```typescript +const UID: string = "cometchat-uid-1"; +const authKey: string = "AUTH_KEY"; CometChat.getLoggedinUser().then( - (user) => { + (user: CometChat.User) => { if (!user) { CometChat.login(UID, authKey).then( - (user) => { + (user: CometChat.User) => { console.log("Login Successful:", { user }); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Login failed with exception:", { error }); } ); } }, - (error) => { - console.log("Something went wrong", error); + (error: CometChat.CometChatException) => { + console.log("Some Error Occured", { error }); } ); ``` - -```typescript -const UID: string = "cometchat-uid-1"; -const authKey: string = "AUTH_KEY"; + +```js +const UID = "UID"; +const authKey = "AUTH_KEY"; CometChat.getLoggedinUser().then( - (user: CometChat.User) => { + (user) => { if (!user) { CometChat.login(UID, authKey).then( - (user: CometChat.User) => { + (user) => { console.log("Login Successful:", { user }); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Login failed with exception:", { error }); } ); } }, - (error: CometChat.CometChatException) => { - console.log("Some Error Occured", { error }); + (error) => { + console.log("Something went wrong", error); } ); ``` @@ -165,50 +165,50 @@ This advanced authentication procedure does not use the Auth Key directly in you 3. Load the Auth Token in your client and pass it to the `login()` method. - -```js -const authToken = "AUTH_TOKEN"; + +```typescript +const authToken: string = "AUTH_TOKEN"; CometChat.getLoggedinUser().then( - (user) => { + (user: CometChat.User) => { if (!user) { CometChat.login(authToken).then( - (user) => { + (user: CometChat.User) => { console.log("Login Successful:", { user }); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Login failed with exception:", { error }); } ); } }, - (error) => { - console.log("Something went wrong", error); + (error: CometChat.CometChatException) => { + console.log("Some Error Occured", { error }); } ); ``` - -```typescript -const authToken: string = "AUTH_TOKEN"; + +```js +const authToken = "AUTH_TOKEN"; CometChat.getLoggedinUser().then( - (user: CometChat.User) => { + (user) => { if (!user) { CometChat.login(authToken).then( - (user: CometChat.User) => { + (user) => { console.log("Login Successful:", { user }); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Login failed with exception:", { error }); } ); } }, - (error: CometChat.CometChatException) => { - console.log("Some Error Occured", { error }); + (error) => { + console.log("Something went wrong", error); } ); ``` @@ -245,13 +245,13 @@ After the user logs in, their information is returned in the `User` object on th You can use the `logout()` method to log out the user from CometChat. We suggest you call this method once your user has been successfully logged out from your app. - -```js + +```typescript CometChat.logout().then( - () => { + (loggedOut: Object) => { console.log("Logout completed successfully"); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Logout failed with exception:", { error }); } ); @@ -259,13 +259,13 @@ CometChat.logout().then( - -```typescript + +```js CometChat.logout().then( - (loggedOut: Object) => { + () => { console.log("Logout completed successfully"); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Logout failed with exception:", { error }); } ); diff --git a/sdk/javascript/block-users.mdx b/sdk/javascript/block-users.mdx index 5fd991ef8..14d24efb4 100644 --- a/sdk/javascript/block-users.mdx +++ b/sdk/javascript/block-users.mdx @@ -27,21 +27,6 @@ let blockedUsers = await request.fetchNext(); Block users to prevent all communication with them. Use `blockUsers()` with an array of UIDs. - -```javascript -const usersList = ["UID1", "UID2", "UID3"]; - -CometChat.blockUsers(usersList).then( -list => { - console.log("users list blocked", { list }); -}, error => { - console.log("Blocking user fails with error", error); -} -); -``` - - - ```typescript const usersList: String[] = ["UID1", "UID2", "UID3"]; @@ -57,6 +42,21 @@ CometChat.blockUsers(usersList).then( + +```javascript +const usersList = ["UID1", "UID2", "UID3"]; + +CometChat.blockUsers(usersList).then( +list => { + console.log("users list blocked", { list }); +}, error => { + console.log("Blocking user fails with error", error); +} +); +``` + + + ```javascript const usersList = ["UID1", "UID2", "UID3"]; @@ -89,21 +89,6 @@ The method returns an array of [`User`](/sdk/reference/entities#user) objects wi Unblock previously blocked users using `unblockUsers()` with an array of UIDs. - -```javascript -const usersList = ["UID1", "UID2", "UID3"]; - -CometChat.unblockUsers(usersList).then( -list => { - console.log("users list unblocked", { list }); -}, error => { - console.log("unblocking user fails with error", error); -} -); -``` - - - ```typescript const usersList: String[] = ["UID1", "UID2", "UID3"]; @@ -119,6 +104,21 @@ CometChat.unblockUsers(usersList).then( + +```javascript +const usersList = ["UID1", "UID2", "UID3"]; + +CometChat.unblockUsers(usersList).then( +list => { + console.log("users list unblocked", { list }); +}, error => { + console.log("unblocking user fails with error", error); +} +); +``` + + + ```javascript const usersList = ["UID1", "UID2", "UID3"]; @@ -155,16 +155,6 @@ Use `BlockedUsersRequestBuilder` to fetch blocked users with filtering and pagin Sets the number of blocked users to fetch per request. - -```javascript -let limit = 30; -let blockedUsersRequest = new CometChat.BlockedUsersRequestBuilder() - .setLimit(limit) - .build(); -``` - - - ```typescript let limit: number = 30; @@ -175,25 +165,23 @@ let blockedUsersRequest: CometChat.BlockedUsersRequest = new CometChat.BlockedUs - - -### Set Search Keyword - -Filters blocked users by a search string. - - - + ```javascript let limit = 30; -let searchKeyword = "super"; let blockedUsersRequest = new CometChat.BlockedUsersRequestBuilder() .setLimit(limit) - .setSearchKeyword(searchKeyword) .build(); ``` + + +### Set Search Keyword + +Filters blocked users by a search string. + + ```typescript let limit: number = 30; @@ -206,6 +194,18 @@ let blockedUsersRequest: CometChat.BlockedUsersRequest = new CometChat.BlockedUs + +```javascript +let limit = 30; +let searchKeyword = "super"; +let blockedUsersRequest = new CometChat.BlockedUsersRequestBuilder() + .setLimit(limit) + .setSearchKeyword(searchKeyword) + .build(); +``` + + + ### Set Direction @@ -217,10 +217,10 @@ Filters by block direction: - `BOTH` — Both directions (default) - -```javascript -let limit = 30; -let blockedUsersRequest = new CometChat.BlockedUsersRequestBuilder() + +```typescript +let limit: number = 30; +let blockedUsersRequest: CometChat.BlockedUsersRequest = new CometChat.BlockedUsersRequestBuilder() .setLimit(limit) .setDirection(CometChat.BlockedUsersRequest.directions.BLOCKED_BY_ME) .build(); @@ -228,10 +228,10 @@ let blockedUsersRequest = new CometChat.BlockedUsersRequestBuilder() - -```typescript -let limit: number = 30; -let blockedUsersRequest: CometChat.BlockedUsersRequest = new CometChat.BlockedUsersRequestBuilder() + +```javascript +let limit = 30; +let blockedUsersRequest = new CometChat.BlockedUsersRequestBuilder() .setLimit(limit) .setDirection(CometChat.BlockedUsersRequest.directions.BLOCKED_BY_ME) .build(); @@ -244,23 +244,6 @@ let blockedUsersRequest: CometChat.BlockedUsersRequest = new CometChat.BlockedUs After configuring the builder, call `build()` to get the `BlockedUsersRequest` object, then call `fetchNext()` to retrieve blocked users. - -```javascript -const limit = 30; -const blockedUsersRequest = new CometChat.BlockedUsersRequestBuilder() - .setLimit(limit) - .build(); -blockedUsersRequest.fetchNext().then( -userList => { - console.log("Blocked user list received:", userList); -}, error => { - console.log("Blocked user list fetching failed with error:", error); -} -); -``` - - - ```typescript let limit: number = 30; @@ -279,6 +262,23 @@ blockedUsersRequest.fetchNext().then( + +```javascript +const limit = 30; +const blockedUsersRequest = new CometChat.BlockedUsersRequestBuilder() + .setLimit(limit) + .build(); +blockedUsersRequest.fetchNext().then( +userList => { + console.log("Blocked user list received:", userList); +}, error => { + console.log("Blocked user list fetching failed with error:", error); +} +); +``` + + + --- diff --git a/sdk/javascript/call-logs.mdx b/sdk/javascript/call-logs.mdx index deeac9afd..41277a847 100644 --- a/sdk/javascript/call-logs.mdx +++ b/sdk/javascript/call-logs.mdx @@ -110,27 +110,27 @@ The `fetchNext()` and `fetchPrevious()` methods return an array of [`Call`](/sdk Retrieve details for a specific call session using `getCallDetails()`: - -```javascript -const sessionID = "SESSION_ID"; + +```typescript +const sessionID: string = "SESSION_ID"; CometChatCalls.getCallDetails(sessionID, authToken).then( - (callLogs) => { + (callLogs: Array) => { console.log("Call details:", callLogs); }, - (error) => { + (error: any) => { console.log("Error fetching call details:", error); } ); ``` - -```typescript -const sessionID: string = "SESSION_ID"; + +```javascript +const sessionID = "SESSION_ID"; CometChatCalls.getCallDetails(sessionID, authToken).then( - (callLogs: Array) => { + (callLogs) => { console.log("Call details:", callLogs); }, - (error: any) => { + (error) => { console.log("Error fetching call details:", error); } ); diff --git a/sdk/javascript/calling-setup.mdx b/sdk/javascript/calling-setup.mdx index 96ffa72cb..e0c160bbb 100644 --- a/sdk/javascript/calling-setup.mdx +++ b/sdk/javascript/calling-setup.mdx @@ -61,15 +61,15 @@ yarn add @cometchat/calls-sdk-javascript Then, import the `CometChatCalls` class wherever you want to use `CometChatCalls`. - -```js + +```typescript import { CometChatCalls } from "@cometchat/calls-sdk-javascript"; ``` - -```typescript + +```js import { CometChatCalls } from "@cometchat/calls-sdk-javascript"; ``` @@ -92,8 +92,8 @@ The `init()` method initializes the Calls SDK. It takes a `CallAppSettings` inst Call `init()` before any other `CometChatCalls` method — ideally on app startup. - -```js + +```typescript let appID = "APP_ID"; let region = "REGION"; @@ -114,8 +114,8 @@ CometChatCalls.init(callAppSetting).then( - -```typescript + +```js let appID = "APP_ID"; let region = "REGION"; diff --git a/sdk/javascript/connection-status.mdx b/sdk/javascript/connection-status.mdx index 20ecaad73..ea2b16327 100644 --- a/sdk/javascript/connection-status.mdx +++ b/sdk/javascript/connection-status.mdx @@ -37,9 +37,9 @@ Once the connection is broken, the disconnected callback is triggered, the SDK a To receive real-time connection status, you need to register `ConnectionListener` wherever you wish to receive the real-time status. You can use the `addConnectionListener()` method to do so. - -```javascript -let listenerID = "UNIQUE_LISTENER_ID"; + +```typescript +let listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addConnectionListener( listenerID, new CometChat.ConnectionListener({ @@ -58,9 +58,9 @@ CometChat.addConnectionListener( - -```typescript -let listenerID: string = "UNIQUE_LISTENER_ID"; + +```javascript +let listenerID = "UNIQUE_LISTENER_ID"; CometChat.addConnectionListener( listenerID, new CometChat.ConnectionListener({ @@ -90,16 +90,16 @@ We recommend you to add the Connection Listener in your method on app startup, p You can also get the current connection status by using `getConnectionStatus` property provided by CometChat SDK - -```javascript -const connectionStatus = CometChat.getConnectionStatus(); + +```typescript +const connectionStatus: string = CometChat.getConnectionStatus(); ``` - -```typescript -const connectionStatus: string = CometChat.getConnectionStatus(); + +```javascript +const connectionStatus = CometChat.getConnectionStatus(); ``` diff --git a/sdk/javascript/create-group.mdx b/sdk/javascript/create-group.mdx index e288bb58b..65366f087 100644 --- a/sdk/javascript/create-group.mdx +++ b/sdk/javascript/create-group.mdx @@ -35,26 +35,6 @@ Group types: - `CometChat.GROUP_TYPE.PRIVATE` - -```javascript -const GUID = "GUID"; -const groupName = "Hello Group!"; -const groupType = CometChat.GROUP_TYPE.PUBLIC; -const password = ""; - -const group = new CometChat.Group(GUID, groupName, groupType, password); - -CometChat.createGroup(group).then( - group => { - console.log("Group created successfully:", group); - }, error => { - console.log("Group creation failed with exception:", error); - } -); -``` - - - ```typescript const GUID: string = "GUID"; @@ -75,6 +55,26 @@ CometChat.createGroup(group).then( + +```javascript +const GUID = "GUID"; +const groupName = "Hello Group!"; +const groupType = CometChat.GROUP_TYPE.PUBLIC; +const password = ""; + +const group = new CometChat.Group(GUID, groupName, groupType, password); + +CometChat.createGroup(group).then( + group => { + console.log("Group created successfully:", group); + }, error => { + console.log("Group creation failed with exception:", error); + } +); +``` + + + ```javascript const GUID = "GUID"; @@ -131,23 +131,23 @@ Parameters: Create a `GroupMember` with: `new CometChat.GroupMember(UID, scope)` - -```js -let GUID = "cometchat-guid-11"; -let UID = "cometchat-uid-1"; -let groupName = "Hello Group!"; -let groupType = CometChat.GROUP_TYPE.PUBLIC; + +```typescript +let GUID: string = "cometchat-guid-11"; +let UID: string = "cometchat-uid-1"; +let groupName: string = "Hello Group!"; +let groupType: string = CometChat.GROUP_TYPE.PUBLIC; -let group = new CometChat.Group(GUID, groupName, groupType); -let members = [ +let group: CometChat.Group = new CometChat.Group(GUID, groupName, groupType); +let members: Array = [ new CometChat.GroupMember(UID, CometChat.GROUP_MEMBER_SCOPE.PARTICIPANT) ]; -let banMembers = ["cometchat-uid-2"]; +let banMembers: Array = ["cometchat-uid-2"]; CometChat.createGroupWithMembers(group, members, banMembers).then( - response => { + (response: Object) => { console.log("Group created successfully", response); - }, error => { + }, (error: CometChat.CometChatException) => { console.log("Some error occured while creating group", error) } ); @@ -155,23 +155,23 @@ CometChat.createGroupWithMembers(group, members, banMembers).then( - -```typescript -let GUID: string = "cometchat-guid-11"; -let UID: string = "cometchat-uid-1"; -let groupName: string = "Hello Group!"; -let groupType: string = CometChat.GROUP_TYPE.PUBLIC; + +```js +let GUID = "cometchat-guid-11"; +let UID = "cometchat-uid-1"; +let groupName = "Hello Group!"; +let groupType = CometChat.GROUP_TYPE.PUBLIC; -let group: CometChat.Group = new CometChat.Group(GUID, groupName, groupType); -let members: Array = [ +let group = new CometChat.Group(GUID, groupName, groupType); +let members = [ new CometChat.GroupMember(UID, CometChat.GROUP_MEMBER_SCOPE.PARTICIPANT) ]; -let banMembers: Array = ["cometchat-uid-2"]; +let banMembers = ["cometchat-uid-2"]; CometChat.createGroupWithMembers(group, members, banMembers).then( - (response: Object) => { + response => { console.log("Group created successfully", response); - }, (error: CometChat.CometChatException) => { + }, error => { console.log("Some error occured while creating group", error) } ); diff --git a/sdk/javascript/default-call.mdx b/sdk/javascript/default-call.mdx index 6dff0e20e..5926d7575 100644 --- a/sdk/javascript/default-call.mdx +++ b/sdk/javascript/default-call.mdx @@ -153,33 +153,28 @@ The `initiateCall()` method returns a [`Call`](/sdk/reference/messages#call) obj Register the `CallListener` to receive real-time call events. Each listener requires a unique `listenerId` string to prevent duplicate registrations and enable targeted removal. - -```javascript -const listenerId = "UNIQUE_LISTENER_ID"; + +```typescript +const listenerId: string = "UNIQUE_LISTENER_ID"; // Register listener CometChat.addCallListener( listenerId, new CometChat.CallListener({ - onIncomingCallReceived: (call) => { + onIncomingCallReceived: (call: CometChat.Call) => { console.log("Incoming call:", call); - // Show incoming call UI }, - onOutgoingCallAccepted: (call) => { + onOutgoingCallAccepted: (call: CometChat.Call) => { console.log("Outgoing call accepted:", call); - // Receiver accepted, start the call session }, - onOutgoingCallRejected: (call) => { + onOutgoingCallRejected: (call: CometChat.Call) => { console.log("Outgoing call rejected:", call); - // Receiver rejected, dismiss outgoing call UI }, - onIncomingCallCancelled: (call) => { + onIncomingCallCancelled: (call: CometChat.Call) => { console.log("Incoming call cancelled:", call); - // Caller cancelled, dismiss incoming call UI }, - onCallEndedMessageReceived: (call) => { + onCallEndedMessageReceived: (call: CometChat.Call) => { console.log("Call ended message:", call); - // Call ended by remote participant } }) ); @@ -188,28 +183,33 @@ CometChat.addCallListener( CometChat.removeCallListener(listenerId); ``` - -```typescript -const listenerId: string = "UNIQUE_LISTENER_ID"; + +```javascript +const listenerId = "UNIQUE_LISTENER_ID"; // Register listener CometChat.addCallListener( listenerId, new CometChat.CallListener({ - onIncomingCallReceived: (call: CometChat.Call) => { + onIncomingCallReceived: (call) => { console.log("Incoming call:", call); + // Show incoming call UI }, - onOutgoingCallAccepted: (call: CometChat.Call) => { + onOutgoingCallAccepted: (call) => { console.log("Outgoing call accepted:", call); + // Receiver accepted, start the call session }, - onOutgoingCallRejected: (call: CometChat.Call) => { + onOutgoingCallRejected: (call) => { console.log("Outgoing call rejected:", call); + // Receiver rejected, dismiss outgoing call UI }, - onIncomingCallCancelled: (call: CometChat.Call) => { + onIncomingCallCancelled: (call) => { console.log("Incoming call cancelled:", call); + // Caller cancelled, dismiss incoming call UI }, - onCallEndedMessageReceived: (call: CometChat.Call) => { + onCallEndedMessageReceived: (call) => { console.log("Call ended message:", call); + // Call ended by remote participant } }) ); @@ -245,6 +245,20 @@ All call listener callbacks receive a [`Call`](/sdk/reference/messages#call) obj When an incoming call is received via `onIncomingCallReceived()`, use `acceptCall()` to accept it. On success, start the call session. + +```typescript +const sessionId: string = call.getSessionId(); // From onIncomingCallReceived + +CometChat.acceptCall(sessionId).then( + (call: CometChat.Call) => { + console.log("Call accepted:", call); + }, + (error: CometChat.CometChatException) => { + console.log("Accept call failed:", error); + } +); +``` + ```javascript const sessionId = call.getSessionId(); // From onIncomingCallReceived @@ -261,27 +275,28 @@ CometChat.acceptCall(sessionId).then( ); ``` + + +## Reject Call + +Use `rejectCall()` to reject an incoming call. Set the status to `CALL_STATUS_REJECTED`. + + ```typescript -const sessionId: string = call.getSessionId(); // From onIncomingCallReceived +const sessionId: string = call.getSessionId(); +const status: string = CometChat.CALL_STATUS.REJECTED; -CometChat.acceptCall(sessionId).then( +CometChat.rejectCall(sessionId, status).then( (call: CometChat.Call) => { - console.log("Call accepted:", call); + console.log("Call rejected:", call); }, (error: CometChat.CometChatException) => { - console.log("Accept call failed:", error); + console.log("Reject call failed:", error); } ); ``` - - -## Reject Call - -Use `rejectCall()` to reject an incoming call. Set the status to `CALL_STATUS_REJECTED`. - - ```javascript const sessionId = call.getSessionId(); @@ -298,28 +313,28 @@ CometChat.rejectCall(sessionId, status).then( ); ``` + + +## Cancel Call + +The caller can cancel an outgoing call before it's answered using `rejectCall()` with status `CALL_STATUS_CANCELLED`. + + ```typescript const sessionId: string = call.getSessionId(); -const status: string = CometChat.CALL_STATUS.REJECTED; +const status: string = CometChat.CALL_STATUS.CANCELLED; CometChat.rejectCall(sessionId, status).then( (call: CometChat.Call) => { - console.log("Call rejected:", call); + console.log("Call cancelled:", call); }, (error: CometChat.CometChatException) => { - console.log("Reject call failed:", error); + console.log("Cancel call failed:", error); } ); ``` - - -## Cancel Call - -The caller can cancel an outgoing call before it's answered using `rejectCall()` with status `CALL_STATUS_CANCELLED`. - - ```javascript const sessionId = call.getSessionId(); @@ -336,21 +351,6 @@ CometChat.rejectCall(sessionId, status).then( ); ``` - -```typescript -const sessionId: string = call.getSessionId(); -const status: string = CometChat.CALL_STATUS.CANCELLED; - -CometChat.rejectCall(sessionId, status).then( - (call: CometChat.Call) => { - console.log("Call cancelled:", call); - }, - (error: CometChat.CometChatException) => { - console.log("Cancel call failed:", error); - } -); -``` - ## Start Call Session @@ -362,15 +362,15 @@ Once the call is accepted, both participants need to start the call session. **Receiver flow:** In the `acceptCall()` success callback, generate a token and start the session. - -```javascript -const sessionId = call.getSessionId(); + +```typescript +const sessionId: string = call.getSessionId(); const loggedInUser = await CometChat.getLoggedinUser(); -const authToken = loggedInUser.getAuthToken(); +const authToken: string = loggedInUser.getAuthToken(); // Step 1: Generate call token CometChatCalls.generateToken(sessionId, authToken).then( - (callToken) => { + (callToken: any) => { // Step 2: Configure call settings const callListener = new CometChatCalls.OngoingCallListener({ onCallEnded: () => { @@ -385,12 +385,12 @@ CometChatCalls.generateToken(sessionId, authToken).then( CometChatCalls.endSession(); // Close calling screen }, - (error) => console.log("End call failed:", error) + (error: CometChat.CometChatException) => console.log("End call failed:", error) ); }, - onUserJoined: (user) => console.log("User joined:", user), - onUserLeft: (user) => console.log("User left:", user), - onError: (error) => console.log("Call error:", error) + onUserJoined: (user: any) => console.log("User joined:", user), + onUserLeft: (user: any) => console.log("User left:", user), + onError: (error: any) => console.log("Call error:", error) }); const callSettings = new CometChatCalls.CallSettingsBuilder() @@ -400,24 +400,24 @@ CometChatCalls.generateToken(sessionId, authToken).then( .build(); // Step 3: Start the session - const htmlElement = document.getElementById("call-container"); + const htmlElement = document.getElementById("call-container") as HTMLElement; CometChatCalls.startSession(callToken, callSettings, htmlElement); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Token generation failed:", error); } ); ``` - -```typescript -const sessionId: string = call.getSessionId(); + +```javascript +const sessionId = call.getSessionId(); const loggedInUser = await CometChat.getLoggedinUser(); -const authToken: string = loggedInUser.getAuthToken(); +const authToken = loggedInUser.getAuthToken(); // Step 1: Generate call token CometChatCalls.generateToken(sessionId, authToken).then( - (callToken: any) => { + (callToken) => { // Step 2: Configure call settings const callListener = new CometChatCalls.OngoingCallListener({ onCallEnded: () => { @@ -432,12 +432,12 @@ CometChatCalls.generateToken(sessionId, authToken).then( CometChatCalls.endSession(); // Close calling screen }, - (error: CometChat.CometChatException) => console.log("End call failed:", error) + (error) => console.log("End call failed:", error) ); }, - onUserJoined: (user: any) => console.log("User joined:", user), - onUserLeft: (user: any) => console.log("User left:", user), - onError: (error: any) => console.log("Call error:", error) + onUserJoined: (user) => console.log("User joined:", user), + onUserLeft: (user) => console.log("User left:", user), + onError: (error) => console.log("Call error:", error) }); const callSettings = new CometChatCalls.CallSettingsBuilder() @@ -447,10 +447,10 @@ CometChatCalls.generateToken(sessionId, authToken).then( .build(); // Step 3: Start the session - const htmlElement = document.getElementById("call-container") as HTMLElement; + const htmlElement = document.getElementById("call-container"); CometChatCalls.startSession(callToken, callSettings, htmlElement); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Token generation failed:", error); } ); @@ -469,34 +469,34 @@ To end an active call in the ringing flow, the process differs based on who ends When the user clicks the end call button, the `onCallEndButtonPressed()` callback is triggered. Inside this callback, call `CometChat.endCall()` to notify other participants. On success, call `CometChat.clearActiveCall()` and `CometChatCalls.endSession()` to release resources. - -```javascript + +```typescript onCallEndButtonPressed: () => { CometChat.endCall(sessionId).then( - (call) => { + (call: CometChat.Call) => { console.log("Call ended successfully"); CometChat.clearActiveCall(); CometChatCalls.endSession(); // Close the calling screen }, - (error) => { + (error: CometChat.CometChatException) => { console.log("End call failed:", error); } ); } ``` - -```typescript + +```javascript onCallEndButtonPressed: () => { CometChat.endCall(sessionId).then( - (call: CometChat.Call) => { + (call) => { console.log("Call ended successfully"); CometChat.clearActiveCall(); CometChatCalls.endSession(); // Close the calling screen }, - (error: CometChat.CometChatException) => { + (error) => { console.log("End call failed:", error); } ); @@ -508,8 +508,8 @@ onCallEndButtonPressed: () => { **Remote participant** (receives `onCallEnded()` callback): - -```javascript + +```typescript onCallEnded: () => { CometChat.clearActiveCall(); CometChatCalls.endSession(); @@ -517,8 +517,8 @@ onCallEnded: () => { } ``` - -```typescript + +```javascript onCallEnded: () => { CometChat.clearActiveCall(); CometChatCalls.endSession(); @@ -535,31 +535,31 @@ For more details, see the [End Call Session](/sdk/javascript/direct-call#end-cal If the receiver is already on another call, you can reject the incoming call with `CALL_STATUS_BUSY` status. - -```javascript -const sessionId = call.getSessionId(); -const status = CometChat.CALL_STATUS.BUSY; + +```typescript +const sessionId: string = call.getSessionId(); +const status: string = CometChat.CALL_STATUS.BUSY; CometChat.rejectCall(sessionId, status).then( - (call) => { + (call: CometChat.Call) => { console.log("Busy status sent:", call); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Busy rejection failed:", error); } ); ``` - -```typescript -const sessionId: string = call.getSessionId(); -const status: string = CometChat.CALL_STATUS.BUSY; + +```javascript +const sessionId = call.getSessionId(); +const status = CometChat.CALL_STATUS.BUSY; CometChat.rejectCall(sessionId, status).then( - (call: CometChat.Call) => { + (call) => { console.log("Busy status sent:", call); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Busy rejection failed:", error); } ); diff --git a/sdk/javascript/delete-group.mdx b/sdk/javascript/delete-group.mdx index 643324371..b2b25382d 100644 --- a/sdk/javascript/delete-group.mdx +++ b/sdk/javascript/delete-group.mdx @@ -24,21 +24,6 @@ This operation is irreversible. Deleted groups and their messages cannot be reco Use `deleteGroup()` to permanently delete a group. Only group admins can perform this operation. - -```javascript -const GUID = "GUID"; - -CometChat.deleteGroup(GUID).then( -response => { - console.log("Groups deleted successfully:", response); -}, error => { - console.log("Group delete failed with exception:", error); -} -); -``` - - - ```typescript const GUID: string = "GUID"; @@ -54,6 +39,21 @@ CometChat.deleteGroup(GUID).then( + +```javascript +const GUID = "GUID"; + +CometChat.deleteGroup(GUID).then( +response => { + console.log("Groups deleted successfully:", response); +}, error => { + console.log("Group delete failed with exception:", error); +} +); +``` + + + ```javascript const GUID = "GUID"; diff --git a/sdk/javascript/delete-message.mdx b/sdk/javascript/delete-message.mdx index 12757717c..03c45b01e 100644 --- a/sdk/javascript/delete-message.mdx +++ b/sdk/javascript/delete-message.mdx @@ -37,21 +37,6 @@ Deleting a message is straightforward. Receiving delete events has two parts: Use `deleteMessage()` with the message ID. - -```javascript -let messageId = "ID_OF_THE_MESSAGE_YOU_WANT_TO_DELETE"; - -CometChat.deleteMessage(messageId).then( -message => { - console.log("Message deleted", message); -}, error => { - console.log("Message delete failed with error:", error); -} -); -``` - - - ```typescript let messageId: number = 1; @@ -67,6 +52,21 @@ CometChat.deleteMessage(messageId).then( + +```javascript +let messageId = "ID_OF_THE_MESSAGE_YOU_WANT_TO_DELETE"; + +CometChat.deleteMessage(messageId).then( +message => { + console.log("Message deleted", message); +}, error => { + console.log("Message delete failed with error:", error); +} +); +``` + + + ```javascript let messageId = "ID_OF_THE_MESSAGE_YOU_WANT_TO_DELETE"; @@ -108,22 +108,6 @@ By default, CometChat allows certain roles to delete a message. Use `onMessageDeleted` in `MessageListener` to receive real-time delete events. - -```javascript -let listenerID = "UNIQUE_LISTENER_ID"; - -CometChat.addMessageListener( -listenerID, -new CometChat.MessageListener({ - onMessageDeleted: message => { - console.log("Deleted Message", message); - } -}) -); -``` - - - ```typescript let listenerID: string = "UNIQUE_LISTENER_ID"; @@ -140,6 +124,22 @@ CometChat.addMessageListener( + +```javascript +let listenerID = "UNIQUE_LISTENER_ID"; + +CometChat.addMessageListener( +listenerID, +new CometChat.MessageListener({ + onMessageDeleted: message => { + console.log("Deleted Message", message); + } +}) +); +``` + + + The `onMessageDeleted` callback receives a [`BaseMessage`](/sdk/reference/messages#basemessage) object with the `deletedAt` and `deletedBy` fields set. Access the data using getter methods: diff --git a/sdk/javascript/delivery-read-receipts.mdx b/sdk/javascript/delivery-read-receipts.mdx index 3d42ec12d..fc5f9c78d 100644 --- a/sdk/javascript/delivery-read-receipts.mdx +++ b/sdk/javascript/delivery-read-receipts.mdx @@ -42,25 +42,25 @@ Use `markAsDelivered()` to mark messages as delivered. You can pass either a mes ### Using Message Object - -```javascript + +```typescript CometChat.markAsDelivered(message).then( () => { console.log("Marked as delivered successfully"); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Error marking as delivered:", error); } ); ``` - -```typescript + +```javascript CometChat.markAsDelivered(message).then( () => { console.log("Marked as delivered successfully"); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Error marking as delivered:", error); } ); @@ -222,25 +222,25 @@ Use `markAsRead()` to mark messages as read. You can pass either a message objec ### Using Message Object - -```javascript + +```typescript CometChat.markAsRead(message).then( () => { console.log("Marked as read successfully"); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Error marking as read:", error); } ); ``` - -```typescript + +```javascript CometChat.markAsRead(message).then( () => { console.log("Marked as read successfully"); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Error marking as read:", error); } ); @@ -397,27 +397,27 @@ You cannot mark your own messages as unread. This method only works for messages - -```javascript + +```typescript CometChat.markMessageAsUnread(message).then( - (conversation) => { + (conversation: CometChat.Conversation) => { console.log("Marked as unread successfully", conversation); console.log("Unread count:", conversation.getUnreadMessageCount()); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Error marking as unread:", error); } ); ``` - -```typescript + +```javascript CometChat.markMessageAsUnread(message).then( - (conversation: CometChat.Conversation) => { + (conversation) => { console.log("Marked as unread successfully", conversation); console.log("Unread count:", conversation.getUnreadMessageCount()); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Error marking as unread:", error); } ); @@ -439,46 +439,46 @@ Register a `MessageListener` to receive delivery and read receipt events. | `onMessagesReadByAll` | Group message read by all members | - -```javascript -let listenerID = "UNIQUE_LISTENER_ID"; + +```typescript +let listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onMessagesDelivered: (messageReceipt) => { + onMessagesDelivered: (messageReceipt: CometChat.MessageReceipt) => { console.log("Message delivered:", messageReceipt); }, - onMessagesRead: (messageReceipt) => { + onMessagesRead: (messageReceipt: CometChat.MessageReceipt) => { console.log("Message read:", messageReceipt); }, - onMessagesDeliveredToAll: (messageReceipt) => { + onMessagesDeliveredToAll: (messageReceipt: CometChat.MessageReceipt) => { console.log("Message delivered to all group members:", messageReceipt); }, - onMessagesReadByAll: (messageReceipt) => { + onMessagesReadByAll: (messageReceipt: CometChat.MessageReceipt) => { console.log("Message read by all group members:", messageReceipt); } }) ); ``` - -```typescript -let listenerID: string = "UNIQUE_LISTENER_ID"; + +```javascript +let listenerID = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onMessagesDelivered: (messageReceipt: CometChat.MessageReceipt) => { + onMessagesDelivered: (messageReceipt) => { console.log("Message delivered:", messageReceipt); }, - onMessagesRead: (messageReceipt: CometChat.MessageReceipt) => { + onMessagesRead: (messageReceipt) => { console.log("Message read:", messageReceipt); }, - onMessagesDeliveredToAll: (messageReceipt: CometChat.MessageReceipt) => { + onMessagesDeliveredToAll: (messageReceipt) => { console.log("Message delivered to all group members:", messageReceipt); }, - onMessagesReadByAll: (messageReceipt: CometChat.MessageReceipt) => { + onMessagesReadByAll: (messageReceipt) => { console.log("Message read by all group members:", messageReceipt); } }) @@ -514,29 +514,29 @@ The listener callbacks receive a [`MessageReceipt`](/sdk/reference/auxiliary#mes 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 = 123; + +```typescript +let messageId: number = 123; CometChat.getMessageReceipts(messageId).then( - (receipts) => { + (receipts: CometChat.MessageReceipt[]) => { console.log("Message receipts:", receipts); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Error fetching receipts:", error); } ); ``` - -```typescript -let messageId: number = 123; + +```javascript +let messageId = 123; CometChat.getMessageReceipts(messageId).then( - (receipts: CometChat.MessageReceipt[]) => { + (receipts) => { console.log("Message receipts:", receipts); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Error fetching receipts:", error); } ); diff --git a/sdk/javascript/direct-call.mdx b/sdk/javascript/direct-call.mdx index 110a9d887..dcaa9aec5 100644 --- a/sdk/javascript/direct-call.mdx +++ b/sdk/javascript/direct-call.mdx @@ -47,35 +47,35 @@ You can generate the token just before starting the call, or generate and store Use the `generateToken()` method to create a call token: - -```javascript + +```typescript const loggedInUser = await CometChat.getLoggedinUser(); const authToken = loggedInUser.getAuthToken(); -const sessionId = "SESSION_ID"; // Random or from Call object in ringing flow +const sessionId: string = "SESSION_ID"; // Random or from Call object in ringing flow CometChatCalls.generateToken(sessionId, authToken).then( - (callToken) => { + (callToken: any) => { console.log("Call token generated:", callToken.token); // Use callToken to start the session }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Token generation failed:", error); } ); ``` - -```typescript + +```javascript const loggedInUser = await CometChat.getLoggedinUser(); const authToken = loggedInUser.getAuthToken(); -const sessionId: string = "SESSION_ID"; // Random or from Call object in ringing flow +const sessionId = "SESSION_ID"; // Random or from Call object in ringing flow CometChatCalls.generateToken(sessionId, authToken).then( - (callToken: any) => { + (callToken) => { console.log("Call token generated:", callToken.token); // Use callToken to start the session }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Token generation failed:", error); } ); @@ -96,16 +96,16 @@ Use the `startSession()` method to join a call session. This method requires: 3. An HTML element where the call UI will be rendered - -```javascript + +```typescript const callListener = new CometChatCalls.OngoingCallListener({ - onUserJoined: (user) => { + onUserJoined: (user: any) => { console.log("User joined:", user); }, - onUserLeft: (user) => { + onUserLeft: (user: any) => { console.log("User left:", user); }, - onUserListUpdated: (userList) => { + onUserListUpdated: (userList: any[]) => { console.log("User list updated:", userList); }, onCallEnded: () => { @@ -115,13 +115,13 @@ const callListener = new CometChatCalls.OngoingCallListener({ console.log("End call button pressed"); // Handle end call - see End Call Session section }, - onError: (error) => { + onError: (error: any) => { console.log("Call error:", error); }, - onMediaDeviceListUpdated: (deviceList) => { + onMediaDeviceListUpdated: (deviceList: any[]) => { console.log("Device list updated:", deviceList); }, - onUserMuted: (event) => { + onUserMuted: (event: any) => { console.log("User muted:", event); }, onScreenShareStarted: () => { @@ -130,7 +130,7 @@ const callListener = new CometChatCalls.OngoingCallListener({ onScreenShareStopped: () => { console.log("Screen sharing stopped"); }, - onCallSwitchedToVideo: (event) => { + onCallSwitchedToVideo: (event: any) => { console.log("Call switched to video:", event); }, onSessionTimeout: () => { @@ -144,20 +144,20 @@ const callSettings = new CometChatCalls.CallSettingsBuilder() .setCallListener(callListener) .build(); -const htmlElement = document.getElementById("call-container"); +const htmlElement = document.getElementById("call-container") as HTMLElement; CometChatCalls.startSession(callToken, callSettings, htmlElement); ``` - -```typescript + +```javascript const callListener = new CometChatCalls.OngoingCallListener({ - onUserJoined: (user: any) => { + onUserJoined: (user) => { console.log("User joined:", user); }, - onUserLeft: (user: any) => { + onUserLeft: (user) => { console.log("User left:", user); }, - onUserListUpdated: (userList: any[]) => { + onUserListUpdated: (userList) => { console.log("User list updated:", userList); }, onCallEnded: () => { @@ -167,13 +167,13 @@ const callListener = new CometChatCalls.OngoingCallListener({ console.log("End call button pressed"); // Handle end call - see End Call Session section }, - onError: (error: any) => { + onError: (error) => { console.log("Call error:", error); }, - onMediaDeviceListUpdated: (deviceList: any[]) => { + onMediaDeviceListUpdated: (deviceList) => { console.log("Device list updated:", deviceList); }, - onUserMuted: (event: any) => { + onUserMuted: (event) => { console.log("User muted:", event); }, onScreenShareStarted: () => { @@ -182,7 +182,7 @@ const callListener = new CometChatCalls.OngoingCallListener({ onScreenShareStopped: () => { console.log("Screen sharing stopped"); }, - onCallSwitchedToVideo: (event: any) => { + onCallSwitchedToVideo: (event) => { console.log("Call switched to video:", event); }, onSessionTimeout: () => { @@ -196,7 +196,7 @@ const callSettings = new CometChatCalls.CallSettingsBuilder() .setCallListener(callListener) .build(); -const htmlElement = document.getElementById("call-container") as HTMLElement; +const htmlElement = document.getElementById("call-container"); CometChatCalls.startSession(callToken, callSettings, htmlElement); ``` @@ -243,18 +243,18 @@ Each listener requires a unique `listenerId` string. This ID is used to: - **Enable targeted removal** — Remove specific listeners without affecting others - -```javascript -const listenerId = "UNIQUE_LISTENER_ID"; + +```typescript +const listenerId: string = "UNIQUE_LISTENER_ID"; CometChatCalls.addCallEventListener(listenerId, { - onUserJoined: (user) => { + onUserJoined: (user: any) => { console.log("User joined:", user); }, - onUserLeft: (user) => { + onUserLeft: (user: any) => { console.log("User left:", user); }, - onUserListUpdated: (userList) => { + onUserListUpdated: (userList: any[]) => { console.log("User list updated:", userList); }, onCallEnded: () => { @@ -263,13 +263,13 @@ CometChatCalls.addCallEventListener(listenerId, { onCallEndButtonPressed: () => { console.log("End call button pressed"); }, - onError: (error) => { + onError: (error: any) => { console.log("Call error:", error); }, - onMediaDeviceListUpdated: (deviceList) => { + onMediaDeviceListUpdated: (deviceList: any[]) => { console.log("Device list updated:", deviceList); }, - onUserMuted: (event) => { + onUserMuted: (event: any) => { console.log("User muted:", event); }, onScreenShareStarted: () => { @@ -278,7 +278,7 @@ CometChatCalls.addCallEventListener(listenerId, { onScreenShareStopped: () => { console.log("Screen sharing stopped"); }, - onCallSwitchedToVideo: (event) => { + onCallSwitchedToVideo: (event: any) => { console.log("Call switched to video:", event); }, onSessionTimeout: () => { @@ -290,18 +290,18 @@ CometChatCalls.addCallEventListener(listenerId, { CometChatCalls.removeCallEventListener(listenerId); ``` - -```typescript -const listenerId: string = "UNIQUE_LISTENER_ID"; + +```javascript +const listenerId = "UNIQUE_LISTENER_ID"; CometChatCalls.addCallEventListener(listenerId, { - onUserJoined: (user: any) => { + onUserJoined: (user) => { console.log("User joined:", user); }, - onUserLeft: (user: any) => { + onUserLeft: (user) => { console.log("User left:", user); }, - onUserListUpdated: (userList: any[]) => { + onUserListUpdated: (userList) => { console.log("User list updated:", userList); }, onCallEnded: () => { @@ -310,13 +310,13 @@ CometChatCalls.addCallEventListener(listenerId, { onCallEndButtonPressed: () => { console.log("End call button pressed"); }, - onError: (error: any) => { + onError: (error) => { console.log("Call error:", error); }, - onMediaDeviceListUpdated: (deviceList: any[]) => { + onMediaDeviceListUpdated: (deviceList) => { console.log("Device list updated:", deviceList); }, - onUserMuted: (event: any) => { + onUserMuted: (event) => { console.log("User muted:", event); }, onScreenShareStarted: () => { @@ -325,7 +325,7 @@ CometChatCalls.addCallEventListener(listenerId, { onScreenShareStopped: () => { console.log("Screen sharing stopped"); }, - onCallSwitchedToVideo: (event: any) => { + onCallSwitchedToVideo: (event) => { console.log("Call switched to video:", event); }, onSessionTimeout: () => { @@ -389,34 +389,34 @@ The Ringing flow requires calling methods from both the Chat SDK (`CometChat.end When the user clicks the end call button in the UI, the `onCallEndButtonPressed()` callback is triggered. You must call `CometChat.endCall()` inside this callback to properly terminate the call and notify other participants. On success, call `CometChat.clearActiveCall()` and `CometChatCalls.endSession()` to release resources. - -```javascript + +```typescript onCallEndButtonPressed: () => { CometChat.endCall(sessionId).then( - (call) => { + (call: CometChat.Call) => { console.log("Call ended successfully"); CometChat.clearActiveCall(); CometChatCalls.endSession(); // Close the calling screen }, - (error) => { + (error: CometChat.CometChatException) => { console.log("End call failed:", error); } ); } ``` - -```typescript + +```javascript onCallEndButtonPressed: () => { CometChat.endCall(sessionId).then( - (call: CometChat.Call) => { + (call) => { console.log("Call ended successfully"); CometChat.clearActiveCall(); CometChatCalls.endSession(); // Close the calling screen }, - (error: CometChat.CometChatException) => { + (error) => { console.log("End call failed:", error); } ); @@ -430,8 +430,8 @@ onCallEndButtonPressed: () => { Call `CometChat.clearActiveCall()` to clear the local call state, then call `CometChatCalls.endSession()` to release media resources. - -```javascript + +```typescript onCallEnded: () => { CometChat.clearActiveCall(); CometChatCalls.endSession(); @@ -439,8 +439,8 @@ onCallEnded: () => { } ``` - -```typescript + +```javascript onCallEnded: () => { CometChat.clearActiveCall(); CometChatCalls.endSession(); @@ -457,16 +457,16 @@ When using the Session Only flow (direct call without ringing), you only need to Call `CometChatCalls.endSession()` in the `onCallEndButtonPressed()` callback to release all media resources and disconnect from the call session. - -```javascript + +```typescript onCallEndButtonPressed: () => { CometChatCalls.endSession(); // Close the calling screen } ``` - -```typescript + +```javascript onCallEndButtonPressed: () => { CometChatCalls.endSession(); // Close the calling screen @@ -488,13 +488,13 @@ These methods can only be called when a call session is active. Toggles between the front and rear camera during a video call. Only supported on mobile browsers. - -```javascript + +```typescript CometChatCalls.switchCamera(); ``` - -```typescript + +```javascript CometChatCalls.switchCamera(); ``` @@ -512,13 +512,13 @@ Controls the local audio stream transmission. When muted, other participants can - `false` — Unmutes the microphone, resumes audio transmission - -```javascript + +```typescript CometChatCalls.muteAudio(true); ``` - -```typescript + +```javascript CometChatCalls.muteAudio(true); ``` @@ -532,13 +532,13 @@ Controls the local video stream transmission. When paused, other participants se - `false` — Resumes the camera, continues video transmission - -```javascript + +```typescript CometChatCalls.pauseVideo(true); ``` - -```typescript + +```javascript CometChatCalls.pauseVideo(true); ``` @@ -549,13 +549,13 @@ CometChatCalls.pauseVideo(true); Starts sharing your screen or a specific application window with other participants. - -```javascript + +```typescript CometChatCalls.startScreenShare(); ``` - -```typescript + +```javascript CometChatCalls.startScreenShare(); ``` @@ -566,13 +566,13 @@ CometChatCalls.startScreenShare(); Stops the current screen sharing session. - -```javascript + +```typescript CometChatCalls.stopScreenShare(); ``` - -```typescript + +```javascript CometChatCalls.stopScreenShare(); ``` @@ -587,13 +587,13 @@ Changes the call UI layout mode dynamically during the call. - `CometChat.CALL_MODE.SPOTLIGHT` — Focus on the active speaker - -```javascript + +```typescript CometChatCalls.setMode(CometChat.CALL_MODE.SPOTLIGHT); ``` - -```typescript + +```javascript CometChatCalls.setMode(CometChat.CALL_MODE.SPOTLIGHT); ``` @@ -604,14 +604,14 @@ CometChatCalls.setMode(CometChat.CALL_MODE.SPOTLIGHT); Returns a list of available audio input devices (microphones). - -```javascript + +```typescript const audioInputDevices = CometChatCalls.getAudioInputDevices(); console.log("Available microphones:", audioInputDevices); ``` - -```typescript + +```javascript const audioInputDevices = CometChatCalls.getAudioInputDevices(); console.log("Available microphones:", audioInputDevices); ``` @@ -623,14 +623,14 @@ console.log("Available microphones:", audioInputDevices); Returns a list of available audio output devices (speakers/headphones). - -```javascript + +```typescript const audioOutputDevices = CometChatCalls.getAudioOutputDevices(); console.log("Available speakers:", audioOutputDevices); ``` - -```typescript + +```javascript const audioOutputDevices = CometChatCalls.getAudioOutputDevices(); console.log("Available speakers:", audioOutputDevices); ``` @@ -642,14 +642,14 @@ console.log("Available speakers:", audioOutputDevices); Returns a list of available video input devices (cameras). - -```javascript + +```typescript const videoInputDevices = CometChatCalls.getVideoInputDevices(); console.log("Available cameras:", videoInputDevices); ``` - -```typescript + +```javascript const videoInputDevices = CometChatCalls.getVideoInputDevices(); console.log("Available cameras:", videoInputDevices); ``` @@ -661,13 +661,13 @@ console.log("Available cameras:", videoInputDevices); Sets the active audio input device (microphone) by device ID. - -```javascript + +```typescript CometChatCalls.setAudioInputDevice(deviceId); ``` - -```typescript + +```javascript CometChatCalls.setAudioInputDevice(deviceId); ``` @@ -678,13 +678,13 @@ CometChatCalls.setAudioInputDevice(deviceId); Sets the active audio output device (speaker/headphones) by device ID. - -```javascript + +```typescript CometChatCalls.setAudioOutputDevice(deviceId); ``` - -```typescript + +```javascript CometChatCalls.setAudioOutputDevice(deviceId); ``` @@ -695,13 +695,13 @@ CometChatCalls.setAudioOutputDevice(deviceId); Sets the active video input device (camera) by device ID. - -```javascript + +```typescript CometChatCalls.setVideoInputDevice(deviceId); ``` - -```typescript + +```javascript CometChatCalls.setVideoInputDevice(deviceId); ``` @@ -712,13 +712,13 @@ CometChatCalls.setVideoInputDevice(deviceId); Upgrades an ongoing audio call to a video call. This enables the camera and starts transmitting video to other participants. The remote participant receives the `onCallSwitchedToVideo()` callback. - -```javascript + +```typescript CometChatCalls.switchToVideoCall(); ``` - -```typescript + +```javascript CometChatCalls.switchToVideoCall(); ``` diff --git a/sdk/javascript/edit-message.mdx b/sdk/javascript/edit-message.mdx index 4587506ca..5e7a1a805 100644 --- a/sdk/javascript/edit-message.mdx +++ b/sdk/javascript/edit-message.mdx @@ -75,27 +75,6 @@ customMessage.setTags(tags); Once the message object is ready, call `editMessage()`. - -```javascript -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); - -CometChat.editMessage(textMessage).then( -message => { - console.log("Message Edited", message); -}, error => { - console.log("Message editing failed with error:", error); -} -); -``` - - - ```typescript let receiverID: string = "RECEIVER_UID"; @@ -117,6 +96,27 @@ CometChat.editMessage(textMessage).then( + +```javascript +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); + +CometChat.editMessage(textMessage).then( +message => { + console.log("Message Edited", message); +}, error => { + console.log("Message editing failed with error:", error); +} +); +``` + + + ```javascript try { @@ -165,14 +165,14 @@ By default, CometChat allows certain roles to edit a message. Use `onMessageEdited` in `MessageListener` to receive real-time edit events. - -```javascript -let listenerID = "UNIQUE_LISTENER_ID"; + +```typescript +let listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onMessageEdited: message => { + onMessageEdited: (message: CometChat.BaseMessage) => { console.log("Edited Message", message); } }) @@ -181,14 +181,14 @@ new CometChat.MessageListener({ - -```typescript -let listenerID: string = "UNIQUE_LISTENER_ID"; + +```javascript +let listenerID = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onMessageEdited: (message: CometChat.BaseMessage) => { + onMessageEdited: message => { console.log("Edited Message", message); } }) diff --git a/sdk/javascript/flag-message.mdx b/sdk/javascript/flag-message.mdx index 3e310ff16..959dd8c41 100644 --- a/sdk/javascript/flag-message.mdx +++ b/sdk/javascript/flag-message.mdx @@ -61,29 +61,29 @@ sequenceDiagram Before flagging a message, retrieve the list of available flag reasons configured in your Dashboard: - - ```javascript + + ```typescript CometChat.getFlagReasons().then( - (reasons) => { + (reasons: CometChat.FlagReason[]) => { console.log("Flag reasons retrieved:", reasons); // reasons is an array of { id, reason } objects // Use these to populate your report dialog UI }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Failed to get flag reasons:", error); } ); ``` - - ```typescript + + ```javascript CometChat.getFlagReasons().then( - (reasons: CometChat.FlagReason[]) => { + (reasons) => { console.log("Flag reasons retrieved:", reasons); // reasons is an array of { id, reason } objects // Use these to populate your report dialog UI }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Failed to get flag reasons:", error); } ); @@ -111,37 +111,37 @@ The response is an array of flag reason objects: To flag a message, use the `flagMessage()` method with the message ID and a payload containing the reason: - - ```javascript - const messageId = "MESSAGE_ID_TO_FLAG"; - const payload = { - reasonId: "spam", // Required: ID from getFlagReasons() - remark: "This message contains promotional content" // Optional + + ```typescript + const messageId: string = "MESSAGE_ID_TO_FLAG"; + const payload: { reasonId: string; remark?: string } = { + reasonId: "spam", + remark: "This message contains promotional content" }; CometChat.flagMessage(messageId, payload).then( - (response) => { + (response: CometChat.FlagMessageResponse) => { console.log("Message flagged successfully:", response); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Message flagging failed:", error); } ); ``` - - ```typescript - const messageId: string = "MESSAGE_ID_TO_FLAG"; - const payload: { reasonId: string; remark?: string } = { - reasonId: "spam", - remark: "This message contains promotional content" + + ```javascript + const messageId = "MESSAGE_ID_TO_FLAG"; + const payload = { + reasonId: "spam", // Required: ID from getFlagReasons() + remark: "This message contains promotional content" // Optional }; CometChat.flagMessage(messageId, payload).then( - (response: CometChat.FlagMessageResponse) => { + (response) => { console.log("Message flagged successfully:", response); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Message flagging failed:", error); } ); diff --git a/sdk/javascript/group-add-members.mdx b/sdk/javascript/group-add-members.mdx index d12c385ba..a08ae2526 100644 --- a/sdk/javascript/group-add-members.mdx +++ b/sdk/javascript/group-add-members.mdx @@ -34,19 +34,19 @@ Use `addMembersToGroup()` to add members to a [Group](/sdk/reference/entities#gr | `bannedMembers` | Array of UIDs to ban (can be empty) | - -```javascript -let GUID = "GUID"; -let UID = "UID"; -let membersList = [ + +```typescript +let GUID: string = "GUID"; +let UID: string = "UID"; +let membersList: CometChat.GroupMember[] = [ new CometChat.GroupMember(UID, CometChat.GROUP_MEMBER_SCOPE.PARTICIPANT), ]; CometChat.addMembersToGroup(GUID, membersList, []).then( - (response) => { + (response: Object) => { console.log("response", response); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Something went wrong", error); } ); @@ -54,19 +54,19 @@ CometChat.addMembersToGroup(GUID, membersList, []).then( - -```typescript -let GUID: string = "GUID"; -let UID: string = "UID"; -let membersList: CometChat.GroupMember[] = [ + +```javascript +let GUID = "GUID"; +let UID = "UID"; +let membersList = [ new CometChat.GroupMember(UID, CometChat.GROUP_MEMBER_SCOPE.PARTICIPANT), ]; CometChat.addMembersToGroup(GUID, membersList, []).then( - (response: Object) => { + (response) => { console.log("response", response); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Something went wrong", error); } ); @@ -89,14 +89,19 @@ When a group member is added by another member, this event is triggered. When a Implement `onMemberAddedToGroup()` in `GroupListener` to receive real-time notifications when members are added. - -```javascript -const listenerID = "UNIQUE_LISTENER_ID"; + +```typescript +const listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addGroupListener( listenerID, new CometChat.GroupListener({ - onMemberAddedToGroup: (message, userAdded, userAddedBy, userAddedIn) => { + onMemberAddedToGroup: ( + message: CometChat.Action, + userAdded: CometChat.User, + userAddedBy: CometChat.User, + userAddedIn: CometChat.Group + ) => { console.log("User joined", { message, userAdded, @@ -110,19 +115,14 @@ CometChat.addGroupListener( - -```typescript -const listenerID: string = "UNIQUE_LISTENER_ID"; + +```javascript +const listenerID = "UNIQUE_LISTENER_ID"; CometChat.addGroupListener( listenerID, new CometChat.GroupListener({ - onMemberAddedToGroup: ( - message: CometChat.Action, - userAdded: CometChat.User, - userAddedBy: CometChat.User, - userAddedIn: CometChat.Group - ) => { + onMemberAddedToGroup: (message, userAdded, userAddedBy, userAddedIn) => { console.log("User joined", { message, userAdded, diff --git a/sdk/javascript/group-change-member-scope.mdx b/sdk/javascript/group-change-member-scope.mdx index da3338c2b..8b19506db 100644 --- a/sdk/javascript/group-change-member-scope.mdx +++ b/sdk/javascript/group-change-member-scope.mdx @@ -25,23 +25,6 @@ You can change the role of a group member between admin, moderator, and particip Use `updateGroupMemberScope()` to change a member's role within a [Group](/sdk/reference/entities#group). - -```javascript -let GUID = "GUID"; -let UID = "UID"; -let scope = CometChat.GROUP_MEMBER_SCOPE.ADMIN; - -CometChat.updateGroupMemberScope(GUID, UID, scope).then( -response => { - console.log("Group member scopped changed", response); -}, error => { - console.log("Group member scopped changed failed", error); -} -); -``` - - - ```typescript let GUID: string = "GUID"; @@ -59,6 +42,23 @@ CometChat.updateGroupMemberScope(GUID, UID, CometChat.GroupMemberScope.Admin).th + +```javascript +let GUID = "GUID"; +let UID = "UID"; +let scope = CometChat.GROUP_MEMBER_SCOPE.ADMIN; + +CometChat.updateGroupMemberScope(GUID, UID, scope).then( +response => { + console.log("Group member scopped changed", response); +}, error => { + console.log("Group member scopped changed failed", error); +} +); +``` + + + This method takes the below parameters: @@ -78,22 +78,6 @@ On success, the method resolves with a success message string. Implement `onGroupMemberScopeChanged()` in `GroupListener` to receive real-time notifications when a member's scope changes. - -```javascript -let listenerID = "UNIQUE_LISTENER_ID"; - -CometChat.addGroupListener( -listenerID, -new CometChat.GroupListener({ - onGroupMemberScopeChanged: (message, changedUser, newScope, oldScope, changedGroup) => { - console.log("User joined", {message, changedUser, newScope, oldScope, changedGroup}); - } -}) -); -``` - - - ```typescript let listenerID: string = "UNIQUE_LISTENER_ID"; @@ -110,6 +94,22 @@ CometChat.addGroupListener( + +```javascript +let listenerID = "UNIQUE_LISTENER_ID"; + +CometChat.addGroupListener( +listenerID, +new CometChat.GroupListener({ + onGroupMemberScopeChanged: (message, changedUser, newScope, oldScope, changedGroup) => { + console.log("User joined", {message, changedUser, newScope, oldScope, changedGroup}); + } +}) +); +``` + + + diff --git a/sdk/javascript/group-kick-ban-members.mdx b/sdk/javascript/group-kick-ban-members.mdx index a711f8283..1b1b93e89 100644 --- a/sdk/javascript/group-kick-ban-members.mdx +++ b/sdk/javascript/group-kick-ban-members.mdx @@ -37,22 +37,6 @@ Only Admins or Moderators can perform these actions. Admins or Moderators can remove a member using `kickGroupMember()`. The kicked user can rejoin the group later. - -```javascript -const GUID = "GUID"; -const UID = "UID"; - -CometChat.kickGroupMember(GUID, UID).then( -response => { - console.log("Group member kicked successfully", response); -}, error => { - console.log("Group member kicking failed with error", error); -} -); -``` - - - ```typescript let GUID: string = "GUID"; @@ -69,6 +53,22 @@ CometChat.kickGroupMember(GUID, UID).then( + +```javascript +const GUID = "GUID"; +const UID = "UID"; + +CometChat.kickGroupMember(GUID, UID).then( +response => { + console.log("Group member kicked successfully", response); +}, error => { + console.log("Group member kicking failed with error", error); +} +); +``` + + + The `kickGroupMember()` method takes the following parameters: @@ -85,22 +85,6 @@ On success, the method resolves with a success message string. Admins or Moderators can ban a member using `banGroupMember()`. Unlike kicked users, banned users cannot rejoin until unbanned. - -```javascript -const GUID = "GUID"; -const UID = "UID"; - -CometChat.banGroupMember(GUID, UID).then( -response => { - console.log("Group member banned successfully", response); -}, error => { - console.log("Group member banning failed with error", error); -} -); -``` - - - ```typescript let GUID: string = "GUID"; @@ -117,6 +101,22 @@ CometChat.banGroupMember(GUID, UID).then( + +```javascript +const GUID = "GUID"; +const UID = "UID"; + +CometChat.banGroupMember(GUID, UID).then( +response => { + console.log("Group member banned successfully", response); +}, error => { + console.log("Group member banning failed with error", error); +} +); +``` + + + The `banGroupMember()` method takes the following parameters: @@ -133,22 +133,6 @@ On success, the method resolves with a success message string. Admins or Moderators can unban a previously banned member using `unbanGroupMember()`. - -```javascript -const GUID = "GUID"; -const UID = "UID"; - -CometChat.unbanGroupMember(GUID, UID).then( -response => { - console.log("Group member unbanned successfully", response); -}, error => { - console.log("Group member unbanning failed with error", error); -} -); -``` - - - ```typescript let GUID: string = "GUID"; @@ -165,6 +149,22 @@ CometChat.unbanGroupMember(GUID, UID).then( + +```javascript +const GUID = "GUID"; +const UID = "UID"; + +CometChat.unbanGroupMember(GUID, UID).then( +response => { + console.log("Group member unbanned successfully", response); +}, error => { + console.log("Group member unbanning failed with error", error); +} +); +``` + + + The `unbanGroupMember()` method takes the following parameters @@ -185,7 +185,18 @@ Use `BannedMembersRequestBuilder` to fetch banned members of a [Group](/sdk/refe Sets the number of banned members to fetch per request. - + +```typescript +let GUID: string = "GUID"; +let limit: number = 30; +let bannedGroupMembersRequest: CometChat.BannedMembersRequest = new CometChat.BannedMembersRequestBuilder(GUID) + .setLimit(limit) + .build(); +``` + + + + ```javascript let GUID = "GUID"; let limit = 30; @@ -196,25 +207,27 @@ let bannedGroupMembersRequest = new CometChat.BannedMembersRequestBuilder(GUID) + + +### Set Search Keyword + +Filters banned members by a search string. + + ```typescript let GUID: string = "GUID"; let limit: number = 30; +let searchKeyword: string = "super"; let bannedGroupMembersRequest: CometChat.BannedMembersRequest = new CometChat.BannedMembersRequestBuilder(GUID) .setLimit(limit) + .setSearchKeyword(searchKeyword) .build(); ``` - - -### Set Search Keyword - -Filters banned members by a search string. - - - + ```javascript let GUID = "GUID"; let limit = 30; @@ -227,25 +240,31 @@ let bannedGroupMembersRequest = new CometChat.BannedMembersRequestBuilder(GUID) + + +Once configured, call `build()` to create the request, then `fetchNext()` to retrieve banned members. + + ```typescript let GUID: string = "GUID"; let limit: number = 30; -let searchKeyword: string = "super"; let bannedGroupMembersRequest: CometChat.BannedMembersRequest = new CometChat.BannedMembersRequestBuilder(GUID) .setLimit(limit) - .setSearchKeyword(searchKeyword) .build(); + +bannedGroupMembersRequest.fetchNext().then( + (bannedMembers: CometChat.GroupMember[]) => { + console.log("Banned Group Member list fetched successfully:", bannedMembers); + }, (error: CometChat.CometChatException) => { + console.log("Banned Group Member list fetching failed with exception:", error); + } +); ``` - - -Once configured, call `build()` to create the request, then `fetchNext()` to retrieve banned members. - - - + ```javascript let GUID = "GUID"; let limit = 30; @@ -264,25 +283,6 @@ bannedMembers => { - -```typescript -let GUID: string = "GUID"; -let limit: number = 30; -let bannedGroupMembersRequest: CometChat.BannedMembersRequest = new CometChat.BannedMembersRequestBuilder(GUID) - .setLimit(limit) - .build(); - -bannedGroupMembersRequest.fetchNext().then( - (bannedMembers: CometChat.GroupMember[]) => { - console.log("Banned Group Member list fetched successfully:", bannedMembers); - }, (error: CometChat.CometChatException) => { - console.log("Banned Group Member list fetching failed with exception:", error); - } -); -``` - - - ## Real-Time Group Member Kicked/Banned Events @@ -296,28 +296,6 @@ Implement these `GroupListener` methods to receive real-time notifications: | `onGroupMemberUnbanned()` | A member is unbanned | - -```javascript -let listenerID = "UNIQUE_LISTENER_ID"; - -CometChat.addGroupListener( -listenerID, -new CometChat.GroupListener({ - onGroupMemberKicked: (message, kickedUser, kickedBy, kickedFrom) => { - console.log("User kicked", { message, kickedUser, kickedBy, kickedFrom }); - }, - onGroupMemberBanned: (message, bannedUser, bannedBy, bannedFrom) => { - console.log("User banned", { message, bannedUser, bannedBy, bannedFrom }); - }, - onGroupMemberUnbanned: (message, unbannedUser, unbannedBy,unbannedFrom) => { - console.log("User unbanned", {message, unbannedUser, unbannedBy, unbannedFrom}); - } -}) -); -``` - - - ```typescript let listenerID: string = "UNIQUE_LISTENER_ID"; @@ -340,6 +318,28 @@ CometChat.addGroupListener( + +```javascript +let listenerID = "UNIQUE_LISTENER_ID"; + +CometChat.addGroupListener( +listenerID, +new CometChat.GroupListener({ + onGroupMemberKicked: (message, kickedUser, kickedBy, kickedFrom) => { + console.log("User kicked", { message, kickedUser, kickedBy, kickedFrom }); + }, + onGroupMemberBanned: (message, bannedUser, bannedBy, bannedFrom) => { + console.log("User banned", { message, bannedUser, bannedBy, bannedFrom }); + }, + onGroupMemberUnbanned: (message, unbannedUser, unbannedBy,unbannedFrom) => { + console.log("User unbanned", {message, unbannedUser, unbannedBy, unbannedFrom}); + } +}) +); +``` + + + diff --git a/sdk/javascript/initialization.mdx b/sdk/javascript/initialization.mdx index bc918d41a..f66032036 100644 --- a/sdk/javascript/initialization.mdx +++ b/sdk/javascript/initialization.mdx @@ -8,22 +8,22 @@ The `init()` method initializes the SDK and must be called before any other Come ## Basic Initialization - -```javascript -let appID = "APP_ID"; -let region = "APP_REGION"; + +```typescript +let appID: string = "APP_ID"; +let region: string = "APP_REGION"; -let appSetting = new CometChat.AppSettingsBuilder() +let appSetting: CometChat.AppSettings = new CometChat.AppSettingsBuilder() .subscribePresenceForAllUsers() .setRegion(region) .autoEstablishSocketConnection(true) .build(); CometChat.init(appID, appSetting).then( - () => { - console.log("Initialization completed successfully"); + (initialized: boolean) => { + console.log("Initialization completed successfully", initialized); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Initialization failed with error:", error); } ); @@ -31,22 +31,22 @@ CometChat.init(appID, appSetting).then( - -```typescript -let appID: string = "APP_ID"; -let region: string = "APP_REGION"; + +```javascript +let appID = "APP_ID"; +let region = "APP_REGION"; -let appSetting: CometChat.AppSettings = new CometChat.AppSettingsBuilder() +let appSetting = new CometChat.AppSettingsBuilder() .subscribePresenceForAllUsers() .setRegion(region) .autoEstablishSocketConnection(true) .build(); CometChat.init(appID, appSetting).then( - (initialized: boolean) => { - console.log("Initialization completed successfully", initialized); + () => { + console.log("Initialization completed successfully"); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Initialization failed with error:", error); } ); diff --git a/sdk/javascript/interactive-messages.mdx b/sdk/javascript/interactive-messages.mdx index db180414d..3570fb421 100644 --- a/sdk/javascript/interactive-messages.mdx +++ b/sdk/javascript/interactive-messages.mdx @@ -50,12 +50,12 @@ The [`InteractiveMessage`](/sdk/reference/messages#interactivemessage) class rep Use `sendInteractiveMessage()` to send an interactive message. - -```javascript -let receiverId = "UID"; -let receiverType = CometChat.RECEIVER_TYPE.USER; + +```typescript +let receiverId: string = "UID"; +let receiverType: string = CometChat.RECEIVER_TYPE.USER; -let interactiveData = { +let interactiveData: Object = { title: "Survey", formFields: [ { @@ -109,7 +109,7 @@ let interactiveData = { } }; -let interactiveMessage = new CometChat.InteractiveMessage( +let interactiveMessage: CometChat.InteractiveMessage = new CometChat.InteractiveMessage( receiverId, receiverType, "form", @@ -117,21 +117,21 @@ let interactiveMessage = new CometChat.InteractiveMessage( ); CometChat.sendInteractiveMessage(interactiveMessage).then( - (message) => { + (message: CometChat.InteractiveMessage) => { console.log("Interactive message sent successfully", message); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Interactive message sending failed with error:", error); } ); ``` - -```typescript -let receiverId: string = "UID"; -let receiverType: string = CometChat.RECEIVER_TYPE.USER; + +```javascript +let receiverId = "UID"; +let receiverType = CometChat.RECEIVER_TYPE.USER; -let interactiveData: Object = { +let interactiveData = { title: "Survey", formFields: [ { @@ -185,7 +185,7 @@ let interactiveData: Object = { } }; -let interactiveMessage: CometChat.InteractiveMessage = new CometChat.InteractiveMessage( +let interactiveMessage = new CometChat.InteractiveMessage( receiverId, receiverType, "form", @@ -193,10 +193,10 @@ let interactiveMessage: CometChat.InteractiveMessage = new CometChat.Interactive ); CometChat.sendInteractiveMessage(interactiveMessage).then( - (message: CometChat.InteractiveMessage) => { + (message) => { console.log("Interactive message sent successfully", message); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Interactive message sending failed with error:", error); } ); @@ -300,15 +300,15 @@ An `InteractionGoal` defines when the user's interaction with the message is con ### Set an Interaction Goal - -```javascript -let elementIds = ["name", "gender", "submitButton"]; -let interactionGoal = new CometChat.InteractionGoal( + +```typescript +let elementIds: Array = ["name", "gender", "submitButton"]; +let interactionGoal: CometChat.InteractionGoal = new CometChat.InteractionGoal( CometChat.GoalType.ALL_OF, elementIds ); -let interactiveMessage = new CometChat.InteractiveMessage( +let interactiveMessage: CometChat.InteractiveMessage = new CometChat.InteractiveMessage( receiverId, receiverType, "form", @@ -317,24 +317,24 @@ let interactiveMessage = new CometChat.InteractiveMessage( interactiveMessage.setInteractionGoal(interactionGoal); CometChat.sendInteractiveMessage(interactiveMessage).then( - (message) => { + (message: CometChat.InteractiveMessage) => { console.log("Interactive message sent successfully", message); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Interactive message sending failed with error:", error); } ); ``` - -```typescript -let elementIds: Array = ["name", "gender", "submitButton"]; -let interactionGoal: CometChat.InteractionGoal = new CometChat.InteractionGoal( + +```javascript +let elementIds = ["name", "gender", "submitButton"]; +let interactionGoal = new CometChat.InteractionGoal( CometChat.GoalType.ALL_OF, elementIds ); -let interactiveMessage: CometChat.InteractiveMessage = new CometChat.InteractiveMessage( +let interactiveMessage = new CometChat.InteractiveMessage( receiverId, receiverType, "form", @@ -343,10 +343,10 @@ let interactiveMessage: CometChat.InteractiveMessage = new CometChat.Interactive interactiveMessage.setInteractionGoal(interactionGoal); CometChat.sendInteractiveMessage(interactiveMessage).then( - (message: CometChat.InteractiveMessage) => { + (message) => { console.log("Interactive message sent successfully", message); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Interactive message sending failed with error:", error); } ); @@ -368,31 +368,31 @@ An `Interaction` represents a single user action on an interactive element. Use `markAsInteracted()` to record when a user interacts with an element. - -```javascript -let messageId = 123; -let elementId = "submitButton"; + +```typescript +let messageId: number = 123; +let elementId: string = "submitButton"; CometChat.markAsInteracted(messageId, elementId).then( - (response) => { + (response: string) => { console.log("Marked as interacted successfully", response); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Failed to mark as interacted:", error); } ); ``` - -```typescript -let messageId: number = 123; -let elementId: string = "submitButton"; + +```javascript +let messageId = 123; +let elementId = "submitButton"; CometChat.markAsInteracted(messageId, elementId).then( - (response: string) => { + (response) => { console.log("Marked as interacted successfully", response); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Failed to mark as interacted:", error); } ); @@ -407,14 +407,14 @@ Register a `MessageListener` to receive interactive message events. ### Receive Interactive Messages - -```javascript -let listenerID = "UNIQUE_LISTENER_ID"; + +```typescript +let listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onInteractiveMessageReceived: (message) => { + onInteractiveMessageReceived: (message: CometChat.InteractiveMessage) => { console.log("Interactive message received", message); // Render the interactive UI based on message.getInteractiveData() } @@ -422,14 +422,14 @@ CometChat.addMessageListener( ); ``` - -```typescript -let listenerID: string = "UNIQUE_LISTENER_ID"; + +```javascript +let listenerID = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onInteractiveMessageReceived: (message: CometChat.InteractiveMessage) => { + onInteractiveMessageReceived: (message) => { console.log("Interactive message received", message); // Render the interactive UI based on message.getInteractiveData() } @@ -444,14 +444,14 @@ CometChat.addMessageListener( Triggered when a user's interactions satisfy the defined `InteractionGoal`. - -```javascript -let listenerID = "UNIQUE_LISTENER_ID"; + +```typescript +let listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onInteractionGoalCompleted: (receipt) => { + onInteractionGoalCompleted: (receipt: CometChat.InteractionReceipt) => { console.log("Interaction goal completed", receipt); // Handle goal completion (e.g., show confirmation, trigger next step) } @@ -459,14 +459,14 @@ CometChat.addMessageListener( ); ``` - -```typescript -let listenerID: string = "UNIQUE_LISTENER_ID"; + +```javascript +let listenerID = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onInteractionGoalCompleted: (receipt: CometChat.InteractionReceipt) => { + onInteractionGoalCompleted: (receipt) => { console.log("Interaction goal completed", receipt); // Handle goal completion (e.g., show confirmation, trigger next step) } @@ -489,9 +489,9 @@ CometChat.removeMessageListener("UNIQUE_LISTENER_ID"); By default, the sender cannot interact with their own interactive message. Enable sender interaction: - -```javascript -let interactiveMessage = new CometChat.InteractiveMessage( + +```typescript +let interactiveMessage: CometChat.InteractiveMessage = new CometChat.InteractiveMessage( receiverId, receiverType, "form", @@ -500,18 +500,18 @@ let interactiveMessage = new CometChat.InteractiveMessage( interactiveMessage.setIsSenderInteractionAllowed(true); CometChat.sendInteractiveMessage(interactiveMessage).then( - (message) => { + (message: CometChat.InteractiveMessage) => { console.log("Interactive message sent successfully", message); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Interactive message sending failed with error:", error); } ); ``` - -```typescript -let interactiveMessage: CometChat.InteractiveMessage = new CometChat.InteractiveMessage( + +```javascript +let interactiveMessage = new CometChat.InteractiveMessage( receiverId, receiverType, "form", @@ -520,10 +520,10 @@ let interactiveMessage: CometChat.InteractiveMessage = new CometChat.Interactive interactiveMessage.setIsSenderInteractionAllowed(true); CometChat.sendInteractiveMessage(interactiveMessage).then( - (message: CometChat.InteractiveMessage) => { + (message) => { console.log("Interactive message sent successfully", message); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Interactive message sending failed with error:", error); } ); diff --git a/sdk/javascript/join-group.mdx b/sdk/javascript/join-group.mdx index 20b35ec77..0f24155d1 100644 --- a/sdk/javascript/join-group.mdx +++ b/sdk/javascript/join-group.mdx @@ -28,7 +28,22 @@ Join groups to participate in group conversations and receive real-time events w Use `joinGroup()` to join a group. - + +```typescript +const GUID: string = "GUID"; + +CometChat.joinGroup(GUID, CometChat.GroupType.Public).then( + (group: CometChat.Group) => { + console.log("Group joined successfully:", group); + }, (error: CometChat.CometChatException) => { + console.log("Group joining failed with exception:", error); + } +); +``` + + + + ```javascript const GUID = "GUID"; const password = ""; @@ -45,21 +60,6 @@ group => { - -```typescript -const GUID: string = "GUID"; - -CometChat.joinGroup(GUID, CometChat.GroupType.Public).then( - (group: CometChat.Group) => { - console.log("Group joined successfully:", group); - }, (error: CometChat.CometChatException) => { - console.log("Group joining failed with exception:", error); - } -); -``` - - - | Parameter | Description | @@ -86,12 +86,12 @@ The method returns a [`Group`](/sdk/reference/entities#group) object with `hasJo Register a `GroupListener` to receive events when members join. - -```javascript + +```typescript CometChat.addGroupListener( "UNIQUE_LISTNER_ID", new CometChat.GroupListener({ - onGroupMemberJoined: (message, joinedUser, joinedGroup) => { + onGroupMemberJoined: (message: CometChat.Action, joinedUser: CometChat.User, joinedGroup: CometChat.Group) => { console.log("User joined", { message, joinedUser, joinedGroup }); } }) @@ -100,12 +100,12 @@ CometChat.addGroupListener( - -```typescript + +```javascript CometChat.addGroupListener( "UNIQUE_LISTNER_ID", new CometChat.GroupListener({ - onGroupMemberJoined: (message: CometChat.Action, joinedUser: CometChat.User, joinedGroup: CometChat.Group) => { + onGroupMemberJoined: (message, joinedUser, joinedGroup) => { console.log("User joined", { message, joinedUser, joinedGroup }); } }) diff --git a/sdk/javascript/leave-group.mdx b/sdk/javascript/leave-group.mdx index 18988a705..caf03152b 100644 --- a/sdk/javascript/leave-group.mdx +++ b/sdk/javascript/leave-group.mdx @@ -25,21 +25,6 @@ Leave a group to stop receiving updates and messages from that conversation. Use `leaveGroup()` to leave a group. - -```javascript -const GUID = "GUID"; - -CometChat.leaveGroup(GUID).then( -hasLeft => { - console.log("Group left successfully:", hasLeft); -}, error => { - console.log("Group leaving failed with exception:", error); -} -); -``` - - - ```typescript const GUID: string = "GUID"; @@ -55,6 +40,21 @@ CometChat.leaveGroup(GUID).then( + +```javascript +const GUID = "GUID"; + +CometChat.leaveGroup(GUID).then( +hasLeft => { + console.log("Group left successfully:", hasLeft); +}, error => { + console.log("Group leaving failed with exception:", error); +} +); +``` + + + | Parameter | Description | @@ -70,12 +70,12 @@ On success, the method resolves with a success message string confirming the ope Register a `GroupListener` to receive events when members leave. - -```javascript + +```typescript CometChat.addGroupListener( "UNIQUE_LISTENER_ID", new CometChat.GroupListener({ - onGroupMemberLeft: (message, leavingUser, group) => { + onGroupMemberLeft: (message: CometChat.Action, leavingUser: CometChat.User, group: CometChat.Group) => { console.log("User left", { message, leavingUser, group }); } }) @@ -84,12 +84,12 @@ CometChat.addGroupListener( - -```typescript + +```javascript CometChat.addGroupListener( "UNIQUE_LISTENER_ID", new CometChat.GroupListener({ - onGroupMemberLeft: (message: CometChat.Action, leavingUser: CometChat.User, group: CometChat.Group) => { + onGroupMemberLeft: (message, leavingUser, group) => { console.log("User left", { message, leavingUser, group }); } }) diff --git a/sdk/javascript/login-listener.mdx b/sdk/javascript/login-listener.mdx index 5a103fd20..47dbcaf45 100644 --- a/sdk/javascript/login-listener.mdx +++ b/sdk/javascript/login-listener.mdx @@ -32,23 +32,23 @@ The CometChat SDK provides you with real-time updates for the `login` and `logou To add the `LoginListener`, you need to use the `addLoginListener()` method provided by the SDK which takes a unique identifier for the listener and of the the `LoginListener` class itself. - -```js - let listenerID = "UNIQUE_LISTENER_ID"; + +```typescript + const listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addLoginListener( listenerID, new CometChat.LoginListener({ - loginSuccess: (e) => { - console.log("LoginListener :: loginSuccess", e); + loginSuccess: (user: CometChat.User) => { + console.log("LoginListener :: loginSuccess", user); }, - loginFailure: (e) => { - console.log("LoginListener :: loginFailure", e); + loginFailure: (error: CometChat.CometChatException) => { + console.log("LoginListener :: loginFailure", error); }, logoutSuccess: () => { console.log("LoginListener :: logoutSuccess"); }, - logoutFailure: (e) => { - console.log("LoginListener :: logoutFailure", e); + logoutFailure: (error: CometChat.CometChatException) => { + console.log("LoginListener :: logoutFailure", error); } }) ); @@ -56,23 +56,23 @@ To add the `LoginListener`, you need to use the `addLoginListener()` method prov - -```typescript - const listenerID: string = "UNIQUE_LISTENER_ID"; + +```js + let listenerID = "UNIQUE_LISTENER_ID"; CometChat.addLoginListener( listenerID, new CometChat.LoginListener({ - loginSuccess: (user: CometChat.User) => { - console.log("LoginListener :: loginSuccess", user); + loginSuccess: (e) => { + console.log("LoginListener :: loginSuccess", e); }, - loginFailure: (error: CometChat.CometChatException) => { - console.log("LoginListener :: loginFailure", error); + loginFailure: (e) => { + console.log("LoginListener :: loginFailure", e); }, logoutSuccess: () => { console.log("LoginListener :: logoutSuccess"); }, - logoutFailure: (error: CometChat.CometChatException) => { - console.log("LoginListener :: logoutFailure", error); + logoutFailure: (e) => { + console.log("LoginListener :: logoutFailure", e); } }) ); @@ -87,28 +87,27 @@ To add the `LoginListener`, you need to use the `addLoginListener()` method prov If you're using React, register the listener inside a `useEffect` hook and clean it up on unmount: - -```javascript + +```typescript import { useEffect } from "react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; -function useLoginListener() { +function useLoginListener(): void { useEffect(() => { - const listenerID = "LOGIN_LISTENER"; + const listenerID: string = "LOGIN_LISTENER"; CometChat.addLoginListener( listenerID, new CometChat.LoginListener({ - loginSuccess: (user) => { + loginSuccess: (user: CometChat.User) => { console.log("User logged in:", user); }, - loginFailure: (error) => { + loginFailure: (error: CometChat.CometChatException) => { console.log("Login failed:", error); }, logoutSuccess: () => { console.log("User logged out"); - // Redirect to login page, clear app state, etc. }, - logoutFailure: (error) => { + logoutFailure: (error: CometChat.CometChatException) => { console.log("Logout failed:", error); }, }) @@ -121,27 +120,28 @@ function useLoginListener() { } ``` - -```typescript + +```javascript import { useEffect } from "react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; -function useLoginListener(): void { +function useLoginListener() { useEffect(() => { - const listenerID: string = "LOGIN_LISTENER"; + const listenerID = "LOGIN_LISTENER"; CometChat.addLoginListener( listenerID, new CometChat.LoginListener({ - loginSuccess: (user: CometChat.User) => { + loginSuccess: (user) => { console.log("User logged in:", user); }, - loginFailure: (error: CometChat.CometChatException) => { + loginFailure: (error) => { console.log("Login failed:", error); }, logoutSuccess: () => { console.log("User logged out"); + // Redirect to login page, clear app state, etc. }, - logoutFailure: (error: CometChat.CometChatException) => { + logoutFailure: (error) => { console.log("Logout failed:", error); }, }) @@ -159,17 +159,17 @@ function useLoginListener(): void { 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 - const listenerID = "UNIQUE_LISTENER_ID"; + +```typescript + const listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.removeLoginListener(listenerID); ``` - -```typescript - const listenerID: string = "UNIQUE_LISTENER_ID"; + +```js + const listenerID = "UNIQUE_LISTENER_ID"; CometChat.removeLoginListener(listenerID); ``` diff --git a/sdk/javascript/managing-web-sockets-connections-manually.mdx b/sdk/javascript/managing-web-sockets-connections-manually.mdx index 6cd7a7380..27215fbf6 100644 --- a/sdk/javascript/managing-web-sockets-connections-manually.mdx +++ b/sdk/javascript/managing-web-sockets-connections-manually.mdx @@ -41,20 +41,20 @@ The CometChat SDK also allows you to modify the above default behaviour of the S 1. While calling the init() function on the app startup, you need to inform the SDK that you will be managing the web socket connect. You can do so by using the `autoEstablishSocketConnection()` method provided by the `AppSettingsBuilder` class. This method takes a boolean value as an input. If set to `true` , the SDK will manage the web-socket connection internally based on the default behaviour mentioned above. If set to `false` , the web socket connection can will not be managed by the SDK and you will have to handle it manually. You can refer to the below code snippet for the same: - -```js -let appID = "APP_ID"; -let region = "APP_REGION"; -let appSetting = new CometChat.AppSettingsBuilder() + +```typescript +let appID: string = "APP_ID"; +let region: string = "APP_REGION"; +let appSetting: CometChat.AppSettings = new CometChat.AppSettingsBuilder() .subscribePresenceForAllUsers() .setRegion(region) .autoEstablishSocketConnection(false) .build(); CometChat.init(appID, appSetting).then( - () => { + (isInitialized: boolean) => { console.log("Initialization completed successfully"); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Initialization failed with error:", error); } ); @@ -62,20 +62,20 @@ CometChat.init(appID, appSetting).then( - -```typescript -let appID: string = "APP_ID"; -let region: string = "APP_REGION"; -let appSetting: CometChat.AppSettings = new CometChat.AppSettingsBuilder() + +```js +let appID = "APP_ID"; +let region = "APP_REGION"; +let appSetting = new CometChat.AppSettingsBuilder() .subscribePresenceForAllUsers() .setRegion(region) .autoEstablishSocketConnection(false) .build(); CometChat.init(appID, appSetting).then( - (isInitialized: boolean) => { + () => { console.log("Initialization completed successfully"); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Initialization failed with error:", error); } ); diff --git a/sdk/javascript/message-structure-and-hierarchy.mdx b/sdk/javascript/message-structure-and-hierarchy.mdx index 1f93fc379..17b27315b 100644 --- a/sdk/javascript/message-structure-and-hierarchy.mdx +++ b/sdk/javascript/message-structure-and-hierarchy.mdx @@ -37,57 +37,57 @@ Every message in CometChat belongs to a category and has a specific type. Unders Use `getCategory()` and `getType()` to determine how to handle a received message: - -```javascript -const category = message.getCategory(); -const type = message.getType(); + +```typescript +const category: string = message.getCategory(); +const type: string = message.getType(); switch (category) { case CometChat.CATEGORY_MESSAGE: if (type === CometChat.MESSAGE_TYPE.TEXT) { - console.log("Text:", message.getText()); + const textMsg = message as CometChat.TextMessage; + console.log("Text:", textMsg.getText()); } else if (type === CometChat.MESSAGE_TYPE.IMAGE) { - console.log("Image URL:", message.getData().url); + const mediaMsg = message as CometChat.MediaMessage; + console.log("Image URL:", mediaMsg.getData().url); } break; case CometChat.CATEGORY_CUSTOM: - console.log("Custom type:", type, "data:", message.getData()); + const customMsg = message as CometChat.CustomMessage; + console.log("Custom type:", type, "data:", customMsg.getData()); break; case CometChat.CATEGORY_ACTION: - console.log("Action:", message.getAction()); + const actionMsg = message as CometChat.Action; + console.log("Action:", actionMsg.getAction()); break; case CometChat.CATEGORY_CALL: - console.log("Call status:", message.getStatus()); + const callMsg = message as CometChat.Call; + console.log("Call status:", callMsg.getStatus()); break; } ``` - -```typescript -const category: string = message.getCategory(); -const type: string = message.getType(); + +```javascript +const category = message.getCategory(); +const type = message.getType(); switch (category) { case CometChat.CATEGORY_MESSAGE: if (type === CometChat.MESSAGE_TYPE.TEXT) { - const textMsg = message as CometChat.TextMessage; - console.log("Text:", textMsg.getText()); + console.log("Text:", message.getText()); } else if (type === CometChat.MESSAGE_TYPE.IMAGE) { - const mediaMsg = message as CometChat.MediaMessage; - console.log("Image URL:", mediaMsg.getData().url); + console.log("Image URL:", message.getData().url); } break; case CometChat.CATEGORY_CUSTOM: - const customMsg = message as CometChat.CustomMessage; - console.log("Custom type:", type, "data:", customMsg.getData()); + console.log("Custom type:", type, "data:", message.getData()); break; case CometChat.CATEGORY_ACTION: - const actionMsg = message as CometChat.Action; - console.log("Action:", actionMsg.getAction()); + console.log("Action:", message.getAction()); break; case CometChat.CATEGORY_CALL: - const callMsg = message as CometChat.Call; - console.log("Call status:", callMsg.getStatus()); + console.log("Call status:", message.getStatus()); break; } ``` diff --git a/sdk/javascript/rate-limits.mdx b/sdk/javascript/rate-limits.mdx index 1d8a4a86c..c7689f4ef 100644 --- a/sdk/javascript/rate-limits.mdx +++ b/sdk/javascript/rate-limits.mdx @@ -40,15 +40,18 @@ CometChat includes rate limit information in response headers: When you exceed the rate limit, CometChat returns HTTP `429 Too Many Requests`. Implement exponential backoff to handle this gracefully: - -```javascript -async function callWithRetry(apiCall, maxRetries = 3) { + +```typescript +async function callWithRetry( + apiCall: () => Promise, + maxRetries: number = 3 +): Promise { for (let attempt = 0; attempt < maxRetries; attempt++) { try { return await apiCall(); - } catch (error) { + } catch (error: any) { if (error.code === "ERR_TOO_MANY_REQUESTS" && attempt < maxRetries - 1) { - const waitTime = Math.pow(2, attempt) * 1000; // 1s, 2s, 4s + const waitTime = Math.pow(2, attempt) * 1000; console.log(`Rate limited. Retrying in ${waitTime / 1000}s...`); await new Promise((resolve) => setTimeout(resolve, waitTime)); } else { @@ -56,26 +59,24 @@ async function callWithRetry(apiCall, maxRetries = 3) { } } } + throw new Error("Max retries exceeded"); } // Usage -const users = await callWithRetry(() => +const users: CometChat.User[] = await callWithRetry(() => new CometChat.UsersRequestBuilder().setLimit(30).build().fetchNext() ); ``` - -```typescript -async function callWithRetry( - apiCall: () => Promise, - maxRetries: number = 3 -): Promise { + +```javascript +async function callWithRetry(apiCall, maxRetries = 3) { for (let attempt = 0; attempt < maxRetries; attempt++) { try { return await apiCall(); - } catch (error: any) { + } catch (error) { if (error.code === "ERR_TOO_MANY_REQUESTS" && attempt < maxRetries - 1) { - const waitTime = Math.pow(2, attempt) * 1000; + 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 { @@ -83,11 +84,10 @@ async function callWithRetry( } } } - throw new Error("Max retries exceeded"); } // Usage -const users: CometChat.User[] = await callWithRetry(() => +const users = await callWithRetry(() => new CometChat.UsersRequestBuilder().setLimit(30).build().fetchNext() ); ``` diff --git a/sdk/javascript/reactions.mdx b/sdk/javascript/reactions.mdx index 82e226f6e..12c22fd34 100644 --- a/sdk/javascript/reactions.mdx +++ b/sdk/javascript/reactions.mdx @@ -34,32 +34,32 @@ Enhance user engagement in your chat application with message reactions. Users c Users can add a reaction to a message by calling `addReaction` with the message ID and the reaction emoji. - -```js -let messageId = "1"; -let emoji = "😊"; + +```typescript +let messageId:string = "1"; +let emoji:string = "😊"; CometChat.addReaction(messageId, emoji) -.then((res) => { +.then((res:CometChat.BaseMessage) => { console.log('response', res); -}).catch(err => { +}).catch((err:CometChat.CometChatException) => { console.log('err', err); -}) +}) ``` - -```typescript -let messageId:string = "1"; -let emoji:string = "😊"; + +```js +let messageId = "1"; +let emoji = "😊"; CometChat.addReaction(messageId, emoji) -.then((res:CometChat.BaseMessage) => { +.then((res) => { console.log('response', res); -}).catch((err:CometChat.CometChatException) => { +}).catch(err => { console.log('err', err); -}) +}) ``` @@ -77,32 +77,32 @@ You can react on text message, media message and custom message Removing a reaction from a message can be done using the `removeReaction` method. - -```js -let messageId = "1"; -let emoji = "😊"; + +```typescript +let messageId:string = "1"; +let emoji:string = "😊"; CometChat.removeReaction(messageId, emoji) -.then((res) => { +.then((res:CometChat.BaseMessage) => { console.log('response', res); -}).catch(err => { +}).catch((err:CometChat.CometChatException) => { console.log('err', err); -}) +}) ``` - -```typescript -let messageId:string = "1"; -let emoji:string = "😊"; + +```js +let messageId = "1"; +let emoji = "😊"; CometChat.removeReaction(messageId, emoji) -.then((res:CometChat.BaseMessage) => { +.then((res) => { console.log('response', res); -}).catch((err:CometChat.CometChatException) => { +}).catch(err => { console.log('err', err); -}) +}) ``` @@ -133,10 +133,10 @@ To get all reactions for a specific message, first create a `ReactionRequest` us The `fetchNext()` method fetches the next set of reactions for the message. - -```js -let limit = 10; -let messageId = 1; + +```typescript +let limit:number = 10; +let messageId:number = 1; let reactionRequest = new CometChat.ReactionRequestBuilder() .setMessageId(messageId) @@ -144,21 +144,21 @@ let reactionRequest = new CometChat.ReactionRequestBuilder() .build(); reactionRequest.fetchNext().then( - messages => { + (messages: MessageReaction[]) => { console.log("list fetched:", messages); }, - error => {a + (error: CometChat.CometChatException) => { console.log('list fetching failed with error:', error); }, - ); + ); ``` - -```typescript -let limit:number = 10; -let messageId:number = 1; + +```js +let limit = 10; +let messageId = 1; let reactionRequest = new CometChat.ReactionRequestBuilder() .setMessageId(messageId) @@ -166,13 +166,13 @@ let reactionRequest = new CometChat.ReactionRequestBuilder() .build(); reactionRequest.fetchNext().then( - (messages: MessageReaction[]) => { + messages => { console.log("list fetched:", messages); }, - (error: CometChat.CometChatException) => { + error => {a console.log('list fetching failed with error:', error); }, - ); + ); ``` @@ -182,10 +182,10 @@ reactionRequest.fetchNext().then( Fetch Previous The `fetchPrevious()` method fetches the previous set of reactions for the message. - -```js -let limit = 10; -let messageId = 1; + +```typescript +let limit:number = 10; +let messageId:number = 1; let reactionRequest = new CometChat.ReactionRequestBuilder() .setMessageId(messageId) @@ -193,21 +193,21 @@ let reactionRequest = new CometChat.ReactionRequestBuilder() .build(); reactionRequest.fetchPrevious().then( - messages => { + (messages: MessageReaction[]) => { console.log("list fetched:", messages); }, - error => {a + (error: CometChat.CometChatException) => { console.log('list fetching failed with error:', error); }, - ); + ); ``` - -```typescript -let limit:number = 10; -let messageId:number = 1; + +```js +let limit = 10; +let messageId = 1; let reactionRequest = new CometChat.ReactionRequestBuilder() .setMessageId(messageId) @@ -215,13 +215,13 @@ let reactionRequest = new CometChat.ReactionRequestBuilder() .build(); reactionRequest.fetchPrevious().then( - (messages: MessageReaction[]) => { + messages => { console.log("list fetched:", messages); }, - (error: CometChat.CometChatException) => { + error => {a console.log('list fetching failed with error:', error); }, - ); + ); ``` @@ -237,34 +237,34 @@ Always remove listeners when they're no longer needed (e.g., on component unmoun - -```js -let listenerID = "UNIQUE_LISTENER_ID"; + +```typescript +let listenerID:string = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener(listenerID, { - onMessageReactionAdded:(message) => { + onMessageReactionAdded:(message: Object) => { console.log("Reaction added", message); }, - onMessageReactionRemoved:(message) => { + onMessageReactionRemoved:(message: Object) => { console.log("Reaction removed", message); } - }) + }) ``` - -```typescript -let listenerID:string = "UNIQUE_LISTENER_ID"; + +```js +let listenerID = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener(listenerID, { - onMessageReactionAdded:(message: Object) => { + onMessageReactionAdded:(message) => { console.log("Reaction added", message); }, - onMessageReactionRemoved:(message: Object) => { + onMessageReactionRemoved:(message) => { console.log("Reaction removed", message); } - }) + }) ``` @@ -286,20 +286,20 @@ Each reaction listener callback receives a [`ReactionEvent`](/sdk/reference/auxi To stop listening for reaction events, remove the listener as follows: - -```js -let listenerID = "UNIQUE_LISTENER_ID"; + +```typescript +let listenerID:string = "UNIQUE_LISTENER_ID"; -CometChat.removeMessageListener(listenerID); +CometChat.removeMessageReactionListener(listenerID); ``` - -```typescript -let listenerID:string = "UNIQUE_LISTENER_ID"; + +```js +let listenerID = "UNIQUE_LISTENER_ID"; -CometChat.removeMessageReactionListener(listenerID); +CometChat.removeMessageListener(listenerID); ``` @@ -311,16 +311,16 @@ CometChat.removeMessageReactionListener(listenerID); To retrieve the list of reactions reacted on particular message, you can use the `message.getReactions()` method. This method will return an array containing the reactions, or an empty array if no one reacted on the message. - -```js -message.getReactions() + +```typescript +message.getReactions() ``` - -```typescript -message.getReactions() + +```js +message.getReactions() ``` @@ -332,22 +332,22 @@ message.getReactions() 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. - -```js + +```typescript let reactions = message.getReactions(); reactions.forEach((reaction) => { reaction.getReactedByMe(); //Return true is logged-in user reacted on that message, otherwise false -}) +}) ``` - -```typescript + +```js let reactions = message.getReactions(); reactions.forEach((reaction) => { reaction.getReactedByMe(); //Return true is logged-in user reacted on that message, otherwise false -}) +}) ``` @@ -363,42 +363,42 @@ The `updateMessageWithReactionInfo()` method provides a seamless way to update t 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. - -```js + +```typescript // The message to which the reaction is related -let message = ...; +let message: CometChat.BaseMessage = ...; // The reaction event data received in real-time -let messageReaction = ...; +let messageReaction: CometChat.MessageReaction = ...; // The recieved reaction event real-time action type. Can be CometChatConstants.REACTION_ADDED or CometChatConstants.REACTION_REMOVED -let action = CometChat.REACTION_ACTION.REACTION_ADDED; +let action: CometChat.REACTION_ACTION = CometChat.REACTION_ACTION.REACTION_ADDED; let modifiedBaseMessage = CometChat.CometChatHelper.updateMessageWithReactionInfo( baseMessage, messageReaction, action -); +); ``` - -```typescript + +```js // The message to which the reaction is related -let message: CometChat.BaseMessage = ...; +let message = ...; // The reaction event data received in real-time -let messageReaction: CometChat.MessageReaction = ...; +let messageReaction = ...; // The recieved reaction event real-time action type. Can be CometChatConstants.REACTION_ADDED or CometChatConstants.REACTION_REMOVED -let action: CometChat.REACTION_ACTION = CometChat.REACTION_ACTION.REACTION_ADDED; +let action = CometChat.REACTION_ACTION.REACTION_ADDED; let modifiedBaseMessage = CometChat.CometChatHelper.updateMessageWithReactionInfo( baseMessage, messageReaction, action -); +); ``` diff --git a/sdk/javascript/receive-message.mdx b/sdk/javascript/receive-message.mdx index c4ac562d4..798325a4b 100644 --- a/sdk/javascript/receive-message.mdx +++ b/sdk/javascript/receive-message.mdx @@ -29,20 +29,20 @@ Always remove listeners when they're no longer needed (e.g., on component unmoun - -```javascript -let listenerID = "UNIQUE_LISTENER_ID"; + +```typescript +let listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onTextMessageReceived: (textMessage) => { + onTextMessageReceived: (textMessage: CometChat.TextMessage) => { console.log("Text message received successfully", textMessage); }, - onMediaMessageReceived: (mediaMessage) => { + onMediaMessageReceived: (mediaMessage: CometChat.MediaMessage) => { console.log("Media message received successfully", mediaMessage); }, - onCustomMessageReceived: (customMessage) => { + onCustomMessageReceived: (customMessage: CometChat.CustomMessage) => { console.log("Custom message received successfully", customMessage); }, }) @@ -51,20 +51,20 @@ CometChat.addMessageListener( - -```typescript -let listenerID: string = "UNIQUE_LISTENER_ID"; + +```javascript +let listenerID = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener( listenerID, new CometChat.MessageListener({ - onTextMessageReceived: (textMessage: CometChat.TextMessage) => { + onTextMessageReceived: (textMessage) => { console.log("Text message received successfully", textMessage); }, - onMediaMessageReceived: (mediaMessage: CometChat.MediaMessage) => { + onMediaMessageReceived: (mediaMessage) => { console.log("Media message received successfully", mediaMessage); }, - onCustomMessageReceived: (customMessage: CometChat.CustomMessage) => { + onCustomMessageReceived: (customMessage) => { console.log("Custom message received successfully", customMessage); }, }) @@ -82,18 +82,18 @@ CometChat.addMessageListener( Remove the listener when you no longer need to receive messages: - -```javascript -let listenerID = "UNIQUE_LISTENER_ID"; + +```typescript +let listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.removeMessageListener(listenerID); ``` - -```typescript -let listenerID: string = "UNIQUE_LISTENER_ID"; + +```javascript +let listenerID = "UNIQUE_LISTENER_ID"; CometChat.removeMessageListener(listenerID); ``` @@ -126,30 +126,6 @@ Use `getLastDeliveredMessageId()` to get the ID of the last delivered message, t ### Fetch Missed Messages of a particular one-on-one conversation - -```javascript -let UID = "UID"; -let limit = 30; -let latestId = await CometChat.getLastDeliveredMessageId(); - -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setMessageId(latestId) - .setLimit(limit) - .build(); - -messagesRequest.fetchNext().then( - (messages) => { - console.log("Message list fetched:", messages); - }, - (error) => { - console.log("Message fetching failed with error:", error); - } -); -``` - - - ```typescript let UID: string = "UID", @@ -174,19 +150,14 @@ messagesRequest.fetchNext().then( - - -### Fetch Missed Messages of a particular group conversation - - - + ```javascript -let GUID = "GUID"; +let UID = "UID"; let limit = 30; let latestId = await CometChat.getLastDeliveredMessageId(); let messagesRequest = new CometChat.MessagesRequestBuilder() - .setGUID(GUID) + .setUID(UID) .setMessageId(latestId) .setLimit(limit) .build(); @@ -203,6 +174,11 @@ messagesRequest.fetchNext().then( + + +### Fetch Missed Messages of a particular group conversation + + ```typescript let GUID: string = "GUID", @@ -227,6 +203,30 @@ messagesRequest.fetchNext().then( + +```javascript +let GUID = "GUID"; +let limit = 30; +let latestId = await CometChat.getLastDeliveredMessageId(); + +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setMessageId(latestId) + .setLimit(limit) + .build(); + +messagesRequest.fetchNext().then( + (messages) => { + console.log("Message list fetched:", messages); + }, + (error) => { + console.log("Message fetching failed with error:", error); + } +); +``` + + + 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: @@ -246,28 +246,6 @@ Fetch unread messages by setting `setUnread(true)` on the builder. ### Fetch Unread Messages of a particular one-on-one conversation - -```javascript -let UID = "UID"; -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setUnread(true) - .setLimit(limit) - .build(); - -messagesRequest.fetchPrevious().then( - (messages) => { - console.log("Message list fetched:", messages); - }, - (error) => { - console.log("Message fetching failed with error:", error); - } -); -``` - - - ```typescript let UID: string = "UID", @@ -291,17 +269,12 @@ messagesRequest.fetchPrevious().then( - - -### Fetch Unread Messages of a particular group conversation - - - + ```javascript -let GUID = "GUID"; +let UID = "UID"; let limit = 30; let messagesRequest = new CometChat.MessagesRequestBuilder() - .setGUID(GUID) + .setUID(UID) .setUnread(true) .setLimit(limit) .build(); @@ -318,6 +291,11 @@ messagesRequest.fetchPrevious().then( + + +### Fetch Unread Messages of a particular group conversation + + ```typescript let GUID: string = "GUID", @@ -341,27 +319,13 @@ messagesRequest.fetchPrevious().then( - - - -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 - -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 - -Set the UID using `setUID()` to fetch the conversation with a specific user. - - - + ```javascript -let UID = "UID"; +let GUID = "GUID"; let limit = 30; let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) + .setGUID(GUID) + .setUnread(true) .setLimit(limit) .build(); @@ -377,6 +341,21 @@ messagesRequest.fetchPrevious().then( + + + +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 + +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 + +Set the UID using `setUID()` to fetch the conversation with a specific user. + + ```typescript let UID: string = "UID", @@ -396,19 +375,12 @@ messagesRequest.fetchPrevious().then( - - -### Fetch Message History of a particular group conversation - -Set the GUID using `setGUID()` to fetch messages from a group you've joined. - - - + ```javascript -let GUID = "GUID"; +let UID = "UID"; let limit = 30; let messagesRequest = new CometChat.MessagesRequestBuilder() - .setGUID(GUID) + .setUID(UID) .setLimit(limit) .build(); @@ -424,6 +396,13 @@ messagesRequest.fetchPrevious().then( + + +### Fetch Message History of a particular group conversation + +Set the GUID using `setGUID()` to fetch messages from a group you've joined. + + ```typescript let GUID: string = "GUID", @@ -446,6 +425,27 @@ messagesRequest.fetchPrevious().then( + +```javascript +let GUID = "GUID"; +let limit = 30; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setLimit(limit) + .build(); + +messagesRequest.fetchPrevious().then( + (messages) => { + console.log("Message list fetched:", messages); + }, + (error) => { + console.log("Message fetching failed with error:", error); + } +); +``` + + + 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: @@ -478,29 +478,6 @@ The `Conversation & Advanced Search` is only available in `Advanced` & `Custom` ### Search Messages in a particular one-on-one conversation - -```javascript -let UID = "UID"; -let limit = 30; -let searchKeyword = "Hello"; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setLimit(limit) - .setSearchKeyword(searchKeyword) - .build(); - -messagesRequest.fetchPrevious().then( - (messages) => { - console.log("Message list fetched:", messages); - }, - (error) => { - console.log("Message fetching failed with error:", error); - } -); -``` - - - ```typescript let UID: string = "UID", @@ -525,18 +502,13 @@ messagesRequest.fetchPrevious().then( - - -### Search Messages in a particular group conversation - - - + ```javascript -let GUID = "GUID"; +let UID = "UID"; let limit = 30; let searchKeyword = "Hello"; let messagesRequest = new CometChat.MessagesRequestBuilder() - .setGUID(GUID) + .setUID(UID) .setLimit(limit) .setSearchKeyword(searchKeyword) .build(); @@ -553,6 +525,11 @@ messagesRequest.fetchPrevious().then( + + +### Search Messages in a particular group conversation + + ```typescript let GUID: string = "GUID", @@ -577,6 +554,29 @@ messagesRequest.fetchPrevious().then( + +```javascript +let GUID = "GUID"; +let limit = 30; +let searchKeyword = "Hello"; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setLimit(limit) + .setSearchKeyword(searchKeyword) + .build(); + +messagesRequest.fetchPrevious().then( + (messages) => { + console.log("Message list fetched:", messages); + }, + (error) => { + console.log("Message fetching failed with error:", error); + } +); +``` + + + ## Unread Message Count @@ -588,16 +588,16 @@ Get the number of unread messages for users, groups, or all conversations. Use `getUnreadMessageCountForUser()` to get the unread count for a specific user. - -```javascript + +```typescript +let UID: string = "UID"; CometChat.getUnreadMessageCountForUser(UID); ``` - -```typescript -let UID: string = "UID"; + +```javascript CometChat.getUnreadMessageCountForUser(UID); ``` @@ -608,17 +608,17 @@ CometChat.getUnreadMessageCountForUser(UID); To ignore messages from blocked users, set the boolean parameter to true: - -```javascript + +```typescript +let UID: string = "UID", + hideMessagesFromBlockedUsers: boolean = true; CometChat.getUnreadMessageCountForUser(UID, hideMessagesFromBlockedUsers); ``` - -```typescript -let UID: string = "UID", - hideMessagesFromBlockedUsers: boolean = true; + +```javascript CometChat.getUnreadMessageCountForUser(UID, hideMessagesFromBlockedUsers); ``` @@ -627,15 +627,15 @@ CometChat.getUnreadMessageCountForUser(UID, hideMessagesFromBlockedUsers); - -```javascript -let UID = "UID"; + +```typescript +let UID: string = "UID"; CometChat.getUnreadMessageCountForUser(UID).then( - (unreadMessageCountObject) => { - console.log("Unread message count fetched", unreadMessageCountObject); + (unreadMessageCount: Object) => { + console.log("Unread message count fetched", unreadMessageCount); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Error in getting unread message count", error); } ); @@ -643,15 +643,15 @@ CometChat.getUnreadMessageCountForUser(UID).then( - -```typescript -let UID: string = "UID"; + +```javascript +let UID = "UID"; CometChat.getUnreadMessageCountForUser(UID).then( - (unreadMessageCount: Object) => { - console.log("Unread message count fetched", unreadMessageCount); + (unreadMessageCountObject) => { + console.log("Unread message count fetched", unreadMessageCountObject); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Error in getting unread message count", error); } ); @@ -668,16 +668,16 @@ Returns an object with the UID as key and unread message count as value. Use `getUnreadMessageCountForGroup()` to get the unread count for a specific group. - -```javascript + +```typescript +let GUID: string = "GUID"; CometChat.getUnreadMessageCountForGroup(GUID); ``` - -```typescript -let GUID: string = "GUID"; + +```javascript CometChat.getUnreadMessageCountForGroup(GUID); ``` @@ -688,17 +688,17 @@ CometChat.getUnreadMessageCountForGroup(GUID); To ignore messages from blocked users, set the boolean parameter to true: - -```javascript + +```typescript +let GUID: string = "GUID", + hideMessagesFromBlockedUsers: boolean = true; CometChat.getUnreadMessageCountForGroup(GUID, hideMessagesFromBlockedUsers); ``` - -```typescript -let GUID: string = "GUID", - hideMessagesFromBlockedUsers: boolean = true; + +```javascript CometChat.getUnreadMessageCountForGroup(GUID, hideMessagesFromBlockedUsers); ``` @@ -707,15 +707,15 @@ CometChat.getUnreadMessageCountForGroup(GUID, hideMessagesFromBlockedUsers); - -```javascript -let GUID = "GUID"; + +```typescript +let GUID: string = "GUID"; CometChat.getUnreadMessageCountForGroup(GUID).then( - (unreadMessageCountObject) => { - console.log("Unread message count fetched", unreadMessageCountObject); + (unreadMessageCount: Object) => { + console.log("Unread message count fetched", unreadMessageCount); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Error in getting unread message count", error); } ); @@ -723,15 +723,15 @@ CometChat.getUnreadMessageCountForGroup(GUID).then( - -```typescript -let GUID: string = "GUID"; + +```javascript +let GUID = "GUID"; CometChat.getUnreadMessageCountForGroup(GUID).then( - (unreadMessageCount: Object) => { - console.log("Unread message count fetched", unreadMessageCount); + (unreadMessageCountObject) => { + console.log("Unread message count fetched", unreadMessageCountObject); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Error in getting unread message count", error); } ); @@ -748,15 +748,15 @@ Returns an object with the GUID as key and unread message count as value. Use `getUnreadMessageCount()` to get unread counts for all users and groups combined. - -```javascript + +```typescript CometChat.getUnreadMessageCount(); ``` - -```typescript + +```javascript CometChat.getUnreadMessageCount(); ``` @@ -767,16 +767,16 @@ CometChat.getUnreadMessageCount(); To ignore messages from blocked users, set the boolean parameter to true: - -```javascript + +```typescript +let hideMessagesFromBlockedUsers: boolean = true; CometChat.getUnreadMessageCount(hideMessagesFromBlockedUsers); ``` - -```typescript -let hideMessagesFromBlockedUsers: boolean = true; + +```javascript CometChat.getUnreadMessageCount(hideMessagesFromBlockedUsers); ``` @@ -785,13 +785,13 @@ CometChat.getUnreadMessageCount(hideMessagesFromBlockedUsers); - -```javascript + +```typescript CometChat.getUnreadMessageCount().then( - (unreadMessageCountObject) => { - console.log("Unread message count fetched", unreadMessageCountObject); + (unreadMessageCount: Object) => { + console.log("Unread message count fetched", unreadMessageCount); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Error in getting unread message count", error); } ); @@ -799,13 +799,13 @@ CometChat.getUnreadMessageCount().then( - -```typescript + +```javascript CometChat.getUnreadMessageCount().then( - (unreadMessageCount: Object) => { - console.log("Unread message count fetched", unreadMessageCount); + (unreadMessageCountObject) => { + console.log("Unread message count fetched", unreadMessageCountObject); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Error in getting unread message count", error); } ); @@ -824,15 +824,15 @@ Returns an object with two keys: Use `getUnreadMessageCountForAllUsers()` to get unread counts for all user conversations. - -```javascript + +```typescript CometChat.getUnreadMessageCountForAllUsers(); ``` - -```typescript + +```javascript CometChat.getUnreadMessageCountForAllUsers(); ``` @@ -843,16 +843,16 @@ CometChat.getUnreadMessageCountForAllUsers(); To ignore messages from blocked users, set the boolean parameter to true: - -```javascript + +```typescript +let hideMessagesFromBlockedUsers: boolean = true; CometChat.getUnreadMessageCountForAllUsers(hideMessagesFromBlockedUsers); ``` - -```typescript -let hideMessagesFromBlockedUsers: boolean = true; + +```javascript CometChat.getUnreadMessageCountForAllUsers(hideMessagesFromBlockedUsers); ``` @@ -861,13 +861,13 @@ CometChat.getUnreadMessageCountForAllUsers(hideMessagesFromBlockedUsers); - -```javascript + +```typescript CometChat.getUnreadMessageCountForAllUsers().then( - (unreadMessageCountObject) => { - console.log("Unread message count fetched", unreadMessageCountObject); + (unreadMessageCount: Object) => { + console.log("Unread message count fetched", unreadMessageCount); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Error in getting unread message count", error); } ); @@ -875,13 +875,13 @@ CometChat.getUnreadMessageCountForAllUsers().then( - -```typescript + +```javascript CometChat.getUnreadMessageCountForAllUsers().then( - (unreadMessageCount: Object) => { - console.log("Unread message count fetched", unreadMessageCount); + (unreadMessageCountObject) => { + console.log("Unread message count fetched", unreadMessageCountObject); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Error in getting unread message count", error); } ); @@ -898,15 +898,15 @@ Returns an object with UIDs as keys and unread counts as values. Use `getUnreadMessageCountForAllGroups()` to get unread counts for all group conversations. - -```javascript + +```typescript CometChat.getUnreadMessageCountForAllGroups(); ``` - -```typescript + +```javascript CometChat.getUnreadMessageCountForAllGroups(); ``` @@ -917,16 +917,16 @@ CometChat.getUnreadMessageCountForAllGroups(); To ignore messages from blocked users, set the boolean parameter to true: - -```javascript + +```typescript +let hideMessagesFromBlockedUsers: boolean = true; CometChat.getUnreadMessageCountForAllGroups(hideMessagesFromBlockedUsers); ``` - -```typescript -let hideMessagesFromBlockedUsers: boolean = true; + +```javascript CometChat.getUnreadMessageCountForAllGroups(hideMessagesFromBlockedUsers); ``` @@ -935,13 +935,13 @@ CometChat.getUnreadMessageCountForAllGroups(hideMessagesFromBlockedUsers); - -```javascript + +```typescript CometChat.getUnreadMessageCountForAllGroups().then( - (unreadMessageCountObject) => { - console.log("Unread message count fetched", unreadMessageCountObject); + (unreadMessageCount: Object) => { + console.log("Unread message count fetched", unreadMessageCount); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Error in getting unread message count", error); } ); @@ -949,13 +949,13 @@ CometChat.getUnreadMessageCountForAllGroups().then( - -```typescript + +```javascript CometChat.getUnreadMessageCountForAllGroups().then( - (unreadMessageCount: Object) => { - console.log("Unread message count fetched", unreadMessageCount); + (unreadMessageCountObject) => { + console.log("Unread message count fetched", unreadMessageCountObject); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Error in getting unread message count", error); } ); diff --git a/sdk/javascript/recording.mdx b/sdk/javascript/recording.mdx index 1f8b119be..1e36e23bb 100644 --- a/sdk/javascript/recording.mdx +++ b/sdk/javascript/recording.mdx @@ -37,8 +37,8 @@ Always remove listeners when they're no longer needed (e.g., on component unmoun - -```js + +```typescript // Add listeners onRecordingStarted and onRecordingStopped to the startCall method const defaultLayout = true; const audioOnly = false; @@ -62,8 +62,8 @@ CometChatCalls.startSession(callToken, callSettings, htmlElement); - -```typescript + +```js // Add listeners onRecordingStarted and onRecordingStopped to the startCall method const defaultLayout = true; const audioOnly = false; @@ -105,15 +105,15 @@ For custom UI without the default layout, use these methods to control recording You can use the startRecording() method to start call recording. - -```javascript + +```typescript CometChatCalls.startRecording(); ``` - -```typescript + +```javascript CometChatCalls.startRecording(); ``` @@ -126,15 +126,15 @@ CometChatCalls.startRecording(); You can use the stopRecording() method to stop call recording. - -```javascript + +```typescript CometChatCalls.stopRecording(); ``` - -```typescript + +```javascript CometChatCalls.stopRecording(); ``` diff --git a/sdk/javascript/retrieve-conversations.mdx b/sdk/javascript/retrieve-conversations.mdx index f8be2187d..ce474aeef 100644 --- a/sdk/javascript/retrieve-conversations.mdx +++ b/sdk/javascript/retrieve-conversations.mdx @@ -35,16 +35,6 @@ Use `ConversationsRequestBuilder` to fetch conversations with various filters. Set the number of conversations to fetch per request. - -```javascript -let limit = 30; -let conversationRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .build(); -``` - - - ```typescript let limit: number = 30, @@ -55,25 +45,23 @@ let limit: number = 30, - - -### Set Conversation Type - -Filter by conversation type: `user` for one-on-one or `group` for group conversations. If not set, both types are returned. - - - + ```javascript let limit = 30; -let conversationType = "group"; let conversationRequest = new CometChat.ConversationsRequestBuilder() .setLimit(limit) - .setConversationType(conversationType) .build(); ``` + + +### Set Conversation Type + +Filter by conversation type: `user` for one-on-one or `group` for group conversations. If not set, both types are returned. + + ```typescript let limit: number = 30, @@ -86,6 +74,18 @@ let limit: number = 30, + +```javascript +let limit = 30; +let conversationType = "group"; +let conversationRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setConversationType(conversationType) + .build(); +``` + + + @@ -99,17 +99,6 @@ When conversations are fetched successfully, the response includes an array of [ Use `withUserAndGroupTags(true)` to include user/group tags in the response. Default is `false`. - -```javascript -let limit = 30; -let conversationRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .withUserAndGroupTags(true) - .build(); -``` - - - ```typescript let limit: number = 30, @@ -121,6 +110,17 @@ let limit: number = 30, + +```javascript +let limit = 30; +let conversationRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .withUserAndGroupTags(true) + .build(); +``` + + + When conversations are fetched successfully, the response includes `tags` arrays on the `conversationWith` objects. @@ -130,18 +130,6 @@ When conversations are fetched successfully, the response includes `tags` arrays Fetch user conversations where the user has specific tags. - -```js -let limit = 30; -let userTags = ["tag1"]; -let conversationRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setUserTags(userTags) - .build(); -``` - - - ```typescript let limit: number = 30, @@ -154,27 +142,27 @@ let limit: number = 30, - - -When conversations are fetched successfully, the response includes only user conversations where the user has the specified tags. - -### Set Group Tags - -Fetch group conversations where the group has specific tags. - - ```js let limit = 30; -let groupTags = ["tag1"]; +let userTags = ["tag1"]; let conversationRequest = new CometChat.ConversationsRequestBuilder() .setLimit(limit) - .setGroupTags(groupTags) - .build(); + .setUserTags(userTags) + .build(); ``` + + +When conversations are fetched successfully, the response includes only user conversations where the user has the specified tags. + +### Set Group Tags + +Fetch group conversations where the group has specific tags. + + ```typescript let limit: number = 30, @@ -187,6 +175,18 @@ let limit: number = 30, + +```js +let limit = 30; +let groupTags = ["tag1"]; +let conversationRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setGroupTags(groupTags) + .build(); +``` + + + When conversations are fetched successfully, the response includes only group conversations where the group has the specified tags. @@ -196,17 +196,6 @@ When conversations are fetched successfully, the response includes only group co Use `withTags(true)` to include conversation tags in the response. Default is `false`. - -```javascript -let limit = 30; -let conversationRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .withTags(true) - .build(); -``` - - - ```typescript let limit: number = 30, @@ -218,24 +207,23 @@ conversationRequest: CometChat.ConversationsRequest = new CometChat.Conversation - -### Set Tags - -Fetch conversations that have specific tags. - - - + ```javascript let limit = 30; -let tags = ["archivedChat"]; let conversationRequest = new CometChat.ConversationsRequestBuilder() .setLimit(limit) - .setTags(tags) + .withTags(true) .build(); ``` + +### Set Tags + +Fetch conversations that have specific tags. + + ```typescript let limit: number = 30, @@ -248,23 +236,24 @@ let limit: number = 30, - -### Include Blocked Users - -Use `setIncludeBlockedUsers(true)` to include conversations with users you've blocked. - - -```js +```javascript let limit = 30; +let tags = ["archivedChat"]; let conversationRequest = new CometChat.ConversationsRequestBuilder() .setLimit(limit) - .setIncludeBlockedUsers(true) + .setTags(tags) .build(); ``` + +### Include Blocked Users + +Use `setIncludeBlockedUsers(true)` to include conversations with users you've blocked. + + ```typescript let limit: number = 30, @@ -276,26 +265,26 @@ let limit: number = 30, - - -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 - -Use `setWithBlockedInfo(true)` to include blocked user information in the response. - - ```js let limit = 30; let conversationRequest = new CometChat.ConversationsRequestBuilder() .setLimit(limit) - .setWithBlockedInfo(true) + .setIncludeBlockedUsers(true) .build(); ``` + + +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 + +Use `setWithBlockedInfo(true)` to include blocked user information in the response. + + ```typescript let limit: number = 30, @@ -307,6 +296,17 @@ let limit: number = 30, + +```js +let limit = 30; +let conversationRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setWithBlockedInfo(true) + .build(); +``` + + + ### Search Conversations @@ -319,17 +319,6 @@ This feature is only available with `Conversation & Advanced Search`. The `Conve - -```js -let limit = 30; -let conversationRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setSearchKeyword("Hiking") - .build(); -``` - - - ```typescript let limit: number = 30, @@ -341,6 +330,17 @@ let limit: number = 30, + +```js +let limit = 30; +let conversationRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setSearchKeyword("Hiking") + .build(); +``` + + + When conversations are fetched successfully, the response includes conversations where the user or group name matches the search keyword. @@ -356,17 +356,6 @@ This feature is only available with `Conversation & Advanced Search`. The `Conve - -```js -let limit = 30; -let conversationRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setUnread(true) - .build(); -``` - - - ```typescript let limit: number = 30, @@ -378,26 +367,26 @@ let limit: number = 30, - - -When conversations are fetched successfully, the response includes only conversations with unread messages (`unreadMessageCount` > 0). - -### Hide Agentic Conversations - -Use `setHideAgentic(true)` to exclude AI agent conversations from the list. - - ```js let limit = 30; let conversationRequest = new CometChat.ConversationsRequestBuilder() .setLimit(limit) - .setHideAgentic(true) + .setUnread(true) .build(); ``` + + +When conversations are fetched successfully, the response includes only conversations with unread messages (`unreadMessageCount` > 0). + +### Hide Agentic Conversations + +Use `setHideAgentic(true)` to exclude AI agent conversations from the list. + + ```typescript let limit: number = 30, @@ -409,23 +398,23 @@ let limit: number = 30, - -### Only Agentic Conversations - -Use `setOnlyAgentic(true)` to fetch only AI agent conversations. - - ```js let limit = 30; let conversationRequest = new CometChat.ConversationsRequestBuilder() .setLimit(limit) - .setOnlyAgentic(true) + .setHideAgentic(true) .build(); ``` + +### Only Agentic Conversations + +Use `setOnlyAgentic(true)` to fetch only AI agent conversations. + + ```typescript let limit: number = 30, @@ -437,6 +426,17 @@ let limit: number = 30, + +```js +let limit = 30; +let conversationRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setOnlyAgentic(true) + .build(); +``` + + + @@ -450,18 +450,18 @@ When conversations are fetched successfully, the response includes only AI agent Call `build()` to create the request, then `fetchNext()` to retrieve conversations. Maximum 50 per request. - -```javascript -let limit = 30; -let conversationsRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .build(); + +```typescript +let limit: number = 30, + conversationsRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .build(); conversationsRequest.fetchNext().then( - (conversationList) => { + (conversationList: CometChat.Conversation[]) => { console.log("Conversations list received:", conversationList); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Conversations list fetching failed with error:", error); } ); @@ -469,18 +469,18 @@ conversationsRequest.fetchNext().then( - -```typescript -let limit: number = 30, - conversationsRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .build(); + +```javascript +let limit = 30; +let conversationsRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .build(); conversationsRequest.fetchNext().then( - (conversationList: CometChat.Conversation[]) => { + (conversationList) => { console.log("Conversations list received:", conversationList); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Conversations list fetching failed with error:", error); } ); @@ -529,15 +529,17 @@ Use `tagConversation()` to add tags to a conversation. | `tags` | Array of tags to add | - -```javascript -let tags = ["archivedChat"]; + +```typescript +let conversationWith: string = "UID", + tags: Array = ["archivedChat"], + conversationType: string = "user"; -CometChat.tagConversation("conversationWith", "conversationType", tags).then( - (conversation) => { +CometChat.tagConversation(conversationWith, conversationType, tags).then( + (conversation: CometChat.Conversation) => { console.log("conversation", conversation); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("error while fetching a conversation", error); } ); @@ -545,17 +547,15 @@ CometChat.tagConversation("conversationWith", "conversationType", tags).then( - -```typescript -let conversationWith: string = "UID", - tags: Array = ["archivedChat"], - conversationType: string = "user"; + +```javascript +let tags = ["archivedChat"]; -CometChat.tagConversation(conversationWith, conversationType, tags).then( - (conversation: CometChat.Conversation) => { +CometChat.tagConversation("conversationWith", "conversationType", tags).then( + (conversation) => { console.log("conversation", conversation); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("error while fetching a conversation", error); } ); @@ -581,13 +581,16 @@ Use `getConversation()` to fetch a specific conversation. | `conversationType` | `user` or `group` | - -```javascript -CometChat.getConversation("conversationWith", "conversationType").then( - (conversation) => { + +```typescript +let conversationWith: string = "UID", + conversationType: string = "user"; + +CometChat.getConversation(conversationWith, conversationType).then( + (conversation: CometChat.Conversation) => { console.log("conversation", conversation); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("error while fetching a conversation", error); } ); @@ -595,16 +598,13 @@ CometChat.getConversation("conversationWith", "conversationType").then( - -```typescript -let conversationWith: string = "UID", - conversationType: string = "user"; - -CometChat.getConversation(conversationWith, conversationType).then( - (conversation: CometChat.Conversation) => { + +```javascript +CometChat.getConversation("conversationWith", "conversationType").then( + (conversation) => { console.log("conversation", conversation); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("error while fetching a conversation", error); } ); @@ -621,12 +621,14 @@ When the conversation is fetched successfully, the response returns a single [`C 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. - -```javascript + +```typescript +let message: CometChat.TextMessage | CometChat.MediaMessage | CometChat.CustomMessage; + CometChat.CometChatHelper.getConversationFromMessage(message).then( - (conversation) => { + (conversation: CometChat.Conversation) => { console.log("Conversation Object", conversation); - }, (error) => { + },(error: CometChat.CometChatException) => { console.log("Error while converting message object", error); } ); @@ -634,14 +636,12 @@ CometChat.CometChatHelper.getConversationFromMessage(message).then( - -```typescript -let message: CometChat.TextMessage | CometChat.MediaMessage | CometChat.CustomMessage; - + +```javascript CometChat.CometChatHelper.getConversationFromMessage(message).then( - (conversation: CometChat.Conversation) => { + (conversation) => { console.log("Conversation Object", conversation); - },(error: CometChat.CometChatException) => { + }, (error) => { console.log("Error while converting message object", error); } ); diff --git a/sdk/javascript/retrieve-group-members.mdx b/sdk/javascript/retrieve-group-members.mdx index cf916ddff..f895c8042 100644 --- a/sdk/javascript/retrieve-group-members.mdx +++ b/sdk/javascript/retrieve-group-members.mdx @@ -32,17 +32,6 @@ Use `GroupMembersRequestBuilder` to fetch members of a [Group](/sdk/reference/en Sets the number of members to fetch per request. - -```javascript -let GUID = "GUID"; -let limit = 30; -let groupMembersRequest = new CometChat.GroupMembersRequestBuilder(GUID) - .setLimit(limit) - .build(); -``` - - - ```typescript let GUID: string = "GUID"; @@ -54,26 +43,24 @@ let groupMembersRequest: CometChat.GroupMembersRequest = new CometChat.GroupMemb - - -### Set Search Keyword - -Filters members by a search string. - - - + ```javascript let GUID = "GUID"; let limit = 30; -let searchKeyword = "super"; let groupMembersRequest = new CometChat.GroupMembersRequestBuilder(GUID) .setLimit(limit) - .setSearchKeyword(searchKeyword) - .build(); + .build(); ``` + + +### Set Search Keyword + +Filters members by a search string. + + ```typescript let GUID: string = "GUID"; @@ -87,26 +74,26 @@ let groupMembersRequest: CometChat.GroupMembersRequest = new CometChat.GroupMemb - - -### Set Scopes - -Filters members by one or more scopes (`admin`, `moderator`, `participant`). - - - + ```javascript let GUID = "GUID"; let limit = 30; -let scopes = ["admin", "moderator"]; +let searchKeyword = "super"; let groupMembersRequest = new CometChat.GroupMembersRequestBuilder(GUID) .setLimit(limit) - .setScopes(scopes) + .setSearchKeyword(searchKeyword) .build(); ``` + + +### Set Scopes + +Filters members by one or more scopes (`admin`, `moderator`, `participant`). + + ```typescript let GUID: string = "GUID"; @@ -120,6 +107,19 @@ let groupMembersRequest: CometChat.GroupMembersRequest = new CometChat.GroupMemb + +```javascript +let GUID = "GUID"; +let limit = 30; +let scopes = ["admin", "moderator"]; +let groupMembersRequest = new CometChat.GroupMembersRequestBuilder(GUID) + .setLimit(limit) + .setScopes(scopes) + .build(); +``` + + + ### Set Status @@ -134,18 +134,6 @@ Filters members by online status: If not set, returns all members regardless of status. - -```javascript -let GUID = "GUID"; -let limit = 30; -let groupMembersRequest = new CometChat.GroupMembersRequestBuilder(GUID) - .setLimit(limit) - .setStatus(CometChat.USER_STATUS.ONLINE) - .build(); -``` - - - ```typescript let GUID: string = "GUID"; @@ -158,30 +146,23 @@ let groupMembersRequest: CometChat.GroupMembersRequest = new CometChat.GroupMemb - - -Once configured, call `build()` to create the request, then `fetchNext()` to retrieve members. - - - + ```javascript let GUID = "GUID"; let limit = 30; -let groupMemberRequest = new CometChat.GroupMembersRequestBuilder(GUID) +let groupMembersRequest = new CometChat.GroupMembersRequestBuilder(GUID) .setLimit(limit) + .setStatus(CometChat.USER_STATUS.ONLINE) .build(); - -groupMemberRequest.fetchNext().then( -groupMembers => { - console.log("Group Member list fetched successfully:", groupMembers); -}, error => { - console.log("Group Member list fetching failed with exception:", error); -} -); ``` + + +Once configured, call `build()` to create the request, then `fetchNext()` to retrieve members. + + ```typescript let GUID: string = "GUID"; @@ -201,6 +182,25 @@ groupMembersRequest.fetchNext().then( + +```javascript +let GUID = "GUID"; +let limit = 30; +let groupMemberRequest = new CometChat.GroupMembersRequestBuilder(GUID) + .setLimit(limit) + .build(); + +groupMemberRequest.fetchNext().then( +groupMembers => { + console.log("Group Member list fetched successfully:", groupMembers); +}, error => { + console.log("Group Member list fetching failed with exception:", error); +} +); +``` + + + 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: diff --git a/sdk/javascript/retrieve-groups.mdx b/sdk/javascript/retrieve-groups.mdx index d5bbce763..33343fdec 100644 --- a/sdk/javascript/retrieve-groups.mdx +++ b/sdk/javascript/retrieve-groups.mdx @@ -34,8 +34,8 @@ Use `GroupsRequestBuilder` to fetch groups with filtering, searching, and pagina Sets the number of groups to fetch per request. - -```javascript + +```typescript let limit = 30; let groupsRequest = new CometChat.GroupsRequestBuilder() .setLimit(limit) @@ -44,8 +44,8 @@ let groupsRequest = new CometChat.GroupsRequestBuilder() - -```typescript + +```javascript let limit = 30; let groupsRequest = new CometChat.GroupsRequestBuilder() .setLimit(limit) @@ -61,18 +61,6 @@ let groupsRequest = new CometChat.GroupsRequestBuilder() Filters groups by a search string. - -```javascript -let limit = 30; -let searchKeyword = "group"; -let groupsRequest = new CometChat.GroupsRequestBuilder() - .setLimit(limit) - .setSearchKeyword(searchKeyword) - .build(); -``` - - - ```typescript let limit: number = 30; @@ -85,24 +73,25 @@ let groupsRequest: CometChat.GroupsRequest = new CometChat.GroupsRequestBuilder( - - -### Joined Only - -When `true`, returns only groups the logged-in user has joined. - - - + ```javascript let limit = 30; +let searchKeyword = "group"; let groupsRequest = new CometChat.GroupsRequestBuilder() .setLimit(limit) - .joinedOnly(true) + .setSearchKeyword(searchKeyword) .build(); ``` + + +### Joined Only + +When `true`, returns only groups the logged-in user has joined. + + ```typescript let limit: number = 30; @@ -114,25 +103,24 @@ let groupsRequest: CometChat.GroupsRequest = new CometChat.GroupsRequestBuilder( - - -### Set Tags - -Filters groups by specified tags. - - - + ```javascript let limit = 30; -let tags = ["tag1", "tag2"]; let groupsRequest = new CometChat.GroupsRequestBuilder() .setLimit(limit) - .setTags(tags) + .joinedOnly(true) .build(); ``` + + +### Set Tags + +Filters groups by specified tags. + + ```typescript let limit: number = 30; @@ -145,24 +133,25 @@ let groupsRequest: CometChat.GroupsRequest = new CometChat.GroupsRequestBuilder( - - -### With Tags - -When `true`, includes tag data in the returned group objects. - - - + ```javascript let limit = 30; +let tags = ["tag1", "tag2"]; let groupsRequest = new CometChat.GroupsRequestBuilder() .setLimit(limit) - .withTags(true) - .build(); + .setTags(tags) + .build(); ``` + + +### With Tags + +When `true`, includes tag data in the returned group objects. + + ```typescript let limit: number = 30; @@ -174,6 +163,17 @@ let groupsRequest: CometChat.GroupsRequest = new CometChat.GroupsRequestBuilder( + +```javascript +let limit = 30; +let groupsRequest = new CometChat.GroupsRequestBuilder() + .setLimit(limit) + .withTags(true) + .build(); +``` + + + After configuring the builder, call `build()` to get the `GroupsRequest` object, then call `fetchNext()` to retrieve groups. @@ -183,24 +183,6 @@ The list only includes public and password-protected groups. Private groups appe - -```javascript -let limit = 30; -let groupsRequest = new CometChat.GroupsRequestBuilder() - .setLimit(limit) - .build(); - -groupsRequest.fetchNext().then( -groupList => { - console.log("Groups list fetched successfully", groupList); -}, error => { - console.log("Groups list fetching failed with error", error); -} -); -``` - - - ```typescript let limit: number = 30; @@ -219,6 +201,24 @@ groupsRequest.fetchNext().then( + +```javascript +let limit = 30; +let groupsRequest = new CometChat.GroupsRequestBuilder() + .setLimit(limit) + .build(); + +groupsRequest.fetchNext().then( +groupList => { + console.log("Groups list fetched successfully", groupList); +}, error => { + console.log("Groups list fetching failed with error", error); +} +); +``` + + + The `fetchNext()` method returns an array of [`Group`](/sdk/reference/entities#group) objects. Access the response data using getter methods: @@ -237,20 +237,6 @@ The `fetchNext()` method returns an array of [`Group`](/sdk/reference/entities#g Use `getGroup()` to fetch a specific group's details by GUID. - -```javascript -const GUID = "GUID"; -CometChat.getGroup(GUID).then( -group => { - console.log("Group details fetched successfully:", group); -}, error => { - console.log("Group details fetching failed with exception:", error); -} -); -``` - - - ```typescript const GUID: string = "GUID"; @@ -265,6 +251,20 @@ CometChat.getGroup(GUID).then( + +```javascript +const GUID = "GUID"; +CometChat.getGroup(GUID).then( +group => { + console.log("Group details fetched successfully:", group); +}, error => { + console.log("Group details fetching failed with exception:", error); +} +); +``` + + + | Parameter | Description | @@ -289,20 +289,6 @@ The method returns a [`Group`](/sdk/reference/entities#group) object. Access the Use `getOnlineGroupMemberCount()` to get the number of online members in specified groups. - -```javascript -let guids = ["cometchat-guid-1"]; -CometChat.getOnlineGroupMemberCount(guids).then( -groupMemberCount => { - console.log("Total online user for specified groups:", groupMemberCount); -}, error => { - console.log("Online group member count fetching failed with error:", error); -} -); -``` - - - ```typescript let guids: String[] = ["cometchat-guid-1"]; @@ -317,6 +303,20 @@ CometChat.getOnlineGroupMemberCount(guids).then( + +```javascript +let guids = ["cometchat-guid-1"]; +CometChat.getOnlineGroupMemberCount(guids).then( +groupMemberCount => { + console.log("Total online user for specified groups:", groupMemberCount); +}, error => { + console.log("Online group member count fetching failed with error:", error); +} +); +``` + + + Returns an object with GUIDs as keys and online member counts as values. diff --git a/sdk/javascript/retrieve-users.mdx b/sdk/javascript/retrieve-users.mdx index e7f27204a..91ecaf581 100644 --- a/sdk/javascript/retrieve-users.mdx +++ b/sdk/javascript/retrieve-users.mdx @@ -29,18 +29,6 @@ const count = await CometChat.getOnlineUserCount(); 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. - -```javascript -CometChat.getLoggedinUser().then( -user => { - console.log("user details:", { user }); -}, error => { - console.log("error getting details:", { error }); -} -); -``` - - ```typescript @@ -55,6 +43,19 @@ CometChat.getLoggedinUser().then( + +```javascript +CometChat.getLoggedinUser().then( +user => { + console.log("user details:", { user }); +}, error => { + console.log("error getting details:", { error }); +} +); +``` + + + This method returns a [`User`](/sdk/reference/entities#user) object with the logged-in user's information. @@ -79,15 +80,6 @@ Use `UsersRequestBuilder` to fetch users with filtering, searching, and paginati Sets the number of users to fetch per request. - -```javascript -let limit = 30; -let usersRequest = new CometChat.UsersRequestBuilder() - .setLimit(limit) - .build(); -``` - - ```typescript @@ -99,25 +91,24 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() - - -### Set Search Keyword - -Filters users by a search string. - - - + ```javascript let limit = 30; -let searchKeyword = "super"; let usersRequest = new CometChat.UsersRequestBuilder() .setLimit(limit) - .setSearchKeyword(searchKeyword) .build(); ``` + + +### Set Search Keyword + +Filters users by a search string. + + + ```typescript let limit: number = 30; @@ -130,27 +121,26 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() - - -### Search In - -Specifies which user properties to search. Works with `setSearchKeyword()`. By default, searches both UID and name. - - -```js +```javascript let limit = 30; let searchKeyword = "super"; -let searchIn = ["uid", "name"]; let usersRequest = new CometChat.UsersRequestBuilder() .setLimit(limit) .setSearchKeyword(searchKeyword) - .searchIn(searchIn) .build(); ``` + + +### Search In + +Specifies which user properties to search. Works with `setSearchKeyword()`. By default, searches both UID and name. + + + ```typescript let limit: number = 30; @@ -165,6 +155,20 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() + +```js +let limit = 30; +let searchKeyword = "super"; +let searchIn = ["uid", "name"]; +let usersRequest = new CometChat.UsersRequestBuilder() + .setLimit(limit) + .setSearchKeyword(searchKeyword) + .searchIn(searchIn) + .build(); +``` + + + ### Set Status @@ -177,16 +181,6 @@ Filters users by online status: If not set, returns all users. - -```javascript -let limit = 30; -let usersRequest = new CometChat.UsersRequestBuilder() - .setLimit(limit) - .setStatus(CometChat.USER_STATUS.ONLINE) - .build() -``` - - ```typescript @@ -199,24 +193,24 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() - - -### Hide Blocked Users - -When `true`, excludes users blocked by the logged-in user from the results. - - - + ```javascript let limit = 30; let usersRequest = new CometChat.UsersRequestBuilder() .setLimit(limit) - .hideBlockedUsers(true) - .build(); + .setStatus(CometChat.USER_STATUS.ONLINE) + .build() ``` + + +### Hide Blocked Users + +When `true`, excludes users blocked by the logged-in user from the results. + + ```typescript let limit: number = 30; @@ -228,25 +222,24 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() - - -### Set Roles - -Filters users by specified roles. - - - + ```javascript let limit = 30; -let roles = ["default", "dev"]; let usersRequest = new CometChat.UsersRequestBuilder() .setLimit(limit) - .setRoles(roles) + .hideBlockedUsers(true) .build(); ``` + + +### Set Roles + +Filters users by specified roles. + + ```typescript let limit: number = 30; @@ -259,24 +252,25 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() - - -### Friends Only - -When `true`, returns only friends of the logged-in user. - - - + ```javascript let limit = 30; +let roles = ["default", "dev"]; let usersRequest = new CometChat.UsersRequestBuilder() .setLimit(limit) - .friendsOnly(true) + .setRoles(roles) .build(); ``` + + +### Friends Only + +When `true`, returns only friends of the logged-in user. + + ```typescript let limit: number = 30; @@ -288,25 +282,24 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() - - -### Set Tags - -Filters users by specified tags. - - - + ```javascript let limit = 30; -let tags = ["tag1", "tag2"]; let usersRequest = new CometChat.UsersRequestBuilder() .setLimit(limit) - .setTags(tags) + .friendsOnly(true) .build(); ``` + + +### Set Tags + +Filters users by specified tags. + + ```typescript let limit: number = 30; @@ -319,24 +312,25 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() - - -### With Tags - -When `true`, includes tag data in the returned user objects. - - - + ```javascript let limit = 30; +let tags = ["tag1", "tag2"]; let usersRequest = new CometChat.UsersRequestBuilder() .setLimit(limit) - .withTags(true) + .setTags(tags) .build(); ``` + + +### With Tags + +When `true`, includes tag data in the returned user objects. + + ```typescript let limit: number = 30; @@ -348,25 +342,24 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() - - -### Set UIDs - -Fetches specific users by their UIDs. Maximum 25 users per request. - - - + ```javascript let limit = 30; -let UIDs = ["cometchat-uid-1", "cometchat-uid-2"]; let usersRequest = new CometChat.UsersRequestBuilder() .setLimit(limit) - .setUIDs(UIDs) + .withTags(true) .build(); ``` + + +### Set UIDs + +Fetches specific users by their UIDs. Maximum 25 users per request. + + ```typescript let limit: number = 30; @@ -379,26 +372,25 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() - - -### Sort By - -Sorts the user list by a specific property. Default sort order: `status → name → UID`. Pass `"name"` to sort by `name → UID`. - - -```js +```javascript let limit = 30; let UIDs = ["cometchat-uid-1", "cometchat-uid-2"]; -let sortBy = "name"; let usersRequest = new CometChat.UsersRequestBuilder() .setLimit(limit) - .sortBy(sortBy) + .setUIDs(UIDs) .build(); ``` + + +### Sort By + +Sorts the user list by a specific property. Default sort order: `status → name → UID`. Pass `"name"` to sort by `name → UID`. + + ```typescript let limit: number = 30; @@ -411,6 +403,19 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() + +```js +let limit = 30; +let UIDs = ["cometchat-uid-1", "cometchat-uid-2"]; +let sortBy = "name"; +let usersRequest = new CometChat.UsersRequestBuilder() + .setLimit(limit) + .sortBy(sortBy) + .build(); +``` + + + ### Sort By Order @@ -418,6 +423,18 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() Sets the sort order. Default is ascending (`"asc"`). Use `"desc"` for descending. + +```typescript +let limit: number = 30; +let sortOrder: string = "desc"; +let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() + .setLimit(limit) + .sortOrder(sortOrder) + .build(); +``` + + + ```js let limit = 30; @@ -430,23 +447,29 @@ let usersReques = new CometChat.UsersRequestBuilder() + + +After configuring the builder, call `build()` to get the `UsersRequest` object, then call `fetchNext()` to retrieve users. + + ```typescript let limit: number = 30; -let sortOrder: string = "desc"; let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() - .setLimit(limit) - .sortOrder(sortOrder) - .build(); +.setLimit(limit) +.build(); + +usersRequest.fetchNext().then( + (userList: CometChat.User[]) => { + console.log("User list received:", userList); + }, (error: CometChat.CometChatException) => { + console.log("User list fetching failed with error:", error); + } +); ``` - - -After configuring the builder, call `build()` to get the `UsersRequest` object, then call `fetchNext()` to retrieve users. - - ```javascript const limit = 30; @@ -465,24 +488,6 @@ userList => { - -```typescript -let limit: number = 30; -let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() -.setLimit(limit) -.build(); - -usersRequest.fetchNext().then( - (userList: CometChat.User[]) => { - console.log("User list received:", userList); - }, (error: CometChat.CometChatException) => { - console.log("User list fetching failed with error:", error); - } -); -``` - - - The `fetchNext()` method returns an array of [`User`](/sdk/reference/entities#user) objects. Access the response data using getter methods: @@ -501,20 +506,6 @@ The `fetchNext()` method returns an array of [`User`](/sdk/reference/entities#us Use `getUser()` to fetch a specific user's details by UID. - -```javascript -let UID = "UID"; -CometChat.getUser(UID).then( -user => { - console.log("User details fetched for user:", user); -}, error => { - console.log("User details fetching failed with error:", error); -} -); -``` - - - ```typescript let UID: string = "UID"; @@ -529,6 +520,20 @@ CometChat.getUser(UID).then( + +```javascript +let UID = "UID"; +CometChat.getUser(UID).then( +user => { + console.log("User details fetched for user:", user); +}, error => { + console.log("User details fetching failed with error:", error); +} +); +``` + + + | Parameter | Description | @@ -553,19 +558,6 @@ The method returns a [`User`](/sdk/reference/entities#user) object. Access the r Use `getOnlineUserCount()` to get the total number of online users in your app. - -```javascript -CometChat.getOnlineUserCount().then( -userCount => { - console.log("Total online user count:", userCount); -}, error => { - console.log("Online user count fetching failed with error:", error); -} -); -``` - - - ```typescript CometChat.getOnlineUserCount().then( @@ -579,6 +571,19 @@ CometChat.getOnlineUserCount().then( + +```javascript +CometChat.getOnlineUserCount().then( +userCount => { + console.log("Total online user count:", userCount); +}, error => { + console.log("Online user count fetching failed with error:", error); +} +); +``` + + + Returns the total online user count as a number. diff --git a/sdk/javascript/send-message.mdx b/sdk/javascript/send-message.mdx index 0d8458111..034d6030b 100644 --- a/sdk/javascript/send-message.mdx +++ b/sdk/javascript/send-message.mdx @@ -151,9 +151,9 @@ On success, `sendMessage()` returns a [TextMessage](/sdk/reference/messages#text Attach custom JSON data to the message: - -```javascript -let metadata = { + +```typescript +let metadata: Object = { latitude: "50.6192171633316", longitude: "-72.68182268750002", }; @@ -161,9 +161,9 @@ let metadata = { textMessage.setMetadata(metadata); ``` - -```typescript -let metadata: Object = { + +```javascript +let metadata = { latitude: "50.6192171633316", longitude: "-72.68182268750002", }; @@ -178,16 +178,16 @@ textMessage.setMetadata(metadata); Tag messages for easy filtering later: - -```javascript -let tags = ["starredMessage"]; + +```typescript +let tags: Array = ["starredMessage"]; textMessage.setTags(tags); ``` - -```typescript -let tags: Array = ["starredMessage"]; + +```javascript +let tags = ["starredMessage"]; textMessage.setTags(tags); ``` @@ -199,13 +199,13 @@ textMessage.setTags(tags); Reply to a specific message by setting its ID: - -```javascript + +```typescript textMessage.setQuotedMessageId(10); ``` - -```typescript + +```javascript textMessage.setQuotedMessageId(10); ``` @@ -477,13 +477,13 @@ On success, `sendMediaMessage()` returns a [MediaMessage](/sdk/reference/message Add text along with the media: - -```javascript + +```typescript mediaMessage.setCaption("Check out this photo!"); ``` - -```typescript + +```javascript mediaMessage.setCaption("Check out this photo!"); ``` diff --git a/sdk/javascript/standalone-calling.mdx b/sdk/javascript/standalone-calling.mdx index 54db56dca..a9bbb772a 100644 --- a/sdk/javascript/standalone-calling.mdx +++ b/sdk/javascript/standalone-calling.mdx @@ -59,33 +59,33 @@ You can generate the token just before starting the call, or generate and store Use the `generateToken()` method to create a call token: - -```javascript -const sessionId = "UNIQUE_SESSION_ID"; // Generate a unique session ID -const userAuthToken = "USER_AUTH_TOKEN"; // Obtained from REST API + +```typescript +const sessionId: string = "UNIQUE_SESSION_ID"; // Generate a unique session ID +const userAuthToken: string = "USER_AUTH_TOKEN"; // Obtained from REST API CometChatCalls.generateToken(sessionId, userAuthToken).then( - (callToken) => { + (callToken: any) => { console.log("Call token generated:", callToken.token); // Use callToken to start the session }, - (error) => { + (error: any) => { console.log("Token generation failed:", error); } ); ``` - -```typescript -const sessionId: string = "UNIQUE_SESSION_ID"; // Generate a unique session ID -const userAuthToken: string = "USER_AUTH_TOKEN"; // Obtained from REST API + +```javascript +const sessionId = "UNIQUE_SESSION_ID"; // Generate a unique session ID +const userAuthToken = "USER_AUTH_TOKEN"; // Obtained from REST API CometChatCalls.generateToken(sessionId, userAuthToken).then( - (callToken: any) => { + (callToken) => { console.log("Call token generated:", callToken.token); // Use callToken to start the session }, - (error: any) => { + (error) => { console.log("Token generation failed:", error); } ); @@ -106,16 +106,16 @@ Use the `startSession()` method to join a call session. This method requires: 3. An HTML element where the call UI will be rendered - -```javascript + +```typescript const callListener = new CometChatCalls.OngoingCallListener({ - onUserJoined: (user) => { + onUserJoined: (user: any) => { console.log("User joined:", user); }, - onUserLeft: (user) => { + onUserLeft: (user: any) => { console.log("User left:", user); }, - onUserListUpdated: (userList) => { + onUserListUpdated: (userList: any[]) => { console.log("User list updated:", userList); }, onCallEnded: () => { @@ -128,13 +128,13 @@ const callListener = new CometChatCalls.OngoingCallListener({ CometChatCalls.endSession(); // Close calling screen }, - onError: (error) => { + onError: (error: any) => { console.log("Call error:", error); }, - onMediaDeviceListUpdated: (deviceList) => { + onMediaDeviceListUpdated: (deviceList: any[]) => { console.log("Device list updated:", deviceList); }, - onUserMuted: (event) => { + onUserMuted: (event: any) => { console.log("User muted:", event); }, onScreenShareStarted: () => { @@ -143,7 +143,7 @@ const callListener = new CometChatCalls.OngoingCallListener({ onScreenShareStopped: () => { console.log("Screen sharing stopped"); }, - onCallSwitchedToVideo: (event) => { + onCallSwitchedToVideo: (event: any) => { console.log("Call switched to video:", event); }, onSessionTimeout: () => { @@ -157,20 +157,20 @@ const callSettings = new CometChatCalls.CallSettingsBuilder() .setCallListener(callListener) .build(); -const htmlElement = document.getElementById("call-container"); +const htmlElement = document.getElementById("call-container") as HTMLElement; CometChatCalls.startSession(callToken, callSettings, htmlElement); ``` - -```typescript + +```javascript const callListener = new CometChatCalls.OngoingCallListener({ - onUserJoined: (user: any) => { + onUserJoined: (user) => { console.log("User joined:", user); }, - onUserLeft: (user: any) => { + onUserLeft: (user) => { console.log("User left:", user); }, - onUserListUpdated: (userList: any[]) => { + onUserListUpdated: (userList) => { console.log("User list updated:", userList); }, onCallEnded: () => { @@ -183,13 +183,13 @@ const callListener = new CometChatCalls.OngoingCallListener({ CometChatCalls.endSession(); // Close calling screen }, - onError: (error: any) => { + onError: (error) => { console.log("Call error:", error); }, - onMediaDeviceListUpdated: (deviceList: any[]) => { + onMediaDeviceListUpdated: (deviceList) => { console.log("Device list updated:", deviceList); }, - onUserMuted: (event: any) => { + onUserMuted: (event) => { console.log("User muted:", event); }, onScreenShareStarted: () => { @@ -198,7 +198,7 @@ const callListener = new CometChatCalls.OngoingCallListener({ onScreenShareStopped: () => { console.log("Screen sharing stopped"); }, - onCallSwitchedToVideo: (event: any) => { + onCallSwitchedToVideo: (event) => { console.log("Call switched to video:", event); }, onSessionTimeout: () => { @@ -212,7 +212,7 @@ const callSettings = new CometChatCalls.CallSettingsBuilder() .setCallListener(callListener) .build(); -const htmlElement = document.getElementById("call-container") as HTMLElement; +const htmlElement = document.getElementById("call-container"); CometChatCalls.startSession(callToken, callSettings, htmlElement); ``` @@ -263,18 +263,18 @@ Each listener requires a unique `listenerId` string. This ID is used to: - **Enable targeted removal** — Remove specific listeners without affecting others - -```javascript -const listenerId = "UNIQUE_LISTENER_ID"; + +```typescript +const listenerId: string = "UNIQUE_LISTENER_ID"; CometChatCalls.addCallEventListener(listenerId, { - onUserJoined: (user) => { + onUserJoined: (user: any) => { console.log("User joined:", user); }, - onUserLeft: (user) => { + onUserLeft: (user: any) => { console.log("User left:", user); }, - onUserListUpdated: (userList) => { + onUserListUpdated: (userList: any[]) => { console.log("User list updated:", userList); }, onCallEnded: () => { @@ -287,13 +287,13 @@ CometChatCalls.addCallEventListener(listenerId, { CometChatCalls.endSession(); // Close calling screen }, - onError: (error) => { + onError: (error: any) => { console.log("Call error:", error); }, - onMediaDeviceListUpdated: (deviceList) => { + onMediaDeviceListUpdated: (deviceList: any[]) => { console.log("Device list updated:", deviceList); }, - onUserMuted: (event) => { + onUserMuted: (event: any) => { console.log("User muted:", event); }, onScreenShareStarted: () => { @@ -302,7 +302,7 @@ CometChatCalls.addCallEventListener(listenerId, { onScreenShareStopped: () => { console.log("Screen sharing stopped"); }, - onCallSwitchedToVideo: (event) => { + onCallSwitchedToVideo: (event: any) => { console.log("Call switched to video:", event); }, onSessionTimeout: () => { @@ -314,18 +314,18 @@ CometChatCalls.addCallEventListener(listenerId, { CometChatCalls.removeCallEventListener(listenerId); ``` - -```typescript -const listenerId: string = "UNIQUE_LISTENER_ID"; + +```javascript +const listenerId = "UNIQUE_LISTENER_ID"; CometChatCalls.addCallEventListener(listenerId, { - onUserJoined: (user: any) => { + onUserJoined: (user) => { console.log("User joined:", user); }, - onUserLeft: (user: any) => { + onUserLeft: (user) => { console.log("User left:", user); }, - onUserListUpdated: (userList: any[]) => { + onUserListUpdated: (userList) => { console.log("User list updated:", userList); }, onCallEnded: () => { @@ -338,13 +338,13 @@ CometChatCalls.addCallEventListener(listenerId, { CometChatCalls.endSession(); // Close calling screen }, - onError: (error: any) => { + onError: (error) => { console.log("Call error:", error); }, - onMediaDeviceListUpdated: (deviceList: any[]) => { + onMediaDeviceListUpdated: (deviceList) => { console.log("Device list updated:", deviceList); }, - onUserMuted: (event: any) => { + onUserMuted: (event) => { console.log("User muted:", event); }, onScreenShareStarted: () => { @@ -353,7 +353,7 @@ CometChatCalls.addCallEventListener(listenerId, { onScreenShareStopped: () => { console.log("Screen sharing stopped"); }, - onCallSwitchedToVideo: (event: any) => { + onCallSwitchedToVideo: (event) => { console.log("Call switched to video:", event); }, onSessionTimeout: () => { @@ -389,16 +389,16 @@ CometChatCalls.removeCallEventListener(listenerId); To end the call session and release all media resources (camera, microphone, network connections), call `CometChatCalls.endSession()` in the `onCallEndButtonPressed()` callback. - -```javascript + +```typescript onCallEndButtonPressed: () => { CometChatCalls.endSession(); // Close the calling screen } ``` - -```typescript + +```javascript onCallEndButtonPressed: () => { CometChatCalls.endSession(); // Close the calling screen @@ -420,13 +420,13 @@ These methods can only be called when a call session is active. Toggles between the front and rear camera during a video call. Only supported on mobile browsers. - -```javascript + +```typescript CometChatCalls.switchCamera(); ``` - -```typescript + +```javascript CometChatCalls.switchCamera(); ``` @@ -444,13 +444,13 @@ Controls the local audio stream transmission. When muted, other participants can - `false` — Unmutes the microphone, resumes audio transmission - -```javascript + +```typescript CometChatCalls.muteAudio(true); ``` - -```typescript + +```javascript CometChatCalls.muteAudio(true); ``` @@ -464,13 +464,13 @@ Controls the local video stream transmission. When paused, other participants se - `false` — Resumes the camera, continues video transmission - -```javascript + +```typescript CometChatCalls.pauseVideo(true); ``` - -```typescript + +```javascript CometChatCalls.pauseVideo(true); ``` @@ -481,13 +481,13 @@ CometChatCalls.pauseVideo(true); Starts sharing your screen or a specific application window with other participants. - -```javascript + +```typescript CometChatCalls.startScreenShare(); ``` - -```typescript + +```javascript CometChatCalls.startScreenShare(); ``` @@ -498,13 +498,13 @@ CometChatCalls.startScreenShare(); Stops the current screen sharing session. - -```javascript + +```typescript CometChatCalls.stopScreenShare(); ``` - -```typescript + +```javascript CometChatCalls.stopScreenShare(); ``` @@ -519,13 +519,13 @@ Changes the call UI layout mode dynamically during the call. - `CometChat.CALL_MODE.SPOTLIGHT` — Focus on the active speaker - -```javascript + +```typescript CometChatCalls.setMode(CometChat.CALL_MODE.SPOTLIGHT); ``` - -```typescript + +```javascript CometChatCalls.setMode(CometChat.CALL_MODE.SPOTLIGHT); ``` @@ -536,14 +536,14 @@ CometChatCalls.setMode(CometChat.CALL_MODE.SPOTLIGHT); Returns a list of available audio input devices (microphones). - -```javascript + +```typescript const audioInputDevices = CometChatCalls.getAudioInputDevices(); console.log("Available microphones:", audioInputDevices); ``` - -```typescript + +```javascript const audioInputDevices = CometChatCalls.getAudioInputDevices(); console.log("Available microphones:", audioInputDevices); ``` @@ -555,14 +555,14 @@ console.log("Available microphones:", audioInputDevices); Returns a list of available audio output devices (speakers/headphones). - -```javascript + +```typescript const audioOutputDevices = CometChatCalls.getAudioOutputDevices(); console.log("Available speakers:", audioOutputDevices); ``` - -```typescript + +```javascript const audioOutputDevices = CometChatCalls.getAudioOutputDevices(); console.log("Available speakers:", audioOutputDevices); ``` @@ -574,14 +574,14 @@ console.log("Available speakers:", audioOutputDevices); Returns a list of available video input devices (cameras). - -```javascript + +```typescript const videoInputDevices = CometChatCalls.getVideoInputDevices(); console.log("Available cameras:", videoInputDevices); ``` - -```typescript + +```javascript const videoInputDevices = CometChatCalls.getVideoInputDevices(); console.log("Available cameras:", videoInputDevices); ``` @@ -593,13 +593,13 @@ console.log("Available cameras:", videoInputDevices); Sets the active audio input device (microphone) by device ID. - -```javascript + +```typescript CometChatCalls.setAudioInputDevice(deviceId); ``` - -```typescript + +```javascript CometChatCalls.setAudioInputDevice(deviceId); ``` @@ -610,13 +610,13 @@ CometChatCalls.setAudioInputDevice(deviceId); Sets the active audio output device (speaker/headphones) by device ID. - -```javascript + +```typescript CometChatCalls.setAudioOutputDevice(deviceId); ``` - -```typescript + +```javascript CometChatCalls.setAudioOutputDevice(deviceId); ``` @@ -627,13 +627,13 @@ CometChatCalls.setAudioOutputDevice(deviceId); Sets the active video input device (camera) by device ID. - -```javascript + +```typescript CometChatCalls.setVideoInputDevice(deviceId); ``` - -```typescript + +```javascript CometChatCalls.setVideoInputDevice(deviceId); ``` @@ -644,13 +644,13 @@ CometChatCalls.setVideoInputDevice(deviceId); Upgrades an ongoing audio call to a video call. This enables the camera and starts transmitting video to other participants. The remote participant receives the `onCallSwitchedToVideo()` callback. - -```javascript + +```typescript CometChatCalls.switchToVideoCall(); ``` - -```typescript + +```javascript CometChatCalls.switchToVideoCall(); ``` @@ -661,13 +661,13 @@ 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 + +```typescript CometChatCalls.endSession(); ``` - -```typescript + +```javascript CometChatCalls.endSession(); ``` diff --git a/sdk/javascript/threaded-messages.mdx b/sdk/javascript/threaded-messages.mdx index e3d2bcf27..842bd8997 100644 --- a/sdk/javascript/threaded-messages.mdx +++ b/sdk/javascript/threaded-messages.mdx @@ -31,22 +31,6 @@ Threaded messages (or threads) are messages started from a particular parent mes 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. - -```javascript -let textMessage = new CometChat.TextMessage(UID, "Hello", CometChat.RECEIVER_TYPE.USER); -textMessage.setParentMessageId(100); - -CometChat.sendMessage(textMessage).then( - message => { - console.log('Message sent successfully', message); - }, err => { - console.log('err', err); - } -) -``` - - - ```typescript let receiverId = "UID", @@ -67,6 +51,22 @@ CometChat.sendMessage(textMessage).then( + +```javascript +let textMessage = new CometChat.TextMessage(UID, "Hello", CometChat.RECEIVER_TYPE.USER); +textMessage.setParentMessageId(100); + +CometChat.sendMessage(textMessage).then( + message => { + console.log('Message sent successfully', message); + }, err => { + console.log('err', err); + } +) +``` + + + The above snippet sends "Hello" in the thread with `parentMessageId` 100. Media and Custom messages can also be sent in threads using `setParentMessageId()`. @@ -76,35 +76,6 @@ The above snippet sends "Hello" in the thread with `parentMessageId` 100. Media Use `MessageListener` to receive real-time thread messages. Check if the received message belongs to the active thread using `getParentMessageId()`. - -```javascript -const listenerID = "UNIQUE_LISTENER_ID"; -const activeThreadId = 100; - -CometChat.addMessageListener( -listenerID, -new CometChat.MessageListener({ - onTextMessageReceived: textMessage => { - if(textMessage.getParentMessageId() == activeThreadId) { - console.log("Text message received for active thread.", textMessage); - } - }, - onMediaMessageReceived: mediaMessage => { - if(mediaMessage.getParentMessageId() == activeThreadId) { - console.log("Media message received for active thread.", mediaMessage); - } - }, - onCustomMessageReceived: customMessage => { - if(customMessage.getParentMessageId() == activeThreadId) { - console.log("Custom message received for active thread.", customMessage); - } - } -}) -); -``` - - - ```typescript const listenerID: string = "UNIQUE_LISTENER_ID"; @@ -134,6 +105,35 @@ CometChat.addMessageListener( + +```javascript +const listenerID = "UNIQUE_LISTENER_ID"; +const activeThreadId = 100; + +CometChat.addMessageListener( +listenerID, +new CometChat.MessageListener({ + onTextMessageReceived: textMessage => { + if(textMessage.getParentMessageId() == activeThreadId) { + console.log("Text message received for active thread.", textMessage); + } + }, + onMediaMessageReceived: mediaMessage => { + if(mediaMessage.getParentMessageId() == activeThreadId) { + console.log("Media message received for active thread.", mediaMessage); + } + }, + onCustomMessageReceived: customMessage => { + if(customMessage.getParentMessageId() == activeThreadId) { + console.log("Custom message received for active thread.", customMessage); + } + } +}) +); +``` + + + ### Fetch all the messages for any particular thread. @@ -141,26 +141,6 @@ CometChat.addMessageListener( Use `MessagesRequestBuilder` with `setParentMessageId()` to fetch messages belonging to a specific thread. Call `fetchPrevious()` to get messages (max 100 per request). - -```javascript -let limit = 30; -let parentMessageId = 1; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setLimit(limit) - .setParentMessageId(parentMessageId) - .build(); - -messagesRequest.fetchPrevious().then( - messages => { - console.log("Messages for thread fetched successfully", messages); - }, error => { - console.log("Message fetching failed with error:", error); - } -); -``` - - - ```typescript let limit: number = 30, @@ -181,6 +161,26 @@ messagesRequest.fetchPrevious().then( + +```javascript +let limit = 30; +let parentMessageId = 1; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setLimit(limit) + .setParentMessageId(parentMessageId) + .build(); + +messagesRequest.fetchPrevious().then( + messages => { + console.log("Messages for thread fetched successfully", messages); + }, error => { + console.log("Message fetching failed with error:", error); + } +); +``` + + + The `fetchPrevious()` method returns an array of [`BaseMessage`](/sdk/reference/messages#basemessage) objects representing thread replies. Access the data using getter methods: diff --git a/sdk/javascript/transfer-group-ownership.mdx b/sdk/javascript/transfer-group-ownership.mdx index 1fa9199cb..bb50b7896 100644 --- a/sdk/javascript/transfer-group-ownership.mdx +++ b/sdk/javascript/transfer-group-ownership.mdx @@ -20,32 +20,32 @@ Only the owner of a [Group](/sdk/reference/entities#group) can transfer ownershi Use `transferGroupOwnership()` to transfer ownership to another member. - -```javascript -let GUID = "GUID"; -let UID = "UID"; + +```typescript +let GUID: string = "GUID"; +let UID: string = "UID"; CometChat.transferGroupOwnership(GUID, UID).then( - () => { + (ownershipTransferred: string) => { console.log("Successfully transferred ownership of the group."); }, error => { console.log("Could not transfer ownership of the group: ", error); } -) +); ``` - -```typescript -let GUID: string = "GUID"; -let UID: string = "UID"; + +```javascript +let GUID = "GUID"; +let UID = "UID"; CometChat.transferGroupOwnership(GUID, UID).then( - (ownershipTransferred: string) => { + () => { console.log("Successfully transferred ownership of the group."); }, error => { console.log("Could not transfer ownership of the group: ", error); } -); +) ``` diff --git a/sdk/javascript/transient-messages.mdx b/sdk/javascript/transient-messages.mdx index f80d95bbe..adb347406 100644 --- a/sdk/javascript/transient-messages.mdx +++ b/sdk/javascript/transient-messages.mdx @@ -85,22 +85,6 @@ Always remove listeners when they're no longer needed (e.g., on component unmoun You will receive the transient message in the `onTransientMessageReceived()` method of the registered `MessageListener` class. - -```javascript -let listenerId = "UNIQUE_LITENER_ID"; - -CometChat.addMessageListener( -listenerId, -new CometChat.MessageListener({ - onTransientMessageReceived: transientMessage => { - console.log('transient message received', transientMessage); - }, -}) -); -``` - - - ```typescript let listenerId: string = "UNIQUE_LITENER_ID"; @@ -117,6 +101,22 @@ CometChat.addMessageListener( + +```javascript +let listenerId = "UNIQUE_LITENER_ID"; + +CometChat.addMessageListener( +listenerId, +new CometChat.MessageListener({ + onTransientMessageReceived: transientMessage => { + console.log('transient message received', transientMessage); + }, +}) +); +``` + + + The [`TransientMessage`](/sdk/reference/auxiliary#transientmessage) class consists of the below parameters: diff --git a/sdk/javascript/typing-indicators.mdx b/sdk/javascript/typing-indicators.mdx index 1fb3a0cb4..bdf1cb205 100644 --- a/sdk/javascript/typing-indicators.mdx +++ b/sdk/javascript/typing-indicators.mdx @@ -136,25 +136,6 @@ Use `setMetadata()` on `TypingIndicator` to pass additional custom data. Retriev Use `onTypingStarted` and `onTypingEnded` in `MessageListener` to receive typing events. - -```javascript -let listenerId = "UNIQUE_LITENER_ID"; - -CometChat.addMessageListener( -listenerId, -new CometChat.MessageListener({ - onTypingStarted: typingIndicator => { - console.log("Typing started :", typingIndicator); - }, - onTypingEnded: typingIndicator => { - console.log("Typing ended :", typingIndicator); - } -}) -); -``` - - - ```typescript let listenerId: string = "UNIQUE_LITENER_ID"; @@ -174,6 +155,25 @@ CometChat.addMessageListener( + +```javascript +let listenerId = "UNIQUE_LITENER_ID"; + +CometChat.addMessageListener( +listenerId, +new CometChat.MessageListener({ + onTypingStarted: typingIndicator => { + console.log("Typing started :", typingIndicator); + }, + onTypingEnded: typingIndicator => { + console.log("Typing ended :", typingIndicator); + } +}) +); +``` + + + The [`TypingIndicator`](/sdk/reference/auxiliary#typingindicator) object contains: diff --git a/sdk/javascript/update-group.mdx b/sdk/javascript/update-group.mdx index 16124425c..e8320af40 100644 --- a/sdk/javascript/update-group.mdx +++ b/sdk/javascript/update-group.mdx @@ -19,24 +19,6 @@ const updated = await CometChat.updateGroup(group); Use `updateGroup()` to modify group details. Pass a `Group` object with the updated values. - -```javascript -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 => { - console.log("Groups details updated successfully:", group); -}, error => { - console.log("Group details update failed with exception:", error); -} -); -``` - - - ```typescript const GUID: string = "GUID"; @@ -56,6 +38,24 @@ CometChat.updateGroup(group).then( + +```javascript +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 => { + console.log("Groups details updated successfully:", group); +}, error => { + console.log("Group details update failed with exception:", error); +} +); +``` + + + | Parameter | Description | diff --git a/sdk/javascript/user-management.mdx b/sdk/javascript/user-management.mdx index a5625c047..5d87d92f1 100644 --- a/sdk/javascript/user-management.mdx +++ b/sdk/javascript/user-management.mdx @@ -40,42 +40,42 @@ User creation should ideally happen on your backend via the [REST API](https://a For client-side creation (development only), use `createUser()`: - -```javascript -let authKey = "AUTH_KEY"; -let uid = "user1"; -let name = "Kevin"; + +```typescript +let authKey: string = "AUTH_KEY"; +let uid: string = "user1"; +let name: string = "Kevin"; -let user = new CometChat.User(uid); +let user: CometChat.User = new CometChat.User(uid); user.setName(name); CometChat.createUser(user, authKey).then( - user => { + (user: CometChat.User) => { console.log("user created", user); - }, error => { + }, (error: CometChat.CometChatException) => { console.log("error", error); } -) +); ``` - -```typescript -let authKey: string = "AUTH_KEY"; -let uid: string = "user1"; -let name: string = "Kevin"; + +```javascript +let authKey = "AUTH_KEY"; +let uid = "user1"; +let name = "Kevin"; -let user: CometChat.User = new CometChat.User(uid); +let user = new CometChat.User(uid); user.setName(name); CometChat.createUser(user, authKey).then( - (user: CometChat.User) => { + user => { console.log("user created", user); - }, (error: CometChat.CometChatException) => { + }, error => { console.log("error", error); } -); +) ``` @@ -103,39 +103,39 @@ Like creation, user updates should ideally happen on your backend via the [REST For client-side updates (development only), use `updateUser()`: - -```javascript -let authKey = "AUTH_KEY"; -let uid = "user1"; -let name = "Kevin Fernandez"; + +```typescript +let authKey: string = "AUTH_KEY"; +let uid: string = "user1"; +let name: string = "Kevin Fernandez"; -let user = new CometChat.User(uid); +let user: CometChat.User = new CometChat.User(uid); user.setName(name); CometChat.updateUser(user, authKey).then( - user => { + (user: CometChat.User) => { console.log("user updated", user); - }, error => { + }, (error: CometChat.CometChatException) => { console.log("error", error); } ) ``` - -```typescript -let authKey: string = "AUTH_KEY"; -let uid: string = "user1"; -let name: string = "Kevin Fernandez"; + +```javascript +let authKey = "AUTH_KEY"; +let uid = "user1"; +let name = "Kevin Fernandez"; -let user: CometChat.User = new CometChat.User(uid); +let user = new CometChat.User(uid); user.setName(name); CometChat.updateUser(user, authKey).then( - (user: CometChat.User) => { + user => { console.log("user updated", user); - }, (error: CometChat.CometChatException) => { + }, error => { console.log("error", error); } ) @@ -160,40 +160,40 @@ The method returns a [`User`](/sdk/reference/entities#user) object. Access the r Use `updateCurrentUserDetails()` to update the current user without an Auth Key. Note: You cannot update the user's role with this method. - -```javascript -let uid = "user1"; -let name = "Kevin Fernandez"; + +```typescript +let uid: string = "user1"; +let name: string = "Kevin Fernandez"; -let user = new CometChat.User(uid); +let user: CometChat.User = new CometChat.User(uid); user.setName(name); CometChat.updateCurrentUserDetails(user).then( - user => { + (user: CometChat.User) => { console.log("user updated", user); - }, error => { + }, (error: CometChat.CometChatException) => { console.log("error", error); } -) +); ``` - -```typescript -let uid: string = "user1"; -let name: string = "Kevin Fernandez"; + +```javascript +let uid = "user1"; +let name = "Kevin Fernandez"; -let user: CometChat.User = new CometChat.User(uid); +let user = new CometChat.User(uid); user.setName(name); CometChat.updateCurrentUserDetails(user).then( - (user: CometChat.User) => { + user => { console.log("user updated", user); - }, (error: CometChat.CometChatException) => { + }, error => { console.log("error", error); } -); +) ``` diff --git a/sdk/javascript/user-presence.mdx b/sdk/javascript/user-presence.mdx index 0b62bf35c..f85b09166 100644 --- a/sdk/javascript/user-presence.mdx +++ b/sdk/javascript/user-presence.mdx @@ -45,34 +45,34 @@ You must configure presence subscription in `AppSettings` during `CometChat.init Register a `UserListener` to receive presence events: - -```javascript -let listenerID = "UNIQUE_LISTENER_ID"; + +```typescript +let listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addUserListener( listenerID, new CometChat.UserListener({ - onUserOnline: onlineUser => { + onUserOnline: (onlineUser: CometChat.User) => { console.log("On User Online:", { onlineUser }); }, - onUserOffline: offlineUser => { + onUserOffline: (offlineUser: CometChat.User) => { console.log("On User Offline:", { offlineUser }); } }) ); ``` - -```typescript -let listenerID: string = "UNIQUE_LISTENER_ID"; + +```javascript +let listenerID = "UNIQUE_LISTENER_ID"; CometChat.addUserListener( listenerID, new CometChat.UserListener({ - onUserOnline: (onlineUser: CometChat.User) => { + onUserOnline: onlineUser => { console.log("On User Online:", { onlineUser }); }, - onUserOffline: (offlineUser: CometChat.User) => { + onUserOffline: offlineUser => { console.log("On User Offline:", { offlineUser }); } }) @@ -99,18 +99,18 @@ The listener callbacks provide a [`User`](/sdk/reference/entities#user) object w Remove the listener when no longer needed: - -```javascript -let listenerID = "UNIQUE_LISTENER_ID"; -CometChat.removeUserListener(listenerID); -``` - ```typescript let listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.removeUserListener(listenerID); ``` + +```javascript +let listenerID = "UNIQUE_LISTENER_ID"; +CometChat.removeUserListener(listenerID); +``` + diff --git a/sdk/javascript/video-view-customisation.mdx b/sdk/javascript/video-view-customisation.mdx index 84e242291..c02eccfc2 100644 --- a/sdk/javascript/video-view-customisation.mdx +++ b/sdk/javascript/video-view-customisation.mdx @@ -33,9 +33,9 @@ The `MainVideoContainerSetting` class customizes the main video view. Pass a `Ma Example: - -```javascript -let videoSettings = new CometChat.MainVideoContainerSetting(); + +```typescript +let videoSettings: CometChat.MainVideoContainerSetting = new CometChat.MainVideoContainerSetting(); videoSettings.setMainVideoAspectRatio(CometChat.CallSettings.ASPECT_RATIO_CONTAIN); videoSettings.setFullScreenButtonParams(CometChat.CallSettings.POSITION_BOTTOM_RIGHT, true); @@ -43,9 +43,9 @@ videoSettings.setNameLabelParams(CometChat.CallSettings.POSITION_BOTTOM_LEFT, tr videoSettings.setNetworkLabelParams(CometChat.CallSettings.POSITION_BOTTOM_RIGHT, true); ``` - -```typescript -let videoSettings: CometChat.MainVideoContainerSetting = new CometChat.MainVideoContainerSetting(); + +```javascript +let videoSettings = new CometChat.MainVideoContainerSetting(); videoSettings.setMainVideoAspectRatio(CometChat.CallSettings.ASPECT_RATIO_CONTAIN); videoSettings.setFullScreenButtonParams(CometChat.CallSettings.POSITION_BOTTOM_RIGHT, true); diff --git a/sdk/javascript/virtual-background.mdx b/sdk/javascript/virtual-background.mdx index f3f7a2a74..86bbc1e07 100644 --- a/sdk/javascript/virtual-background.mdx +++ b/sdk/javascript/virtual-background.mdx @@ -35,18 +35,18 @@ For custom UI without the default layout, use these methods to control virtual b You can use the `openVirtualBackground()` method to open the virtual background settings pop-up. - -```javascript -let callController = CometChat.CallController.getInstance(); -callController.openVirtualBackground(); -``` - ```typescript let callController: CometChat.CallController = CometChat.CallController.getInstance(); callController.openVirtualBackground(); ``` + +```javascript +let callController = CometChat.CallController.getInstance(); +callController.openVirtualBackground(); +``` + ### Set Background Blur @@ -54,13 +54,6 @@ callController.openVirtualBackground(); You can use the `setBackgroundBlur()` method to apply background blur on the video stream. This method accepts a number which decides the level of blur to be applied. - -```javascript -let callController = CometChat.CallController.getInstance(); -let blurLevel = 1; -callController.setBackgroundBlur(blurLevel); -``` - ```typescript let callController: CometChat.CallController = CometChat.CallController.getInstance(); @@ -68,6 +61,13 @@ let blurLevel: number = 1; callController.setBackgroundBlur(blurLevel); ``` + +```javascript +let callController = CometChat.CallController.getInstance(); +let blurLevel = 1; +callController.setBackgroundBlur(blurLevel); +``` + ### Set Background Image @@ -75,13 +75,6 @@ callController.setBackgroundBlur(blurLevel); You can use the `setBackgroundImage()`method to set the background image. This method takes either a URL or file Object & sets that image as the background. - -```javascript -let callController = CometChat.CallController.getInstance(); -let imageURL = "URL_OF_BACKGROUND_IMAGE"; -callController.setBackgroundImage(imageURL); -``` - ```typescript let callController: CometChat.CallController = CometChat.CallController.getInstance(); @@ -89,6 +82,13 @@ let imageURL: string = "URL_OF_BACKGROUND_IMAGE"; callController.setBackgroundImage(imageURL); ``` + +```javascript +let callController = CometChat.CallController.getInstance(); +let imageURL = "URL_OF_BACKGROUND_IMAGE"; +callController.setBackgroundImage(imageURL); +``` + ## Virtual Background Settings From 789a54b919683e7d76a73cb05628a75d5a86c5c4 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 25 Mar 2026 16:01:38 +0530 Subject: [PATCH 051/139] Update retrieve-users.mdx --- sdk/javascript/retrieve-users.mdx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/sdk/javascript/retrieve-users.mdx b/sdk/javascript/retrieve-users.mdx index 91ecaf581..745f2c697 100644 --- a/sdk/javascript/retrieve-users.mdx +++ b/sdk/javascript/retrieve-users.mdx @@ -429,7 +429,7 @@ let limit: number = 30; let sortOrder: string = "desc"; let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() .setLimit(limit) - .sortOrder(sortOrder) + .sortByOrder(sortOrder) .build(); ``` @@ -438,8 +438,8 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() ```js let limit = 30; -let sortByOrder = "desc"; -let usersReques = new CometChat.UsersRequestBuilder() +let sortOrder = "desc"; +let usersRequest = new CometChat.UsersRequestBuilder() .setLimit(limit) .sortByOrder(sortOrder) .build(); From fef346bab64eee27df59c1523197b7c4e0b6de5b Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 25 Mar 2026 16:21:59 +0530 Subject: [PATCH 052/139] updates navigation --- docs.json | 175 ++++++---- sdk/javascript/advanced-overview.mdx | 2 +- sdk/javascript/ai-agents.mdx | 9 +- sdk/javascript/authentication-overview.mdx | 101 +++++- sdk/javascript/best-practices.mdx | 2 +- sdk/javascript/connection-status.mdx | 2 +- sdk/javascript/key-concepts.mdx | 4 +- ...aging-web-sockets-connections-manually.mdx | 2 +- ...ge-filtering.mdx => message-filtering.mdx} | 4 +- .../message-structure-and-hierarchy.mdx | 2 +- sdk/javascript/setup-sdk.mdx | 312 +++++++++++++++--- sdk/javascript/troubleshooting.mdx | 2 +- 12 files changed, 476 insertions(+), 141 deletions(-) rename sdk/javascript/{additional-message-filtering.mdx => message-filtering.mdx} (99%) diff --git a/docs.json b/docs.json index 0edf9dff2..619485fc4 100644 --- a/docs.json +++ b/docs.json @@ -37,7 +37,9 @@ { "group": "Docs MCP", "hidden": true, - "pages": ["mcp-server"] + "pages": [ + "mcp-server" + ] } ] }, @@ -89,7 +91,9 @@ { "dropdown": "Kubernetes", "icon": "/images/icons/kubernetes.svg", - "pages": ["on-premise-deployment/kubernetes/overview"] + "pages": [ + "on-premise-deployment/kubernetes/overview" + ] } ] } @@ -100,7 +104,9 @@ "tabs": [ { "tab": "Chat & Calling", - "pages": ["chat-call"] + "pages": [ + "chat-call" + ] }, { "tab": "Platform", @@ -207,17 +213,21 @@ "pages": [ "fundamentals/webhooks-overview", "fundamentals/webhooks-management", - "fundamentals/webhooks-events", + "fundamentals/webhooks-events", "fundamentals/webhooks-legacy" ] }, { "group": "User-Roles", - "pages": ["fundamentals/user-roles-and-permissions"] + "pages": [ + "fundamentals/user-roles-and-permissions" + ] }, { "group": "Guides", - "pages": ["fundamentals/user-auth"] + "pages": [ + "fundamentals/user-auth" + ] } ] }, @@ -230,11 +240,11 @@ "pages": [ "/widget/html/overview", "/widget/html/integration", - "/widget/html/advanced", + "/widget/html/advanced", { "group": " ", "pages": [ - "/widget/html/legacy" + "/widget/html/legacy" ] } ] @@ -272,7 +282,10 @@ { "dropdown": "Wix", "icon": "/images/icons/wix.svg", - "pages": ["/widget/wix/overview", "/widget/wix/integration"] + "pages": [ + "/widget/wix/overview", + "/widget/wix/integration" + ] }, { "dropdown": "Webflow", @@ -978,9 +991,9 @@ { "group": "Migration Guide", "pages": [ - "ui-kit/react-native/upgrading-from-v4" + "ui-kit/react-native/upgrading-from-v4" ] - }, + }, "ui-kit/react-native/troubleshooting", "ui-kit/react-native/link/sample", "ui-kit/react-native/link/changelog" @@ -1266,7 +1279,10 @@ }, { "group": "Reference", - "pages": ["ui-kit/ios/methods", "ui-kit/ios/events"] + "pages": [ + "ui-kit/ios/methods", + "ui-kit/ios/events" + ] }, { "group": "Advanced", @@ -1853,7 +1869,9 @@ "pages": [ { "group": "Overview", - "pages": ["ui-kit/flutter/overview"] + "pages": [ + "ui-kit/flutter/overview" + ] }, { "group": "Getting Started", @@ -2517,38 +2535,15 @@ { "group": " ", "pages": [ - { - "group": "Overview", - "pages": [ - "sdk/javascript/overview", - "sdk/javascript/key-concepts", - "sdk/javascript/message-structure-and-hierarchy", - "sdk/javascript/rate-limits" - ] - }, - { - "group": "Setup", - "pages": [ - "sdk/javascript/setup-sdk", - "sdk/javascript/installation", - "sdk/javascript/initialization", - "sdk/javascript/ssr-compatibility" - ] - }, - { - "group": "Authentication", - "pages": [ - "sdk/javascript/authentication-overview", - "sdk/javascript/login-listener" - ] - }, + "sdk/javascript/overview", + "sdk/javascript/setup-sdk", + "sdk/javascript/authentication-overview", { "group": "Messaging", "pages": [ - "sdk/javascript/messaging-overview", "sdk/javascript/send-message", "sdk/javascript/receive-message", - "sdk/javascript/additional-message-filtering", + "sdk/javascript/message-filtering", "sdk/javascript/retrieve-conversations", "sdk/javascript/threaded-messages", "sdk/javascript/edit-message", @@ -2591,7 +2586,9 @@ }, { "group": "User Presence", - "pages": ["sdk/javascript/user-presence"] + "pages": [ + "sdk/javascript/user-presence" + ] }, { "group": "Groups", @@ -2612,19 +2609,13 @@ }, "sdk/javascript/ai-moderation", "sdk/javascript/ai-agents", - "sdk/javascript/ai-integration-quick-reference", { "group": "Resources", "pages": [ - "sdk/javascript/resources-overview", "sdk/javascript/all-real-time-listeners", - "sdk/javascript/upgrading-from-v3" - ] - }, - { - "group": "Advanced", - "pages": [ - "sdk/javascript/advanced-overview", + "sdk/javascript/key-concepts", + "sdk/javascript/message-structure-and-hierarchy", + "sdk/javascript/rate-limits", "sdk/javascript/connection-status", "sdk/javascript/managing-web-sockets-connections-manually" ] @@ -2645,13 +2636,13 @@ "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", "sdk/javascript/webhooks-overview", + "sdk/javascript/upgrading-from-v3", "sdk/javascript/changelog" ] } @@ -4728,7 +4719,9 @@ }, { "group": "Users", - "pages": ["rest-api/data-import-apis/users/import-users"] + "pages": [ + "rest-api/data-import-apis/users/import-users" + ] }, { "group": "Groups", @@ -5248,7 +5241,9 @@ "tabs": [ { "tab": "AI Agents", - "pages": ["ai-agents"] + "pages": [ + "ai-agents" + ] }, { "tab": "Agent Builder", @@ -5311,11 +5306,15 @@ "/ai-agents/crew-ai-tools", { "group": "Guides", - "pages": ["/ai-agents/crew-ai-knowledge-agent"] + "pages": [ + "/ai-agents/crew-ai-knowledge-agent" + ] }, { "group": "Tutorials", - "pages": ["/ai-agents/crew-ai-product-hunt-agent"] + "pages": [ + "/ai-agents/crew-ai-product-hunt-agent" + ] } ] }, @@ -5328,11 +5327,15 @@ "/ai-agents/agno-tools", { "group": "Guides", - "pages": ["/ai-agents/agno-knowledge-agent"] + "pages": [ + "/ai-agents/agno-knowledge-agent" + ] }, { "group": "Tutorials", - "pages": ["/ai-agents/agno-product-hunt-agent"] + "pages": [ + "/ai-agents/agno-product-hunt-agent" + ] } ] }, @@ -5345,11 +5348,15 @@ "/ai-agents/vercel-tools", { "group": "Guides", - "pages": ["/ai-agents/vercel-knowledge-agent"] + "pages": [ + "/ai-agents/vercel-knowledge-agent" + ] }, { "group": "Tutorials", - "pages": ["/ai-agents/vercel-product-hunt-agent"] + "pages": [ + "/ai-agents/vercel-product-hunt-agent" + ] } ] }, @@ -5360,11 +5367,15 @@ "/ai-agents/langgraph", { "group": "Guides", - "pages": ["/ai-agents/langgraph-knowledge-agent"] + "pages": [ + "/ai-agents/langgraph-knowledge-agent" + ] }, { "group": "Tutorials", - "pages": ["/ai-agents/langgraph-product-hunt-agent"] + "pages": [ + "/ai-agents/langgraph-product-hunt-agent" + ] } ] }, @@ -5377,11 +5388,15 @@ "/ai-agents/ag2-tools", { "group": "Guides", - "pages": ["/ai-agents/ag2-knowledge-agent"] + "pages": [ + "/ai-agents/ag2-knowledge-agent" + ] }, { "group": "Tutorials", - "pages": ["/ai-agents/ag2-product-hunt-agent"] + "pages": [ + "/ai-agents/ag2-product-hunt-agent" + ] } ] }, @@ -5394,7 +5409,9 @@ "/ai-agents/ag-ui-tools", { "group": "Guides", - "pages": ["/ai-agents/cometchat-ag-ui-byoa"] + "pages": [ + "/ai-agents/cometchat-ag-ui-byoa" + ] }, { "group": "Implementation", @@ -5410,12 +5427,16 @@ { "tab": "Widget Builder", "tab-id": "ai-agent-chat-builder", - "pages": ["/ai-agents/chat-widget"] + "pages": [ + "/ai-agents/chat-widget" + ] }, { "tab": "Custom Bots", "hidden": true, - "pages": ["/ai-chatbots/custom-bots"] + "pages": [ + "/ai-chatbots/custom-bots" + ] }, { "tab": "AI Bots (Legacy)", @@ -5472,7 +5493,9 @@ "tabs": [ { "tab": "Notifications", - "pages": ["notifications"] + "pages": [ + "notifications" + ] }, { "tab": "Push", @@ -5504,7 +5527,9 @@ }, { "group": " ", - "pages": ["notifications/push-notifications-extension-legacy"] + "pages": [ + "notifications/push-notifications-extension-legacy" + ] } ] }, @@ -5518,7 +5543,9 @@ "notifications/email-custom-providers", { "group": " ", - "pages": ["notifications/email-notifications-extension-legacy"] + "pages": [ + "notifications/email-notifications-extension-legacy" + ] } ] }, @@ -5532,7 +5559,9 @@ "notifications/sms-custom-providers", { "group": " ", - "pages": ["notifications/sms-notifications-extension-legacy"] + "pages": [ + "notifications/sms-notifications-extension-legacy" + ] } ] } @@ -5543,7 +5572,9 @@ "tabs": [ { "tab": "Insights", - "pages": ["insights"] + "pages": [ + "insights" + ] } ] } @@ -6284,7 +6315,7 @@ }, { "source": "/notifications/react-native-push-notifications", - "destination": "/notifications/react-native-push-notifications-android" + "destination": "/notifications/react-native-push-notifications-android" }, { "source": "/sdk/ionic/overview", diff --git a/sdk/javascript/advanced-overview.mdx b/sdk/javascript/advanced-overview.mdx index 964125fac..d38b93f35 100644 --- a/sdk/javascript/advanced-overview.mdx +++ b/sdk/javascript/advanced-overview.mdx @@ -38,7 +38,7 @@ This section helps you to know about the Connection Listeners. Manually manage WebSocket connections - + Listen for login and logout events diff --git a/sdk/javascript/ai-agents.mdx b/sdk/javascript/ai-agents.mdx index 80e5da475..6da69da5b 100644 --- a/sdk/javascript/ai-agents.mdx +++ b/sdk/javascript/ai-agents.mdx @@ -1,12 +1,18 @@ --- 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." +description: "Integrate AI Agents, AI Moderation, and AI User Copilot into your app using the CometChat JavaScript SDK." --- {/* TL;DR for Agents and Quick Reference */} +| Feature | Description | +| --- | --- | +| [AI Agents](#agent-run-lifecycle-and-message-flow) | Intelligent automated conversations with real-time streaming | +| [AI Moderation](/sdk/javascript/ai-moderation) | Automatic content moderation with `PENDING` → `APPROVED` / `DISAPPROVED` flow | +| [AI User Copilot](/fundamentals/ai-user-copilot/overview) | Smart Replies, Conversation Starter, Conversation Summary (Dashboard-enabled) | + ```javascript // Listen for real-time AI Agent events (streaming) CometChat.addAIAssistantListener("LISTENER_ID", { @@ -25,6 +31,7 @@ CometChat.removeAIAssistantListener("LISTENER_ID"); CometChat.removeMessageListener("LISTENER_ID"); ``` +**Prerequisites:** `CometChat.init()` + `CometChat.login()` completed, AI features enabled in [Dashboard](https://app.cometchat.com) **Event flow:** Run Start → Tool Call(s) → Text Message Stream → Run Finished diff --git a/sdk/javascript/authentication-overview.mdx b/sdk/javascript/authentication-overview.mdx index 9b6a07ebb..8f57169e0 100644 --- a/sdk/javascript/authentication-overview.mdx +++ b/sdk/javascript/authentication-overview.mdx @@ -289,19 +289,110 @@ try { --- +## Login Listener + +The CometChat SDK provides real-time updates for `login` and `logout` events via the `LoginListener` class. + +| Delegate Method | Description | +| --- | --- | +| `loginSuccess(event)` | User logged in successfully. Provides the `User` object. | +| `loginFailure(event)` | Login failed. Provides a `CometChatException`. | +| `logoutSuccess()` | User logged out successfully. | +| `logoutFailure(event)` | Logout failed. Provides a `CometChatException`. | + +### Add Login Listener + + + +```typescript +const listenerID: string = "UNIQUE_LISTENER_ID"; +CometChat.addLoginListener( + listenerID, + new CometChat.LoginListener({ + loginSuccess: (user: CometChat.User) => { + console.log("LoginListener :: loginSuccess", user); + }, + loginFailure: (error: CometChat.CometChatException) => { + console.log("LoginListener :: loginFailure", error); + }, + logoutSuccess: () => { + console.log("LoginListener :: logoutSuccess"); + }, + logoutFailure: (error: CometChat.CometChatException) => { + console.log("LoginListener :: logoutFailure", error); + } + }) +); +``` + + + + +```js +let listenerID = "UNIQUE_LISTENER_ID"; +CometChat.addLoginListener( + listenerID, + new CometChat.LoginListener({ + loginSuccess: (e) => { + console.log("LoginListener :: loginSuccess", e); + }, + loginFailure: (e) => { + console.log("LoginListener :: loginFailure", e); + }, + logoutSuccess: () => { + console.log("LoginListener :: logoutSuccess"); + }, + logoutFailure: (e) => { + console.log("LoginListener :: logoutFailure", e); + } + }) +); +``` + + + + + +### Remove Login Listener + + + +```typescript +const listenerID: string = "UNIQUE_LISTENER_ID"; +CometChat.removeLoginListener(listenerID); +``` + + + + +```js +const listenerID = "UNIQUE_LISTENER_ID"; +CometChat.removeLoginListener(listenerID); +``` + + + + + + +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 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 + + Monitor the SDK connection state in real time + + + Complete reference for all SDK event listeners diff --git a/sdk/javascript/best-practices.mdx b/sdk/javascript/best-practices.mdx index 64cdc95a9..fbaebfcea 100644 --- a/sdk/javascript/best-practices.mdx +++ b/sdk/javascript/best-practices.mdx @@ -14,7 +14,7 @@ Follow these best practices to build reliable, performant, and secure applicatio | 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. | +| Handle token expiry | Implement a mechanism to detect login failures due to expired tokens. Use the [Login Listener](/sdk/javascript/authentication-overview#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 diff --git a/sdk/javascript/connection-status.mdx b/sdk/javascript/connection-status.mdx index ea2b16327..8080128f4 100644 --- a/sdk/javascript/connection-status.mdx +++ b/sdk/javascript/connection-status.mdx @@ -134,7 +134,7 @@ Always remove connection listeners when they're no longer needed (e.g., on compo Manually manage WebSocket connections - + Listen for login and logout events diff --git a/sdk/javascript/key-concepts.mdx b/sdk/javascript/key-concepts.mdx index 138c523c9..9a26ab643 100644 --- a/sdk/javascript/key-concepts.mdx +++ b/sdk/javascript/key-concepts.mdx @@ -125,8 +125,8 @@ For more details, see the [Message Structure and Hierarchy](/sdk/javascript/mess | 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) | +| Tags | String labels for categorizing users, groups, conversations, or messages | [Message Filtering](/sdk/javascript/message-filtering) | +| RequestBuilder | Builder pattern class for constructing filtered/paginated queries | [Message Filtering](/sdk/javascript/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) | diff --git a/sdk/javascript/managing-web-sockets-connections-manually.mdx b/sdk/javascript/managing-web-sockets-connections-manually.mdx index 27215fbf6..76b996f5e 100644 --- a/sdk/javascript/managing-web-sockets-connections-manually.mdx +++ b/sdk/javascript/managing-web-sockets-connections-manually.mdx @@ -123,7 +123,7 @@ CometChat.disconnect(); Monitor the SDK connection state in real time - + Listen for login and logout events diff --git a/sdk/javascript/additional-message-filtering.mdx b/sdk/javascript/message-filtering.mdx similarity index 99% rename from sdk/javascript/additional-message-filtering.mdx rename to sdk/javascript/message-filtering.mdx index 8145670dd..681b9ec98 100644 --- a/sdk/javascript/additional-message-filtering.mdx +++ b/sdk/javascript/message-filtering.mdx @@ -1,6 +1,6 @@ --- -title: "Additional Message Filtering" -sidebarTitle: "Additional Filtering" +title: "Message Filtering" +sidebarTitle: "Message Filtering" description: "Advanced filtering options for fetching messages using MessagesRequestBuilder in the CometChat JavaScript SDK." --- diff --git a/sdk/javascript/message-structure-and-hierarchy.mdx b/sdk/javascript/message-structure-and-hierarchy.mdx index 17b27315b..5046d4cbf 100644 --- a/sdk/javascript/message-structure-and-hierarchy.mdx +++ b/sdk/javascript/message-structure-and-hierarchy.mdx @@ -181,7 +181,7 @@ See [Default Calling](/sdk/javascript/default-call) or [Direct Calling](/sdk/jav Send messages with embedded forms and buttons - + Advanced message filtering with RequestBuilder
diff --git a/sdk/javascript/setup-sdk.mdx b/sdk/javascript/setup-sdk.mdx index b9a70607b..053b85ce6 100644 --- a/sdk/javascript/setup-sdk.mdx +++ b/sdk/javascript/setup-sdk.mdx @@ -1,10 +1,32 @@ --- title: "Setup" -sidebarTitle: "Overview" +sidebarTitle: "Setup" description: "Install, configure, and initialize the CometChat JavaScript SDK in your application." --- -This section covers everything you need to get the CometChat JavaScript SDK running in your application. +{/* TL;DR for Agents and Quick Reference */} + + +```bash +npm install @cometchat/chat-sdk-javascript +``` + +```typescript +import { CometChat } from "@cometchat/chat-sdk-javascript"; + +const appSettings: CometChat.AppSettings = new CometChat.AppSettingsBuilder() + .setRegion("APP_REGION") + .subscribePresenceForAllUsers() + .autoEstablishSocketConnection(true) + .build(); + +await CometChat.init("APP_ID", appSettings); +await CometChat.login("UID", "AUTH_KEY"); // dev only +``` + +**Prerequisites:** npm 8+, Node.js 16+, credentials from [CometChat Dashboard](https://app.cometchat.com) +**SSR:** SDK requires browser APIs — initialize client-side only (useEffect / mounted) + ## Prerequisites @@ -13,80 +35,264 @@ This section covers everything you need to get the CometChat JavaScript SDK runn | npm | 8.x or above | | Node.js | 16 or above | -You'll also need your credentials from the [CometChat Dashboard](https://app.cometchat.com): +Get your credentials from the [CometChat Dashboard](https://app.cometchat.com): - App ID - Region - Auth Key (for development) -## Setup Steps + +**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. + - - - 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). - - +## Installation -## Framework Guides +### Package Manager -Using an SSR framework? The SDK requires browser APIs and needs client-side initialization: +```bash +npm install @cometchat/chat-sdk-javascript +``` - - - Dynamic imports with useEffect - - - Client-side mounted hook - - - Direct SDK usage - - +Then import wherever needed: - -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). - +```javascript +import { CometChat } from "@cometchat/chat-sdk-javascript"; +``` -## Quick Reference +### CDN -```bash -# Install -npm install @cometchat/chat-sdk-javascript +```html + +``` + +When using the CDN, `CometChat` is available as a global variable. + +## Initialization + +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`). + + + + +```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 -import { CometChat } from "@cometchat/chat-sdk-javascript"; +let appID = "APP_ID"; +let region = "APP_REGION"; -// Initialize -const appSettings = new CometChat.AppSettingsBuilder() - .setRegion("REGION") +let appSetting = new CometChat.AppSettingsBuilder() .subscribePresenceForAllUsers() + .setRegion(region) + .autoEstablishSocketConnection(true) .build(); -await CometChat.init("APP_ID", appSettings); +CometChat.init(appID, appSetting).then( + () => { + console.log("Initialization completed successfully"); + }, + (error) => { + console.log("Initialization failed with error:", error); + } +); +``` + + -// Login -await CometChat.login("UID", "AUTH_KEY"); + +```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); +} ``` -## Pages in This Section + + + + +Replace `APP_ID` and `APP_REGION` with your credentials 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(); +``` + +## SSR Compatibility + +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`: + +```javascript +import React from "react"; + +export default function Home() { + let [ready, setReady] = React.useState(false); + + React.useEffect(() => { + window.CometChat = require("@cometchat/chat-sdk-javascript").CometChat; + setReady(true); + }, []); + + return ready ? :

Loading...

; +} +``` + +### NuxtJS + +Import the SDK in the `mounted` lifecycle hook: + +```javascript +export default { + data() { + return { ready: false }; + }, + mounted() { + window.CometChat = require("@cometchat/chat-sdk-javascript").CometChat; + this.ready = true; + } +}; +``` + +### Ionic/Cordova + +Use the JavaScript SDK directly. Import and initialize in your root component: + +```typescript +import { CometChat } from "@cometchat/chat-sdk-javascript"; + +ngOnInit() { + const appSetting = new CometChat.AppSettingsBuilder() + .subscribePresenceForAllUsers() + .setRegion("APP_REGION") + .autoEstablishSocketConnection(true) + .build(); + + CometChat.init("APP_ID", 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. + + +--- + +## Next Steps - - Add the SDK via npm or CDN - - - Configure and initialize the SDK - - - Next.js, Nuxt, and Ionic setup - - Log in users with Auth Key or Token + Log in users with Auth Key or Auth Token + + + Send your first message diff --git a/sdk/javascript/troubleshooting.mdx b/sdk/javascript/troubleshooting.mdx index ce02a53ff..79a65bb55 100644 --- a/sdk/javascript/troubleshooting.mdx +++ b/sdk/javascript/troubleshooting.mdx @@ -175,7 +175,7 @@ Find solutions to common issues when building with the CometChat JavaScript SDK. Recommended patterns and practices - + AI Agents, Moderation, and Copilot From 10c5d61ab1e94a657979cb129c4037615bd2e92d Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 25 Mar 2026 16:23:04 +0530 Subject: [PATCH 053/139] Update authentication-overview.mdx --- sdk/javascript/authentication-overview.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/javascript/authentication-overview.mdx b/sdk/javascript/authentication-overview.mdx index 8f57169e0..363144d2a 100644 --- a/sdk/javascript/authentication-overview.mdx +++ b/sdk/javascript/authentication-overview.mdx @@ -1,6 +1,6 @@ --- title: "Authentication" -sidebarTitle: "Overview" +sidebarTitle: "Authentication" description: "Create users, log in with Auth Key or Auth Token, check login status, and log out using the CometChat JavaScript SDK." --- From e2dd9284016e44c0a2c0f043ab8aabc626877c85 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 25 Mar 2026 16:39:22 +0530 Subject: [PATCH 054/139] Update overview.mdx --- sdk/javascript/overview.mdx | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/sdk/javascript/overview.mdx b/sdk/javascript/overview.mdx index 9be62764f..5d286af0a 100644 --- a/sdk/javascript/overview.mdx +++ b/sdk/javascript/overview.mdx @@ -4,6 +4,37 @@ 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 */} + + +```bash +npm install @cometchat/chat-sdk-javascript +``` + +```javascript +import { CometChat } from "@cometchat/chat-sdk-javascript"; + +// 1. Initialize (once at app startup) +const appSettings = new CometChat.AppSettingsBuilder() + .setRegion("APP_REGION") // e.g. "us", "eu", "in" + .subscribePresenceForAllUsers() + .autoEstablishSocketConnection(true) + .build(); + +await CometChat.init("APP_ID", appSettings); + +// 2. Login (check session first) +const existing = await CometChat.getLoggedinUser(); +if (!existing) { + await CometChat.login("cometchat-uid-1", "AUTH_KEY"); // dev only — use Auth Token in production +} +``` + +**Credentials:** App ID, Region, Auth Key from [CometChat Dashboard](https://app.cometchat.com) +**Test UIDs:** `cometchat-uid-1` through `cometchat-uid-5` +**SSR:** SDK requires browser APIs — initialize client-side only (`useEffect` / `mounted`) + + 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. ## What You Can Build From bda4eadc661b6293673f9c6aa1e387cfbfffc33e Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 25 Mar 2026 16:42:22 +0530 Subject: [PATCH 055/139] Update authentication-overview.mdx --- sdk/javascript/authentication-overview.mdx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/sdk/javascript/authentication-overview.mdx b/sdk/javascript/authentication-overview.mdx index 363144d2a..e50f79fdc 100644 --- a/sdk/javascript/authentication-overview.mdx +++ b/sdk/javascript/authentication-overview.mdx @@ -96,7 +96,7 @@ CometChat.getLoggedinUser().then( } }, (error: CometChat.CometChatException) => { - console.log("Some Error Occured", { error }); + console.log("Some Error Occurred", { error }); } ); ``` @@ -105,7 +105,7 @@ CometChat.getLoggedinUser().then( ```js -const UID = "UID"; +const UID = "cometchat-uid-1"; const authKey = "AUTH_KEY"; CometChat.getLoggedinUser().then( @@ -122,7 +122,7 @@ CometChat.getLoggedinUser().then( } }, (error) => { - console.log("Something went wrong", error); + console.log("Some Error Occurred", { error }); } ); ``` @@ -183,7 +183,7 @@ CometChat.getLoggedinUser().then( } }, (error: CometChat.CometChatException) => { - console.log("Some Error Occured", { error }); + console.log("Some Error Occurred", { error }); } ); ``` From 540c3e431828a1dc07d64f61998c51d3c96b4985 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 25 Mar 2026 16:44:34 +0530 Subject: [PATCH 056/139] Update setup-sdk.mdx --- sdk/javascript/setup-sdk.mdx | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/sdk/javascript/setup-sdk.mdx b/sdk/javascript/setup-sdk.mdx index 053b85ce6..d0021b41a 100644 --- a/sdk/javascript/setup-sdk.mdx +++ b/sdk/javascript/setup-sdk.mdx @@ -224,8 +224,8 @@ let appSetting = new CometChat.AppSettingsBuilder() 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`: ```javascript @@ -243,8 +243,9 @@ export default function Home() { } ``` -### NuxtJS + + Import the SDK in the `mounted` lifecycle hook: ```javascript @@ -259,8 +260,9 @@ export default { }; ``` -### Ionic/Cordova + + Use the JavaScript SDK directly. Import and initialize in your root component: ```typescript @@ -284,6 +286,10 @@ ngOnInit() { The dedicated Ionic Cordova SDK has been deprecated. For new Ionic/Cordova applications, use the JavaScript SDK as shown above. + + + + --- ## Next Steps From 4fbab3f2b02880f1f916bbc9d0ea1ce071a9b536 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 25 Mar 2026 16:48:59 +0530 Subject: [PATCH 057/139] Update authentication-overview.mdx --- sdk/javascript/authentication-overview.mdx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/sdk/javascript/authentication-overview.mdx b/sdk/javascript/authentication-overview.mdx index e50f79fdc..537e90ac9 100644 --- a/sdk/javascript/authentication-overview.mdx +++ b/sdk/javascript/authentication-overview.mdx @@ -12,7 +12,7 @@ description: "Create users, log in with Auth Key or Auth Token, check login stat const user = await CometChat.getLoggedinUser(); // Login with Auth Key (development only) -CometChat.login("UID", "AUTH_KEY").then(user => console.log("Logged in:", user)); +CometChat.login("cometchat-uid-1", "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)); @@ -54,7 +54,7 @@ sequenceDiagram -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`. +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`. @@ -131,7 +131,7 @@ CometChat.getLoggedinUser().then( ```javascript -const UID = "UID"; +const UID = "cometchat-uid-1"; const authKey = "AUTH_KEY"; try { @@ -208,7 +208,7 @@ CometChat.getLoggedinUser().then( } }, (error) => { - console.log("Something went wrong", error); + console.log("Some Error Occurred", { error }); } ); ``` From cca23b4cc9e990da87bb2af95c6869a6aa0de5cb Mon Sep 17 00:00:00 2001 From: PrajwalDhuleCC Date: Wed, 25 Mar 2026 17:01:08 +0530 Subject: [PATCH 058/139] docs(sdk/javascript): Update group management documentation with reference links and return type clarifications - Remove redundant Group class field tables from create-group and join-group docs, consolidating into reference links - Update kickGroupMember, banGroupMember, and unbanGroupMember return types from Object to boolean in code examples and descriptions - Add return type documentation for unbanGroupMember and fetchNext methods in banned members section - Add GroupMember reference link and scope field documentation to retrieve-group-members - Replace inline field documentation with links to centralized entity reference for consistency across group management guides --- sdk/javascript/create-group.mdx | 14 ++-------- sdk/javascript/group-kick-ban-members.mdx | 14 ++++++---- sdk/javascript/join-group.mdx | 11 +------- sdk/javascript/retrieve-group-members.mdx | 24 ++++++++++------ sdk/javascript/retrieve-groups.mdx | 34 ++++++++--------------- 5 files changed, 39 insertions(+), 58 deletions(-) diff --git a/sdk/javascript/create-group.mdx b/sdk/javascript/create-group.mdx index 4f8883c2c..d9d7e1e7d 100644 --- a/sdk/javascript/create-group.mdx +++ b/sdk/javascript/create-group.mdx @@ -112,18 +112,8 @@ The createGroup() method takes the following parameters: | --------- | ---------------------------- | | `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. +After successful creation of the group, you will receive an instance of [`Group`](/sdk/reference/entities#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 | @@ -224,7 +214,7 @@ 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. +This method returns an Object which has two keys: `group` & `members` . The group key has the [`Group`](/sdk/reference/entities#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. ## Group Class diff --git a/sdk/javascript/group-kick-ban-members.mdx b/sdk/javascript/group-kick-ban-members.mdx index 99c0d3ce4..a083361a4 100644 --- a/sdk/javascript/group-kick-ban-members.mdx +++ b/sdk/javascript/group-kick-ban-members.mdx @@ -63,7 +63,7 @@ let GUID: string = "GUID"; let UID: string = "UID"; CometChat.kickGroupMember(GUID, UID).then( - (response: Object) => { + (response: boolean) => { console.log("Group member kicked successfully", response); }, (error: CometChat.CometChatException) => { console.log("Group member kicking failed with error", error); @@ -84,7 +84,7 @@ 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. +On success, the method resolves with a `boolean` value (`true`) confirming the operation. ## Ban a Group Member @@ -113,7 +113,7 @@ let GUID: string = "GUID"; let UID: string = "UID"; CometChat.banGroupMember(GUID, UID).then( - (response: Object) => { + (response: boolean) => { console.log("Group member banned successfully", response); }, (error: CometChat.CometChatException) => { console.log("Group member banning failed with error", error); @@ -134,7 +134,7 @@ 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. +On success, the method resolves with a `boolean` value (`true`) confirming the operation. ## Unban a Banned Group Member from a Group @@ -163,7 +163,7 @@ let GUID: string = "GUID"; let UID: string = "UID"; CometChat.unbanGroupMember(GUID, UID).then( - (response: Object) => { + (response: boolean) => { console.log("Group member unbanned successfully", response); }, (error: CometChat.CometChatException) => { console.log("Group member unbanning failed with error", error); @@ -184,6 +184,8 @@ The `unbanGroupMember()` method takes the following parameters The unbanned user can now rejoin the group. +On success, the method resolves with a `boolean` value (`true`) confirming the operation. + ## 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. @@ -299,6 +301,8 @@ bannedGroupMembersRequest.fetchNext().then( +The `fetchNext()` method returns an array of [`GroupMember`](/sdk/reference/entities#groupmember) objects representing the banned members of the group. + ## 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?* diff --git a/sdk/javascript/join-group.mdx b/sdk/javascript/join-group.mdx index 7a6ba0f11..8cc770225 100644 --- a/sdk/javascript/join-group.mdx +++ b/sdk/javascript/join-group.mdx @@ -80,16 +80,7 @@ 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 | +The method returns a [`Group`](/sdk/reference/entities#group) object with `hasJoined` set to `true`. ## Real-time Group Member Joined Events diff --git a/sdk/javascript/retrieve-group-members.mdx b/sdk/javascript/retrieve-group-members.mdx index 5eb5820f7..60738b4b7 100644 --- a/sdk/javascript/retrieve-group-members.mdx +++ b/sdk/javascript/retrieve-group-members.mdx @@ -34,6 +34,8 @@ 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. +Fetching using this builder will return [`GroupMember`](/sdk/reference/entities#groupmember) objects. `GroupMember` extends `User` and adds group-specific fields. + ### Set Limit This method sets the limit i.e. the number of members that should be fetched in a single iteration. @@ -129,6 +131,12 @@ let groupMembersRequest: CometChat.GroupMembersRequest = new CometChat.GroupMemb +Relevant fields to access on returned members: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| scope | `getScope()` | `string` | Scope of the member in the group (`"admin"`, `"moderator"`, or `"participant"`) | + ### 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: @@ -165,6 +173,12 @@ let groupMembersRequest: CometChat.GroupMembersRequest = new CometChat.GroupMemb +Relevant fields to access on returned members: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| status | `getStatus()` | `string` | Online status of the member (`"online"` or `"offline"`) | + 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. @@ -210,15 +224,7 @@ 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 | +The `fetchNext()` method returns an array of [`GroupMember`](/sdk/reference/entities#groupmember) objects. `GroupMember` extends `User` and adds group-specific fields. - **Paginate results** — Always use `fetchNext()` in a loop or on-scroll. Set a reasonable limit (10–30) per request to avoid large payloads. diff --git a/sdk/javascript/retrieve-groups.mdx b/sdk/javascript/retrieve-groups.mdx index 1e74e2898..181bd8236 100644 --- a/sdk/javascript/retrieve-groups.mdx +++ b/sdk/javascript/retrieve-groups.mdx @@ -34,6 +34,8 @@ const count = await CometChat.getOnlineGroupMemberCount(["GUID"]); 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. +Fetching using this builder will return [`Group`](/sdk/reference/entities#group) objects + The `GroupsRequestBuilder` class allows you to set the below parameters: ### Set Limit @@ -183,6 +185,12 @@ let groupsRequest: CometChat.GroupsRequest = new CometChat.GroupsRequestBuilder( +Relevant fields to access on returned groups: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| tags | `getTags()` | `string[]` | Tags associated with the group | + 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. 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. @@ -228,16 +236,7 @@ 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 | +The `fetchNext()` method returns an array of [`Group`](/sdk/reference/entities#group) objects. ## Retrieve Particular Group Details @@ -280,18 +279,7 @@ CometChat.getGroup(GUID).then( | --------- | ------------------------------------------------------------ | | `GUID` | The GUID of the group for whom the details are to be fetched | -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 | +It returns a [`Group`](/sdk/reference/entities#group) object containing the details of the group. ## Get online group member count @@ -330,6 +318,8 @@ 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. +`getOnlineGroupMemberCount()` resolves with a `{ guid: count }` object where each key is a group GUID and its value is the number of currently online members in that group. + - **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. From 01e4f080bff76f94df42c0cc57dddd87ae114bf4 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 25 Mar 2026 17:02:19 +0530 Subject: [PATCH 059/139] typo fixes --- sdk/javascript/delete-conversation.mdx | 2 +- sdk/javascript/delivery-read-receipts.mdx | 2 +- sdk/javascript/interactive-messages.mdx | 2 +- sdk/javascript/message-filtering.mdx | 6 +++--- sdk/javascript/reactions.mdx | 26 +++++++++++------------ sdk/javascript/retrieve-conversations.mdx | 10 +++++++-- sdk/javascript/transient-messages.mdx | 4 ++-- sdk/javascript/typing-indicators.mdx | 4 ++-- 8 files changed, 31 insertions(+), 25 deletions(-) diff --git a/sdk/javascript/delete-conversation.mdx b/sdk/javascript/delete-conversation.mdx index fafb284dc..3b99dce50 100644 --- a/sdk/javascript/delete-conversation.mdx +++ b/sdk/javascript/delete-conversation.mdx @@ -55,7 +55,7 @@ CometChat.deleteConversation(GUID, type).then( - + ```typescript let UID: string = "UID"; let type: string = "user"; diff --git a/sdk/javascript/delivery-read-receipts.mdx b/sdk/javascript/delivery-read-receipts.mdx index fc5f9c78d..2d8f4f9e7 100644 --- a/sdk/javascript/delivery-read-receipts.mdx +++ b/sdk/javascript/delivery-read-receipts.mdx @@ -4,7 +4,7 @@ sidebarTitle: "Delivery & Read Receipts" description: "Mark messages as delivered, read, or unread and receive real-time receipt events using the CometChat JavaScript SDK." --- - + | Method | Description | | --- | --- | diff --git a/sdk/javascript/interactive-messages.mdx b/sdk/javascript/interactive-messages.mdx index 3570fb421..0721aa6e6 100644 --- a/sdk/javascript/interactive-messages.mdx +++ b/sdk/javascript/interactive-messages.mdx @@ -4,7 +4,7 @@ sidebarTitle: "Interactive Messages" description: "Send and receive interactive messages with embedded forms, buttons, and other UI elements using the CometChat JavaScript SDK." --- - + | Component | Description | | --- | --- | diff --git a/sdk/javascript/message-filtering.mdx b/sdk/javascript/message-filtering.mdx index 681b9ec98..efdd502ec 100644 --- a/sdk/javascript/message-filtering.mdx +++ b/sdk/javascript/message-filtering.mdx @@ -9,7 +9,7 @@ description: "Advanced filtering options for fetching messages using MessagesReq ```javascript // Filter by category and type -let messagesRequest = new CometChat.MessagesRequestBuilder() +let mediaRequest = new CometChat.MessagesRequestBuilder() .setUID("UID") .setCategories(["message"]) .setTypes(["image", "video", "audio", "file"]) @@ -17,14 +17,14 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() .build(); // Unread messages only -let messagesRequest = new CometChat.MessagesRequestBuilder() +let unreadRequest = new CometChat.MessagesRequestBuilder() .setUID("UID") .setUnread(true) .setLimit(50) .build(); // Threaded messages -let messagesRequest = new CometChat.MessagesRequestBuilder() +let threadRequest = new CometChat.MessagesRequestBuilder() .setUID("UID") .setParentMessageId(parentId) .setLimit(50) diff --git a/sdk/javascript/reactions.mdx b/sdk/javascript/reactions.mdx index 12c22fd34..8cb639979 100644 --- a/sdk/javascript/reactions.mdx +++ b/sdk/javascript/reactions.mdx @@ -169,10 +169,10 @@ reactionRequest.fetchNext().then( messages => { console.log("list fetched:", messages); }, - error => {a + error => { console.log('list fetching failed with error:', error); }, - ); + ); ``` @@ -218,10 +218,10 @@ reactionRequest.fetchPrevious().then( messages => { console.log("list fetched:", messages); }, - error => {a + error => { console.log('list fetching failed with error:', error); }, - ); + ); ``` @@ -241,14 +241,14 @@ Always remove listeners when they're no longer needed (e.g., on component unmoun ```typescript let listenerID:string = "UNIQUE_LISTENER_ID"; -CometChat.addMessageListener(listenerID, { +CometChat.addMessageListener(listenerID, new CometChat.MessageListener({ onMessageReactionAdded:(message: Object) => { console.log("Reaction added", message); }, onMessageReactionRemoved:(message: Object) => { console.log("Reaction removed", message); } - }) + })) ``` @@ -257,14 +257,14 @@ CometChat.addMessageListener(listenerID, { ```js let listenerID = "UNIQUE_LISTENER_ID"; -CometChat.addMessageListener(listenerID, { +CometChat.addMessageListener(listenerID, new CometChat.MessageListener({ onMessageReactionAdded:(message) => { console.log("Reaction added", message); }, onMessageReactionRemoved:(message) => { console.log("Reaction removed", message); } - }) + })) ``` @@ -290,7 +290,7 @@ To stop listening for reaction events, remove the listener as follows: ```typescript let listenerID:string = "UNIQUE_LISTENER_ID"; -CometChat.removeMessageReactionListener(listenerID); +CometChat.removeMessageListener(listenerID); ``` @@ -375,8 +375,8 @@ let messageReaction: CometChat.MessageReaction = ...; let action: CometChat.REACTION_ACTION = CometChat.REACTION_ACTION.REACTION_ADDED; let modifiedBaseMessage = CometChat.CometChatHelper.updateMessageWithReactionInfo( -baseMessage, -messageReaction, +message, +messageReaction, action ); ``` @@ -395,8 +395,8 @@ let messageReaction = ...; let action = CometChat.REACTION_ACTION.REACTION_ADDED; let modifiedBaseMessage = CometChat.CometChatHelper.updateMessageWithReactionInfo( -baseMessage, -messageReaction, +message, +messageReaction, action ); ``` diff --git a/sdk/javascript/retrieve-conversations.mdx b/sdk/javascript/retrieve-conversations.mdx index ce474aeef..1c1b456ac 100644 --- a/sdk/javascript/retrieve-conversations.mdx +++ b/sdk/javascript/retrieve-conversations.mdx @@ -551,7 +551,10 @@ CometChat.tagConversation(conversationWith, conversationType, tags).then( ```javascript let tags = ["archivedChat"]; -CometChat.tagConversation("conversationWith", "conversationType", tags).then( +let conversationWith = "UID"; +let conversationType = "user"; + +CometChat.tagConversation(conversationWith, conversationType, tags).then( (conversation) => { console.log("conversation", conversation); }, @@ -600,7 +603,10 @@ CometChat.getConversation(conversationWith, conversationType).then( ```javascript -CometChat.getConversation("conversationWith", "conversationType").then( +let conversationWith = "UID"; +let conversationType = "user"; + +CometChat.getConversation(conversationWith, conversationType).then( (conversation) => { console.log("conversation", conversation); }, diff --git a/sdk/javascript/transient-messages.mdx b/sdk/javascript/transient-messages.mdx index adb347406..22bd62fd6 100644 --- a/sdk/javascript/transient-messages.mdx +++ b/sdk/javascript/transient-messages.mdx @@ -87,7 +87,7 @@ You will receive the transient message in the `onTransientMessageReceived()` met ```typescript -let listenerId: string = "UNIQUE_LITENER_ID"; +let listenerId: string = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener( listenerId, @@ -103,7 +103,7 @@ CometChat.addMessageListener( ```javascript -let listenerId = "UNIQUE_LITENER_ID"; +let listenerId = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener( listenerId, diff --git a/sdk/javascript/typing-indicators.mdx b/sdk/javascript/typing-indicators.mdx index bdf1cb205..be9a7078f 100644 --- a/sdk/javascript/typing-indicators.mdx +++ b/sdk/javascript/typing-indicators.mdx @@ -138,7 +138,7 @@ Use `onTypingStarted` and `onTypingEnded` in `MessageListener` to receive typing ```typescript -let listenerId: string = "UNIQUE_LITENER_ID"; +let listenerId: string = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener( listenerId, @@ -157,7 +157,7 @@ CometChat.addMessageListener( ```javascript -let listenerId = "UNIQUE_LITENER_ID"; +let listenerId = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener( listenerId, From 8751f020a1bc157eaa8e48aa2fc7a70b33401902 Mon Sep 17 00:00:00 2001 From: PrajwalDhuleCC Date: Wed, 25 Mar 2026 18:54:38 +0530 Subject: [PATCH 060/139] docs(sdk/javascript): Add relevant fields reference tables to message documentation - Add field accessor tables to additional-message-filtering.mdx for category and type fields - Add focused field accessor tables to delete-message.mdx removing generic id and sender fields - Add return type clarification for markConversationAsDelivered() in delivery-read-receipts.mdx - Add focused field accessor tables to edit-message.mdx removing generic id, text, and sender fields - Add field accessor table to mentions.mdx for mentionedUsers and tags fields - Add field accessor tables to receive-message.mdx for message metadata fields - Add field accessor tables to send-message.mdx for message metadata fields - Add field accessor table to transient-messages.mdx for transient field - Add field accessor table to typing-indicators.mdx for typingIndicator fields - Improve consistency by showing only relevant fields specific to each operation's response --- .../additional-message-filtering.mdx | 14 ++++++++++++ sdk/javascript/delete-message.mdx | 12 +++++----- sdk/javascript/delivery-read-receipts.mdx | 2 ++ sdk/javascript/edit-message.mdx | 13 +++++------ sdk/javascript/mentions.mdx | 21 +++++++++++++----- sdk/javascript/receive-message.mdx | 6 +++++ sdk/javascript/send-message.mdx | 12 +++++++--- sdk/javascript/transient-messages.mdx | 20 +++-------------- sdk/javascript/typing-indicators.mdx | 22 +++++-------------- 9 files changed, 67 insertions(+), 55 deletions(-) diff --git a/sdk/javascript/additional-message-filtering.mdx b/sdk/javascript/additional-message-filtering.mdx index f90b8a6c0..5ccf9b0e7 100644 --- a/sdk/javascript/additional-message-filtering.mdx +++ b/sdk/javascript/additional-message-filtering.mdx @@ -652,6 +652,13 @@ 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`. + +Relevant fields to access on returned messages: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| category | `getCategory()` | `string` | Category of the message (`"message"`, `"custom"`, `"action"`, `"call"`) | + ## Messages for multiple types *In other words, how do I fetch messages belonging to multiple types* @@ -730,6 +737,13 @@ let GUID: string = "GUID", Using the above code snippet, you can fetch all the media messages. + +Relevant fields to access on returned messages: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| type | `getType()` | `string` | Type of the message (`"text"`, `"image"`, `"video"`, `"audio"`, `"file"`, or custom types) | + ## 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* diff --git a/sdk/javascript/delete-message.mdx b/sdk/javascript/delete-message.mdx index d25092cb7..4aa307972 100644 --- a/sdk/javascript/delete-message.mdx +++ b/sdk/javascript/delete-message.mdx @@ -91,12 +91,12 @@ 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: +The `deleteMessage()` method returns a [`BaseMessage`](/sdk/reference/messages#basemessage) object. + +Relevant fields to access on the returned message: | 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 | @@ -150,12 +150,12 @@ 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: +The `onMessageDeleted` callback receives a [`BaseMessage`](/sdk/reference/messages#basemessage) object with the `deletedAt` and `deletedBy` fields set. + +Relevant fields to access on the returned message: | 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 | diff --git a/sdk/javascript/delivery-read-receipts.mdx b/sdk/javascript/delivery-read-receipts.mdx index 1946624a9..cbaf4d96a 100644 --- a/sdk/javascript/delivery-read-receipts.mdx +++ b/sdk/javascript/delivery-read-receipts.mdx @@ -267,6 +267,8 @@ You can mark an entire conversation as delivered for a user or group using the ` This method will mark all messages in the conversation as delivered. +`markConversationAsDelivered()` resolves with a `string` on success. + ```javascript diff --git a/sdk/javascript/edit-message.mdx b/sdk/javascript/edit-message.mdx index ca502e46d..11c4fe3d0 100644 --- a/sdk/javascript/edit-message.mdx +++ b/sdk/javascript/edit-message.mdx @@ -147,13 +147,12 @@ 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: +The `editMessage()` method returns a [`BaseMessage`](/sdk/reference/messages#basemessage) object (or a subclass like [`TextMessage`](/sdk/reference/messages#textmessage)). + +Relevant fields to access on the returned message: | 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 | @@ -215,12 +214,12 @@ 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: +The `onMessageEdited` callback receives a [`BaseMessage`](/sdk/reference/messages#basemessage) object with the `editedAt` and `editedBy` fields set. + +Relevant fields to access on the returned message: | 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 | diff --git a/sdk/javascript/mentions.mdx b/sdk/javascript/mentions.mdx index 5c3995e17..853a1089a 100644 --- a/sdk/javascript/mentions.mdx +++ b/sdk/javascript/mentions.mdx @@ -146,6 +146,13 @@ By default, the SDK will fetch all the messages irrespective of the fact that th To get a list of messages in a conversation where users are mentioned along with the user tags of the mentioned users. +Relevant fields to access on returned messages and their mentioned users: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| mentionedUsers | `getMentionedUsers()` | [`User[]`](/sdk/reference/entities#user) | Array of users mentioned in the message | +| tags (on each mentioned user) | `getTags()` | `string[]` | Tags associated with the mentioned user | + ```javascript @@ -265,6 +272,14 @@ messagesRequest.fetchPrevious().then( To get a list of messages in a conversation where users are mentioned along with the blocked relationship of the mentioned users with the logged-in user. +Relevant fields to access on returned messages and their mentioned users: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| mentionedUsers | `getMentionedUsers()` | [`User[]`](/sdk/reference/entities#user) | Array of users mentioned in the message | +| blockedByMe (on each mentioned user) | `getBlockedByMe()` | `boolean` | Whether the logged-in user has blocked this mentioned user | +| hasBlockedMe (on each mentioned user) | `getHasBlockedMe()` | `boolean` | Whether this mentioned user has blocked the logged-in user | + ```javascript @@ -392,12 +407,8 @@ 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 | +The getMentionedUsers() method returns an array of [`User`](/sdk/reference/entities#user) objects. - **Use correct format**: Always use `<@uid:UID>` format for mentions in message text diff --git a/sdk/javascript/receive-message.mdx b/sdk/javascript/receive-message.mdx index aeb5e40de..c18ee4e25 100644 --- a/sdk/javascript/receive-message.mdx +++ b/sdk/javascript/receive-message.mdx @@ -708,6 +708,8 @@ CometChat.getUnreadMessageCountForUser(UID).then( +The `getUnreadMessageCountForUser()` method returns a count object where the key is the UID and the value is the unread message count (e.g., `{ "UID": 5 }`). + It will return an object which will contain the UID as the key and the unread message count as the value. ### Fetch Unread Message Count of a particular group conversation @@ -792,6 +794,8 @@ CometChat.getUnreadMessageCountForGroup(GUID).then( +The `getUnreadMessageCountForGroup()` method returns a count object where the key is the GUID and the value is the unread message count (e.g., `{ "GUID": 12 }`). + It will return an object which will contain the GUID as the key and the unread message count as the value. ### Fetch Unread Message Count of all one-on-one & group conversations @@ -870,6 +874,8 @@ CometChat.getUnreadMessageCount().then( +The `getUnreadMessageCount()` method returns a count object with two keys: `users` (a map of `{ UID: count }`) and `groups` (a map of `{ GUID: count }`), representing unread message counts across all conversations. + 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. diff --git a/sdk/javascript/send-message.mdx b/sdk/javascript/send-message.mdx index 9b0cf7af5..7303acea9 100644 --- a/sdk/javascript/send-message.mdx +++ b/sdk/javascript/send-message.mdx @@ -345,7 +345,9 @@ The `TextMessage` class constructor takes the following parameters: | **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. + +The `sendMessage()` method returns a [`TextMessage`](/sdk/reference/messages#textmessage) | [`MediaMessage`](/sdk/reference/messages#mediamessage) | [`CustomMessage`](/sdk/reference/messages#custommessage) | [`BaseMessage`](/sdk/reference/messages#basemessage) object depending on the input message type. + ## Media Message *In other words, as a sender, how do I send a media message like photos, videos & files?* @@ -860,7 +862,9 @@ 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. + +The `sendMediaMessage()` method returns a [`MediaMessage`](/sdk/reference/messages#mediamessage) object. + ## 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: @@ -1764,7 +1768,9 @@ 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. + +The `sendCustomMessage()` method returns a [`CustomMessage`](/sdk/reference/messages#custommessage) object. + It is also possible to send interactive messages from CometChat, to know more [click here](/sdk/javascript/interactive-messages) diff --git a/sdk/javascript/transient-messages.mdx b/sdk/javascript/transient-messages.mdx index e326eff37..1826bec8b 100644 --- a/sdk/javascript/transient-messages.mdx +++ b/sdk/javascript/transient-messages.mdx @@ -80,6 +80,8 @@ CometChat.sendTransientMessage(transientMessage); +`sendTransientMessage()` returns `void` — the message is sent as a fire-and-forget operation with no response. + ## Real-time Transient Messages *In other words, as a recipient, how do I know when someone sends a transient message?* @@ -125,23 +127,7 @@ CometChat.addMessageListener( -The `TransientMessage` class consists of the below parameters: - -| Parameter | Information | -| ---------------- | -------------------------------------------------------------------------------------------------------- | -| **sender** | An object of the User class holding all the information. related to the sender of the transient message. | -| **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. | - -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 | +The received object is a [`TransientMessage`](/sdk/reference/auxiliary#transientmessage). --- diff --git a/sdk/javascript/typing-indicators.mdx b/sdk/javascript/typing-indicators.mdx index 04ead8e2a..9f9acb6f2 100644 --- a/sdk/javascript/typing-indicators.mdx +++ b/sdk/javascript/typing-indicators.mdx @@ -81,6 +81,8 @@ CometChat.startTyping(typingNotification); +`startTyping()` returns `void` — the typing indicator is sent as a fire-and-forget operation. + ### 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. @@ -132,6 +134,8 @@ CometChat.endTyping(typingNotification); +`endTyping()` returns `void` — the typing indicator is sent as a fire-and-forget operation. + Custom Data @@ -190,23 +194,7 @@ CometChat.addMessageListener( -The `TypingIndicator` class consists of the below parameters: - -| 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. | - -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 | +The received object is a [`TypingIndicator`](/sdk/reference/auxiliary#typingindicator). - **Debounce typing events**: Don't call `startTyping()` on every keystroke - debounce to ~300ms intervals From 42dc14344295e8c528601dada59c5571d40ef472 Mon Sep 17 00:00:00 2001 From: PrajwalDhuleCC Date: Wed, 25 Mar 2026 19:28:48 +0530 Subject: [PATCH 061/139] docs(sdk/javascript): Remove redundant field reference tables from documentation - Remove Call object getter methods table from direct-call.mdx - Remove BaseMessage getter methods table from flag-message.mdx - Remove InteractiveMessage getter methods table from interactive-messages.mdx - Remove message object getter methods tables from receive-message.mdx (multiple instances) - Remove User object getter methods table from setup-sdk.mdx - Remove Presence object getter methods table from user-presence.mdx - Remove Group object getter methods table from update-group.mdx - Remove ThreadedMessage getter methods table from threaded-messages.mdx - Consolidate field documentation to centralized reference pages to reduce duplication and improve maintainability --- sdk/javascript/direct-call.mdx | 10 +------- sdk/javascript/flag-message.mdx | 8 ------- sdk/javascript/interactive-messages.mdx | 9 +------ sdk/javascript/reactions.mdx | 31 ++++++++++--------------- sdk/javascript/receive-message.mdx | 31 +++---------------------- sdk/javascript/setup-sdk.mdx | 12 +--------- sdk/javascript/threaded-messages.mdx | 11 +-------- sdk/javascript/update-group.mdx | 12 +--------- sdk/javascript/user-presence.mdx | 7 +++--- 9 files changed, 23 insertions(+), 108 deletions(-) diff --git a/sdk/javascript/direct-call.mdx b/sdk/javascript/direct-call.mdx index ee7538645..ae45431eb 100644 --- a/sdk/javascript/direct-call.mdx +++ b/sdk/javascript/direct-call.mdx @@ -360,15 +360,7 @@ 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 | +The ringing flow methods (`initiateCall()`, `acceptCall()`, `rejectCall()`, `endCall()`) return [`Call`](/sdk/reference/messages#call) objects. ## End Call Session diff --git a/sdk/javascript/flag-message.mdx b/sdk/javascript/flag-message.mdx index ab3bd4257..430cd72c2 100644 --- a/sdk/javascript/flag-message.mdx +++ b/sdk/javascript/flag-message.mdx @@ -170,14 +170,6 @@ 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 diff --git a/sdk/javascript/interactive-messages.mdx b/sdk/javascript/interactive-messages.mdx index a934cf2b9..063376bf6 100644 --- a/sdk/javascript/interactive-messages.mdx +++ b/sdk/javascript/interactive-messages.mdx @@ -166,14 +166,7 @@ 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 | +The `sendInteractiveMessage()` method returns an [`InteractiveMessage`](/sdk/reference/messages#interactivemessage) object. ## Event Listeners diff --git a/sdk/javascript/reactions.mdx b/sdk/javascript/reactions.mdx index 3148fbf1f..45f3fffcb 100644 --- a/sdk/javascript/reactions.mdx +++ b/sdk/javascript/reactions.mdx @@ -113,13 +113,7 @@ 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 | +Both `addReaction()` and `removeReaction()` return a [`BaseMessage`](/sdk/reference/messages#basemessage) object with the updated reactions. ## Fetch Reactions for a Message @@ -170,8 +164,8 @@ let reactionRequest = new CometChat.ReactionRequestBuilder() .build(); reactionRequest.fetchNext().then( - (messages: MessageReaction[]) => { - console.log("list fetched:", messages); + (reactions: CometChat.Reaction[]) => { + console.log("list fetched:", reactions); }, (error: CometChat.CometChatException) => { console.log('list fetching failed with error:', error); @@ -183,6 +177,8 @@ reactionRequest.fetchNext().then( +The `fetchNext()` method returns an array of [`Reaction`](/sdk/reference/auxiliary#reaction) objects representing individual user reactions on the message. + Fetch Previous The `fetchPrevious()` method fetches the previous set of reactions for the message. @@ -219,8 +215,8 @@ let reactionRequest = new CometChat.ReactionRequestBuilder() .build(); reactionRequest.fetchPrevious().then( - (messages: MessageReaction[]) => { - console.log("list fetched:", messages); + (reactions: CometChat.Reaction[]) => { + console.log("list fetched:", reactions); }, (error: CometChat.CometChatException) => { console.log('list fetching failed with error:', error); @@ -275,14 +271,7 @@ 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 | +Each reaction listener callback receives a [`ReactionEvent`](/sdk/reference/auxiliary#reactionevent) object. ## Removing a Reaction Listener @@ -330,6 +319,8 @@ message.getReactions() +The `getReactions()` method returns an array of [`ReactionCount`](/sdk/reference/auxiliary#reactioncount) objects, each containing the reaction emoji, the total count of users who reacted with it, and whether the logged-in user used that reaction. + ## 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. @@ -357,6 +348,8 @@ reaction.getReactedByMe(); //Return true is logged-in user reacted on that messa +The `getReactedByMe()` method on a [`ReactionCount`](/sdk/reference/auxiliary#reactioncount) object returns a `boolean` — `true` if the logged-in user has reacted with that specific emoji, `false` otherwise. + ## Update Message With Reaction Info 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. diff --git a/sdk/javascript/receive-message.mdx b/sdk/javascript/receive-message.mdx index c18ee4e25..bea382c90 100644 --- a/sdk/javascript/receive-message.mdx +++ b/sdk/javascript/receive-message.mdx @@ -130,16 +130,7 @@ 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) | +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. ## Missed Messages @@ -259,15 +250,7 @@ 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 | +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). ## Unread Messages @@ -487,15 +470,7 @@ 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 | +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). ## Search Messages diff --git a/sdk/javascript/setup-sdk.mdx b/sdk/javascript/setup-sdk.mdx index 342b8f4b3..81aeac626 100644 --- a/sdk/javascript/setup-sdk.mdx +++ b/sdk/javascript/setup-sdk.mdx @@ -200,17 +200,7 @@ 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. +After initialization, `CometChat.login()` returns a [`User`](/sdk/reference/entities#user) object representing the logged-in user. 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 0fee3d530..8ce913411 100644 --- a/sdk/javascript/threaded-messages.mdx +++ b/sdk/javascript/threaded-messages.mdx @@ -207,16 +207,7 @@ 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 | +The `fetchPrevious()` method returns an array of [`BaseMessage`](/sdk/reference/messages#basemessage) objects representing thread replies. ## Avoid Threaded Messages in User/Group Conversations diff --git a/sdk/javascript/update-group.mdx b/sdk/javascript/update-group.mdx index aa9aaf5f0..f7419de0d 100644 --- a/sdk/javascript/update-group.mdx +++ b/sdk/javascript/update-group.mdx @@ -71,17 +71,7 @@ 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 | +The method returns a [`Group`](/sdk/reference/entities#group) object. For more information on the `Group` class, please check [here](/sdk/javascript/create-group#create-a-group). diff --git a/sdk/javascript/user-presence.mdx b/sdk/javascript/user-presence.mdx index 807a92862..b8caa983e 100644 --- a/sdk/javascript/user-presence.mdx +++ b/sdk/javascript/user-presence.mdx @@ -94,14 +94,13 @@ CometChat.addUserListener( | ------------ | --------------------------------------------- | | `listenerID` | An ID that uniquely identifies that listener. | -You will receive an object of the `User` class in the listener methods. +You will receive an object of the [`User`](/sdk/reference/entities#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: + +Relevant fields to access on returned users: | 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 | From f58293c6c7dd31c98607029447b8e5a92ac037e8 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 25 Mar 2026 19:39:47 +0530 Subject: [PATCH 062/139] Update overview.mdx --- sdk/javascript/overview.mdx | 65 ++++++++++++++++++++----------------- 1 file changed, 35 insertions(+), 30 deletions(-) diff --git a/sdk/javascript/overview.mdx b/sdk/javascript/overview.mdx index 5d286af0a..2da77b008 100644 --- a/sdk/javascript/overview.mdx +++ b/sdk/javascript/overview.mdx @@ -35,26 +35,16 @@ if (!existing) { **SSR:** SDK requires browser APIs — initialize client-side only (`useEffect` / `mounted`) -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. - -## What You Can Build - -- 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 +The CometChat JavaScript SDK lets you add real-time messaging, voice, and video calling to any JavaScript application — React, Angular, Vue, Next.js, Nuxt, or vanilla JS. ## Requirements -| Requirement | Version | -|-------------|---------| -| npm | 8.x or above | -| Node.js | 16 or above | +| Requirement | Minimum Version | +|-------------|-----------------| +| npm | 8.x | +| Node.js | 16 | -The SDK works in all modern browsers (Chrome, Firefox, Safari, Edge) and can be used with SSR frameworks like Next.js and Nuxt. +Works in all modern browsers (Chrome, Firefox, Safari, Edge) and SSR frameworks (Next.js, Nuxt) with [client-side initialization](/sdk/javascript/setup-sdk#ssr-compatibility). ## Getting Started @@ -68,11 +58,28 @@ The SDK works in all modern browsers (Chrome, Firefox, Safari, Edge) and can be 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). + + Send your first message, make a call, or manage users and groups. +## Features + + + + 1:1 and group chat, threads, reactions, typing indicators, read receipts, file sharing, and interactive messages. + + + Ringing flows, direct call sessions, standalone calling, recording, virtual backgrounds, and screen sharing. + + + Create, retrieve, and manage users. Track online/offline presence and block/unblock users. + + + Public, private, and password-protected groups with member management, roles, and ownership transfer. + + + ## Sample Apps Explore working examples with full source code: @@ -91,32 +98,30 @@ Explore working examples with full source code: ## UI Kits -Skip the UI work and use our pre-built components: +Skip the UI work — use pre-built, customizable components: - - Ready-to-use React components + + React UI Kit - - Ready-to-use Angular components + + Angular UI Kit - - Ready-to-use Vue components + + Vue UI Kit -## Chat Widget - -For the fastest integration, embed our [Chat Widget](/widget/html/overview) with just a few lines of code — no SDK knowledge required. +For the fastest integration, embed the [Chat Widget](/widget/html/overview) with just a few lines of code. ## Resources - Understand UIDs, GUIDs, auth tokens, and core concepts + UIDs, GUIDs, auth tokens, and core SDK concepts - See what's new in the latest SDK version + Latest SDK version and release notes Migration guide for V3 users From 2e3b1b4f5106bb9dda43a45ec8025e71c353d243 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 25 Mar 2026 19:51:15 +0530 Subject: [PATCH 063/139] Update message-filtering.mdx --- sdk/javascript/message-filtering.mdx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/sdk/javascript/message-filtering.mdx b/sdk/javascript/message-filtering.mdx index efdd502ec..d372fd2e8 100644 --- a/sdk/javascript/message-filtering.mdx +++ b/sdk/javascript/message-filtering.mdx @@ -53,6 +53,8 @@ To fetch messages: Messages are paginated with a maximum of 100 per request. Call `fetchPrevious()`/`fetchNext()` repeatedly on the same object to get subsequent pages. +Both methods return an array of [`BaseMessage`](/sdk/reference/messages#basemessage) objects. Each message may be a [`TextMessage`](/sdk/reference/messages#textmessage), [`MediaMessage`](/sdk/reference/messages#mediamessage), [`CustomMessage`](/sdk/reference/messages#custommessage), [`Action`](/sdk/reference/messages#action), or [`Call`](/sdk/reference/messages#call). Use `instanceof` to check the type. + ## Number of messages fetched Set the number of messages to fetch per request using `setLimit()`. Maximum is 100. From 5121686d156fc6a4253a6f9064e4be2c3f623a5b Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 25 Mar 2026 20:00:46 +0530 Subject: [PATCH 064/139] Update retrieve-conversations.mdx --- sdk/javascript/retrieve-conversations.mdx | 18 ++---------------- 1 file changed, 2 insertions(+), 16 deletions(-) diff --git a/sdk/javascript/retrieve-conversations.mdx b/sdk/javascript/retrieve-conversations.mdx index 1c1b456ac..70b095102 100644 --- a/sdk/javascript/retrieve-conversations.mdx +++ b/sdk/javascript/retrieve-conversations.mdx @@ -24,7 +24,7 @@ const conversation = await CometChat.CometChatHelper.getConversationFromMessage( ``` -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. +Conversations provide the last message for every one-on-one and group conversation the logged-in user is part of. Each [`Conversation`](/sdk/reference/entities#conversation) object includes the other participant (user or group), the last message, unread counts, and optional tags. Use this to build a Recent Chats list. ## Retrieve List of Conversations @@ -447,7 +447,7 @@ When conversations are fetched successfully, the response includes only AI agent ### Fetch Conversations -Call `build()` to create the request, then `fetchNext()` to retrieve conversations. Maximum 50 per request. +After configuring the builder, call `build()` to create the request, then `fetchNext()` to retrieve conversations. Maximum 50 per request. Call `fetchNext()` repeatedly on the same object to paginate. @@ -490,20 +490,6 @@ conversationsRequest.fetchNext().then( -The [`Conversation`](/sdk/reference/entities#conversation) object contains: - -| 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: | Field | Getter | Return Type | Description | From ed9adc29cebfe79cec1d9ddc1bf74b44978794b0 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 25 Mar 2026 20:06:22 +0530 Subject: [PATCH 065/139] Update retrieve-groups.mdx --- sdk/javascript/retrieve-groups.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/javascript/retrieve-groups.mdx b/sdk/javascript/retrieve-groups.mdx index 33343fdec..7bb5cf0c7 100644 --- a/sdk/javascript/retrieve-groups.mdx +++ b/sdk/javascript/retrieve-groups.mdx @@ -25,6 +25,8 @@ const count = await CometChat.getOnlineGroupMemberCount(["GUID"]); ``` +Fetch the list of [`Group`](/sdk/reference/entities#group) objects the logged-in user can see, get details for a specific group, or check online member counts. + ## Retrieve List of Groups Use `GroupsRequestBuilder` to fetch groups with filtering, searching, and pagination. @@ -271,8 +273,6 @@ group => { | --------- | ----------- | | `GUID` | The GUID of the group to fetch | -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: | Field | Getter | Return Type | Description | From f063bd6265fb5ffdcf289ce9416cfac58791e399 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 25 Mar 2026 20:32:56 +0530 Subject: [PATCH 066/139] Update overview.mdx --- sdk/javascript/overview.mdx | 3 +++ 1 file changed, 3 insertions(+) diff --git a/sdk/javascript/overview.mdx b/sdk/javascript/overview.mdx index 2da77b008..2b3cf997a 100644 --- a/sdk/javascript/overview.mdx +++ b/sdk/javascript/overview.mdx @@ -120,6 +120,9 @@ For the fastest integration, embed the [Chat Widget](/widget/html/overview) with UIDs, GUIDs, auth tokens, and core SDK concepts + + Message categories, types, and hierarchy + Latest SDK version and release notes From 6648c3e078deb0bdef29cfc17f3623a9280eee1a Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 13:48:01 +0530 Subject: [PATCH 067/139] Update authentication-overview.mdx --- sdk/javascript/authentication-overview.mdx | 109 ++++++++------------- 1 file changed, 40 insertions(+), 69 deletions(-) diff --git a/sdk/javascript/authentication-overview.mdx b/sdk/javascript/authentication-overview.mdx index 537e90ac9..d1c9258ce 100644 --- a/sdk/javascript/authentication-overview.mdx +++ b/sdk/javascript/authentication-overview.mdx @@ -25,14 +25,9 @@ CometChat.logout().then(() => console.log("Logged out")); **Test UIDs:** `cometchat-uid-1` through `cometchat-uid-5` -## Create User +After [initializing](/sdk/javascript/initialization) the SDK, the next step is to authenticate your user. CometChat provides two login methods — Auth Key for quick development, and Auth Token for production — both accessed through the `login()` method. -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 +### How It Works ```mermaid sequenceDiagram @@ -52,28 +47,34 @@ sequenceDiagram CometChat-->>YourApp: User object (logged in) ``` - +## Before You Log In -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`. +### Create a User - +A user must exist in CometChat before they can log in. -Once initialization is successful, you will need to log the user into CometChat using the `login()` method. +- **During development:** Create users from the [CometChat Dashboard](https://app.cometchat.com). Five test users are already available with UIDs `cometchat-uid-1` through `cometchat-uid-5`. +- **In production:** Call the [Create User REST API](https://api-explorer.cometchat.com/reference/creates-user) when a user signs up in your app. -We recommend you call the CometChat login method once your user logs into your app. The `login()` method needs to be called only once. +### Check for an Existing Session - +The SDK persists the logged-in user's session locally. Before calling `login()`, always check whether a session already exists — this avoids unnecessary login calls and keeps your app responsive. -The CometChat SDK maintains the session of the logged-in user within the SDK. Thus you do not need to call the login method for every session. You can use the CometChat.getLoggedinUser() method to check if there is any existing session in the SDK. This method should return the details of the logged-in user. If this method returns null, it implies there is no session present within the SDK and you need to log the user into CometChat. +```javascript +const user = await CometChat.getLoggedinUser(); +if (user) { + // User is already logged in — proceed to your app +} +``` - +If `getLoggedinUser()` returns `null`, no active session exists and you need to call `login()`. -## Login using Auth Key +## Login with Auth Key -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 login is the simplest way to get started. Pass a UID and your Auth Key directly from the client. -**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. +Auth Keys are meant for development and testing only. For production, use [Auth Token login](#login-with-auth-token) instead. Never ship Auth Keys in client-side code. @@ -100,7 +101,6 @@ CometChat.getLoggedinUser().then( } ); ``` - @@ -126,7 +126,6 @@ CometChat.getLoggedinUser().then( } ); ``` - @@ -144,25 +143,23 @@ try { console.log("Login failed with exception:", { error }); } ``` - - -| Parameters | Description | -| ---------- | ------------------------------------------------ | -| UID | The UID of the user that you would like to login | -| authKey | CometChat Auth Key | +| Parameter | Description | +| --------- | ----------- | +| UID | The UID of the user to log in | +| authKey | Your CometChat Auth Key | -After the user logs in, their information is returned in the `User` object on `Promise` resolved. +On success, the `Promise` resolves with a `User` object containing the logged-in user's details. -## Login using Auth Token +## Login with Auth Token -This advanced authentication procedure does not use the Auth Key directly in your client code thus ensuring safety. +Auth Token login keeps your Auth Key off the client entirely. Your server generates a token via the REST API and passes it to the client. -1. [Create a User](https://api-explorer.cometchat.com/reference/creates-user) via the CometChat API when the user signs up in your app. -2. [Create an Auth Token](https://api-explorer.cometchat.com/reference/create-authtoken) via the CometChat API for the new user and save the token in your database. -3. Load the Auth Token in your client and pass it to the `login()` method. +1. [Create the user](https://api-explorer.cometchat.com/reference/creates-user) via the REST API when they sign up (first time only). +2. [Generate an Auth Token](https://api-explorer.cometchat.com/reference/create-authtoken) on your server and return it to the client. +3. Pass the token to `login()`. @@ -187,7 +184,6 @@ CometChat.getLoggedinUser().then( } ); ``` - @@ -212,7 +208,6 @@ CometChat.getLoggedinUser().then( } ); ``` - @@ -229,20 +224,18 @@ try { console.log("Login failed with exception:", { error }); } ``` - - -| Parameter | Description | -| --------- | ---------------------------------------------- | -| authToken | Auth Token of the user you would like to login | +| Parameter | Description | +| --------- | ----------- | +| authToken | Auth Token generated on your server for the user | -After the user logs in, their information is returned in the `User` object on the `Promise` resolved. +On success, the `Promise` resolves with a `User` object containing the logged-in user's details. ## Logout -You can use the `logout()` method to log out the user from CometChat. We suggest you call this method once your user has been successfully logged out from your app. +Call `logout()` when your user logs out of your app. This clears the local session. @@ -256,7 +249,6 @@ CometChat.logout().then( } ); ``` - @@ -270,7 +262,6 @@ CometChat.logout().then( } ); ``` - @@ -282,25 +273,23 @@ try { console.log("Logout failed with exception:", { error }); } ``` - - --- ## Login Listener -The CometChat SDK provides real-time updates for `login` and `logout` events via the `LoginListener` class. +You can listen for login and logout events in real time using `LoginListener`. This is useful for updating UI state or triggering side effects when the auth state changes. -| Delegate Method | Description | +| Callback | Description | | --- | --- | | `loginSuccess(event)` | User logged in successfully. Provides the `User` object. | | `loginFailure(event)` | Login failed. Provides a `CometChatException`. | | `logoutSuccess()` | User logged out successfully. | | `logoutFailure(event)` | Logout failed. Provides a `CometChatException`. | -### Add Login Listener +### Add a Listener @@ -324,7 +313,6 @@ CometChat.addLoginListener( }) ); ``` - @@ -348,32 +336,15 @@ CometChat.addLoginListener( }) ); ``` - - -### Remove Login Listener - - - -```typescript -const listenerID: string = "UNIQUE_LISTENER_ID"; -CometChat.removeLoginListener(listenerID); -``` +### Remove a Listener - - - -```js -const listenerID = "UNIQUE_LISTENER_ID"; -CometChat.removeLoginListener(listenerID); +```javascript +CometChat.removeLoginListener("UNIQUE_LISTENER_ID"); ``` - - - - 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. From 5c90b81254623f3ed2e2eb7827ca17fb0f1cd7b4 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 14:06:52 +0530 Subject: [PATCH 068/139] Update receive-message.mdx --- sdk/javascript/receive-message.mdx | 853 +++++------------------------ 1 file changed, 152 insertions(+), 701 deletions(-) diff --git a/sdk/javascript/receive-message.mdx b/sdk/javascript/receive-message.mdx index 798325a4b..3881e7440 100644 --- a/sdk/javascript/receive-message.mdx +++ b/sdk/javascript/receive-message.mdx @@ -17,16 +17,16 @@ description: "Receive real-time messages, fetch missed and unread messages, retr Receiving messages with CometChat has two parts: -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 +1. Adding a [real-time listener](#real-time-messages) to receive messages while your app is running +2. Fetching [missed](#missed-messages), [unread](#unread-messages), or [historical](#message-history) messages when your app starts up or the user scrolls back -## Real-Time Messages + +The TypeScript and JavaScript APIs are identical — the only difference is type annotations (e.g., `: string`, `: CometChat.BaseMessage[]`). The Real-Time Messages section shows both for reference. The remaining sections use TypeScript only to keep things concise — just drop the type annotations for plain JavaScript. + -Register the `MessageListener` to receive incoming messages in real-time using `addMessageListener()`. +## Real-Time Messages - -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 a `MessageListener` to receive incoming messages as they arrive. Each callback receives the specific message subclass — [`TextMessage`](/sdk/reference/messages#textmessage), [`MediaMessage`](/sdk/reference/messages#mediamessage), or [`CustomMessage`](/sdk/reference/messages#custommessage). @@ -48,7 +48,6 @@ CometChat.addMessageListener( }) ); ``` - @@ -70,43 +69,28 @@ CometChat.addMessageListener( }) ); ``` - - | Parameter | Description | | --- | --- | -| `listenerID` | An ID that uniquely identifies that listener | - -Remove the listener when you no longer need to receive messages: - - - -```typescript -let listenerID: string = "UNIQUE_LISTENER_ID"; +| `listenerID` | An ID that uniquely identifies that listener. Use the same ID to remove it later. | -CometChat.removeMessageListener(listenerID); -``` - - +Remove the listener when you no longer need it: - ```javascript -let listenerID = "UNIQUE_LISTENER_ID"; - -CometChat.removeMessageListener(listenerID); +CometChat.removeMessageListener("UNIQUE_LISTENER_ID"); ``` - - - + +Always remove listeners when they're no longer needed (e.g., on component unmount). Failing to do so can cause memory leaks and duplicate event handling. + -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. +As a sender, you will not receive your own message in a real-time event. However, if a user is logged in on multiple devices, they will receive the event on the 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: +### Message Fields | Field | Getter | Return Type | Description | |-------|--------|-------------|-------------| @@ -119,24 +103,21 @@ Each listener callback receives the specific message subclass — [`TextMessage` ## Missed Messages -Fetch messages that were sent while your app was offline using `MessagesRequestBuilder` with `setMessageId()` and `fetchNext()`. - -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 +Fetch messages that arrived while your app was offline. Use `getLastDeliveredMessageId()` to find where you left off, then call `fetchNext()` to get everything after that point. Call `fetchNext()` repeatedly on the same request object to paginate. - + ```typescript -let UID: string = "UID", - limit: number = 30, - latestId: number = await CometChat.getLastDeliveredMessageId(), - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setMessageId(latestId) - .setLimit(limit) - .build(); +let UID: string = "UID"; +let limit: number = 30; +let latestId: number = await CometChat.getLastDeliveredMessageId(); + +let messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setMessageId(latestId) + .setLimit(limit) + .build(); messagesRequest.fetchNext().then( (messages: CometChat.BaseMessage[]) => { @@ -147,49 +128,20 @@ messagesRequest.fetchNext().then( } ); ``` - - -```javascript -let UID = "UID"; -let limit = 30; -let latestId = await CometChat.getLastDeliveredMessageId(); - -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setMessageId(latestId) - .setLimit(limit) - .build(); - -messagesRequest.fetchNext().then( - (messages) => { - console.log("Message list fetched:", messages); - }, - (error) => { - console.log("Message fetching failed with error:", error); - } -); -``` - - - - - -### Fetch Missed Messages of a particular group conversation - - - + ```typescript -let GUID: string = "GUID", - limit: number = 30, - latestId: number = await CometChat.getLastDeliveredMessageId(), - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setMessageId(latestId) - .setLimit(limit) - .build(); +let GUID: string = "GUID"; +let limit: number = 30; +let latestId: number = await CometChat.getLastDeliveredMessageId(); + +let messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setMessageId(latestId) + .setLimit(limit) + .build(); messagesRequest.fetchNext().then( (messages: CometChat.BaseMessage[]) => { @@ -200,36 +152,12 @@ messagesRequest.fetchNext().then( } ); ``` - - - -```javascript -let GUID = "GUID"; -let limit = 30; -let latestId = await CometChat.getLastDeliveredMessageId(); - -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setMessageId(latestId) - .setLimit(limit) - .build(); - -messagesRequest.fetchNext().then( - (messages) => { - console.log("Message list fetched:", messages); - }, - (error) => { - console.log("Message fetching failed with error:", error); - } -); -``` - - - -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: +The only difference between one-on-one and group is `setUID(UID)` vs `setGUID(GUID)`. This pattern applies to all the builder-based methods below. + +`fetchNext()` 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 | |-------|--------|-------------|-------------| @@ -241,21 +169,20 @@ The `fetchNext()` method returns an array of [`BaseMessage`](/sdk/reference/mess ## Unread Messages -Fetch unread messages by setting `setUnread(true)` on the builder. - -### Fetch Unread Messages of a particular one-on-one conversation +Fetch unread messages by adding `setUnread(true)` to the builder. Use `fetchPrevious()` to retrieve them. - + ```typescript -let UID: string = "UID", - limit: number = 30, - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setUnread(true) - .setLimit(limit) - .build(); +let UID: string = "UID"; +let limit: number = 30; + +let messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setUnread(true) + .setLimit(limit) + .build(); messagesRequest.fetchPrevious().then( (messages: CometChat.BaseMessage[]) => { @@ -266,46 +193,19 @@ messagesRequest.fetchPrevious().then( } ); ``` - - - - -```javascript -let UID = "UID"; -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setUnread(true) - .setLimit(limit) - .build(); - -messagesRequest.fetchPrevious().then( - (messages) => { - console.log("Message list fetched:", messages); - }, - (error) => { - console.log("Message fetching failed with error:", error); - } -); -``` - - - -### Fetch Unread Messages of a particular group conversation - - - + ```typescript -let GUID: string = "GUID", - limit: number = 30, - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setUnread(true) - .setLimit(limit) - .build(); +let GUID: string = "GUID"; +let limit: number = 30; + +let messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setUnread(true) + .setLimit(limit) + .build(); messagesRequest.fetchPrevious().then( (messages: CometChat.BaseMessage[]) => { @@ -316,52 +216,28 @@ messagesRequest.fetchPrevious().then( } ); ``` - - - -```javascript -let GUID = "GUID"; -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setUnread(true) - .setLimit(limit) - .build(); - -messagesRequest.fetchPrevious().then( - (messages) => { - console.log("Message list fetched:", messages); - }, - (error) => { - console.log("Message fetching failed with error:", error); - } -); -``` - - - -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. +Results are returned as [`BaseMessage`](/sdk/reference/messages#basemessage) objects, which may be instances of [`TextMessage`](/sdk/reference/messages#textmessage), [`MediaMessage`](/sdk/reference/messages#mediamessage), [`CustomMessage`](/sdk/reference/messages#custommessage), `Action`, or `Call`. Use the `instanceof` operator to check the type. ## 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 - -Set the UID using `setUID()` to fetch the conversation with a specific user. +Fetch the full conversation history using `fetchPrevious()`. Call it repeatedly on the same request object to paginate — useful for implementing upward scrolling. - + ```typescript -let UID: string = "UID", - limit: number = 30, - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder().setUID(UID).setLimit(limit).build(); +let UID: string = "UID"; +let limit: number = 30; + +let messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setLimit(limit) + .build(); messagesRequest.fetchPrevious().then( (messages: CometChat.BaseMessage[]) => { @@ -372,46 +248,18 @@ messagesRequest.fetchPrevious().then( } ); ``` - - - - -```javascript -let UID = "UID"; -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setLimit(limit) - .build(); - -messagesRequest.fetchPrevious().then( - (messages) => { - console.log("Message list fetched:", messages); - }, - (error) => { - console.log("Message fetching failed with error:", error); - } -); -``` - - - -### Fetch Message History of a particular group conversation - -Set the GUID using `setGUID()` to fetch messages from a group you've joined. - - - + ```typescript -let GUID: string = "GUID", - limit: number = 30, - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setLimit(limit) - .build(); +let GUID: string = "GUID"; +let limit: number = 30; + +let messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setLimit(limit) + .build(); messagesRequest.fetchPrevious().then( (messages: CometChat.BaseMessage[]) => { @@ -422,33 +270,10 @@ messagesRequest.fetchPrevious().then( } ); ``` - - - -```javascript -let GUID = "GUID"; -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setLimit(limit) - .build(); - -messagesRequest.fetchPrevious().then( - (messages) => { - console.log("Message list fetched:", messages); - }, - (error) => { - console.log("Message fetching failed with error:", error); - } -); -``` - - - -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: +### Message Fields | Field | Getter | Return Type | Description | |-------|--------|-------------|-------------| @@ -460,35 +285,21 @@ The `fetchPrevious()` method returns an array of [`BaseMessage`](/sdk/reference/ ## Search Messages -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 | -| ---------------- | ------------ | -------------- | -| Text search | ✅ | ✅ | -| File name search | ❌ | ✅ | -| Mentions search | ❌ | ✅ | -| Mime type search | ❌ | ✅ | - -### Search Messages in a particular one-on-one conversation +Add `setSearchKeyword()` to the builder to filter messages by keyword. - + ```typescript -let UID: string = "UID", - limit: number = 30, - searchKeyword: string = "Hello", - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setLimit(limit) - .setSearchKeyword(searchKeyword) - .build(); +let UID: string = "UID"; +let limit: number = 30; +let searchKeyword: string = "Hello"; + +let messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setLimit(limit) + .setSearchKeyword(searchKeyword) + .build(); messagesRequest.fetchPrevious().then( (messages: CometChat.BaseMessage[]) => { @@ -499,48 +310,20 @@ messagesRequest.fetchPrevious().then( } ); ``` - - -```javascript -let UID = "UID"; -let limit = 30; -let searchKeyword = "Hello"; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setLimit(limit) - .setSearchKeyword(searchKeyword) - .build(); - -messagesRequest.fetchPrevious().then( - (messages) => { - console.log("Message list fetched:", messages); - }, - (error) => { - console.log("Message fetching failed with error:", error); - } -); -``` - - - - - -### Search Messages in a particular group conversation - - - + ```typescript -let GUID: string = "GUID", - limit: number = 30, - searchKeyword: string = "Hello", - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setLimit(limit) - .setSearchKeyword(searchKeyword) - .build(); +let GUID: string = "GUID"; +let limit: number = 30; +let searchKeyword: string = "Hello"; + +let messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setLimit(limit) + .setSearchKeyword(searchKeyword) + .build(); messagesRequest.fetchPrevious().then( (messages: CometChat.BaseMessage[]) => { @@ -551,422 +334,90 @@ messagesRequest.fetchPrevious().then( } ); ``` - - - -```javascript -let GUID = "GUID"; -let limit = 30; -let searchKeyword = "Hello"; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setLimit(limit) - .setSearchKeyword(searchKeyword) - .build(); - -messagesRequest.fetchPrevious().then( - (messages) => { - console.log("Message list fetched:", messages); - }, - (error) => { - console.log("Message fetching failed with error:", error); - } -); -``` - - - -## Unread Message Count - -Get the number of unread messages for users, groups, or all conversations. - -### Fetch Unread Message Count of a particular one-on-one conversation - -Use `getUnreadMessageCountForUser()` to get the unread count for a specific user. - - - -```typescript -let UID: string = "UID"; -CometChat.getUnreadMessageCountForUser(UID); -``` - - +### Search Capabilities - -```javascript -CometChat.getUnreadMessageCountForUser(UID); -``` +By default, search only matches message text. With `Conversation & Advanced Search` enabled, it also matches file names, mentions, and MIME types. - +| Feature | Basic Search | Advanced Search | +| ---------------- | ------------ | --------------- | +| Text search | ✅ | ✅ | +| File name search | ❌ | ✅ | +| Mentions search | ❌ | ✅ | +| MIME type search | ❌ | ✅ | - - -To ignore messages from blocked users, set the boolean parameter to true: + +`Conversation & Advanced Search` is available on `Advanced` and `Custom` [plans](https://www.cometchat.com/pricing). Enable it from the [CometChat Dashboard](https://app.cometchat.com) under Chats → Settings → General Configuration. + - - -```typescript -let UID: string = "UID", - hideMessagesFromBlockedUsers: boolean = true; -CometChat.getUnreadMessageCountForUser(UID, hideMessagesFromBlockedUsers); -``` +## Unread Message Count - +CometChat provides several methods to get unread counts at different scopes. All return a `Promise` that resolves with an object mapping IDs to counts. - -```javascript -CometChat.getUnreadMessageCountForUser(UID, hideMessagesFromBlockedUsers); -``` +Each method accepts an optional boolean parameter to exclude messages from blocked users. - +| Method | Scope | Returns | +| --- | --- | --- | +| `getUnreadMessageCountForUser(UID)` | Single user conversation | `{ [UID]: count }` | +| `getUnreadMessageCountForGroup(GUID)` | Single group conversation | `{ [GUID]: count }` | +| `getUnreadMessageCountForAllUsers()` | All user conversations | `{ [UID]: count, ... }` | +| `getUnreadMessageCountForAllGroups()` | All group conversations | `{ [GUID]: count, ... }` | +| `getUnreadMessageCount()` | Everything | `{ users: { ... }, groups: { ... } }` | - +### Single Conversation - - ```typescript +// One-on-one let UID: string = "UID"; - CometChat.getUnreadMessageCountForUser(UID).then( - (unreadMessageCount: Object) => { - console.log("Unread message count fetched", unreadMessageCount); - }, - (error: CometChat.CometChatException) => { - console.log("Error in getting unread message count", error); - } + (count: Object) => console.log("Unread count:", count), + (error: CometChat.CometChatException) => console.log("Error:", error) ); -``` - - - - -```javascript -let UID = "UID"; - -CometChat.getUnreadMessageCountForUser(UID).then( - (unreadMessageCountObject) => { - console.log("Unread message count fetched", unreadMessageCountObject); - }, - (error) => { - console.log("Error in getting unread message count", error); - } -); -``` - - - - - -Returns an object with the UID as key and unread message count as value. - -### Fetch Unread Message Count of a particular group conversation - -Use `getUnreadMessageCountForGroup()` to get the unread count for a specific group. - - -```typescript +// Group let GUID: string = "GUID"; -CometChat.getUnreadMessageCountForGroup(GUID); -``` - - - - -```javascript -CometChat.getUnreadMessageCountForGroup(GUID); -``` - - - - - -To ignore messages from blocked users, set the boolean parameter to true: - - - -```typescript -let GUID: string = "GUID", - hideMessagesFromBlockedUsers: boolean = true; -CometChat.getUnreadMessageCountForGroup(GUID, hideMessagesFromBlockedUsers); -``` - - - - -```javascript -CometChat.getUnreadMessageCountForGroup(GUID, hideMessagesFromBlockedUsers); -``` - - - - - - - -```typescript -let GUID: string = "GUID"; - CometChat.getUnreadMessageCountForGroup(GUID).then( - (unreadMessageCount: Object) => { - console.log("Unread message count fetched", unreadMessageCount); - }, - (error: CometChat.CometChatException) => { - console.log("Error in getting unread message count", error); - } + (count: Object) => console.log("Unread count:", count), + (error: CometChat.CometChatException) => console.log("Error:", error) ); ``` - +### All Conversations - -```javascript -let GUID = "GUID"; - -CometChat.getUnreadMessageCountForGroup(GUID).then( - (unreadMessageCountObject) => { - console.log("Unread message count fetched", unreadMessageCountObject); - }, - (error) => { - console.log("Error in getting unread message count", error); - } -); -``` - - - - - -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 - -Use `getUnreadMessageCount()` to get unread counts for all users and groups combined. - - - -```typescript -CometChat.getUnreadMessageCount(); -``` - - - - -```javascript -CometChat.getUnreadMessageCount(); -``` - - - - - -To ignore messages from blocked users, set the boolean parameter to true: - - - -```typescript -let hideMessagesFromBlockedUsers: boolean = true; -CometChat.getUnreadMessageCount(hideMessagesFromBlockedUsers); -``` - - - - -```javascript -CometChat.getUnreadMessageCount(hideMessagesFromBlockedUsers); -``` - - - - - - - ```typescript +// All users and groups combined CometChat.getUnreadMessageCount().then( - (unreadMessageCount: Object) => { - console.log("Unread message count fetched", unreadMessageCount); - }, - (error: CometChat.CometChatException) => { - console.log("Error in getting unread message count", error); - } + (count: Object) => console.log("Unread count:", count), + (error: CometChat.CometChatException) => console.log("Error:", error) ); -``` - - - -```javascript -CometChat.getUnreadMessageCount().then( - (unreadMessageCountObject) => { - console.log("Unread message count fetched", unreadMessageCountObject); - }, - (error) => { - console.log("Error in getting unread message count", error); - } -); -``` - - - - - -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 - -Use `getUnreadMessageCountForAllUsers()` to get unread counts for all user conversations. - - - -```typescript -CometChat.getUnreadMessageCountForAllUsers(); -``` - - - - -```javascript -CometChat.getUnreadMessageCountForAllUsers(); -``` - - - - - -To ignore messages from blocked users, set the boolean parameter to true: - - - -```typescript -let hideMessagesFromBlockedUsers: boolean = true; -CometChat.getUnreadMessageCountForAllUsers(hideMessagesFromBlockedUsers); -``` - - - - -```javascript -CometChat.getUnreadMessageCountForAllUsers(hideMessagesFromBlockedUsers); -``` - - - - - - - -```typescript +// All user conversations only CometChat.getUnreadMessageCountForAllUsers().then( - (unreadMessageCount: Object) => { - console.log("Unread message count fetched", unreadMessageCount); - }, - (error: CometChat.CometChatException) => { - console.log("Error in getting unread message count", error); - } + (count: Object) => console.log("Unread count:", count), + (error: CometChat.CometChatException) => console.log("Error:", error) ); -``` - - - -```javascript -CometChat.getUnreadMessageCountForAllUsers().then( - (unreadMessageCountObject) => { - console.log("Unread message count fetched", unreadMessageCountObject); - }, - (error) => { - console.log("Error in getting unread message count", error); - } +// All group conversations only +CometChat.getUnreadMessageCountForAllGroups().then( + (count: Object) => console.log("Unread count:", count), + (error: CometChat.CometChatException) => console.log("Error:", error) ); ``` - - - - -Returns an object with UIDs as keys and unread counts as values. - -### Fetch Unread Message Count of all group conversations - -Use `getUnreadMessageCountForAllGroups()` to get unread counts for all group conversations. - - - -```typescript -CometChat.getUnreadMessageCountForAllGroups(); -``` - - - - -```javascript -CometChat.getUnreadMessageCountForAllGroups(); -``` - - - - - -To ignore messages from blocked users, set the boolean parameter to true: - - - -```typescript -let hideMessagesFromBlockedUsers: boolean = true; -CometChat.getUnreadMessageCountForAllGroups(hideMessagesFromBlockedUsers); -``` - - +### Excluding Blocked Users - -```javascript -CometChat.getUnreadMessageCountForAllGroups(hideMessagesFromBlockedUsers); -``` - - - - +Pass `true` as the last argument to any of the methods above: - - ```typescript -CometChat.getUnreadMessageCountForAllGroups().then( - (unreadMessageCount: Object) => { - console.log("Unread message count fetched", unreadMessageCount); - }, - (error: CometChat.CometChatException) => { - console.log("Error in getting unread message count", error); - } -); +CometChat.getUnreadMessageCountForUser(UID, true); +CometChat.getUnreadMessageCountForGroup(GUID, true); +CometChat.getUnreadMessageCount(true); +CometChat.getUnreadMessageCountForAllUsers(true); +CometChat.getUnreadMessageCountForAllGroups(true); ``` - - - -```javascript -CometChat.getUnreadMessageCountForAllGroups().then( - (unreadMessageCountObject) => { - console.log("Unread message count fetched", unreadMessageCountObject); - }, - (error) => { - console.log("Error in getting unread message count", error); - } -); -``` - - - - - -Returns an object with GUIDs as keys and unread counts as values. - --- ## Next Steps From a657e7c84cd76af3f99c5d219f0ec914d08ad541 Mon Sep 17 00:00:00 2001 From: PrajwalDhuleCC Date: Thu, 26 Mar 2026 14:37:54 +0530 Subject: [PATCH 069/139] docs(sdk): Remove redundant Call field tables and add Reaction reference - Remove duplicate Call object field reference tables from call-logs.mdx and default-call.mdx, keeping only links to canonical reference - Remove redundant Call field table from call listener callbacks documentation - Add new Reaction class documentation to auxiliary.mdx with properties and getter methods - Update recording.mdx examples to remove unused event parameter from onRecordingStopped callback - Add documentation for onRecordingStarted and onRecordingStopped callback signatures and parameters - Update auxiliary.mdx description to include Reaction in the list of covered classes - Consolidate Call object documentation to single reference location to reduce duplication --- sdk/javascript/call-logs.mdx | 11 +--- sdk/javascript/default-call.mdx | 22 +------ sdk/javascript/recording.mdx | 20 ++++-- sdk/reference/auxiliary.mdx | 19 +++++- sdk/reference/calls.mdx | 104 ++++++++++++++++++++++++++++++++ 5 files changed, 140 insertions(+), 36 deletions(-) create mode 100644 sdk/reference/calls.mdx diff --git a/sdk/javascript/call-logs.mdx b/sdk/javascript/call-logs.mdx index 221a7a895..5aac4130d 100644 --- a/sdk/javascript/call-logs.mdx +++ b/sdk/javascript/call-logs.mdx @@ -102,16 +102,7 @@ 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 | +The `fetchNext()` and `fetchPrevious()` methods return an array of [`CallLog`](/sdk/reference/calls#calllog) objects. ## Get Call Details diff --git a/sdk/javascript/default-call.mdx b/sdk/javascript/default-call.mdx index 8f62558b4..e8fd6ca27 100644 --- a/sdk/javascript/default-call.mdx +++ b/sdk/javascript/default-call.mdx @@ -139,18 +139,8 @@ CometChat.initiateCall(call).then( | `receiverType` | `CometChat.RECEIVER_TYPE.USER` or `CometChat.RECEIVER_TYPE.GROUP` | | `callType` | `CometChat.CALL_TYPE.AUDIO` or `CometChat.CALL_TYPE.VIDEO` | -On success, a `Call` object is returned containing the call details including a unique `sessionId` required for starting the call session. +On success, a [`Call`](/sdk/reference/messages#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 @@ -234,15 +224,7 @@ 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 | +All call listener callbacks receive a [`Call`](/sdk/reference/messages#call) object. ## Accept Call diff --git a/sdk/javascript/recording.mdx b/sdk/javascript/recording.mdx index a7d57a68f..3f6b90d06 100644 --- a/sdk/javascript/recording.mdx +++ b/sdk/javascript/recording.mdx @@ -17,7 +17,7 @@ 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), + onRecordingStopped: () => console.log("Recording stopped"), }); ``` @@ -52,8 +52,8 @@ const audioOnly = false; const callListener = new CometChatCalls.OngoingCallListener({ onRecordingStarted: (event) => console.log("Listener => onRecordingStarted", event.user), - onRecordingStopped: (event) => - console.log("Listener => onRecordingStopped", event.user), + onRecordingStopped: () => + console.log("Listener => onRecordingStopped"), }); const callSettings = new CometChatCalls.CallSettingsBuilder() @@ -77,8 +77,8 @@ const audioOnly = false; const callListener = new CometChatCalls.OngoingCallListener({ onRecordingStarted: (event) => console.log("Listener => onRecordingStarted", event.user), - onRecordingStopped: (event) => - console.log("Listener => onRecordingStopped", event.user), + onRecordingStopped: () => + console.log("Listener => onRecordingStopped"), }); const callSettings = new CometChatCalls.CallSettingsBuilder() @@ -95,6 +95,16 @@ CometChatCalls.startSession(callToken, callSettings, htmlElement); +The `onRecordingStarted` callback receives an event object: + +| Property | Type | Description | +|----------|------|-------------| +| `event.user` | `object` | The user who started the recording | +| `event.user.name` | `string` | Display name of the user | +| `event.user.uid` | `string` | UID of the user | + +The `onRecordingStopped` callback receives no arguments. + ## 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. diff --git a/sdk/reference/auxiliary.mdx b/sdk/reference/auxiliary.mdx index 8bf7179f6..dc0276d5f 100644 --- a/sdk/reference/auxiliary.mdx +++ b/sdk/reference/auxiliary.mdx @@ -1,6 +1,6 @@ --- title: "Auxiliary" -description: "Class reference for auxiliary objects returned by CometChat SDK methods. Covers MessageReceipt, ReactionCount, ReactionEvent, TypingIndicator, TransientMessage, and Attachment." +description: "Class reference for auxiliary objects returned by CometChat SDK methods. Covers MessageReceipt, Reaction, 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. @@ -28,6 +28,23 @@ All properties are accessed via getter methods. --- +## Reaction + +`Reaction` represents an individual user's reaction on a message. It is returned by `fetchNext()` and `fetchPrevious()` on a `ReactionsRequest` object, and is also available within a `ReactionEvent`. + +### Properties + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| id | `getReactionId()` | `string` | Unique identifier for this reaction | +| messageId | `getMessageId()` | `string` | ID of the message this reaction belongs to | +| reaction | `getReaction()` | `string` | The reaction emoji (e.g., `"😀"`, `"👍"`) | +| uid | `getUid()` | `string` | UID of the user who reacted | +| reactedAt | `getReactedAt()` | `number` | Timestamp when the reaction was added (epoch seconds) | +| reactedBy | `getReactedBy()` | `User` | The user who added this reaction | + +--- + ## ReactionCount `ReactionCount` represents the count of a specific reaction on a message. It is available via `getReactions()` on a `BaseMessage` object. diff --git a/sdk/reference/calls.mdx b/sdk/reference/calls.mdx new file mode 100644 index 000000000..7eea32d64 --- /dev/null +++ b/sdk/reference/calls.mdx @@ -0,0 +1,104 @@ +--- +title: "Calls" +description: "Class reference for objects returned by the CometChat Calls SDK. Covers CallLog, CallUser, CallGroup, Participant, and Recording." +--- + +This page documents the classes used in the CometChat Calls SDK. These objects are returned by call log queries and call session methods. + +All properties on proper classes are accessed via getter methods. Listener event objects are plain objects accessed via dot notation. + +--- + +## CallLog + +`CallLog` represents a call history entry. It is returned by `CallLogRequestBuilder.fetchNext()` and `CallLogRequestBuilder.fetchPrevious()`. + +### Properties + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| sessionId | `getSessionID()` | `string` | Unique session ID of the call | +| totalAudioMinutes | `getTotalAudioMinutes()` | `number` | Total audio minutes in the call | +| totalVideoMinutes | `getTotalVideoMinutes()` | `number` | Total video minutes in the call | +| totalDuration | `getTotalDuration()` | `string` | Total duration of the call as a formatted string | +| totalDurationInMinutes | `getTotalDurationInMinutes()` | `number` | Total duration in minutes | +| hasRecording | `getHasRecording()` | `boolean` | Whether the call has a recording | +| initiatedAt | `getInitiatedAt()` | `number` | Timestamp when the call was initiated | +| endedAt | `getEndedAt()` | `number` | Timestamp when the call ended | +| callCategory | `getCallCategory()` | `string` | Category of the call (`"call"` or `"meet"`) | +| type | `getType()` | `string` | Type of the call (`"audio"` or `"video"`) | +| status | `getStatus()` | `string` | Status of the call (`"ongoing"`, `"ended"`, `"cancelled"`, etc.) | +| receiverType | `getReceiverType()` | `string` | Receiver type (`"user"` or `"group"`) | +| totalParticipants | `getTotalParticipants()` | `number` | Total number of participants | +| mid | `getMid()` | `string` | Message ID associated with the call | +| initiator | `getInitiator()` | [`CallUser`](#calluser) | The user who initiated the call | +| receiver | `getReceiver()` | [`CallUser`](#calluser) \| [`CallGroup`](#callgroup) | The user or group that received the call | +| participants | `getParticipants()` | [`Participant[]`](#participant) | Array of call participants | +| recordings | `getRecordings()` | [`Recording[]`](#recording) | Array of call recordings | + +--- + +## CallUser + +`CallUser` represents a user within the Calls SDK context (used in `CallLog` as initiator/receiver). + +### 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 | + +--- + +## CallGroup + +`CallGroup` represents a group within the Calls SDK context (used in `CallLog` as receiver for group calls). + +### Properties + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| guid | `getGuid()` | `string` | Unique group ID | +| name | `getName()` | `string` | Display name of the group | +| icon | `getIcon()` | `string` | URL of the group icon | + +--- + +## Participant + +`Participant` represents a user who participated in a call. It is available via `getParticipants()` on a [`CallLog`](#calllog) object. + +### Properties + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| uid | `getUid()` | `string` | Unique user ID | +| name | `getName()` | `string` | Display name of the participant | +| avatar | `getAvatar()` | `string` | URL of the participant's avatar | +| totalAudioMinutes | `getTotalAudioMinutes()` | `number` | Audio minutes for this participant | +| totalVideoMinutes | `getTotalVideoMinutes()` | `number` | Video minutes for this participant | +| totalDurationInMinutes | `getTotalDurationInMinutes()` | `number` | Total duration in minutes for this participant | +| deviceID | `getDeviceID()` | `string` | Device ID of the participant | +| hasJoined | `getHasJoined()` | `boolean` | Whether the participant joined the call | +| joinedAt | `getJoinedAt()` | `number` | Timestamp when the participant joined | +| leftAt | `getLeftAt()` | `number` | Timestamp when the participant left | +| mid | `getMid()` | `string` | Media ID of the participant | +| state | `getState()` | `string` | State of the participant | + +--- + +## Recording + +`Recording` represents a call recording. It is available via `getRecordings()` on a [`CallLog`](#calllog) object. + +### Properties + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| rid | `getRid()` | `string` | Unique recording ID | +| recordingUrl | `getRecordingURL()` | `string` | URL to download the recording | +| startTime | `getStartTime()` | `number` | Timestamp when the recording started | +| endTime | `getEndTime()` | `number` | Timestamp when the recording ended | +| duration | `getDuration()` | `number` | Duration of the recording in seconds | From a38925e3db10e806d0e001e34cd988d4865cde24 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 14:44:56 +0530 Subject: [PATCH 070/139] Update threaded-messages.mdx --- sdk/javascript/threaded-messages.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/javascript/threaded-messages.mdx b/sdk/javascript/threaded-messages.mdx index 842bd8997..ea2e740a8 100644 --- a/sdk/javascript/threaded-messages.mdx +++ b/sdk/javascript/threaded-messages.mdx @@ -285,7 +285,7 @@ messagesRequest.fetchPrevious().then( -The above snippet returns messages excluding threaded replies. +The response is an array of [`BaseMessage`](/sdk/reference/messages#basemessage) objects, excluding any messages that are replies within a thread. Only top-level messages in the conversation are returned. --- From de219d1075288b968f6b49afbc8092bc3f24f3bd Mon Sep 17 00:00:00 2001 From: PrajwalDhuleCC Date: Thu, 26 Mar 2026 15:56:50 +0530 Subject: [PATCH 071/139] docs(sdk): Replace redundant callback tables with OngoingCallListener reference - Remove duplicate event/callback tables from direct-call, presenter-mode, and recording documentation - Add reference links to OngoingCallListener in calls reference for centralized callback documentation - Update device list method descriptions to include MediaDeviceInfo return type references - Clarify generateToken() return value in standalone-calling documentation - Consolidate callback documentation to reduce duplication and improve maintainability --- sdk/javascript/direct-call.mdx | 21 +---- sdk/javascript/presenter-mode.mdx | 18 +---- sdk/javascript/recording.mdx | 8 +- sdk/javascript/standalone-calling.mdx | 25 ++---- sdk/reference/auxiliary.mdx | 17 +++- sdk/reference/calls.mdx | 109 +++++++++++++++++++++++++- 6 files changed, 138 insertions(+), 60 deletions(-) diff --git a/sdk/javascript/direct-call.mdx b/sdk/javascript/direct-call.mdx index ae45431eb..30430a20d 100644 --- a/sdk/javascript/direct-call.mdx +++ b/sdk/javascript/direct-call.mdx @@ -345,20 +345,7 @@ CometChatCalls.removeCallEventListener(listenerId); ### Events -| Event | Description | -| ----- | ----------- | -| `onCallEnded()` | Invoked when the call session terminates for a 1:1 call. Both participants receive this callback. Only fires for calls with exactly 2 participants. | -| `onSessionTimeout()` | Invoked when the call is auto-terminated due to inactivity (default: 180 seconds). Warning appears 60 seconds before. *v4.1.0+* | -| `onCallEndButtonPressed()` | Invoked when the local user clicks the end call button. For ringing flow, call `CometChat.endCall()`. For standalone, call `CometChatCalls.endSession()`. | -| `onUserJoined(user)` | Invoked when a remote participant joins. The `user` contains UID, name, and avatar. | -| `onUserLeft(user)` | Invoked when a remote participant leaves the call session. | -| `onUserListUpdated(userList)` | Invoked whenever the participant list changes (join or leave events). | -| `onMediaDeviceListUpdated(deviceList)` | Invoked when available audio/video devices change (e.g., new microphone connected). | -| `onUserMuted(event)` | Invoked when a participant's mute state changes. Contains `muted` and `mutedBy` properties. | -| `onScreenShareStarted()` | Invoked when the local user starts sharing their screen. | -| `onScreenShareStopped()` | Invoked when the local user stops sharing their screen. | -| `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. | +For the full list of callbacks, their descriptions, and parameter shapes, see the [`OngoingCallListener`](/sdk/reference/calls#ongoingcalllistener) reference. The ringing flow methods (`initiateCall()`, `acceptCall()`, `rejectCall()`, `endCall()`) return [`Call`](/sdk/reference/messages#call) objects. @@ -597,7 +584,7 @@ CometChatCalls.setMode(CometChat.CALL_MODE.SPOTLIGHT); ### Get Audio Input Devices -Returns a list of available audio input devices (microphones). +Returns a list of available audio input devices (microphones) as [`MediaDeviceInfo[]`](/sdk/reference/calls#mediadeviceinfo). @@ -616,7 +603,7 @@ console.log("Available microphones:", audioInputDevices); ### Get Audio Output Devices -Returns a list of available audio output devices (speakers/headphones). +Returns a list of available audio output devices (speakers/headphones) as [`MediaDeviceInfo[]`](/sdk/reference/calls#mediadeviceinfo). @@ -635,7 +622,7 @@ console.log("Available speakers:", audioOutputDevices); ### Get Video Input Devices -Returns a list of available video input devices (cameras). +Returns a list of available video input devices (cameras) as [`MediaDeviceInfo[]`](/sdk/reference/calls#mediadeviceinfo). diff --git a/sdk/javascript/presenter-mode.mdx b/sdk/javascript/presenter-mode.mdx index d7f94aa34..c74ba2200 100644 --- a/sdk/javascript/presenter-mode.mdx +++ b/sdk/javascript/presenter-mode.mdx @@ -103,9 +103,6 @@ useEffect(() => { onError: error => { console.log('Call Error: ', error); }, - onAudioModesUpdated: (audioModes) => { - console.log("audio modes:", audioModes); - }, onUserMuted: (event) => { console.log("user muted:", event); } @@ -118,20 +115,7 @@ useEffect(() => { -The `CometChatCallsEventsListener` listener provides you with the below callback methods: - -| Callback Method | Description | -| ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | -| onCallEnded() | This method is called when the call is successfully ended. The call details can be obtained from the `Call` object provided. | -| onCallEndButtonPressed() | This method is called when the user press end call button. | -| onUserJoined(user: RTCUser) | This method is called when any other user joins the call. The user details can be obtained from the `User` object provided. | -| onUserLeft(user: RTCUser) | This method is called when a user leaves the call. The details of the user can be obtained from the provided `User` object. | -| onUserListUpdated(users: Array\) | This method is triggered every time a participant joins or leaves the call providing the list of users active in the call | -| onAudioModesUpdated(devices: Array\) | This callback is triggered if any new audio output source is available or becomes unavailable. | -| onUserMuted(muteObj: RTCMutedUser) | This method is triggered when a user is muted in the ongoing call. | -| onRecordingStarted(user: RTCUser) | This method is triggered when a recording starts. | -| onRecordingStopped(user: RTCUser) | This method is triggered when a recording stops. | -| onError(e: CometChatException) | This method is called when there is some error in establishing the call. | +The `OngoingCallListener` provides the same callbacks as in [Call Session](/sdk/javascript/direct-call) and [Standalone Calling](/sdk/javascript/standalone-calling). For the full list of callbacks and their parameter shapes, see the [`OngoingCallListener`](/sdk/reference/calls#ongoingcalllistener) reference. ## Settings diff --git a/sdk/javascript/recording.mdx b/sdk/javascript/recording.mdx index 3f6b90d06..52682d5ab 100644 --- a/sdk/javascript/recording.mdx +++ b/sdk/javascript/recording.mdx @@ -95,13 +95,7 @@ CometChatCalls.startSession(callToken, callSettings, htmlElement); -The `onRecordingStarted` callback receives an event object: - -| Property | Type | Description | -|----------|------|-------------| -| `event.user` | `object` | The user who started the recording | -| `event.user.name` | `string` | Display name of the user | -| `event.user.uid` | `string` | UID of the user | +The `onRecordingStarted` callback receives an event object — see the [`OngoingCallListener`](/sdk/reference/calls#ongoingcalllistener) reference for the full shape. The `onRecordingStopped` callback receives no arguments. diff --git a/sdk/javascript/standalone-calling.mdx b/sdk/javascript/standalone-calling.mdx index d576f9f0b..3cdacd7f9 100644 --- a/sdk/javascript/standalone-calling.mdx +++ b/sdk/javascript/standalone-calling.mdx @@ -98,6 +98,8 @@ CometChatCalls.generateToken(sessionId, userAuthToken).then( | `sessionId` | A unique session ID for the call. Generate this yourself or use a shared ID for participants to join the same call. | | `userAuthToken` | The user auth token obtained from the CometChat REST API. | +`generateToken()` resolves with a token object containing a `token` string property used to authenticate into a call session. + ## Start Call Session Use the `startSession()` method to join a call session. This method requires: @@ -224,6 +226,8 @@ CometChatCalls.startSession(callToken, callSettings, htmlElement); | `callSettings` | Object of `CallSettings` class configured via `CallSettingsBuilder` | | `htmlElement` | DOM element where the call UI will be rendered | +`startSession()` renders the call UI inside the provided HTML element and joins the user into the active call session. + ### Call Settings Configure the call experience using the following `CallSettingsBuilder` methods: @@ -369,20 +373,7 @@ CometChatCalls.removeCallEventListener(listenerId); ### Events -| Event | Description | -| ----- | ----------- | -| `onCallEnded()` | Invoked when the call session terminates for a 1:1 call. Both participants receive this callback. Only fires for calls with exactly 2 participants. | -| `onSessionTimeout()` | Invoked when the call is auto-terminated due to inactivity (default: 180 seconds). Warning appears 60 seconds before. *v4.1.0+* | -| `onCallEndButtonPressed()` | Invoked when the local user clicks the end call button. Call `CometChatCalls.endSession()` to leave the session. | -| `onUserJoined(user)` | Invoked when a remote participant joins. The `user` contains UID, name, and avatar. | -| `onUserLeft(user)` | Invoked when a remote participant leaves the call session. | -| `onUserListUpdated(userList)` | Invoked whenever the participant list changes (join or leave events). | -| `onMediaDeviceListUpdated(deviceList)` | Invoked when available audio/video devices change (e.g., new microphone connected). | -| `onUserMuted(event)` | Invoked when a participant's mute state changes. Contains `muted` and `mutedBy` properties. | -| `onScreenShareStarted()` | Invoked when the local user starts sharing their screen. | -| `onScreenShareStopped()` | Invoked when the local user stops sharing their screen. | -| `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. | +For the full list of callbacks, their descriptions, and parameter shapes, see the [`OngoingCallListener`](/sdk/reference/calls#ongoingcalllistener) reference. ## End Call Session @@ -533,7 +524,7 @@ CometChatCalls.setMode(CometChat.CALL_MODE.SPOTLIGHT); ### Get Audio Input Devices -Returns a list of available audio input devices (microphones). +Returns a list of available audio input devices (microphones) as [`MediaDeviceInfo[]`](/sdk/reference/calls#mediadeviceinfo). @@ -552,7 +543,7 @@ console.log("Available microphones:", audioInputDevices); ### Get Audio Output Devices -Returns a list of available audio output devices (speakers/headphones). +Returns a list of available audio output devices (speakers/headphones) as [`MediaDeviceInfo[]`](/sdk/reference/calls#mediadeviceinfo). @@ -571,7 +562,7 @@ console.log("Available speakers:", audioOutputDevices); ### Get Video Input Devices -Returns a list of available video input devices (cameras). +Returns a list of available video input devices (cameras) as [`MediaDeviceInfo[]`](/sdk/reference/calls#mediadeviceinfo). diff --git a/sdk/reference/auxiliary.mdx b/sdk/reference/auxiliary.mdx index dc0276d5f..ea1107012 100644 --- a/sdk/reference/auxiliary.mdx +++ b/sdk/reference/auxiliary.mdx @@ -1,6 +1,6 @@ --- title: "Auxiliary" -description: "Class reference for auxiliary objects returned by CometChat SDK methods. Covers MessageReceipt, Reaction, ReactionCount, ReactionEvent, TypingIndicator, TransientMessage, and Attachment." +description: "Class reference for auxiliary objects returned by CometChat SDK methods. Covers MessageReceipt, Reaction, ReactionCount, ReactionEvent, TypingIndicator, TransientMessage, Attachment, and CometChatException." --- This page documents the auxiliary classes used across all CometChat SDKs. These objects are returned by listener callbacks and specific SDK methods. @@ -118,3 +118,18 @@ All properties are accessed via getter methods. | 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 | + +--- + +## CometChatException + +`CometChatException` represents an error from the Chat SDK. It is received in rejection callbacks of promise-based SDK methods (e.g., `sendMessage`, `login`, `getGroup`). + +### Properties + +| Property | Type | Description | +|----------|------|-------------| +| `code` | `string` \| `number` | Error code identifying the type of error | +| `name` | `string` | Name/category of the error | +| `message` | `string` | Human-readable error description | +| `details` | `string` | Additional error details | diff --git a/sdk/reference/calls.mdx b/sdk/reference/calls.mdx index 7eea32d64..0c32a935e 100644 --- a/sdk/reference/calls.mdx +++ b/sdk/reference/calls.mdx @@ -1,6 +1,6 @@ --- title: "Calls" -description: "Class reference for objects returned by the CometChat Calls SDK. Covers CallLog, CallUser, CallGroup, Participant, and Recording." +description: "Class reference for objects returned by the CometChat Calls SDK. Covers CallLog, CallUser, CallGroup, Participant, Recording, OngoingCallListener, CometChatCallsException, and MediaDeviceInfo." --- This page documents the classes used in the CometChat Calls SDK. These objects are returned by call log queries and call session methods. @@ -102,3 +102,110 @@ All properties on proper classes are accessed via getter methods. Listener event | startTime | `getStartTime()` | `number` | Timestamp when the recording started | | endTime | `getEndTime()` | `number` | Timestamp when the recording ended | | duration | `getDuration()` | `number` | Duration of the recording in seconds | + +--- + +## OngoingCallListener + +`OngoingCallListener` provides real-time callbacks for call session events. It is used with `CallSettingsBuilder.setCallListener()` or `CometChatCalls.addCallEventListener()`. + +All three calling flows — [Call Session](/sdk/javascript/direct-call), [Standalone Calling](/sdk/javascript/standalone-calling), and [Presenter Mode](/sdk/javascript/presenter-mode) — use the same `OngoingCallListener` with identical callbacks. + +### Callbacks + +| Callback | Parameter | Description | +|----------|-----------|-------------| +| `onUserJoined(user)` | `user` object | A remote participant joined the call | +| `onUserLeft(user)` | `user` object | A remote participant left the call | +| `onUserListUpdated(userList)` | Array of `user` objects | The participant list changed (join or leave) | +| `onCallEnded()` | — | The call session terminated (1:1 calls only, fires for both participants) | +| `onCallEndButtonPressed()` | — | The local user clicked the end call button | +| `onSessionTimeout()` | — | The call was auto-terminated due to inactivity. *v4.1.0+* | +| `onScreenShareStarted()` | — | The local user started sharing their screen | +| `onScreenShareStopped()` | — | The local user stopped sharing their screen | +| `onUserMuted(event)` | `event` object | A participant's mute state changed | +| `onCallSwitchedToVideo(event)` | `event` object | An audio call was upgraded to video | +| `onMediaDeviceListUpdated(deviceList)` | `deviceList` object | Available audio/video devices changed | +| `onRecordingStarted(event)` | `event` object | A user started recording the call | +| `onRecordingStopped()` | — | Recording was stopped | +| `onError(error)` | [`CometChatCallsException`](#cometchatcallsexception) | An error occurred during the call session | + +### Callback Parameter Shapes + +**`user` object** (received by `onUserJoined`, `onUserLeft`): + +| Property | Type | Description | +|----------|------|-------------| +| `name` | `string` | Display name of the user | +| `avatar` | `string` | URL of the user's avatar | +| `uid` | `string` | UID of the user | + +**`onUserListUpdated(userList)`** — receives an array of `user` objects with the same shape as above. + +**`onUserMuted(event)`**: + +| Property | Type | Description | +|----------|------|-------------| +| `event.muted.name` | `string` | Name of the muted user | +| `event.muted.uid` | `string` | UID of the muted user | +| `event.muted.isAudioMuted` | `boolean` | Whether audio is muted | +| `event.muted.isVideoMuted` | `boolean` | Whether video is muted | +| `event.mutedBy.name` | `string` | Name of the user who muted | +| `event.mutedBy.uid` | `string` | UID of the user who muted | + +**`onCallSwitchedToVideo(event)`**: + +| Property | Type | Description | +|----------|------|-------------| +| `event.sessionId` | `string` | Session ID of the call | +| `event.initiator.name` | `string` | Name of the user who initiated the switch | +| `event.initiator.uid` | `string` | UID of the initiator | +| `event.responder.name` | `string` | Name of the responder | +| `event.responder.uid` | `string` | UID of the responder | + +**`onMediaDeviceListUpdated(deviceList)`**: + +| Property | Type | Description | +|----------|------|-------------| +| `deviceList.videoInputDevices` | [`MediaDeviceInfo[]`](#mediadeviceinfo) | Available cameras | +| `deviceList.audioInputDevices` | [`MediaDeviceInfo[]`](#mediadeviceinfo) | Available microphones | +| `deviceList.audioOutputDevices` | [`MediaDeviceInfo[]`](#mediadeviceinfo) | Available speakers/headphones | + +**`onRecordingStarted(event)`**: + +| Property | Type | Description | +|----------|------|-------------| +| `event.user.name` | `string` | Name of the user who started recording | +| `event.user.uid` | `string` | UID of the user who started recording | + +--- + +## CometChatCallsException + +`CometChatCallsException` represents an error from the Calls SDK. It is received in the `onError` callback of `OngoingCallListener` and in rejection callbacks of Calls SDK promise-based methods. + +### Properties + +| Property | Type | Description | +|----------|------|-------------| +| `code` | `string` \| `number` | Error code identifying the type of error | +| `name` | `string` | Name/category of the error | +| `message` | `string` | Human-readable error description | +| `details` | `string` | Additional error details | + +--- + +## MediaDeviceInfo + +`MediaDeviceInfo` represents an audio or video device available on the user's system. It is returned by `getAudioInputDevices()`, `getAudioOutputDevices()`, and `getVideoInputDevices()` methods, and also received in the `onMediaDeviceListUpdated` callback. + +These objects follow the browser's [MediaDeviceInfo](https://developer.mozilla.org/en-US/docs/Web/API/MediaDeviceInfo) interface shape. + +### Properties + +| Property | Type | Description | +|----------|------|-------------| +| `deviceId` | `string` | Unique device identifier | +| `kind` | `string` | Device type (`"videoinput"`, `"audioinput"`, or `"audiooutput"`) | +| `label` | `string` | Human-readable device name | +| `groupId` | `string` | Group identifier for related devices (e.g., a headset's mic and speaker share a group) | From f12dae9a1cc8e921a65f9d1410e06051bf8a85fa Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 16:15:20 +0530 Subject: [PATCH 072/139] Update reactions.mdx --- sdk/javascript/reactions.mdx | 179 +++++++++++++++-------------------- 1 file changed, 74 insertions(+), 105 deletions(-) diff --git a/sdk/javascript/reactions.mdx b/sdk/javascript/reactions.mdx index 8cb639979..85c14fb69 100644 --- a/sdk/javascript/reactions.mdx +++ b/sdk/javascript/reactions.mdx @@ -4,7 +4,6 @@ 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." --- -{/* TL;DR for Agents and Quick Reference */} ```javascript @@ -27,11 +26,13 @@ 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. +Reactions let users respond to messages with emoji. You can add or remove reactions, fetch all reactions on a message, listen for reaction events in real time, and update your UI when reactions change. + +Reactions work on text messages, media messages, and custom messages. ## Add a Reaction -Users can add a reaction to a message by calling `addReaction` with the message ID and the reaction emoji. +Call `addReaction()` with a message ID and an emoji string. @@ -46,7 +47,6 @@ CometChat.addReaction(messageId, emoji) console.log('err', err); }) ``` - @@ -61,20 +61,12 @@ CometChat.addReaction(messageId, emoji) console.log('err', err); }) ``` - - - - -You can react on text message, media message and custom message - - - ## Remove a Reaction -Removing a reaction from a message can be done using the `removeReaction` method. +Call `removeReaction()` with the same message ID and emoji. @@ -89,7 +81,6 @@ CometChat.removeReaction(messageId, emoji) console.log('err', err); }) ``` - @@ -104,9 +95,7 @@ CometChat.removeReaction(messageId, emoji) console.log('err', err); }) ``` - - Both `addReaction()` and `removeReaction()` return a [`BaseMessage`](/sdk/reference/messages#basemessage) object with the updated reactions. Access the reaction data using getter methods: @@ -117,20 +106,63 @@ Both `addReaction()` and `removeReaction()` return a [`BaseMessage`](/sdk/refere | 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 +## Read Reaction Data from a Message + +Any [`BaseMessage`](/sdk/reference/messages#basemessage) exposes reaction data through two methods: + +### Get All Reactions + +Use `getReactions()` to retrieve the list of reactions on a message. Returns an empty array if no one has reacted. + + + +```typescript +message.getReactions() +``` + + + +```js +message.getReactions() +``` + + + +### Check if the Logged-in User Has Reacted + +Call `getReactedByMe()` on any [`ReactionCount`](/sdk/reference/auxiliary#reactioncount) object to check whether the logged-in user has reacted with that particular emoji. -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. + + +```typescript +let reactions = message.getReactions(); +reactions.forEach((reaction) => { +reaction.getReactedByMe(); //Return true is logged-in user reacted on that message, otherwise false +}) +``` + + + +```js +let reactions = message.getReactions(); +reactions.forEach((reaction) => { +reaction.getReactedByMe(); //Return true is logged-in user reacted on that message, otherwise false +}) +``` + + -| Setting | Description | -| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `setMessageId(value)` | Specifies the unique identifier of the message for which you want to fetch reactions. This parameter is mandatory as it tells the SDK which message's reactions are being requested. | -| `setReaction(value)` | Filters the reactions fetched by the specified reaction type (e.g., "😊", "😂", "👍"). When set, this method will cause the ReactionRequest to only retrieve details of the provided reaction for the given message. | +## Fetch Reactions for a Message -*** +To get the full list of who reacted with what on a specific message, use `ReactionRequestBuilder`. You can paginate through results with `fetchNext()` and `fetchPrevious()` (max 100 per request). -## Fetch Next +| Builder Method | Description | +| --- | --- | +| `setMessageId(value)` | The message ID to fetch reactions for. Required. | +| `setReaction(value)` | Filter to a specific emoji (e.g., `"😊"`). When set, only reactions matching this emoji are returned. | +| `setLimit(value)` | Number of reactions to fetch per request. Max 100. | -The `fetchNext()` method fetches the next set of reactions for the message. +### Fetch Next @@ -152,7 +184,6 @@ reactionRequest.fetchNext().then( }, ); ``` - @@ -174,12 +205,10 @@ reactionRequest.fetchNext().then( }, ); ``` - - -Fetch Previous The `fetchPrevious()` method fetches the previous set of reactions for the message. +### Fetch Previous @@ -201,7 +230,6 @@ reactionRequest.fetchPrevious().then( }, ); ``` - @@ -223,18 +251,12 @@ reactionRequest.fetchPrevious().then( }, ); ``` - - -## Real-time Reaction Events - -Keep the chat interactive with real-time updates for reactions. Register a listener for these events and make your UI responsive. +## Real-Time Reaction Events - -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 a `MessageListener` to receive reaction events as they happen. This is how you keep your UI in sync when other users add or remove reactions. @@ -250,7 +272,6 @@ CometChat.addMessageListener(listenerID, new CometChat.MessageListener({ } })) ``` - @@ -266,12 +287,10 @@ CometChat.addMessageListener(listenerID, new CometChat.MessageListener({ } })) ``` - - -Each reaction listener callback receives a [`ReactionEvent`](/sdk/reference/auxiliary#reactionevent) object. Access the event data using getter methods: +Each callback receives a [`ReactionEvent`](/sdk/reference/auxiliary#reactionevent) object: | Field | Getter | Return Type | Description | |-------|--------|-------------|-------------| @@ -281,9 +300,7 @@ Each reaction listener callback receives a [`ReactionEvent`](/sdk/reference/auxi | conversationId | `getConversationId()` | `string` | ID of the conversation | | parentMessageId | `getParentMessageId()` | `string` | ID of the parent message (for threaded messages) | -## Removing a Reaction Listener - -To stop listening for reaction events, remove the listener as follows: +### Remove the Listener @@ -292,7 +309,6 @@ let listenerID:string = "UNIQUE_LISTENER_ID"; CometChat.removeMessageListener(listenerID); ``` - @@ -301,66 +317,16 @@ let listenerID = "UNIQUE_LISTENER_ID"; CometChat.removeMessageListener(listenerID); ``` - - - - - -## Get Reactions List - -To retrieve the list of reactions reacted on particular message, you can use the `message.getReactions()` method. This method will return an array containing the reactions, or an empty array if no one reacted on the message. - - - -```typescript -message.getReactions() -``` - - - -```js -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`](/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. - - - -```typescript -let reactions = message.getReactions(); -reactions.forEach((reaction) => { -reaction.getReactedByMe(); //Return true is logged-in user reacted on that message, otherwise false -}) -``` - - - - -```js -let reactions = message.getReactions(); -reactions.forEach((reaction) => { -reaction.getReactedByMe(); //Return true is logged-in user reacted on that message, otherwise false -}) -``` - - - - - -## Update Message With Reaction Info - -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. + +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. + -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. +## Update a Message with Reaction Info -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. +When you receive a real-time reaction event, you'll want to update the corresponding message object so your UI reflects the change. `updateMessageWithReactionInfo()` does this — it takes the [`BaseMessage`](/sdk/reference/messages#basemessage) instance, the [`MessageReaction`](/sdk/reference/auxiliary#messagereaction) event data, and the action type, then returns the updated message. @@ -380,7 +346,6 @@ messageReaction, action ); ``` - @@ -400,12 +365,16 @@ messageReaction, 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. +After calling this method, use `modifiedBaseMessage.getReactions()` to get the latest reactions and refresh your UI. + +| Parameter | Type | Description | +|-----------|------|-------------| +| `message` | [`BaseMessage`](/sdk/reference/messages#basemessage) | The message object to update | +| `messageReaction` | [`MessageReaction`](/sdk/reference/auxiliary#messagereaction) | The reaction event received from the listener | +| `action` | `REACTION_ACTION` | `CometChat.REACTION_ACTION.REACTION_ADDED` or `CometChat.REACTION_ACTION.REACTION_REMOVED` | --- From 0b30f5803d779c41fd144412eb8057c4a77ebf2e Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 16:21:28 +0530 Subject: [PATCH 073/139] Update calling-overview.mdx --- sdk/javascript/calling-overview.mdx | 83 +++++++++++------------------ 1 file changed, 31 insertions(+), 52 deletions(-) diff --git a/sdk/javascript/calling-overview.mdx b/sdk/javascript/calling-overview.mdx index a1c0adc69..2abcdd6ad 100644 --- a/sdk/javascript/calling-overview.mdx +++ b/sdk/javascript/calling-overview.mdx @@ -4,7 +4,6 @@ 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 */} Choose your calling approach: @@ -20,13 +19,11 @@ 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. +CometChat provides three ways to add voice and video calling to your web app. Which one you pick depends on how much of the call flow you want CometChat to handle vs. building yourself. ## Prerequisites -1. CometChat SDK installed and configured. See the [Setup](/sdk/javascript/setup) guide. +1. CometChat Chat SDK installed and configured. See the [Setup](/sdk/javascript/setup-sdk) guide. 2. CometChat Calls SDK added to your project: ```bash @@ -35,58 +32,53 @@ npm install @cometchat/calls-sdk-javascript For detailed setup instructions, see the [Calls SDK Setup](/sdk/javascript/calling-setup) guide. -## Choose Your Implementation - -CometChat offers three approaches to implement calling: - - - - Complete calling flow with incoming/outgoing call UI, accept/reject functionality, and call notifications. - - - Direct call session management. Use with Ringing flow or for custom call initiation logic. - - - Calls SDK only implementation without the Chat SDK dependency. - - +## Choose Your Approach -### Ringing +### Ringing (Full Call Flow) -Use this when you need a complete calling experience with: -- Incoming and outgoing call UI -- Call accept/reject/cancel functionality -- Call notifications via push notifications -- Integration with CometChat messaging +The complete calling experience — incoming/outgoing call UI, accept/reject/cancel, push notifications, and integration with CometChat messaging. Use this when you want CometChat to handle the entire call lifecycle. **Flow:** Initiate call → Receiver gets notified → Accept/Reject → Start session -[Get started with Ringing →](/sdk/javascript/default-call) + + Implement the complete ringing call flow + -### Call Session +### Call Session (Session Management) -Use this when you need to: -- Start a call session after the Ringing flow completes -- Implement custom call initiation logic with your own UI -- Join participants to a shared session using a session ID +Manages the actual call session — generating tokens, starting/ending sessions, configuring the call UI, and handling in-call events. The Ringing flow uses this under the hood after a call is accepted. You can also use it directly if you want to build your own call initiation logic. **Flow:** Generate token → Start session → Manage call → End session -[Get started with Call Session →](/sdk/javascript/direct-call) + + Start and manage call sessions + -### Standalone Calling +### Standalone Calling (No Chat SDK) -Use this when you want: -- Calling functionality without the Chat SDK -- Your own user authentication system -- Minimal SDK footprint +Calling without the Chat SDK. You handle user authentication via the REST API and use only the Calls SDK. Ideal when you need voice/video but not the full chat infrastructure. **Flow:** Get auth token via REST API → Generate call token → Start session -[Get started with Standalone Calling →](/sdk/javascript/standalone-calling) + + Implement calling without the Chat SDK + + +### How They Relate + +```mermaid +flowchart LR + A[Ringing Flow] -->|call accepted| B[Call Session] + C[Custom UI] -->|your logic| B + D[Standalone] -->|REST API auth| B +``` + +All three approaches converge on the Call Session layer to manage the actual media connection. The difference is how you get there — CometChat's ringing flow, your own UI, or standalone without the Chat SDK. ## Features +Once you have calling working, you can add these capabilities: + Record audio and video calls for playback, compliance, or archival purposes. @@ -113,16 +105,3 @@ 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 - - From de733f2364067276243ceb9927a5707fb4e87cbe Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 16:26:06 +0530 Subject: [PATCH 074/139] Update calling-setup.mdx --- sdk/javascript/calling-setup.mdx | 111 +++++++++++++++---------------- 1 file changed, 53 insertions(+), 58 deletions(-) diff --git a/sdk/javascript/calling-setup.mdx b/sdk/javascript/calling-setup.mdx index e0c160bbb..33190d07a 100644 --- a/sdk/javascript/calling-setup.mdx +++ b/sdk/javascript/calling-setup.mdx @@ -1,10 +1,9 @@ --- -title: "Setup" +title: "Calls SDK Setup" sidebarTitle: "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** @@ -26,92 +25,61 @@ 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)). - +The Calls SDK handles the media layer for voice and video calls — camera, microphone, screen sharing, and the call UI. It's a separate package from the Chat SDK and requires its own initialization. -## Get your Application Keys +## Prerequisites -[Signup for CometChat](https://app.cometchat.com) and then: +You need your App ID and Region from the [CometChat Dashboard](https://app.cometchat.com). If you haven't created an app yet, [sign up](https://app.cometchat.com) and create one. -1. Create a new app -2. Head over to the **Credentials** section and note the **App ID, Auth Key** & **Region** +If you're using the Chat SDK alongside (i.e., not [Standalone Calling](/sdk/javascript/standalone-calling)), make sure `CometChat.init()` completes before calling `CometChatCalls.init()`. -## Add the CometChatCalls Dependency - -Install the package as NPM module: +## Installation ```bash npm install @cometchat/calls-sdk-javascript ``` - ```bash yarn add @cometchat/calls-sdk-javascript ``` - - -Then, import the `CometChatCalls` class wherever you want to use `CometChatCalls`. - - - -```typescript -import { CometChatCalls } from "@cometchat/calls-sdk-javascript"; -``` - - +Then import wherever needed: - -```js +```javascript import { CometChatCalls } from "@cometchat/calls-sdk-javascript"; ``` - - - +## Initialization -### Initialize CometChatCalls - -The `init()` method initializes the Calls SDK. It takes a `CallAppSettings` instance as its parameter. - -`CallAppSettingsBuilder` accepts three settings: - -| Setting | Description | -| ------- | ----------- | -| `appID` | Your CometChat App ID | -| `region` | The region where your app was created | -| `host` | (Optional) Custom client URL for dedicated deployments | - -Call `init()` before any other `CometChatCalls` method — ideally on app startup. +Call `CometChatCalls.init()` on app startup, after the Chat SDK has initialized (if you're using it). The method takes a `CallAppSettings` object built with `CallAppSettingsBuilder`. ```typescript -let appID = "APP_ID"; -let region = "REGION"; +let appID: string = "APP_ID"; +let region: string = "REGION"; -const callAppSetting = new CometChatCalls.CallAppSettingsBuilder() - .setAppId(appID) - .setRegion(region) - .build(); +const callAppSetting: CometChatCalls.CallAppSettings = + new CometChatCalls.CallAppSettingsBuilder() + .setAppId(appID) + .setRegion(region) + .build(); CometChatCalls.init(callAppSetting).then( () => { console.log("CometChatCalls initialization completed successfully"); }, - (error) => { + (error: unknown) => { console.log("CometChatCalls initialization failed with error:", error); } ); ``` - @@ -133,16 +101,43 @@ CometChatCalls.init(callAppSetting).then( } ); ``` - - -Make sure you replace the `APP_ID` with your CometChat **App ID** and `REGION` with your **App Region** in the above code. +Replace `APP_ID` and `REGION` with your credentials from the [Dashboard](https://app.cometchat.com). + + +`CometChatCalls.init()` must be called before any other Calls SDK method. Calling `generateToken()`, `startSession()`, or registering listeners before `init()` will fail. + + +### CallAppSettings Options + +| Method | Description | +| --- | --- | +| `setAppId(appID)` | Your CometChat App ID. Required. | +| `setRegion(region)` | The region where your app was created. Required. | +| `setHost(host)` | Custom client URL for dedicated deployments. Optional. | + +### Initialization Order + +If you're using both the Chat SDK and Calls SDK, initialize them in sequence: + +```javascript +// 1. Chat SDK first +await CometChat.init(appID, appSettings); + +// 2. Then Calls SDK +const callAppSetting = new CometChatCalls.CallAppSettingsBuilder() + .setAppId(appID) + .setRegion(region) + .build(); + +await CometChatCalls.init(callAppSetting); + +// 3. Now both SDKs are ready +``` -| Parameter | Description | -| ----------------- | ---------------------------------------- | -| `callAppSettings` | An object of the `CallAppSettings` class | +For [Standalone Calling](/sdk/javascript/standalone-calling), you only need `CometChatCalls.init()` — no Chat SDK required. --- @@ -152,8 +147,8 @@ Make sure you replace the `APP_ID` with your CometChat **App ID** and `REGION` w Implement the complete ringing call flow - - Start call sessions without the ringing flow + + Start and manage call sessions Use Calls SDK without the Chat SDK From d3616ddf5fbf862dfaeabddf9b337eee36789d4c Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 16:29:32 +0530 Subject: [PATCH 075/139] AI Integration Quick Reference --- sdk/javascript/calling-setup.mdx | 5 ++--- sdk/javascript/troubleshooting.mdx | 4 +++- sdk/javascript/video-view-customisation.mdx | 6 +++--- sdk/javascript/virtual-background.mdx | 6 +++--- 4 files changed, 11 insertions(+), 10 deletions(-) diff --git a/sdk/javascript/calling-setup.mdx b/sdk/javascript/calling-setup.mdx index 33190d07a..febf85a63 100644 --- a/sdk/javascript/calling-setup.mdx +++ b/sdk/javascript/calling-setup.mdx @@ -4,8 +4,7 @@ sidebarTitle: "Setup" description: "Install and initialize the CometChat Calls SDK for JavaScript to enable voice and video calling in your application." --- - -**Quick Setup Reference** + ```bash npm install @cometchat/calls-sdk-javascript @@ -23,7 +22,7 @@ CometChatCalls.init(callAppSetting).then(() => console.log("Calls SDK ready")); ``` **Required:** App ID, Region from [CometChat Dashboard](https://app.cometchat.com) - + The Calls SDK handles the media layer for voice and video calls — camera, microphone, screen sharing, and the call UI. It's a separate package from the Chat SDK and requires its own initialization. diff --git a/sdk/javascript/troubleshooting.mdx b/sdk/javascript/troubleshooting.mdx index 79a65bb55..03a532438 100644 --- a/sdk/javascript/troubleshooting.mdx +++ b/sdk/javascript/troubleshooting.mdx @@ -6,7 +6,7 @@ description: "Common failure modes and fixes for the CometChat JavaScript SDK." Find solutions to common issues when building with the CometChat JavaScript SDK. -## Quick Reference + | Issue | Fix | |-------|-----| @@ -16,6 +16,8 @@ Find solutions to common issues when building with the CometChat JavaScript SDK. | No real-time events | Check WebSocket connection, verify listeners registered | | SSR errors | Use dynamic imports or `useEffect` for client-side only | + + --- ## Initialization & Authentication diff --git a/sdk/javascript/video-view-customisation.mdx b/sdk/javascript/video-view-customisation.mdx index c02eccfc2..851b50845 100644 --- a/sdk/javascript/video-view-customisation.mdx +++ b/sdk/javascript/video-view-customisation.mdx @@ -4,14 +4,14 @@ sidebarTitle: "Video View Customisation" description: "Customize the main video container in CometChat calls — aspect ratio, full screen button, name label, and network label positioning." --- - -**Quick Reference** + + - **Class:** `CometChat.MainVideoContainerSetting` - **Apply via:** `CallSettingsBuilder.setMainVideoContainerSetting(videoSettings)` - **Customizable elements:** Aspect ratio, full screen button, name label, network label - **Position constants:** `POSITION_TOP_LEFT`, `POSITION_TOP_RIGHT`, `POSITION_BOTTOM_LEFT`, `POSITION_BOTTOM_RIGHT` - **Requires:** [Default Calling](/sdk/javascript/default-call) or [Direct Calling](/sdk/javascript/direct-call) setup - + Customize the main video container layout, including aspect ratio, button positions, and label visibility. diff --git a/sdk/javascript/virtual-background.mdx b/sdk/javascript/virtual-background.mdx index 86bbc1e07..b35aecff7 100644 --- a/sdk/javascript/virtual-background.mdx +++ b/sdk/javascript/virtual-background.mdx @@ -4,14 +4,14 @@ sidebarTitle: "Virtual Background" description: "Implement virtual background features in CometChat video calls — background blur, custom images, and enforced backgrounds using the JavaScript SDK." --- - -**Quick Reference** + + - **Settings class:** `CometChat.VirtualBackground` - **Apply via:** `CallSettingsBuilder.setVirtualBackground(virtualBackground)` - **Toggle UI:** `CallSettingsBuilder.showVirtualBackgroundSetting(true|false)` - **Runtime control:** `CometChat.CallController.getInstance()` → `setBackgroundBlur()`, `setBackgroundImage()`, `openVirtualBackground()` - **Requires:** [Default Calling](/sdk/javascript/default-call) or [Direct Calling](/sdk/javascript/direct-call) setup - + Apply blur or custom image backgrounds during video calls. From 88a5184fba729d24f72d4a4ff7e504c2a4dcf0e2 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 16:34:28 +0530 Subject: [PATCH 076/139] updates code --- sdk/javascript/block-users.mdx | 26 ++++---------------------- sdk/javascript/call-logs.mdx | 4 ++-- sdk/javascript/flag-message.mdx | 13 ++++--------- sdk/javascript/standalone-calling.mdx | 8 +++++--- sdk/reference/messages.mdx | 4 ++-- 5 files changed, 17 insertions(+), 38 deletions(-) diff --git a/sdk/javascript/block-users.mdx b/sdk/javascript/block-users.mdx index 14d24efb4..e1ba8afa4 100644 --- a/sdk/javascript/block-users.mdx +++ b/sdk/javascript/block-users.mdx @@ -73,18 +73,7 @@ try { -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: - -| 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 +Returns an object with UIDs as keys and `"success"` or `"fail"` as values. Each [`User`](/sdk/reference/entities#user) in the request is processed independently. Unblock previously blocked users using `unblockUsers()` with an array of UIDs. @@ -135,16 +124,7 @@ try { -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: - -| 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 | +Returns an object with UIDs as keys and `"success"` or `"fail"` as values. Each [`User`](/sdk/reference/entities#user) in the request is processed independently. ## Get List of Blocked Users @@ -281,6 +261,8 @@ userList => { +The `fetchNext()` method returns an array of [`User`](/sdk/reference/entities#user) objects representing blocked users. + --- ## Next Steps diff --git a/sdk/javascript/call-logs.mdx b/sdk/javascript/call-logs.mdx index 41277a847..2ead14f17 100644 --- a/sdk/javascript/call-logs.mdx +++ b/sdk/javascript/call-logs.mdx @@ -99,8 +99,8 @@ The `fetchNext()` and `fetchPrevious()` methods return an array of [`Call`](/sdk | 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 | +| callInitiator | `getCallInitiator()` | [`User`](/sdk/reference/entities#user) | The user who initiated the call | +| callReceiver | `getCallReceiver()` | [`User`](/sdk/reference/entities#user) \| [`Group`](/sdk/reference/entities#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 | diff --git a/sdk/javascript/flag-message.mdx b/sdk/javascript/flag-message.mdx index 959dd8c41..e0dd7c2b6 100644 --- a/sdk/javascript/flag-message.mdx +++ b/sdk/javascript/flag-message.mdx @@ -93,7 +93,7 @@ Before flagging a message, retrieve the list of available flag reasons configure ### Response -The response is an array of flag reason objects: +The response is an array of `FlagReason` objects, each with an `id` and `reason` string: ```javascript [ @@ -159,6 +159,8 @@ To flag a message, use the `flagMessage()` method with the message ID and a payl ### Response +The `Promise` resolves with a success confirmation object: + ```javascript { "success": true, @@ -166,14 +168,7 @@ 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 | +The flagged message is a [`BaseMessage`](/sdk/reference/messages#basemessage) object. You can identify it using `getId()`, `getSender()` (returns a [`User`](/sdk/reference/entities#user)), and `getType()`. ## Complete Example diff --git a/sdk/javascript/standalone-calling.mdx b/sdk/javascript/standalone-calling.mdx index a9bbb772a..df61c6ff3 100644 --- a/sdk/javascript/standalone-calling.mdx +++ b/sdk/javascript/standalone-calling.mdx @@ -98,6 +98,8 @@ CometChatCalls.generateToken(sessionId, userAuthToken).then( | `sessionId` | A unique session ID for the call. Generate this yourself or use a shared ID for participants to join the same call. | | `userAuthToken` | The user auth token obtained from the CometChat REST API. | +The `Promise` resolves with an object containing a `token` property (string) that you pass to `startSession()`. + ## Start Call Session Use the `startSession()` method to join a call session. This method requires: @@ -533,7 +535,7 @@ CometChatCalls.setMode(CometChat.CALL_MODE.SPOTLIGHT); ### Get Audio Input Devices -Returns a list of available audio input devices (microphones). +Returns a list of available audio input devices (microphones). Each item is a [`MediaDeviceInfo`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDeviceInfo) object with `deviceId`, `label`, and `kind` properties. @@ -552,7 +554,7 @@ console.log("Available microphones:", audioInputDevices); ### Get Audio Output Devices -Returns a list of available audio output devices (speakers/headphones). +Returns a list of available audio output devices (speakers/headphones). Each item is a [`MediaDeviceInfo`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDeviceInfo) object. @@ -571,7 +573,7 @@ console.log("Available speakers:", audioOutputDevices); ### Get Video Input Devices -Returns a list of available video input devices (cameras). +Returns a list of available video input devices (cameras). Each item is a [`MediaDeviceInfo`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDeviceInfo) object. diff --git a/sdk/reference/messages.mdx b/sdk/reference/messages.mdx index 93626688f..f6e555fee 100644 --- a/sdk/reference/messages.mdx +++ b/sdk/reference/messages.mdx @@ -209,8 +209,8 @@ It inherits all properties from `BaseMessage` and adds the following. | 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 | +| callInitiator | `getCallInitiator()` | [`User`](/sdk/reference/entities#user) | The user who initiated the call | +| callReceiver | `getCallReceiver()` | [`User`](/sdk/reference/entities#user) \| [`Group`](/sdk/reference/entities#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 | From 8aa9102206c7ab4b2553a0a64dac7e91cf6a03da Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 16:46:44 +0530 Subject: [PATCH 077/139] Update direct-call.mdx --- sdk/javascript/direct-call.mdx | 256 ++++++++++++++++----------------- 1 file changed, 124 insertions(+), 132 deletions(-) diff --git a/sdk/javascript/direct-call.mdx b/sdk/javascript/direct-call.mdx index dcaa9aec5..8b579d53f 100644 --- a/sdk/javascript/direct-call.mdx +++ b/sdk/javascript/direct-call.mdx @@ -4,7 +4,6 @@ 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." --- -{/* TL;DR for Agents and Quick Reference */} ```javascript @@ -26,17 +25,9 @@ CometChatCalls.endSession(); ``` -## Overview +A call session is the active media connection between participants — camera, microphone, screen sharing, and the call UI. Whether you arrive here from the [Ringing flow](/sdk/javascript/default-call), your own custom UI, or [Standalone Calling](/sdk/javascript/standalone-calling), this page covers how to manage the session itself. -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). - - - -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. - - +Before you begin, make sure you've completed the [Calls SDK Setup](/sdk/javascript/calling-setup). ## Generate Call Token @@ -44,7 +35,8 @@ A call token is required for secure access to a call session. Each token is uniq You can generate the token just before starting the call, or generate and store it ahead of time based on your use case. -Use the `generateToken()` method to create a call token: +- In the Ringing flow, the session ID comes from the [`Call`](/sdk/reference/messages#call) object after the call is accepted. +- For direct sessions, generate your own unique session ID. @@ -88,6 +80,8 @@ CometChatCalls.generateToken(sessionId, authToken).then( | `sessionId` | The unique random session ID. In case you are using the ringing flow, the session ID is available in the `Call` object. | | `authToken` | The user auth token is the logged-in user auth token which you can get by calling `CometChat.getLoggedinUser().getAuthToken()` | +The `Promise` resolves with an object containing a `token` property (string) that you pass to `startSession()`. + ## Start Call Session Use the `startSession()` method to join a call session. This method requires: @@ -229,6 +223,111 @@ Configure the call experience using the following `CallSettingsBuilder` methods: | `setMainVideoContainerSetting(MainVideoContainerSetting)` | Customizes the main video container. See [Video View Customization](/sdk/javascript/video-view-customisation). | | `setIdleTimeoutPeriod(number)` | Sets idle timeout in seconds. Warning appears 60 seconds before auto-termination. Default: `180` seconds. *v4.1.0+* | +## End Call Session + +How you end a call depends on whether you're using the Ringing flow or a direct session. + +### Ringing Flow + +When using the [Ringing](/sdk/javascript/default-call) flow, you must coordinate between the CometChat Chat SDK and the Calls SDK to properly terminate the call and notify all participants. + + +The Ringing flow requires calling methods from both the Chat SDK (`CometChat.endCall()`) and the Calls SDK (`CometChatCalls.endSession()`) to ensure proper call termination and participant notification. + + + + + + +**User who initiates the end call:** + +When the user clicks the end call button in the UI, the `onCallEndButtonPressed()` callback is triggered. You must call `CometChat.endCall()` inside this callback to properly terminate the call and notify other participants. On success, call `CometChat.clearActiveCall()` and `CometChatCalls.endSession()` to release resources. + + + +```typescript +onCallEndButtonPressed: () => { + CometChat.endCall(sessionId).then( + (call: CometChat.Call) => { + console.log("Call ended successfully"); + CometChat.clearActiveCall(); + CometChatCalls.endSession(); + // Close the calling screen + }, + (error: CometChat.CometChatException) => { + console.log("End call failed:", error); + } + ); +} +``` + + +```javascript +onCallEndButtonPressed: () => { + CometChat.endCall(sessionId).then( + (call) => { + console.log("Call ended successfully"); + CometChat.clearActiveCall(); + CometChatCalls.endSession(); + // Close the calling screen + }, + (error) => { + console.log("End call failed:", error); + } + ); +} +``` + + + +**Remote participant** (receives the `onCallEnded()` callback): + +Call `CometChat.clearActiveCall()` to clear the local call state, then call `CometChatCalls.endSession()` to release media resources. + + + +```typescript +onCallEnded: () => { + CometChat.clearActiveCall(); + CometChatCalls.endSession(); + // Close the calling screen +} +``` + + +```javascript +onCallEnded: () => { + CometChat.clearActiveCall(); + CometChatCalls.endSession(); + // Close the calling screen +} +``` + + + +### Session Only Flow + +When using the Session Only flow (direct call without ringing), you only need to call the Calls SDK method to end the session. There's no need to notify the Chat SDK since no call signaling was involved. + + + +```typescript +onCallEndButtonPressed: () => { + CometChatCalls.endSession(); + // Close the calling screen +} +``` + + +```javascript +onCallEndButtonPressed: () => { + CometChatCalls.endSession(); + // Close the calling screen +} +``` + + + ## Call Listeners The `OngoingCallListener` provides real-time callbacks for call session events, including participant changes, call state updates, and error conditions. @@ -339,6 +438,14 @@ CometChatCalls.removeCallEventListener(listenerId); + +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"); +``` + + ### Events | Event | Description | @@ -356,126 +463,19 @@ 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. | +### Ringing Flow Return Types + 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 | +| callInitiator | `getCallInitiator()` | [`User`](/sdk/reference/entities#user) | The user who initiated the call | +| callReceiver | `getCallReceiver()` | [`User`](/sdk/reference/entities#user) \| [`Group`](/sdk/reference/entities#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. - -### Ringing Flow - -When using the [Ringing](/sdk/javascript/default-call) flow, you must coordinate between the CometChat Chat SDK and the Calls SDK to properly terminate the call and notify all participants. - - - -The Ringing flow requires calling methods from both the Chat SDK (`CometChat.endCall()`) and the Calls SDK (`CometChatCalls.endSession()`) to ensure proper call termination and participant notification. - - - - - - - -**User who initiates the end call:** - -When the user clicks the end call button in the UI, the `onCallEndButtonPressed()` callback is triggered. You must call `CometChat.endCall()` inside this callback to properly terminate the call and notify other participants. On success, call `CometChat.clearActiveCall()` and `CometChatCalls.endSession()` to release resources. - - - -```typescript -onCallEndButtonPressed: () => { - CometChat.endCall(sessionId).then( - (call: CometChat.Call) => { - console.log("Call ended successfully"); - CometChat.clearActiveCall(); - CometChatCalls.endSession(); - // Close the calling screen - }, - (error: CometChat.CometChatException) => { - console.log("End call failed:", error); - } - ); -} -``` - - -```javascript -onCallEndButtonPressed: () => { - CometChat.endCall(sessionId).then( - (call) => { - console.log("Call ended successfully"); - CometChat.clearActiveCall(); - CometChatCalls.endSession(); - // Close the calling screen - }, - (error) => { - console.log("End call failed:", error); - } - ); -} -``` - - - -**Remote participant** (receives the `onCallEnded()` callback): - -Call `CometChat.clearActiveCall()` to clear the local call state, then call `CometChatCalls.endSession()` to release media resources. - - - -```typescript -onCallEnded: () => { - CometChat.clearActiveCall(); - CometChatCalls.endSession(); - // Close the calling screen -} -``` - - -```javascript -onCallEnded: () => { - CometChat.clearActiveCall(); - CometChatCalls.endSession(); - // Close the calling screen -} -``` - - - -### Session Only Flow - -When using the Session Only flow (direct call without ringing), you only need to call the Calls SDK method to end the session. There's no need to notify the Chat SDK since no call signaling was involved. - -Call `CometChatCalls.endSession()` in the `onCallEndButtonPressed()` callback to release all media resources and disconnect from the call session. - - - -```typescript -onCallEndButtonPressed: () => { - CometChatCalls.endSession(); - // Close the calling screen -} -``` - - -```javascript -onCallEndButtonPressed: () => { - CometChatCalls.endSession(); - // Close the calling screen -} -``` - - - -## Methods +## In-Call Methods These methods are available for performing custom actions during an active call session. Use them to build custom UI controls or implement specific behaviors based on your use case. @@ -736,14 +736,6 @@ 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 From fde21dc1c6e01c1b63e505b4553b6346ad32fe67 Mon Sep 17 00:00:00 2001 From: PrajwalDhuleCC Date: Thu, 26 Mar 2026 16:57:06 +0530 Subject: [PATCH 078/139] docs(sdk): Add AI Assistant and Ongoing Call listeners documentation with reference links - Add AI Assistant Listener and Ongoing Call Listener (Calls SDK) to real-time listeners overview - Update MessageListener table with new AI Assistant message events (onAIAssistantMessageReceived, onAIToolResultReceived, onAIToolArgumentsReceived) - Add group message delivery and read receipt events to MessageListener (onMessagesDeliveredToAll, onMessagesReadByAll) - Include code examples for new MessageListener events in both JavaScript and TypeScript tabs - Add reference links to AIAssistantBaseEvent, AIAssistantMessage, AIToolResultMessage, and AIToolArgumentMessage in ai-agents documentation - Update documentation navigation structure to include entities and auxiliary reference pages - Update all-real-time-listeners description to reflect newly documented listeners - Enhance documentation with improved cross-references and listener method signatures across multiple SDK pages --- docs.json | 5 +- sdk/javascript/ai-agents.mdx | 8 +- sdk/javascript/all-real-time-listeners.mdx | 230 ++++++++++++++++++++- sdk/javascript/authentication-overview.mdx | 4 +- sdk/javascript/block-users.mdx | 2 +- sdk/javascript/delivery-read-receipts.mdx | 2 +- sdk/javascript/direct-call.mdx | 2 +- sdk/javascript/mentions.mdx | 14 +- sdk/javascript/overview.mdx | 4 +- sdk/javascript/presenter-mode.mdx | 2 +- sdk/javascript/reactions.mdx | 2 + sdk/javascript/recording.mdx | 2 +- sdk/javascript/retrieve-conversations.mdx | 2 +- sdk/javascript/retrieve-group-members.mdx | 4 +- sdk/javascript/standalone-calling.mdx | 2 +- sdk/javascript/user-management.mdx | 8 +- sdk/reference/calls.mdx | 71 +------ sdk/reference/messages.mdx | 105 ++++++++++ 18 files changed, 369 insertions(+), 100 deletions(-) diff --git a/docs.json b/docs.json index fe310ab40..b383fe6d6 100644 --- a/docs.json +++ b/docs.json @@ -2610,7 +2610,10 @@ { "group": "Reference", "pages": [ - "sdk/reference/messages" + "sdk/reference/messages", + "sdk/reference/entities", + "sdk/reference/auxiliary", + "sdk/reference/calls" ] }, { diff --git a/sdk/javascript/ai-agents.mdx b/sdk/javascript/ai-agents.mdx index 8525c4340..f4d1e8949 100644 --- a/sdk/javascript/ai-agents.mdx +++ b/sdk/javascript/ai-agents.mdx @@ -47,7 +47,7 @@ This section explains how a user’s text message to an Agent becomes a structur - After the run completes, persisted Agentic Messages arrive via the **`MessageListener`**. ### Real-time Events -Events are received via the **`onAIAssistantEventReceived`** method of the **`AIAssistantListener`** class in this general order: +Events are received via the **`onAIAssistantEventReceived`** method of the **`AIAssistantListener`** class as [`AIAssistantBaseEvent`](/sdk/reference/messages#aiassistantbaseevent) objects, in this general order: 1. Run Start 2. Zero or more tool call cycles (repeats for each tool invocation): @@ -113,9 +113,9 @@ Notes: ### 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. +- [`AIAssistantMessage`](/sdk/reference/messages#aiassistantmessage): The full assistant reply. +- [`AIToolResultMessage`](/sdk/reference/messages#aitoolresultmessage): The final output of a tool call. +- [`AIToolArgumentMessage`](/sdk/reference/messages#aitoolargumentmessage): The arguments that were passed to a tool. diff --git a/sdk/javascript/all-real-time-listeners.mdx b/sdk/javascript/all-real-time-listeners.mdx index 54a209640..6b33c0c0c 100644 --- a/sdk/javascript/all-real-time-listeners.mdx +++ b/sdk/javascript/all-real-time-listeners.mdx @@ -1,6 +1,6 @@ --- title: "All Real Time Listeners" -description: "Complete reference for all CometChat real-time listeners including User, Group, Message, and Call listeners." +description: "Complete reference for all CometChat real-time listeners including User, Group, Message, Call, AI Assistant, and Ongoing Call (Calls SDK) listeners." --- {/* TL;DR for Agents and Quick Reference */} @@ -46,6 +46,8 @@ CometChat provides 4 listeners viz. 2. [Group Listener](/sdk/javascript/all-real-time-listeners#group-listener) 3. [Message Listener](/sdk/javascript/all-real-time-listeners#message-listener) 4. [Call Listener](/sdk/javascript/all-real-time-listeners#call-listener) +5. [AI Assistant Listener](/sdk/javascript/all-real-time-listeners#ai-assistant-listener) +6. [Ongoing Call Listener (Calls SDK)](/sdk/javascript/all-real-time-listeners#ongoing-call-listener-calls-sdk) ## User Listener @@ -344,6 +346,11 @@ The `MessageListener` class provides you with live events related to messages. B | **onMessageReactionAdded(receipt: CometChat.ReactionEvent)** | This event is triggered when a reaction is added to a message in a user/group conversation. | | **onMessageReactionRemoved(receipt: CometChat.ReactionEvent)** | This event is triggered when a reaction is remove from a message in a user/group conversation. | | **onMessageModerated(message: CometChat.BaseMessage)** | This event is triggered when a message sent by the logged-in user is successfully processed by moderation and receives either an `approved` or `disapproved` status. | +| **onMessagesDeliveredToAll(receipt: CometChat.MessageReceipt)** | This event is triggered when a group message is delivered to all members. Group conversations only. | +| **onMessagesReadByAll(receipt: CometChat.MessageReceipt)** | This event is triggered when a group message is read by all members. Group conversations only. | +| **onAIAssistantMessageReceived(message: CometChat.AIAssistantMessage)** | This event is triggered when a persisted AI assistant reply is received after an agent run completes. | +| **onAIToolResultReceived(message: CometChat.AIToolResultMessage)** | This event is triggered when a persisted AI tool result message is received after an agent run completes. | +| **onAIToolArgumentsReceived(message: CometChat.AIToolArgumentMessage)** | This event is triggered when a persisted AI tool argument message is received after an agent run completes. | To add the `MessageListener`, you need to use the `addMessageListener()` method provided by the `CometChat` class. @@ -397,6 +404,21 @@ CometChat.addMessageListener( onMessageModerated: (message) => { console.log("Message Moderated", message); }, + onMessagesDeliveredToAll: (messageReceipt) => { + console.log("Message Delivered to All", messageReceipt); + }, + onMessagesReadByAll: (messageReceipt) => { + console.log("Message Read by All", messageReceipt); + }, + onAIAssistantMessageReceived: (message) => { + console.log("AI Assistant message received", message); + }, + onAIToolResultReceived: (message) => { + console.log("AI Tool result received", message); + }, + onAIToolArgumentsReceived: (message) => { + console.log("AI Tool arguments received", message); + }, }) ); ``` @@ -453,6 +475,21 @@ CometChat.addMessageListener( onMessageModerated: (message: CometChat.BaseMessage) => { console.log("Message Moderated", message); }, + onMessagesDeliveredToAll: (messageReceipt: CometChat.MessageReceipt) => { + console.log("Message Delivered to All", messageReceipt); + }, + onMessagesReadByAll: (messageReceipt: CometChat.MessageReceipt) => { + console.log("Message Read by All", messageReceipt); + }, + onAIAssistantMessageReceived: (message: CometChat.AIAssistantMessage) => { + console.log("AI Assistant message received", message); + }, + onAIToolResultReceived: (message: CometChat.AIToolResultMessage) => { + console.log("AI Tool result received", message); + }, + onAIToolArgumentsReceived: (message: CometChat.AIToolArgumentMessage) => { + console.log("AI Tool arguments received", message); + }, }) ); ``` @@ -493,6 +530,7 @@ The `CallListener` class provides you with live events related to calls. Below a | **onOutgoingCallAccepted(call: CometChat.Call)** | This event is triggered when the call initiated by the logged-in user is accepted by the recipient. The details of the call can be obtained from the Call object received as the method parameter. | | **onOutgoingCallRejected(call: CometChat.Call)** | This event is triggered when the call initiated by the logged-in user is rejected by the recipient. The details of the call can be obtained from the Call object received as the method parameter | | **onIncomingCallCancelled(call: CometChat.Call)** | This event is triggered when an incoming call is canceled by the initiator of the call. The details of the call can be obtained from the Call object received as the method parameter | +| **onCallEndedMessageReceived(call: CometChat.Call)** | This event is triggered when a call ends. The call object contains the final status and duration. | To add the `CallListener`, you need to use the `addCallListener()` method provided by the `CometChat` class. @@ -514,6 +552,9 @@ CometChat.addCallListener( onIncomingCallCancelled(call) { console.log("Incoming call canceled:", call); }, + onCallEndedMessageReceived(call) { + console.log("Call ended message:", call); + }, }) ); ``` @@ -537,6 +578,9 @@ CometChat.addCallListener( onIncomingCallCancelled: (call: CometChat.Call) => { console.log("Incoming call canceled:", call); }, + onCallEndedMessageReceived: (call: CometChat.Call) => { + console.log("Call ended message:", call); + }, }) ); ``` @@ -586,6 +630,190 @@ CometChat.removeCallListener(listenerID); --- +## AI Assistant Listener + +The `AIAssistantListener` provides real-time streaming events from AI Agent runs. These events are received as the agent processes a user's message, before the final persisted messages arrive via the `MessageListener`. + +| Method | Information | +| ------ | ----------- | +| **onAIAssistantEventReceived(event: CometChat.AIAssistantBaseEvent)** | This event is triggered for each streaming event during an AI Agent run (run start, tool calls, text message streaming, run finished). See [`AIAssistantBaseEvent`](/sdk/reference/messages#aiassistantbaseevent) for the event structure. | + + + +```js +const listenerID = "UNIQUE_LISTENER_ID"; +CometChat.addAIAssistantListener( + listenerID, + { + onAIAssistantEventReceived: (event) => { + console.log("AI Assistant event:", event.getType(), event); + }, + } +); +``` + + +```typescript +const listenerID: string = "UNIQUE_LISTENER_ID"; +CometChat.addAIAssistantListener( + listenerID, + { + onAIAssistantEventReceived: (event: CometChat.AIAssistantBaseEvent) => { + console.log("AI Assistant event:", event.getType(), event); + }, + } +); +``` + + + +To remove the listener: + + + +```js +CometChat.removeAIAssistantListener("UNIQUE_LISTENER_ID"); +``` + + +```typescript +CometChat.removeAIAssistantListener("UNIQUE_LISTENER_ID"); +``` + + + +## Ongoing Call Listener (Calls SDK) + +The `OngoingCallListener` provides real-time callbacks for active call session events. It is part of the CometChat Calls SDK (not the Chat SDK) and is used with `CallSettingsBuilder.setCallListener()` or `CometChatCalls.addCallEventListener()`. + +All three calling flows — [Call Session](/sdk/javascript/direct-call), [Standalone Calling](/sdk/javascript/standalone-calling), and [Presenter Mode](/sdk/javascript/presenter-mode) — use the same `OngoingCallListener`. + +### Callbacks + +| Callback | Parameter | Description | +|----------|-----------|-------------| +| `onUserJoined(user)` | `user` object | A remote participant joined the call | +| `onUserLeft(user)` | `user` object | A remote participant left the call | +| `onUserListUpdated(userList)` | Array of `user` objects | The participant list changed (join or leave) | +| `onCallEnded()` | — | The call session terminated (1:1 calls only, fires for both participants) | +| `onCallEndButtonPressed()` | — | The local user clicked the end call button | +| `onSessionTimeout()` | — | The call was auto-terminated due to inactivity. *v4.1.0+* | +| `onScreenShareStarted()` | — | The local user started sharing their screen | +| `onScreenShareStopped()` | — | The local user stopped sharing their screen | +| `onUserMuted(event)` | `event` object | A participant's mute state changed | +| `onCallSwitchedToVideo(event)` | `event` object | An audio call was upgraded to video | +| `onMediaDeviceListUpdated(deviceList)` | `deviceList` object | Available audio/video devices changed | +| `onRecordingStarted(event)` | `event` object | A user started recording the call | +| `onRecordingStopped()` | — | Recording was stopped | +| `onError(error)` | [`CometChatCallsException`](/sdk/reference/calls#cometchatcallsexception) | An error occurred during the call session | + +### Callback Parameter Shapes + +**`user` object** (received by `onUserJoined`, `onUserLeft`): + +| Property | Type | Description | +|----------|------|-------------| +| `name` | `string` | Display name of the user | +| `avatar` | `string` | URL of the user's avatar | +| `uid` | `string` | UID of the user | + +**`onUserListUpdated(userList)`** — receives an array of `user` objects with the same shape as above. + +**`onUserMuted(event)`**: + +| Property | Type | Description | +|----------|------|-------------| +| `event.muted.name` | `string` | Name of the muted user | +| `event.muted.uid` | `string` | UID of the muted user | +| `event.muted.isAudioMuted` | `boolean` | Whether audio is muted | +| `event.muted.isVideoMuted` | `boolean` | Whether video is muted | +| `event.mutedBy.name` | `string` | Name of the user who muted | +| `event.mutedBy.uid` | `string` | UID of the user who muted | + +**`onCallSwitchedToVideo(event)`**: + +| Property | Type | Description | +|----------|------|-------------| +| `event.sessionId` | `string` | Session ID of the call | +| `event.initiator.name` | `string` | Name of the user who initiated the switch | +| `event.initiator.uid` | `string` | UID of the initiator | +| `event.responder.name` | `string` | Name of the responder | +| `event.responder.uid` | `string` | UID of the responder | + +**`onMediaDeviceListUpdated(deviceList)`**: + +| Property | Type | Description | +|----------|------|-------------| +| `deviceList.videoInputDevices` | [`MediaDeviceInfo[]`](/sdk/reference/calls#mediadeviceinfo) | Available cameras | +| `deviceList.audioInputDevices` | [`MediaDeviceInfo[]`](/sdk/reference/calls#mediadeviceinfo) | Available microphones | +| `deviceList.audioOutputDevices` | [`MediaDeviceInfo[]`](/sdk/reference/calls#mediadeviceinfo) | Available speakers/headphones | + +**`onRecordingStarted(event)`**: + +| Property | Type | Description | +|----------|------|-------------| +| `event.user.name` | `string` | Name of the user who started recording | +| `event.user.uid` | `string` | UID of the user who started recording | + +**`onRecordingStopped()`**, **`onCallEnded()`**, **`onSessionTimeout()`**, **`onCallEndButtonPressed()`**, **`onScreenShareStarted()`**, **`onScreenShareStopped()`** — receive no arguments. + + + +```js +const listenerId = "UNIQUE_LISTENER_ID"; + +CometChatCalls.addCallEventListener(listenerId, { + onUserJoined: (user) => { + console.log("User joined:", user); + }, + onUserLeft: (user) => { + console.log("User left:", user); + }, + onCallEnded: () => { + console.log("Call ended"); + }, + onCallEndButtonPressed: () => { + console.log("End call button pressed"); + }, + onError: (error) => { + console.log("Call error:", error); + }, +}); + +// Remove listener when done +CometChatCalls.removeCallEventListener(listenerId); +``` + + +```typescript +const listenerId: string = "UNIQUE_LISTENER_ID"; + +CometChatCalls.addCallEventListener(listenerId, { + onUserJoined: (user: any) => { + console.log("User joined:", user); + }, + onUserLeft: (user: any) => { + console.log("User left:", user); + }, + onCallEnded: () => { + console.log("Call ended"); + }, + onCallEndButtonPressed: () => { + console.log("End call button pressed"); + }, + onError: (error: any) => { + console.log("Call error:", error); + }, +}); + +// Remove listener when done +CometChatCalls.removeCallEventListener(listenerId); +``` + + + +--- + ## Next Steps diff --git a/sdk/javascript/authentication-overview.mdx b/sdk/javascript/authentication-overview.mdx index 2a4f6499e..3ec339dc6 100644 --- a/sdk/javascript/authentication-overview.mdx +++ b/sdk/javascript/authentication-overview.mdx @@ -155,7 +155,7 @@ try { | UID | The UID of the user that you would like to login | | authKey | CometChat Auth Key | -After the user logs in, their information is returned in the `User` object on `Promise` resolved. +After the user logs in, their information is returned in the [`User`](/sdk/reference/entities#user) object on `Promise` resolved. ## Login using Auth Token @@ -239,7 +239,7 @@ try { | --------- | ---------------------------------------------- | | authToken | Auth Token of the user you would like to login | -After the user logs in, their information is returned in the `User` object on the `Promise` resolved. +After the user logs in, their information is returned in the [`User`](/sdk/reference/entities#user) object on the `Promise` resolved. ## Logout diff --git a/sdk/javascript/block-users.mdx b/sdk/javascript/block-users.mdx index d7467b36b..2303d4d77 100644 --- a/sdk/javascript/block-users.mdx +++ b/sdk/javascript/block-users.mdx @@ -241,7 +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. +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`](/sdk/reference/entities#user) objects containing n number of blocked users where N is the limit set in the builder class. diff --git a/sdk/javascript/delivery-read-receipts.mdx b/sdk/javascript/delivery-read-receipts.mdx index cbaf4d96a..dfca32055 100644 --- a/sdk/javascript/delivery-read-receipts.mdx +++ b/sdk/javascript/delivery-read-receipts.mdx @@ -649,7 +649,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. diff --git a/sdk/javascript/direct-call.mdx b/sdk/javascript/direct-call.mdx index 30430a20d..cd799c3b1 100644 --- a/sdk/javascript/direct-call.mdx +++ b/sdk/javascript/direct-call.mdx @@ -345,7 +345,7 @@ CometChatCalls.removeCallEventListener(listenerId); ### Events -For the full list of callbacks, their descriptions, and parameter shapes, see the [`OngoingCallListener`](/sdk/reference/calls#ongoingcalllistener) reference. +For the full list of callbacks, their descriptions, and parameter shapes, see the [`OngoingCallListener`](/sdk/javascript/all-real-time-listeners#ongoing-call-listener-calls-sdk) reference. The ringing flow methods (`initiateCall()`, `acceptCall()`, `rejectCall()`, `endCall()`) return [`Call`](/sdk/reference/messages#call) objects. diff --git a/sdk/javascript/mentions.mdx b/sdk/javascript/mentions.mdx index 853a1089a..e85eb968d 100644 --- a/sdk/javascript/mentions.mdx +++ b/sdk/javascript/mentions.mdx @@ -146,13 +146,6 @@ By default, the SDK will fetch all the messages irrespective of the fact that th To get a list of messages in a conversation where users are mentioned along with the user tags of the mentioned users. -Relevant fields to access on returned messages and their mentioned users: - -| Field | Getter | Return Type | Description | -|-------|--------|-------------|-------------| -| mentionedUsers | `getMentionedUsers()` | [`User[]`](/sdk/reference/entities#user) | Array of users mentioned in the message | -| tags (on each mentioned user) | `getTags()` | `string[]` | Tags associated with the mentioned user | - ```javascript @@ -268,6 +261,13 @@ messagesRequest.fetchPrevious().then( +Relevant fields to access on returned messages and their mentioned users: + +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| mentionedUsers | `getMentionedUsers()` | [`User[]`](/sdk/reference/entities#user) | Array of users mentioned in the message | +| tags (on each mentioned user) | `getTags()` | `string[]` | Tags associated with the mentioned user | + ## Mentions With Blocked Info To get a list of messages in a conversation where users are mentioned along with the blocked relationship of the mentioned users with the logged-in user. diff --git a/sdk/javascript/overview.mdx b/sdk/javascript/overview.mdx index 2c025e641..1804b65ed 100644 --- a/sdk/javascript/overview.mdx +++ b/sdk/javascript/overview.mdx @@ -413,7 +413,7 @@ Make sure you replace the `APP_ID` with your CometChat **App ID** and `APP_REGIO ## 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. +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`](/sdk/reference/entities#user) object and the `Auth Key` as input parameters and returns the created `User` object if the request is successful. @@ -575,7 +575,7 @@ We have set up 5 users for testing having UIDs: `cometchat-uid-1`, `cometchat-ui -The `login()` method returns the `User` object on `Promise` resolved containing all the information of the logged-in user. +The `login()` method returns the [`User`](/sdk/reference/entities#user) object on `Promise` resolved containing all the information of the logged-in user. diff --git a/sdk/javascript/presenter-mode.mdx b/sdk/javascript/presenter-mode.mdx index c74ba2200..ff8b3719d 100644 --- a/sdk/javascript/presenter-mode.mdx +++ b/sdk/javascript/presenter-mode.mdx @@ -115,7 +115,7 @@ useEffect(() => { -The `OngoingCallListener` provides the same callbacks as in [Call Session](/sdk/javascript/direct-call) and [Standalone Calling](/sdk/javascript/standalone-calling). For the full list of callbacks and their parameter shapes, see the [`OngoingCallListener`](/sdk/reference/calls#ongoingcalllistener) reference. +The `OngoingCallListener` provides the same callbacks as in [Call Session](/sdk/javascript/direct-call) and [Standalone Calling](/sdk/javascript/standalone-calling). For the full list of callbacks and their parameter shapes, see the [`OngoingCallListener`](/sdk/javascript/all-real-time-listeners#ongoing-call-listener-calls-sdk) reference. ## Settings diff --git a/sdk/javascript/reactions.mdx b/sdk/javascript/reactions.mdx index 45f3fffcb..2acb6ccf1 100644 --- a/sdk/javascript/reactions.mdx +++ b/sdk/javascript/reactions.mdx @@ -401,6 +401,8 @@ action +On success, this method returns a [`BaseMessage`](/sdk/reference/messages#basemessage) object + 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. diff --git a/sdk/javascript/recording.mdx b/sdk/javascript/recording.mdx index 52682d5ab..bbdaabf74 100644 --- a/sdk/javascript/recording.mdx +++ b/sdk/javascript/recording.mdx @@ -95,7 +95,7 @@ CometChatCalls.startSession(callToken, callSettings, htmlElement); -The `onRecordingStarted` callback receives an event object — see the [`OngoingCallListener`](/sdk/reference/calls#ongoingcalllistener) reference for the full shape. +The `onRecordingStarted` callback receives an event object — see the [`OngoingCallListener`](/sdk/javascript/all-real-time-listeners#ongoing-call-listener-calls-sdk) reference for the full shape. The `onRecordingStopped` callback receives no arguments. diff --git a/sdk/javascript/retrieve-conversations.mdx b/sdk/javascript/retrieve-conversations.mdx index 60442be6d..2528ce7e1 100644 --- a/sdk/javascript/retrieve-conversations.mdx +++ b/sdk/javascript/retrieve-conversations.mdx @@ -508,7 +508,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. +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`](/sdk/reference/entities#conversation) objects containing X number of users depending on the limit set. A Maximum of only 50 Conversations can be fetched at once. diff --git a/sdk/javascript/retrieve-group-members.mdx b/sdk/javascript/retrieve-group-members.mdx index 60738b4b7..8377ea3dc 100644 --- a/sdk/javascript/retrieve-group-members.mdx +++ b/sdk/javascript/retrieve-group-members.mdx @@ -34,7 +34,7 @@ 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. -Fetching using this builder will return [`GroupMember`](/sdk/reference/entities#groupmember) objects. `GroupMember` extends `User` and adds group-specific fields. +Fetching using this builder will return [`GroupMember`](/sdk/reference/entities#groupmember) objects. `GroupMember` extends [`User`](/sdk/reference/entities#user) and adds group-specific fields. ### Set Limit @@ -224,7 +224,7 @@ groupMembersRequest.fetchNext().then( -The `fetchNext()` method returns an array of [`GroupMember`](/sdk/reference/entities#groupmember) objects. `GroupMember` extends `User` and adds group-specific fields. +The `fetchNext()` method returns an array of [`GroupMember`](/sdk/reference/entities#groupmember) objects. `GroupMember` extends [`User`](/sdk/reference/entities#user) and adds group-specific fields. - **Paginate results** — Always use `fetchNext()` in a loop or on-scroll. Set a reasonable limit (10–30) per request to avoid large payloads. diff --git a/sdk/javascript/standalone-calling.mdx b/sdk/javascript/standalone-calling.mdx index 3cdacd7f9..085825540 100644 --- a/sdk/javascript/standalone-calling.mdx +++ b/sdk/javascript/standalone-calling.mdx @@ -373,7 +373,7 @@ CometChatCalls.removeCallEventListener(listenerId); ### Events -For the full list of callbacks, their descriptions, and parameter shapes, see the [`OngoingCallListener`](/sdk/reference/calls#ongoingcalllistener) reference. +For the full list of callbacks, their descriptions, and parameter shapes, see the [`OngoingCallListener`](/sdk/javascript/all-real-time-listeners#ongoing-call-listener-calls-sdk) reference. ## End Call Session diff --git a/sdk/javascript/user-management.mdx b/sdk/javascript/user-management.mdx index 0655c2d1d..c821df555 100644 --- a/sdk/javascript/user-management.mdx +++ b/sdk/javascript/user-management.mdx @@ -50,7 +50,7 @@ Ideally, user creation should take place at your backend. You can refer our Rest **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. +However, if you wish to create users on the fly, you can use the `createUser()` method. This method takes a [`User`](/sdk/reference/entities#user) object and the `Auth Key` as input parameters and returns the created `User` object if the request is successful. @@ -103,7 +103,7 @@ UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and othe ## Updating a 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. +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`](/sdk/reference/entities#user) object and the `Auth Key` as inputs and returns the updated `User` object on the successful execution of the request. @@ -146,13 +146,13 @@ 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. +Please make sure the [`User`](/sdk/reference/entities#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. ## 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. +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`](/sdk/reference/entities#user) object as input and returns the updated `User` object on the successful execution of the request. diff --git a/sdk/reference/calls.mdx b/sdk/reference/calls.mdx index 0c32a935e..04ea85a3f 100644 --- a/sdk/reference/calls.mdx +++ b/sdk/reference/calls.mdx @@ -107,76 +107,7 @@ All properties on proper classes are accessed via getter methods. Listener event ## OngoingCallListener -`OngoingCallListener` provides real-time callbacks for call session events. It is used with `CallSettingsBuilder.setCallListener()` or `CometChatCalls.addCallEventListener()`. - -All three calling flows — [Call Session](/sdk/javascript/direct-call), [Standalone Calling](/sdk/javascript/standalone-calling), and [Presenter Mode](/sdk/javascript/presenter-mode) — use the same `OngoingCallListener` with identical callbacks. - -### Callbacks - -| Callback | Parameter | Description | -|----------|-----------|-------------| -| `onUserJoined(user)` | `user` object | A remote participant joined the call | -| `onUserLeft(user)` | `user` object | A remote participant left the call | -| `onUserListUpdated(userList)` | Array of `user` objects | The participant list changed (join or leave) | -| `onCallEnded()` | — | The call session terminated (1:1 calls only, fires for both participants) | -| `onCallEndButtonPressed()` | — | The local user clicked the end call button | -| `onSessionTimeout()` | — | The call was auto-terminated due to inactivity. *v4.1.0+* | -| `onScreenShareStarted()` | — | The local user started sharing their screen | -| `onScreenShareStopped()` | — | The local user stopped sharing their screen | -| `onUserMuted(event)` | `event` object | A participant's mute state changed | -| `onCallSwitchedToVideo(event)` | `event` object | An audio call was upgraded to video | -| `onMediaDeviceListUpdated(deviceList)` | `deviceList` object | Available audio/video devices changed | -| `onRecordingStarted(event)` | `event` object | A user started recording the call | -| `onRecordingStopped()` | — | Recording was stopped | -| `onError(error)` | [`CometChatCallsException`](#cometchatcallsexception) | An error occurred during the call session | - -### Callback Parameter Shapes - -**`user` object** (received by `onUserJoined`, `onUserLeft`): - -| Property | Type | Description | -|----------|------|-------------| -| `name` | `string` | Display name of the user | -| `avatar` | `string` | URL of the user's avatar | -| `uid` | `string` | UID of the user | - -**`onUserListUpdated(userList)`** — receives an array of `user` objects with the same shape as above. - -**`onUserMuted(event)`**: - -| Property | Type | Description | -|----------|------|-------------| -| `event.muted.name` | `string` | Name of the muted user | -| `event.muted.uid` | `string` | UID of the muted user | -| `event.muted.isAudioMuted` | `boolean` | Whether audio is muted | -| `event.muted.isVideoMuted` | `boolean` | Whether video is muted | -| `event.mutedBy.name` | `string` | Name of the user who muted | -| `event.mutedBy.uid` | `string` | UID of the user who muted | - -**`onCallSwitchedToVideo(event)`**: - -| Property | Type | Description | -|----------|------|-------------| -| `event.sessionId` | `string` | Session ID of the call | -| `event.initiator.name` | `string` | Name of the user who initiated the switch | -| `event.initiator.uid` | `string` | UID of the initiator | -| `event.responder.name` | `string` | Name of the responder | -| `event.responder.uid` | `string` | UID of the responder | - -**`onMediaDeviceListUpdated(deviceList)`**: - -| Property | Type | Description | -|----------|------|-------------| -| `deviceList.videoInputDevices` | [`MediaDeviceInfo[]`](#mediadeviceinfo) | Available cameras | -| `deviceList.audioInputDevices` | [`MediaDeviceInfo[]`](#mediadeviceinfo) | Available microphones | -| `deviceList.audioOutputDevices` | [`MediaDeviceInfo[]`](#mediadeviceinfo) | Available speakers/headphones | - -**`onRecordingStarted(event)`**: - -| Property | Type | Description | -|----------|------|-------------| -| `event.user.name` | `string` | Name of the user who started recording | -| `event.user.uid` | `string` | UID of the user who started recording | +For the full `OngoingCallListener` documentation including all callbacks and parameter shapes, see the [All Real-Time Listeners](/sdk/javascript/all-real-time-listeners#ongoing-call-listener-calls-sdk) page. --- diff --git a/sdk/reference/messages.mdx b/sdk/reference/messages.mdx index b789a66e9..4d9e79250 100644 --- a/sdk/reference/messages.mdx +++ b/sdk/reference/messages.mdx @@ -215,3 +215,108 @@ It inherits all properties from `BaseMessage` and adds the following. | 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 | + +--- + +## AIAssistantMessage + +`AIAssistantMessage` extends [BaseMessage](#basemessage) and represents the full assistant reply persisted after an AI Agent run completes. It is received via the `onAIAssistantMessageReceived` callback of the [MessageListener](/sdk/javascript/all-real-time-listeners#message-listener). + +It inherits all properties from `BaseMessage` and adds the following. + +### Properties + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| assistantMessageData | `getAssistantMessageData()` | `AIAssistantMessageData` | The assistant message data containing runId, threadId, and text | + +### AIAssistantMessageData + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| runId | `getRunId()` | `string` | The run ID of the agent execution | +| threadId | `getThreadId()` | `string` | The thread ID of the conversation | +| text | `getText()` | `string` | The full text of the assistant's reply | + +--- + +## AIToolResultMessage + +`AIToolResultMessage` extends [BaseMessage](#basemessage) and represents the output of a tool call made during an AI Agent run. It is received via the `onAIToolResultReceived` callback of the [MessageListener](/sdk/javascript/all-real-time-listeners#message-listener). + +It inherits all properties from `BaseMessage` and adds the following. + +### Properties + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| toolResultMessageData | `getToolResultMessageData()` | `AIToolResultMessageData` | The tool result data containing runId, threadId, text, and toolCallId | + +### AIToolResultMessageData + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| runId | `getRunId()` | `string` | The run ID of the agent execution | +| threadId | `getThreadId()` | `string` | The thread ID of the conversation | +| text | `getText()` | `string` | The text output of the tool | +| toolCallId | `getToolCallId()` | `string` | The ID of the tool call this result belongs to | + +--- + +## AIToolArgumentMessage + +`AIToolArgumentMessage` extends [BaseMessage](#basemessage) and represents the arguments passed to a tool during an AI Agent run. It is received via the `onAIToolArgumentsReceived` callback of the [MessageListener](/sdk/javascript/all-real-time-listeners#message-listener). + +It inherits all properties from `BaseMessage` and adds the following. + +### Properties + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| toolArgumentMessageData | `getToolArgumentMessageData()` | `AIToolArgumentMessageData` | The tool argument data containing runId, threadId, and toolCalls | + +### AIToolArgumentMessageData + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| runId | `getRunId()` | `string` | The run ID of the agent execution | +| threadId | `getThreadId()` | `string` | The thread ID of the conversation | +| toolCalls | `getToolCalls()` | `AIToolCall[]` | Array of tool calls with their arguments | + +### AIToolCall + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| id | `getId()` | `string` | Unique tool call ID | +| type | `getType()` | `string` | Type of the tool call | +| displayName | `getDisplayName()` | `string` | Display name of the tool | +| executionText | `getExecutionText()` | `string` | Execution text for the tool | +| function | `getFunction()` | `AIToolCallFunction` | The function details (name and arguments) | + +### AIToolCallFunction + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| name | `getName()` | `string` | Name of the function being called | +| arguments | `getArguments()` | `string` | JSON string of the arguments passed to the function | + +--- + +## AIAssistantBaseEvent + +`AIAssistantBaseEvent` is the base class for all real-time streaming events from an AI Agent run. It is received via the `onAIAssistantEventReceived` callback of the [AIAssistantListener](/sdk/javascript/all-real-time-listeners#ai-assistant-listener). + +The `type` field identifies the specific event (e.g., `"run_started"`, `"tool_call_started"`, `"text_message_content"`, `"run_finished"`). + +### Properties + +| Property | Getter | Return Type | Description | +|----------|--------|-------------|-------------| +| type | `getType()` | `string` | The event type identifier | +| conversationId | `getConversationId()` | `string` | The conversation ID associated with the event | +| messageId | `getMessageId()` | `string` | The message ID associated with the event | +| parentMessageId | `getParentMessageId()` | `string` | The parent message ID (if in a thread) | +| data | `getData()` | `object` | Additional event-specific data | +| data.timestamp | `getTimestamp()` | `number` | Timestamp of the event | +| data.runId | `getRunId()` | `string` | The run ID of the agent execution | +| data.threadId | `getThreadId()` | `string` | The thread ID of the conversation | From 02e9de044be29467bd4540ea8bd12b11b11839f6 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 16:57:12 +0530 Subject: [PATCH 079/139] Update standalone-calling.mdx --- sdk/javascript/standalone-calling.mdx | 62 +++++++++++++-------------- 1 file changed, 31 insertions(+), 31 deletions(-) diff --git a/sdk/javascript/standalone-calling.mdx b/sdk/javascript/standalone-calling.mdx index df61c6ff3..8be85f915 100644 --- a/sdk/javascript/standalone-calling.mdx +++ b/sdk/javascript/standalone-calling.mdx @@ -4,7 +4,6 @@ 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." --- -{/* TL;DR for Agents and Quick Reference */} ```javascript @@ -23,9 +22,10 @@ CometChatCalls.startSession(callToken.token, callSettings, htmlElement); 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. +Standalone Calling lets you add voice and video calls using only the CometChat Calls SDK — no Chat SDK required. This is ideal when you already have your own messaging system and just need calling, or when you want the smallest possible SDK footprint. + +The key difference from the regular [Call Session](/sdk/javascript/direct-call) flow is authentication: instead of using `CometChat.getLoggedinUser()`, you obtain auth tokens directly from the CometChat REST API. Before you begin, ensure you have completed the [Calls SDK setup](/sdk/javascript/calling-setup). @@ -247,14 +247,33 @@ Configure the call experience using the following `CallSettingsBuilder` methods: | `setMainVideoContainerSetting(MainVideoContainerSetting)` | Customizes the main video container. See [Video View Customization](/sdk/javascript/video-view-customisation). | | `setIdleTimeoutPeriod(number)` | Sets idle timeout in seconds. Warning appears 60 seconds before auto-termination. Default: `180` seconds. *v4.1.0+* | +## End Call Session + +To end the call session and release all media resources (camera, microphone, network connections), call `CometChatCalls.endSession()` in the `onCallEndButtonPressed()` callback. + + + +```typescript +onCallEndButtonPressed: () => { + CometChatCalls.endSession(); + // Close the calling screen +} +``` + + +```javascript +onCallEndButtonPressed: () => { + CometChatCalls.endSession(); + // Close the calling screen +} +``` + + + ## Call Listeners 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 @@ -264,6 +283,10 @@ Each listener requires a unique `listenerId` string. This ID is used to: - **Prevent duplicate registrations** — Re-registering with the same ID replaces the existing listener - **Enable targeted removal** — Remove specific listeners without affecting others + +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. + + ```typescript @@ -386,30 +409,7 @@ 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. | -## End Call Session - -To end the call session and release all media resources (camera, microphone, network connections), call `CometChatCalls.endSession()` in the `onCallEndButtonPressed()` callback. - - - -```typescript -onCallEndButtonPressed: () => { - CometChatCalls.endSession(); - // Close the calling screen -} -``` - - -```javascript -onCallEndButtonPressed: () => { - CometChatCalls.endSession(); - // Close the calling screen -} -``` - - - -## Methods +## In-Call Methods These methods are available for performing custom actions during an active call session. Use them to build custom UI controls or implement specific behaviors based on your use case. From 4bf61c5570e3de0712484f8712a9dcf7e584af36 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 16:59:47 +0530 Subject: [PATCH 080/139] Update recording.mdx --- sdk/javascript/recording.mdx | 31 +++++++++++++------------------ 1 file changed, 13 insertions(+), 18 deletions(-) diff --git a/sdk/javascript/recording.mdx b/sdk/javascript/recording.mdx index 1e36e23bb..10378f81c 100644 --- a/sdk/javascript/recording.mdx +++ b/sdk/javascript/recording.mdx @@ -24,17 +24,11 @@ const callListener = new CometChatCalls.OngoingCallListener({ **Recordings are available on the [CometChat Dashboard](https://app.cometchat.com) → Calls section.** -Record voice and video calls for playback, compliance, or archival purposes. +Record voice and video calls for playback, compliance, or archival purposes. Recording is built on top of the [Call Session](/sdk/javascript/direct-call) — you add recording listeners to your call settings and optionally control recording programmatically. -## Implementation +## Setup -After setting up [Ringing](/sdk/javascript/default-call) or [Call Session](/sdk/javascript/direct-call), add recording listeners and methods to your call settings. - -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. - +Add `onRecordingStarted` and `onRecordingStopped` callbacks to your `OngoingCallListener` when building call settings. These fire for all participants when any user starts or stops recording. @@ -59,7 +53,6 @@ const callSettings = new CometChatCalls.CallSettingsBuilder() const htmlElement = document.getElementById("ELEMENT_ID"); CometChatCalls.startSession(callToken, callSettings, htmlElement); ``` - @@ -84,21 +77,23 @@ const callSettings = new CometChatCalls.CallSettingsBuilder() const htmlElement = document.getElementById("ELEMENT_ID"); CometChatCalls.startSession(callToken, callSettings, htmlElement); ``` - - -## Settings + +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. + -Configure recording options using `CallSettingsBuilder`: +## CallSettings Options -| 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** | +| 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 custom UI without the default layout, use these methods to control recording: +## Programmatic Control + +If you're building a custom UI without the default layout, use these methods to control recording during an active call. ### Start Recording From 227360eeb729f7ad7bdc11455bf44240dbed1deb Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 17:01:32 +0530 Subject: [PATCH 081/139] Update virtual-background.mdx --- sdk/javascript/virtual-background.mdx | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/sdk/javascript/virtual-background.mdx b/sdk/javascript/virtual-background.mdx index b35aecff7..808ebb534 100644 --- a/sdk/javascript/virtual-background.mdx +++ b/sdk/javascript/virtual-background.mdx @@ -13,22 +13,24 @@ description: "Implement virtual background features in CometChat video calls — - **Requires:** [Default Calling](/sdk/javascript/default-call) or [Direct Calling](/sdk/javascript/direct-call) setup -Apply blur or custom image backgrounds during video calls. +Virtual backgrounds let users blur their background or replace it with a custom image during video calls. You can configure defaults at build time via `CallSettingsBuilder`, and control them programmatically at runtime via `CallController`. -## Implementation +Before you begin, make sure you've set up [Ringing](/sdk/javascript/default-call) or [Call Session](/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. +## CallSettings Options -## Settings +Configure virtual background behavior when building your call settings: -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** | +| 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 custom UI without the default layout, use these methods to control virtual background: +See [VirtualBackground Class](#virtualbackground-class) below for the full configuration options you can pass to `setVirtualBackground()`. + +## Runtime Control + +For custom UI without the default layout, use `CallController` to control virtual background during an active call. ### Open Virtual Background Setting @@ -91,7 +93,7 @@ callController.setBackgroundImage(imageURL); -## Virtual Background Settings +## VirtualBackground Class The `VirtualBackground` class controls how users interact with virtual background features. Pass a `VirtualBackground` instance to `setVirtualBackground()` in `CallSettingsBuilder`. From 95a71522c47d9b0dfc207c5fb3e5aeb0dc1af277 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 17:04:25 +0530 Subject: [PATCH 082/139] Update video-view-customisation.mdx --- sdk/javascript/video-view-customisation.mdx | 41 +++++++++++++++------ 1 file changed, 29 insertions(+), 12 deletions(-) diff --git a/sdk/javascript/video-view-customisation.mdx b/sdk/javascript/video-view-customisation.mdx index 851b50845..7d5c7179d 100644 --- a/sdk/javascript/video-view-customisation.mdx +++ b/sdk/javascript/video-view-customisation.mdx @@ -13,24 +13,29 @@ 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 -Customize the main video container layout, including aspect ratio, button positions, and label visibility. +Customize the main video container in your call UI — aspect ratio, button positions, and label visibility. Create a `MainVideoContainerSetting` instance, configure it, and pass it to `CallSettingsBuilder.setMainVideoContainerSetting()`. -## Implementation +Before you begin, make sure you've set up [Ringing](/sdk/javascript/default-call) or [Call Session](/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. +## MainVideoContainerSetting -## Main Video Container Setting +| Method | Description | Default | +| ------ | ----------- | ------- | +| `setMainVideoAspectRatio(aspectRatio)` | Aspect ratio of the main video. Values: `ASPECT_RATIO_CONTAIN`, `ASPECT_RATIO_COVER` | `ASPECT_RATIO_CONTAIN` | +| `setFullScreenButtonParams(position, visibility)` | Position and visibility of the full screen button. | Bottom-right, visible | +| `setNameLabelParams(position, visibility, backgroundColor)` | Position, visibility, and background color of the participant name label. | Bottom-left, visible, `rgba(27, 27, 27, 0.4)` | +| `setNetworkLabelParams(position, visibility)` | Position and visibility of the network quality label. | Bottom-right, visible | -The `MainVideoContainerSetting` class customizes the main video view. Pass a `MainVideoContainerSetting` instance to `setMainVideoContainerSetting()` in `CallSettingsBuilder`. +### Position Constants -| Setting | Description | -| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `setMainVideoAspectRatio(aspectRatio: string)` | This method is used to set the aspect ratio of main video. The default value is **contain.**

Possible Values:
**1. CometChat.CallSettings. ASPECT\_RATIO\_CONTAIN\*\*\*\***
**2. CometChat.CallSettings. ASPECT\_RATIO\_COVER** | -| `setFullScreenButtonParams(position: string, visibility: boolean)` | This method is used to set the position & visibility parameter of the full screen button. By default the full screen button is visible in the **bottom-right** position.

Possible Values for **POSITION:**
1. **CometChat.CallSettings. POSITION\_TOP\_LEFT**
2. **CometChat.CallSettings. POSITION\_TOP\_RIGHT**
3. **CometChat.CallSettings. POSITION\_BOTTOM\_LEFT**
4. **CometChat.CallSettings. POSITION\_BOTTOM\_RIGHT**

Possible Values for **VISIBILITY:**
1. **true**
2. **false** | -| `setNameLabelParams(position: string, visibility: boolean, backgroundColor: string)` | This method is used to set the position, visibility & background color of the name label. By default the name label is visible in the **bottom-left** position with a background-color \*\*rgba(27, 27, 27, 0.4)\*\*

Possible Values for **POSITION:**
1. **CometChat.CallSettings. POSITION\_TOP\_LEFT**
2. **CometChat.CallSettings. POSITION\_TOP\_RIGHT**
3. **CometChat.CallSettings. POSITION\_BOTTOM\_LEFT**
4. **CometChat.CallSettings. POSITION\_BOTTOM\_RIGHT**

Possible Values for **VISIBILITY:**
1. **true**
2. **false** | -| `setNetworkLabelParams(position: string, visibility: boolean)` | This method is used to set the position, visibility of the network label. By default the network label is visible in the **bottom-right** position.

Possible Values for **POSITION:**
1. **CometChat.CallSettings. POSITION\_TOP\_LEFT**
2. **CometChat.CallSettings. POSITION\_TOP\_RIGHT**
3. **CometChat.CallSettings. POSITION\_BOTTOM\_LEFT**
4. **CometChat.CallSettings. POSITION\_BOTTOM\_RIGHT**

Possible Values for **VISIBILITY:**
1. **true**
2. **false** | +All position parameters accept one of these values from `CometChat.CallSettings`: -Example: +- `POSITION_TOP_LEFT` +- `POSITION_TOP_RIGHT` +- `POSITION_BOTTOM_LEFT` +- `POSITION_BOTTOM_RIGHT` + +### Example @@ -41,6 +46,12 @@ videoSettings.setMainVideoAspectRatio(CometChat.CallSettings.ASPECT_RATIO_CONTAI videoSettings.setFullScreenButtonParams(CometChat.CallSettings.POSITION_BOTTOM_RIGHT, true); videoSettings.setNameLabelParams(CometChat.CallSettings.POSITION_BOTTOM_LEFT, true, "rgba(27, 27, 27, 0.4)"); videoSettings.setNetworkLabelParams(CometChat.CallSettings.POSITION_BOTTOM_RIGHT, true); + +// Pass to CallSettingsBuilder +const callSettings = new CometChatCalls.CallSettingsBuilder() + .setMainVideoContainerSetting(videoSettings) + // ... other settings + .build(); ``` @@ -51,6 +62,12 @@ videoSettings.setMainVideoAspectRatio(CometChat.CallSettings.ASPECT_RATIO_CONTAI videoSettings.setFullScreenButtonParams(CometChat.CallSettings.POSITION_BOTTOM_RIGHT, true); videoSettings.setNameLabelParams(CometChat.CallSettings.POSITION_BOTTOM_LEFT, true, "rgba(27, 27, 27, 0.4)"); videoSettings.setNetworkLabelParams(CometChat.CallSettings.POSITION_BOTTOM_RIGHT, true); + +// Pass to CallSettingsBuilder +const callSettings = new CometChatCalls.CallSettingsBuilder() + .setMainVideoContainerSetting(videoSettings) + // ... other settings + .build(); ``` From a491fd2cc7ffc054910f33e66539a4a2c5142ea0 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 17:06:25 +0530 Subject: [PATCH 083/139] Update custom-css.mdx --- sdk/javascript/custom-css.mdx | 50 ++++++++++++++++++----------------- 1 file changed, 26 insertions(+), 24 deletions(-) diff --git a/sdk/javascript/custom-css.mdx b/sdk/javascript/custom-css.mdx index e02ba8841..59d7637e0 100644 --- a/sdk/javascript/custom-css.mdx +++ b/sdk/javascript/custom-css.mdx @@ -4,7 +4,6 @@ sidebarTitle: "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 */} ```css @@ -22,37 +21,43 @@ description: "Customize the CometChat calling UI with custom CSS classes for but **Modes:** `DEFAULT` | `TILE` | `SPOTLIGHT` -Style the calling UI with custom CSS to match your application's design. +The CometChat calling UI exposes CSS classes you can target to style buttons, video containers, labels, and layouts. Your CSS is applied globally — any styles you write for these classes will affect the call UI across all modes (DEFAULT, TILE, SPOTLIGHT). -## Common CSS Classes +Before you begin, make sure you've set up [Ringing](/sdk/javascript/default-call) or [Call Session](/sdk/javascript/direct-call). -These classes are available across all call modes: + +Only use CSS classes documented here — targeting undocumented classes may cause UI issues. Avoid resizing the grid container to prevent layout distortions. + + +## CSS Class Reference + +### Layout Containers | 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 | +| `cc-name-label` | User name text container | -## Bottom Buttons +### Action Buttons | Class | Description | | ----- | ----------- | -| `cc-bottom-buttons-container` | Container for all action buttons | +| `cc-bottom-buttons-container` | Bottom bar containing action buttons (mute, end call, etc.) | | `cc-bottom-buttons-icon-container` | Individual button wrapper | +| `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 | -### Individual Button Classes +## Examples -- `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 +### Basic Styling -### Example +This example applies colored backgrounds to buttons and dotted borders to containers to visualize the layout structure: @@ -96,7 +101,7 @@ These classes are available across all call modes: -The above example results in the below output:- +Here's how it looks across the three call modes: **Mode: `DEFAULT`** @@ -172,16 +177,13 @@ The above example results in the below output:-
-The above example results in the below output:- +### Polished UI + +This example shows a more refined customization with rounded buttons, custom spacing, and a patterned video background: -### Guidelines - -- Only use CSS classes documented here — custom classes may cause UI issues -- Avoid resizing the grid container to prevent layout distortions - --- ## Next Steps From b3860673c94f76d9adeed089b26c5964e2143485 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 17:11:18 +0530 Subject: [PATCH 084/139] Update presenter-mode.mdx --- sdk/javascript/presenter-mode.mdx | 43 +++++++++++++------------------ 1 file changed, 18 insertions(+), 25 deletions(-) diff --git a/sdk/javascript/presenter-mode.mdx b/sdk/javascript/presenter-mode.mdx index bc995697d..a6bf72ddd 100644 --- a/sdk/javascript/presenter-mode.mdx +++ b/sdk/javascript/presenter-mode.mdx @@ -4,7 +4,6 @@ sidebarTitle: "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 */} ```javascript @@ -22,24 +21,18 @@ CometChatCalls.joinPresentation(callToken, settings, htmlElement); - **Viewer** (up to 100 total): Passive consumers, no outgoing streams -## Overview - -Presenter Mode enables broadcast-style calling experiences where presenters share content with passive viewers. +Presenter Mode enables broadcast-style calling — up to 5 presenters share content with passive viewers (up to 100 total participants). Use it for webinars, keynotes, all-hands meetings, online classes, or talk shows. | 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 | -Use cases: webinars, keynotes, all-hands meetings, online classes, talk shows. - 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 - -Configure the presentation using `PresentationSettingsBuilder`. Set the user type with `setIsPresenter(true)` for presenters or `setIsPresenter(false)` for viewers. +## Start a Presentation Session -Basic example: +Configure the presentation using `PresentationSettingsBuilder`. Set `setIsPresenter(true)` for presenters or `setIsPresenter(false)` for viewers. @@ -129,21 +122,21 @@ useEffect(() => { Configure the presentation experience using `PresentationSettingsBuilder`: -| Parameter | Description | -| ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `setIsPresenter(isPresenter: boolean)` | If set to `true` user will join as the presenter. If set to `false` user will join as the viewer. | -| `enableDefaultLayout(defaultLayout: boolean)` | If set to `true` enables the default layout for handling the call operations. If set to `false` it hides the button layout and just displays the Call View. **Default value = true** | -| `showEndCallButton(showEndCallButton: boolean)` | If set to `true` it displays the EndCallButton in Button Layout. If set to `false` it hides the EndCallButton in Button Layout. **Default value = true** | -| `showPauseVideoButton(showPauseVideoButton: boolean)` | If set to `true` it displays the PauseVideoButton in Button Layout. If set to `false` it hides the PauseVideoButton in Button Layout. **Default value = true** | -| `showMuteAudioButton`(showMuteAudioButton: boolean)\`\` | If set to `true` it displays the MuteAudioButton in Button Layout. If set to `false` it hides the MuteAudioButton in Button Layout. **Default value = true** | -| `showSwitchCameraButton`(showSwitchCameraButton: boolean)\`\` | If set to `true` it displays the SwitchCameraButton in Button Layout. If set to `false` it hides the SwitchCameraButton in Button Layout. **Default value = true** | -| `showAudioModeButton`(showAudioModeButton: boolean)\`\` | If set to `true` it displays the AudioModeButton in Button Layout. If set to `false` it hides the AudioModeButton in Button Layout. **Default value = true** | -| `setIsAudioOnlyCall(audioOnly: boolean)` | If set to `true`, the call will be strictly an audio call. If set to `false`, the call will be an audio-video call.**Default value = false** | -| `startWithAudioMuted(audioMuted: boolean)` | This ensures the call is started with the audio muted if set to true. **Default value = false** | -| `startWithVideoMuted(videoMuted: boolean)` | This ensures the call is started with the video paused if set to true. **Default value = false** | -| `startWithVideoMuted(videoMuted: boolean)` | If set to true it displays the Recording in Button Layout. if set to false it hides the Recording in Button Layout. **Default value = false** | -| `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 | +| Method | Description | Default | +| ------ | ----------- | ------- | +| `setIsPresenter(isPresenter: boolean)` | If `true`, user joins as presenter. If `false`, user joins as viewer. | — | +| `enableDefaultLayout(defaultLayout: boolean)` | Show/hide the default button layout. If `false`, only the call view is displayed. | `true` | +| `showEndCallButton(showEndCallButton: boolean)` | Show/hide the end call button. | `true` | +| `showPauseVideoButton(showPauseVideoButton: boolean)` | Show/hide the pause video button. | `true` | +| `showMuteAudioButton(showMuteAudioButton: boolean)` | Show/hide the mute audio button. | `true` | +| `showSwitchCameraButton(showSwitchCameraButton: boolean)` | Show/hide the switch camera button. | `true` | +| `showAudioModeButton(showAudioModeButton: boolean)` | Show/hide the audio mode button. | `true` | +| `showRecordingButton(showRecordingButton: boolean)` | Show/hide the recording button. | `false` | +| `setIsAudioOnlyCall(audioOnly: boolean)` | If `true`, the call is audio-only. If `false`, audio-video. | `false` | +| `startWithAudioMuted(audioMuted: boolean)` | Start the call with the microphone muted. | `false` | +| `startWithVideoMuted(videoMuted: boolean)` | Start the call with the camera off. | `false` | +| `setDefaultAudioMode(audioMode: string)` | Start with a specific audio output. Values: `CometChatCalls.AUDIO_MODE.SPEAKER`, `EARPIECE`, `BLUETOOTH`, `HEADPHONES` | — | +| `setCallEventListener(listener)` | Set the event listener for call callbacks. | — | For custom UI, embed your own buttons and use the call control methods described in [Call Session Methods](/sdk/javascript/direct-call#methods). From a2e08d3e253abb51d2ab34a4cbad4d80abc102f4 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 17:12:27 +0530 Subject: [PATCH 085/139] Update call-logs.mdx --- sdk/javascript/call-logs.mdx | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/sdk/javascript/call-logs.mdx b/sdk/javascript/call-logs.mdx index 2ead14f17..cae6154fd 100644 --- a/sdk/javascript/call-logs.mdx +++ b/sdk/javascript/call-logs.mdx @@ -4,7 +4,6 @@ sidebarTitle: "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 */} ```javascript @@ -24,13 +23,13 @@ let details = await CometChatCalls.getCallDetails("SESSION_ID", authToken); **Filters:** `setCallType()`, `setCallStatus()`, `setCallCategory()`, `setCallDirection()`, `setHasRecording()`, `setUid()`, `setGuid()` -## Overview +Call logs let you retrieve and display call history — who called whom, when, how long, and whether it was recorded. Use `CallLogRequestBuilder` to fetch and filter logs, and `getCallDetails()` to get details for a specific session. -Retrieve and display call history including duration, participants, status, and recording information. +Before you begin, make sure you've completed the [Calls SDK Setup](/sdk/javascript/calling-setup). -## Fetching Call Logs +## Fetch Call Logs -Use `CallLogRequestBuilder` to fetch and filter call logs: +Build a request with `CallLogRequestBuilder`, then call `fetchNext()` or `fetchPrevious()` to retrieve logs. Call either method repeatedly on the same builder instance to paginate through results. ```javascript let callLogRequestBuilder = new CometChatCalls.CallLogRequestBuilder() From 67b01ae50c95c4f3f27b7ad4553024ebd5823980 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 17:13:27 +0530 Subject: [PATCH 086/139] Update session-timeout.mdx --- sdk/javascript/session-timeout.mdx | 62 +++++++++++++++++++++++------- 1 file changed, 49 insertions(+), 13 deletions(-) diff --git a/sdk/javascript/session-timeout.mdx b/sdk/javascript/session-timeout.mdx index 357ba57e2..70bd8403d 100644 --- a/sdk/javascript/session-timeout.mdx +++ b/sdk/javascript/session-timeout.mdx @@ -4,32 +4,68 @@ sidebarTitle: "Session Timeout" description: "Handle idle session timeouts in CometChat calls, including automatic termination, user prompts, and the onSessionTimeout event." --- -{/* TL;DR for Agents and Quick Reference */} +```javascript +// Set custom timeout (in seconds) +const callSettings = new CometChatCalls.CallSettingsBuilder() + .setIdleTimeoutPeriod(300) // 5 minutes + .setCallListener(new CometChatCalls.OngoingCallListener({ + onSessionTimeout: () => { + console.log("Session timed out"); + CometChatCalls.endSession(); + } + })) + .build(); +``` + - 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+) +- Warning dialog appears 60 seconds before auto-termination +- Listen for `onSessionTimeout` to handle auto-termination +- Customize with `setIdleTimeoutPeriod(seconds)` in CallSettings (v4.1.0+) *Available since v4.1.0* -## Overview +The Calls SDK automatically terminates call sessions when a participant is alone for too long, preventing abandoned calls from consuming resources. You can customize the timeout duration and handle the termination event. + +## How It Works + +When a participant is alone in a session: + +1. A warning dialog appears 60 seconds before the timeout, with "Stay" or "Leave" options +2. If no action is taken, the call auto-terminates and the `onSessionTimeout` event fires + +The default timeout is 180 seconds (3 minutes). + +## Configuration -The Calls SDK automatically handles idle session timeouts to prevent abandoned calls from consuming resources. +Set a custom timeout period using `setIdleTimeoutPeriod()` in `CallSettingsBuilder`. The warning dialog will always appear 60 seconds before the configured timeout. -**Default behavior** (participant alone in session for 180 seconds): +```javascript +const callSettings = new CometChatCalls.CallSettingsBuilder() + .setIdleTimeoutPeriod(300) // 5 minutes + .enableDefaultLayout(true) + .setCallListener(callListener) + .build(); +``` -1. At 120 seconds: Warning dialog appears with "Stay" or "Leave" options -2. At 180 seconds: Call auto-terminates if no action taken +## Handling the Timeout Event -Customize the timeout period using `setIdleTimeoutPeriod(seconds)` in `CallSettingsBuilder`. +Listen for `onSessionTimeout` in your `OngoingCallListener` to clean up when the call auto-terminates: -### Session Timeout Flow +```javascript +const callListener = new CometChatCalls.OngoingCallListener({ + onSessionTimeout: () => { + console.log("Session timed out due to inactivity"); + CometChatCalls.endSession(); + // Close the calling screen + }, + // ... other listeners +}); +``` -The `onSessionTimeout` event fires when the call auto-terminates due to inactivity. +See [Call Session — Call Listeners](/sdk/javascript/direct-call#call-listeners) for the full list of events. --- From 311803479b58332ca4f47af35f5d52c438af1430 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 17:14:38 +0530 Subject: [PATCH 087/139] Update users-overview.mdx --- sdk/javascript/users-overview.mdx | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/sdk/javascript/users-overview.mdx b/sdk/javascript/users-overview.mdx index 83062c071..a63e5b9f2 100644 --- a/sdk/javascript/users-overview.mdx +++ b/sdk/javascript/users-overview.mdx @@ -4,7 +4,6 @@ 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 */} - [User Management](/sdk/javascript/user-management) — Create and update users @@ -13,7 +12,12 @@ description: "Overview of CometChat user functionality including user management - [Block Users](/sdk/javascript/block-users) — Block and unblock users -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. +Every person who uses your app needs a corresponding user in CometChat. Once a user exists, you can manage their profile, fetch user lists for your UI, track who's online, and control communication with blocking. + +- [User Management](/sdk/javascript/user-management) — Create users when they sign up, update profiles, and delete accounts +- [Retrieve Users](/sdk/javascript/retrieve-users) — Fetch and filter user lists with pagination, search, and role-based filtering +- [User Presence](/sdk/javascript/user-presence) — Monitor real-time online/offline status and subscribe to presence changes +- [Block Users](/sdk/javascript/block-users) — Block and unblock users to prevent all communication ## Next Steps From 30dc21208289499bfe5ca4b591ef87e7320fee63 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 17:18:12 +0530 Subject: [PATCH 088/139] Update retrieve-users.mdx --- sdk/javascript/retrieve-users.mdx | 57 +++++++++++-------------------- 1 file changed, 19 insertions(+), 38 deletions(-) diff --git a/sdk/javascript/retrieve-users.mdx b/sdk/javascript/retrieve-users.mdx index 745f2c697..8c51f7ddf 100644 --- a/sdk/javascript/retrieve-users.mdx +++ b/sdk/javascript/retrieve-users.mdx @@ -4,7 +4,6 @@ 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." --- -{/* TL;DR for Agents and Quick Reference */} ```javascript @@ -24,9 +23,22 @@ const count = await CometChat.getOnlineUserCount(); ``` -## Retrieve Logged In User Details +The CometChat SDK provides methods to retrieve the logged-in user, fetch filtered user lists, look up individual users by UID, and get online user counts. All user methods return [`User`](/sdk/reference/entities#user) objects. -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. +### User Object Fields + +| 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 the Logged-In User + +Use `getLoggedinUser()` to get the current user's details. A rejected promise indicates no user is logged in. @@ -58,18 +70,7 @@ 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: - -| 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 | +Returns a [`User`](/sdk/reference/entities#user) object with the logged-in user's information. ## Retrieve List of Users @@ -490,18 +491,9 @@ userList => { -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 | +The `fetchNext()` method returns an array of [`User`](/sdk/reference/entities#user) objects. Call `fetchNext()` repeatedly on the same request object to paginate. -## Retrieve Particular User Details +## Get a User by UID Use `getUser()` to fetch a specific user's details by UID. @@ -540,18 +532,7 @@ user => { | --------- | ----------- | | UID | The UID of the user to fetch | -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: - -| 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 | +Returns a [`User`](/sdk/reference/entities#user) object. ## Get Online User Count From d9aa0044d4dc961b4329155d36ddfa604098a756 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 17:20:09 +0530 Subject: [PATCH 089/139] Update user-management.mdx --- sdk/javascript/user-management.mdx | 32 +++++++++--------------------- 1 file changed, 9 insertions(+), 23 deletions(-) diff --git a/sdk/javascript/user-management.mdx b/sdk/javascript/user-management.mdx index 5d87d92f1..dad319fb0 100644 --- a/sdk/javascript/user-management.mdx +++ b/sdk/javascript/user-management.mdx @@ -4,7 +4,6 @@ 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." --- -{/* TL;DR for Agents and Quick Reference */} ```javascript @@ -24,11 +23,16 @@ await CometChat.updateCurrentUserDetails(user); **Note:** User creation/deletion should ideally happen on your backend via the [REST API](https://api-explorer.cometchat.com). -Users must exist in CometChat before they can log in. Typically: +Users must exist in CometChat before they can log in. This page covers creating, updating, and deleting users. All methods that return user data return a [`User`](/sdk/reference/entities#user) object. +The typical flow: 1. User registers in your app → Create user in CometChat 2. User logs into your app → [Log user into CometChat](/sdk/javascript/authentication-overview) + +User deletion is only available via the [REST API](https://api-explorer.cometchat.com/reference/delete-user) — there is no client-side SDK method for it. + + ## Creating a User User creation should ideally happen on your backend via the [REST API](https://api-explorer.cometchat.com/reference/creates-user). @@ -80,15 +84,7 @@ 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 | +Returns a [`User`](/sdk/reference/entities#user) object. See [User Class](#user-class) for all available fields. @@ -145,15 +141,7 @@ CometChat.updateUser(user, authKey).then( 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: - -| 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 | +Returns a [`User`](/sdk/reference/entities#user) object. See [User Class](#user-class) for all available fields. ## Updating Logged-in User @@ -198,9 +186,7 @@ CometChat.updateCurrentUserDetails(user).then( -## Deleting a User - -User deletion is only available via the [REST API](https://api-explorer.cometchat.com/reference/delete-user). +Returns a [`User`](/sdk/reference/entities#user) object. See [User Class](#user-class) for all available fields. ## User Class From 4e12c0a3264d620229cb6752f89b2c7dde3b9062 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 17:22:16 +0530 Subject: [PATCH 090/139] Update block-users.mdx --- sdk/javascript/block-users.mdx | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/sdk/javascript/block-users.mdx b/sdk/javascript/block-users.mdx index e1ba8afa4..8fd34a939 100644 --- a/sdk/javascript/block-users.mdx +++ b/sdk/javascript/block-users.mdx @@ -4,7 +4,6 @@ sidebarTitle: "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 */} ```javascript @@ -22,6 +21,8 @@ let blockedUsers = await request.fetchNext(); **Directions:** `BLOCKED_BY_ME` | `HAS_BLOCKED_ME` | `BOTH` (default) +Blocking a user prevents all communication between them and the logged-in user — messages, calls, and presence updates are all suppressed. You can block and unblock users by UID, and fetch the blocked users list with filtering and pagination. + ## Block Users Block users to prevent all communication with them. Use `blockUsers()` with an array of UIDs. @@ -75,6 +76,8 @@ try { Returns an object with UIDs as keys and `"success"` or `"fail"` as values. Each [`User`](/sdk/reference/entities#user) in the request is processed independently. +## Unblock Users + Unblock previously blocked users using `unblockUsers()` with an array of UIDs. From d5ff43780db79fd7f7f478ba4bfc9831bcd80d7a Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 17:22:46 +0530 Subject: [PATCH 091/139] Update docs.json --- docs.json | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/docs.json b/docs.json index cf6946dc9..57ea9d97a 100644 --- a/docs.json +++ b/docs.json @@ -2617,12 +2617,7 @@ "sdk/javascript/block-users" ] }, - { - "group": "User Presence", - "pages": [ - "sdk/javascript/user-presence" - ] - }, + "sdk/javascript/user-presence", { "group": "Groups", "pages": [ From f29ddb9d278923c8c2dbf089c6e0bb2acd167e42 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 17:23:16 +0530 Subject: [PATCH 092/139] Update docs.json --- docs.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs.json b/docs.json index 57ea9d97a..2268f9958 100644 --- a/docs.json +++ b/docs.json @@ -2640,9 +2640,9 @@ { "group": "Resources", "pages": [ - "sdk/javascript/all-real-time-listeners", "sdk/javascript/key-concepts", "sdk/javascript/message-structure-and-hierarchy", + "sdk/javascript/all-real-time-listeners", "sdk/javascript/rate-limits", "sdk/javascript/connection-status", "sdk/javascript/managing-web-sockets-connections-manually" From d6306f44b3ad061f0042bab257624fae80cd57ed Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 17:28:29 +0530 Subject: [PATCH 093/139] Update groups-overview.mdx --- sdk/javascript/groups-overview.mdx | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/sdk/javascript/groups-overview.mdx b/sdk/javascript/groups-overview.mdx index df477b297..94faae6fd 100644 --- a/sdk/javascript/groups-overview.mdx +++ b/sdk/javascript/groups-overview.mdx @@ -18,9 +18,7 @@ description: "Overview of group management in the CometChat JavaScript SDK inclu -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. +Groups let users converse together in a shared space. CometChat supports three group types (public, private, password-protected) and four member roles with different permission levels. ## Group Types @@ -39,6 +37,20 @@ Each group includes three kinds of users- owner, moderator, member. | **Moderator** | Kick and ban members, moderate content | | **Member** | Send/receive messages, leave group | +## Available Operations + +- [Create a Group](/sdk/javascript/create-group) — Create public, private, or password-protected groups +- [Join a Group](/sdk/javascript/join-group) — Join existing groups as a participant +- [Leave a Group](/sdk/javascript/leave-group) — Leave a group you're a member of +- [Update a Group](/sdk/javascript/update-group) — Update group name, description, icon, and settings +- [Delete a Group](/sdk/javascript/delete-group) — Permanently delete a group (owner only) +- [Transfer Ownership](/sdk/javascript/transfer-group-ownership) — Transfer group ownership to another member +- [Retrieve Groups](/sdk/javascript/retrieve-groups) — Fetch and filter the list of groups +- [Retrieve Group Members](/sdk/javascript/retrieve-group-members) — Get the member list for a group +- [Add Members](/sdk/javascript/group-add-members) — Add users to a group +- [Kick & Ban Members](/sdk/javascript/group-kick-ban-members) — Remove or ban members from a group +- [Change Member Scope](/sdk/javascript/group-change-member-scope) — Promote or demote members + --- ## Next Steps From 7c9f9fce1c503b99fad7950acb5c9d4dfed1cfce Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 17:31:39 +0530 Subject: [PATCH 094/139] Update ai-moderation.mdx --- sdk/javascript/ai-moderation.mdx | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/sdk/javascript/ai-moderation.mdx b/sdk/javascript/ai-moderation.mdx index 44f8a4482..b619b46b6 100644 --- a/sdk/javascript/ai-moderation.mdx +++ b/sdk/javascript/ai-moderation.mdx @@ -4,7 +4,6 @@ sidebarTitle: "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 */} ```javascript @@ -27,12 +26,10 @@ CometChat.addMessageListener("MOD_LISTENER", new CometChat.MessageListener({ **Statuses:** `PENDING` → `APPROVED` or `DISAPPROVED` -## Overview - -AI Moderation automatically reviews messages for inappropriate content in real-time, reducing manual intervention and improving user experience. +AI Moderation automatically reviews messages for inappropriate content in real-time. When a user sends a text, image, or video message, it's held in a `PENDING` state while the moderation service analyzes it, then marked as `APPROVED` or `DISAPPROVED` via the `onMessageModerated` event. -For a broader understanding of moderation features, configuring rules, and managing flagged messages, see the [Moderation Overview](/moderation/overview). +For configuring moderation rules and managing flagged messages from the dashboard, see the [Moderation Overview](/moderation/overview). ## Prerequisites From b79c20038c198b38300a17dc83b156bd805ee7c4 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 17:35:05 +0530 Subject: [PATCH 095/139] Update docs.json --- docs.json | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/docs.json b/docs.json index 2268f9958..ff3794d9e 100644 --- a/docs.json +++ b/docs.json @@ -2655,15 +2655,7 @@ "sdk/reference/entities", "sdk/reference/auxiliary" ] - }, - { - "group": "UI Kits", - "pages": [ - "sdk/javascript/react-overview", - "sdk/javascript/vue-overview", - "sdk/javascript/angular-overview" - ] - }, + }, "sdk/javascript/best-practices", "sdk/javascript/troubleshooting", "sdk/javascript/extensions-overview", From cf736910db17fe9151b39acfe0c8ad4684e00d77 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 17:35:40 +0530 Subject: [PATCH 096/139] Update docs.json --- docs.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs.json b/docs.json index ff3794d9e..5bdc81e09 100644 --- a/docs.json +++ b/docs.json @@ -2658,11 +2658,11 @@ }, "sdk/javascript/best-practices", "sdk/javascript/troubleshooting", + "sdk/javascript/upgrading-from-v3", "sdk/javascript/extensions-overview", "sdk/javascript/ai-user-copilot-overview", "sdk/javascript/ai-chatbots-overview", "sdk/javascript/webhooks-overview", - "sdk/javascript/upgrading-from-v3", "sdk/javascript/changelog" ] } From dc365f98fb968ca2a1a6fcc46d17382a89e04f86 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 17:36:50 +0530 Subject: [PATCH 097/139] Update ai-agents.mdx --- sdk/javascript/ai-agents.mdx | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/sdk/javascript/ai-agents.mdx b/sdk/javascript/ai-agents.mdx index 6da69da5b..fadc24086 100644 --- a/sdk/javascript/ai-agents.mdx +++ b/sdk/javascript/ai-agents.mdx @@ -4,7 +4,6 @@ sidebarTitle: "AI Agents" description: "Integrate AI Agents, AI Moderation, and AI User Copilot into your app using the CometChat JavaScript SDK." --- -{/* TL;DR for Agents and Quick Reference */} | Feature | Description | @@ -35,8 +34,6 @@ CometChat.removeMessageListener("LISTENER_ID"); **Event flow:** Run Start → Tool Call(s) → Text Message Stream → Run Finished -# AI Agents Overview - 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). @@ -66,7 +63,7 @@ Events arrive via `onAIAssistantEventReceived` in this order: | 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. +`Run Start` and `Run Finished` are always emitted. Tool Call events only appear when tools are invoked — there can be multiple tool call cycles in a single run. Text Message events are always emitted and carry the assistant's reply incrementally. From 9a14f4c2a8fb51ccd3b7e5c15056acc9a237aa54 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 17:46:25 +0530 Subject: [PATCH 098/139] Update key-concepts.mdx --- sdk/javascript/key-concepts.mdx | 43 +++++++++++++++------------------ 1 file changed, 19 insertions(+), 24 deletions(-) diff --git a/sdk/javascript/key-concepts.mdx b/sdk/javascript/key-concepts.mdx index 9a26ab643..95f260d60 100644 --- a/sdk/javascript/key-concepts.mdx +++ b/sdk/javascript/key-concepts.mdx @@ -17,22 +17,26 @@ Member scopes: `Admin` | `Moderator` | `Participant` Message categories: `message` | `custom` | `action` | `call` -This guide covers the fundamental concepts you need to understand when building with CometChat. +This page covers the core concepts you'll encounter when building with CometChat. Read this before diving into the SDK guides — it'll make everything else click faster. -## CometChat Dashboard +## Users -The [CometChat Dashboard](https://app.cometchat.com) enables you to create new apps (projects) and manage your existing apps. +A user is anyone who uses CometChat. Each user is uniquely identified by a UID (Unique User Identifier). -- 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. +- 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 - -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. - +### User Roles -## API Keys +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. + +## Authentication + +CometChat does not handle user registration or friends management — you handle that in your app, then log users into CometChat programmatically. -You can generate two types of keys from the dashboard: +### API Keys + +You can generate two types of keys from the [CometChat Dashboard](https://app.cometchat.com): | Type | Privileges | Recommended Use | | --- | --- | --- | @@ -43,14 +47,7 @@ You can generate two types of keys from the dashboard: Never expose your REST API Key in client-side code. Use Auth Tokens for production authentication. -## Users - -A user is anyone who uses CometChat. Each user is uniquely identified using a UID (Unique User Identifier). - -- 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 - -## Auth Tokens +### Auth Tokens Auth Tokens are secure, per-user credentials for production use: @@ -58,9 +55,11 @@ Auth Tokens are secure, per-user credentials for production use: - 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 -## Authentication Flow +### Authentication Flow -CometChat does not handle user management or friends management. You handle registration and login in your app, then log users into CometChat programmatically. + +Create your apps in the [CometChat Dashboard](https://app.cometchat.com) — each app gets a unique App ID required for SDK initialization. Ideally, create two apps — one for development and one for production. Use a single app regardless of the number of platforms; if you create separate apps per platform, your users won't be able to communicate across them. + | Your App | Your Server | CometChat | | --- | --- | --- | @@ -69,10 +68,6 @@ CometChat does not handle user management or friends management. You handle regi | 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 - -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 A group enables multiple users to communicate on a particular topic or interest. Each group is uniquely identified using a GUID (Group Unique Identifier). From 1e9af68ce7c06731f25497ec3c96f648310a2164 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 17:49:16 +0530 Subject: [PATCH 099/139] Update message-structure-and-hierarchy.mdx --- sdk/javascript/message-structure-and-hierarchy.mdx | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/sdk/javascript/message-structure-and-hierarchy.mdx b/sdk/javascript/message-structure-and-hierarchy.mdx index 5046d4cbf..158717a7b 100644 --- a/sdk/javascript/message-structure-and-hierarchy.mdx +++ b/sdk/javascript/message-structure-and-hierarchy.mdx @@ -14,7 +14,7 @@ Message categories and types: - **call** → `audio`, `video` -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. +Every message in CometChat belongs to a category (`message`, `custom`, `interactive`, `action`, `call`) and has a specific type within that category. On the SDK side, all messages extend [`BaseMessage`](/sdk/reference/messages#basemessage), with subclasses like [`TextMessage`](/sdk/reference/messages#textmessage), [`MediaMessage`](/sdk/reference/messages#mediamessage), [`CustomMessage`](/sdk/reference/messages#custommessage), [`Action`](/sdk/reference/messages#action), and [`Call`](/sdk/reference/messages#call). Understanding this hierarchy helps you handle different message types correctly. ## Message Hierarchy @@ -94,7 +94,7 @@ switch (category) { -## Message Category +## Standard Messages (`message` Category) Messages with category `message` are standard user-sent messages: @@ -106,7 +106,7 @@ Messages with category `message` are standard user-sent messages: | `audio` | Audio attachment | | `file` | File attachment | -## Custom Category +## Custom Messages (`custom` Category) 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`). @@ -122,7 +122,7 @@ const customMessage = new CometChat.CustomMessage( See [Send Message → Custom Messages](/sdk/javascript/send-message#custom-message) for details. -## Interactive Category +## Interactive Messages (`interactive` Category) Interactive messages contain actionable UI elements that users can interact with directly in the chat: @@ -134,7 +134,7 @@ Interactive messages contain actionable UI elements that users can interact with See [Interactive Messages](/sdk/javascript/interactive-messages) for implementation details. -## Action Category +## Action Messages (`action` Category) Action messages are system-generated events. They have a `type` and an `action` property: @@ -151,7 +151,7 @@ Action messages are system-generated events. They have a `type` and an `action` - `edited` — Message was edited - `deleted` — Message was deleted -## Call Category +## Call Messages (`call` Category) Call messages track call events with types `audio` or `video`. The `status` property indicates the call state: From c7b32daa74e429bc2972fcc2f07075a80beec94a Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 17:53:02 +0530 Subject: [PATCH 100/139] Update all-real-time-listeners.mdx --- sdk/javascript/all-real-time-listeners.mdx | 60 ++++++++++------------ 1 file changed, 28 insertions(+), 32 deletions(-) diff --git a/sdk/javascript/all-real-time-listeners.mdx b/sdk/javascript/all-real-time-listeners.mdx index e2c92ddbc..a0865e592 100644 --- a/sdk/javascript/all-real-time-listeners.mdx +++ b/sdk/javascript/all-real-time-listeners.mdx @@ -3,7 +3,6 @@ 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 */} ```javascript @@ -35,27 +34,28 @@ CometChat.removeCallListener("ID"); ``` +Real-time listeners let you receive live events — messages, presence changes, group updates, and call signals — as they happen. The pattern is the same for all four listener types: + +1. Register a listener with a unique ID using `addXListener()` +2. Handle events in the callback methods +3. Remove the listener with `removeXListener()` when it's no longer needed + +Each listener ID must be unique. Re-registering with the same ID replaces the previous listener. Always remove listeners on component unmount or page navigation to prevent memory leaks. + 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. - -1. [User Listener](/sdk/javascript/all-real-time-listeners#user-listener) -2. [Group Listener](/sdk/javascript/all-real-time-listeners#group-listener) -3. [Message Listener](/sdk/javascript/all-real-time-listeners#message-listener) -4. [Call Listener](/sdk/javascript/all-real-time-listeners#call-listener) - ## User Listener -The `UserListener` class provides you with live events related to users. Below are the callback methods provided by the `UserListener` class. +Receive online/offline presence events for users. | Method | Information | | --------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **onUserOnline(user: CometChat.User)** | This method is triggered when a user comes online and is available to chat. The details of the user can be obtained from the user object received as the method parameter. | | **onUserOffline(user: CometChat.User)** | This method is triggered when a user goes offline. The details of the user can be obtained from the User object received as the parameter. | -To add the `UserListener`, you need to use the `addUserListener()` method provided by the `CometChat` class. +To add the `UserListener`: @@ -98,9 +98,7 @@ CometChat.addUserListener( -where `UNIQUE_LISTENER_ID` is the unique identifier for the listener. Please make sure that no two listeners are added with the same listener id as this could lead to unexpected behavior resulting in loss of events. - -Once the `UserListener` is not in use, you need to remove the listener using the `removeUserListener()` method which takes the id of the listener to be removed as the parameter. +Remove the listener when no longer needed: @@ -113,7 +111,8 @@ CometChat.removeUserListener(listenerID); ```js -CometChat.removeUserListener(UNIQUE_LISTENER_ID); +let listenerID = "UNIQUE_LISTENER_ID"; +CometChat.removeUserListener(listenerID); ``` @@ -122,7 +121,7 @@ CometChat.removeUserListener(UNIQUE_LISTENER_ID); ## Group Listener -The `GroupListener` class provides you with all the real-time events related to groups. Below are the callback methods provided by the `GroupListener` class. +Receive events when group members join, leave, are kicked/banned, or have their scope changed. | Method | Information | | ------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | @@ -134,7 +133,7 @@ The `GroupListener` class provides you with all the real-time events related to | **onGroupMemberScopeChanged(action: CometChat.Action, changedUser: CometChat.User, newScope: string, oldScope: string, changedGroup: CometChat.Group)** | This method is triggered when the scope of any Group Member has been changed. All the members that are a part of that group receive this event | | **onMemberAddedToGroup(action: CometChat.Action, userAdded: CometChat.User, addedBy: CometChat.User, addedTo: CometChat.Group)** | This method is triggered when a user is added to any group. All the members including the user himself receive this event. | -To add the `GroupListener`, you need to use the `addGroupListener()` method provided by the `CometChat` class. +To add the `GroupListener`: @@ -300,9 +299,7 @@ CometChat.addGroupListener( -where `UNIQUE_LISTENER_ID` is the unique identifier for the listener. Please make sure that no two listeners are added with the same listener id as this could lead to unexpected behavior resulting in loss of events. - -Once the `GroupListener` is not in use, you need to remove the listener using the `removeGroupListener()` method which takes the id of the listener to be removed as the parameter. +Remove the listener when no longer needed: @@ -315,7 +312,8 @@ CometChat.removeGroupListener(listenerID); ```js -CometChat.removeGroupListener(UNIQUE_LISTENER_ID); +let listenerID = "UNIQUE_LISTENER_ID"; +CometChat.removeGroupListener(listenerID); ``` @@ -324,7 +322,7 @@ CometChat.removeGroupListener(UNIQUE_LISTENER_ID); ## Message Listener -The `MessageListener` class provides you with live events related to messages. Below are the callback methods provided by the `MessageListener` class. +Receive events for incoming messages, typing indicators, read/delivery receipts, message edits/deletes, reactions, and moderation results. | Method | Information | | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | @@ -343,7 +341,7 @@ The `MessageListener` class provides you with live events related to messages. B | **onMessageReactionAdded(receipt: CometChat.ReactionEvent)** | This event is triggered when a reaction is added to a message in a user/group conversation. | | **onMessageReactionRemoved(receipt: CometChat.ReactionEvent)** | This event is triggered when a reaction is remove from a message in a user/group conversation. | | **onMessageModerated(message: CometChat.BaseMessage)** | This event is triggered when a message sent by the logged-in user is successfully processed by moderation and receives either an `approved` or `disapproved` status. | -To add the `MessageListener`, you need to use the `addMessageListener()` method provided by the `CometChat` class. +To add the `MessageListener`: @@ -460,9 +458,7 @@ CometChat.addMessageListener( -where `UNIQUE_LISTENER_ID` is the unique identifier for the listener. Please make sure that no two listeners are added with the same listener id as this could lead to unexpected behavior resulting in loss of events. - -Once the `MessageListener` is not in use, you need to remove the listener using the `removeMessageListener()` method which takes the id of the listener to be removed as the parameter. +Remove the listener when no longer needed: @@ -475,7 +471,8 @@ CometChat.removeMessageListener(listenerID); ```js -CometChat.removeMessageListener(UNIQUE_LISTENER_ID); +let listenerID = "UNIQUE_LISTENER_ID"; +CometChat.removeMessageListener(listenerID); ``` @@ -484,7 +481,7 @@ CometChat.removeMessageListener(UNIQUE_LISTENER_ID); ## Call Listener -The `CallListener` class provides you with live events related to calls. Below are the callback methods provided by the `CallListener` class. +Receive events for incoming and outgoing call state changes. | Method | Information | | ------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | @@ -493,7 +490,7 @@ The `CallListener` class provides you with live events related to calls. Below a | **onOutgoingCallRejected(call: CometChat.Call)** | This event is triggered when the call initiated by the logged-in user is rejected by the recipient. The details of the call can be obtained from the Call object received as the method parameter | | **onIncomingCallCancelled(call: CometChat.Call)** | This event is triggered when an incoming call is canceled by the initiator of the call. The details of the call can be obtained from the Call object received as the method parameter | -To add the `CallListener`, you need to use the `addCallListener()` method provided by the `CometChat` class. +To add the `CallListener`: @@ -544,9 +541,7 @@ CometChat.addCallListener( -where `UNIQUE_LISTENER_ID` is the unique identifier for the listener. Please make sure that no two listeners are added with the same listener id as this could lead to unexpected behavior resulting in loss of events. - -Once the `CallListener` is not in use, you need to remove the listener using the `removeCallListener()` method which takes the id of the listener to be removed as the parameter. +Remove the listener when no longer needed: @@ -559,7 +554,8 @@ CometChat.removeCallListener(listenerID); ```js -CometChat.removeCallListener(UNIQUE_LISTENER_ID); +let listenerID = "UNIQUE_LISTENER_ID"; +CometChat.removeCallListener(listenerID); ``` From f4b1b6a2a9ecaa6728e4d286ceaa538104dc8bdb Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 17:55:59 +0530 Subject: [PATCH 101/139] Update rate-limits.mdx --- sdk/javascript/rate-limits.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/javascript/rate-limits.mdx b/sdk/javascript/rate-limits.mdx index c7689f4ef..4494fe548 100644 --- a/sdk/javascript/rate-limits.mdx +++ b/sdk/javascript/rate-limits.mdx @@ -11,7 +11,7 @@ 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 applies rate limits to ensure fair usage and platform stability. Understanding these limits helps you build applications that handle high traffic gracefully. +CometChat applies rate limits to REST API requests to ensure fair usage and platform stability. SDK methods that call the REST API under the hood (like fetching users, sending messages, or creating groups) are subject to these limits. Understanding them helps you build applications that handle high traffic gracefully. ## Rate Limit Tiers From 35f5424fa1f0f4be6625321dad3855927abcd467 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 18:02:52 +0530 Subject: [PATCH 102/139] Update connection-status.mdx --- sdk/javascript/connection-status.mdx | 84 +++++++++++----------------- 1 file changed, 33 insertions(+), 51 deletions(-) diff --git a/sdk/javascript/connection-status.mdx b/sdk/javascript/connection-status.mdx index 8080128f4..8720419e1 100644 --- a/sdk/javascript/connection-status.mdx +++ b/sdk/javascript/connection-status.mdx @@ -3,7 +3,6 @@ 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 */} ```javascript @@ -22,19 +21,43 @@ CometChat.removeConnectionListener("LISTENER_ID"); ``` -CometChat SDK provides you with a mechanism to get real-time status of the connection to CometChat web-socket servers. +The CometChat SDK maintains a WebSocket connection to CometChat servers for real-time events. You can check the current connection state and listen for changes — useful for showing connectivity indicators in your UI or queuing operations while offline. -Connection Status provides you with the below 3 methods to get the status of the connection to CometChat web-socket servers: +When the connection drops, the SDK automatically attempts to reconnect, cycling through `disconnected` → `connecting` → `connected`. -| Delegate Method | Information | -| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | -| connecting | This method is triggered when CometChat SDK is trying to establish a connection to the web-socket server. | -| connected | This method is called when CometChat SDK has successfully established a connection and now is connected. | -| disconnected | This method is called when the CometChat SDK gets disconnected due to any issue while maintaining the connection like network fluctuations, etc. | +## Connection States -Once the connection is broken, the disconnected callback is triggered, the SDK automatically tries to establish the connection again, thus going into the connecting state and triggering the `connecting` method. Once the attempt to connect is successful, the `connected` method is triggered thus letting the developer know that the connection is established and is active. +| 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 | -To receive real-time connection status, you need to register `ConnectionListener` wherever you wish to receive the real-time status. You can use the `addConnectionListener()` method to do so. +## Get Current Status + +Use `getConnectionStatus()` to check the current connection state at any time: + + + +```typescript +const connectionStatus: string = CometChat.getConnectionStatus(); +``` + + + + +```javascript +const connectionStatus = CometChat.getConnectionStatus(); +``` + + + + + +## Listen for Connection Changes + +Register a `ConnectionListener` to receive real-time connection state updates. We recommend adding this on app startup after `CometChat.init()` completes. @@ -81,47 +104,6 @@ CometChat.addConnectionListener( - - -We recommend you to add the Connection Listener in your method on app startup, preferably in the index.js file. Once you have successfully initialized CometChat. - - - -You can also get the current connection status by using `getConnectionStatus` property provided by CometChat SDK - - - -```typescript -const connectionStatus: string = CometChat.getConnectionStatus(); -``` - - - - -```javascript -const connectionStatus = CometChat.getConnectionStatus(); -``` - - - - - -The `CometChat.getConnectionStatus` method will return either of the below 3 values: - -1. connecting -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. From f3912e342e97f1289ef3a9531eaa5c231aeffba4 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 18:06:43 +0530 Subject: [PATCH 103/139] Update managing-web-sockets-connections-manually.mdx --- ...aging-web-sockets-connections-manually.mdx | 33 ++++++++----------- 1 file changed, 14 insertions(+), 19 deletions(-) diff --git a/sdk/javascript/managing-web-sockets-connections-manually.mdx b/sdk/javascript/managing-web-sockets-connections-manually.mdx index 76b996f5e..066f01b34 100644 --- a/sdk/javascript/managing-web-sockets-connections-manually.mdx +++ b/sdk/javascript/managing-web-sockets-connections-manually.mdx @@ -3,7 +3,6 @@ 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 */} ```javascript @@ -20,25 +19,21 @@ CometChat.disconnect(); ``` -## Default SDK behaviour on login +By default, the SDK automatically establishes and manages the WebSocket connection — it connects on login, reconnects on `init()` when a session exists, and handles reconnection on network drops. This page covers how to disable that and manage the connection yourself. -When the login method of the SDK is called, the SDK performs the below operations: +You'd want manual control when you need to conserve resources by connecting only when the user is actively chatting, or when you need precise control over when real-time events start flowing. -1. Logs the user into the SDK -2. Saves the details of the logged in user locally. -3. Creates a web-socket connection for the logged in user. +## Default Behavior -This makes sure that the logged in user starts receiving real-time messages sent to him or any groups that he is a part of as soon as he logs in. +When `autoEstablishSocketConnection` is `true` (the default): -When the app is reopened, and the init() method is called, the web-socket connection to the server is established automatically. +1. `CometChat.login()` logs the user in, saves their session locally, and opens a WebSocket connection +2. On app restart, `CometChat.init()` automatically reconnects using the saved session +3. The user immediately starts receiving real-time messages, presence updates, and call events -This is the default behaviour of the CometChat SDKs. However, if you wish to take control of the web-socket connection i.e if you wish to connect and disconnect to the web-socket server manually, you can refer to the Managing Web-socket Connection section. +## Manual Connection Management -## Managing the Web-socket connections manually - -The CometChat SDK also allows you to modify the above default behaviour of the SDK and take the control of the web-socket connection into your own hands. In order to achieve this, you need to follow the below steps: - -1. While calling the init() function on the app startup, you need to inform the SDK that you will be managing the web socket connect. You can do so by using the `autoEstablishSocketConnection()` method provided by the `AppSettingsBuilder` class. This method takes a boolean value as an input. If set to `true` , the SDK will manage the web-socket connection internally based on the default behaviour mentioned above. If set to `false` , the web socket connection can will not be managed by the SDK and you will have to handle it manually. You can refer to the below code snippet for the same: +To take control of the WebSocket connection, set `autoEstablishSocketConnection(false)` during initialization: @@ -85,11 +80,11 @@ CometChat.init(appID, appSetting).then( -You can manage the connection to the web-socket server using the `connect()` and `disconnect()` methods provided by the SDK. +Once initialized with manual mode, use `connect()` and `disconnect()` to control the WebSocket connection. -1. Connect to the web-socket server +### Connect -You need to use the `connect()` method provided by the `CometChat` class to establish the connection to the web-socket server. Please make sure that the user is logged in to the SDK before calling this method. You can use the CometChat.getLoggedInUser() method to check this. Once the connection is established, you will start receiving all the real-time events for the logged in user. +Establishes the WebSocket connection. The user must be logged in first (check with `CometChat.getLoggedinUser()`). Once connected, real-time events start flowing. @@ -101,9 +96,9 @@ CometChat.connect(); -2. Disconnect from the web-socket server +### Disconnect -You can use the `disconnect()` method provided by the `CometChat` class to break the established connection. Once the connection is broken, you will stop receiving all the real-time events for the logged in user. +Breaks the WebSocket connection. Real-time events stop until you call `connect()` again. From fdf0c5831627644f6737ca73b7dc9680533701e3 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 18:18:08 +0530 Subject: [PATCH 104/139] error codes --- docs.json | 1 + sdk/javascript/best-practices.mdx | 2 +- sdk/javascript/error-codes.mdx | 224 ++++++++++++++++++++++++++++++ 3 files changed, 226 insertions(+), 1 deletion(-) create mode 100644 sdk/javascript/error-codes.mdx diff --git a/docs.json b/docs.json index 5bdc81e09..d19dfeeee 100644 --- a/docs.json +++ b/docs.json @@ -2657,6 +2657,7 @@ ] }, "sdk/javascript/best-practices", + "sdk/javascript/error-codes", "sdk/javascript/troubleshooting", "sdk/javascript/upgrading-from-v3", "sdk/javascript/extensions-overview", diff --git a/sdk/javascript/best-practices.mdx b/sdk/javascript/best-practices.mdx index fbaebfcea..b3998e1d7 100644 --- a/sdk/javascript/best-practices.mdx +++ b/sdk/javascript/best-practices.mdx @@ -4,7 +4,7 @@ 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. +Follow these best practices to build reliable, performant, and secure applications with the CometChat JavaScript SDK. Organized by topic — jump to what's relevant for your current work. ## Initialization & Authentication diff --git a/sdk/javascript/error-codes.mdx b/sdk/javascript/error-codes.mdx new file mode 100644 index 000000000..fd3914478 --- /dev/null +++ b/sdk/javascript/error-codes.mdx @@ -0,0 +1,224 @@ +--- +title: "Error Codes" +sidebarTitle: "Error Codes" +description: "Complete reference for CometChat JavaScript SDK error codes, including client-side validation errors, server-side API errors, and how to handle them." +--- + + + +```javascript +// All errors are CometChatException objects +try { + await CometChat.login(uid, authKey); +} catch (error) { + console.log(error.code); // e.g., "AUTH_ERR_AUTH_TOKEN_NOT_FOUND" + console.log(error.name); // e.g., "AUTH_ERR_AUTH_TOKEN_NOT_FOUND" + console.log(error.message); // Human-readable description + console.log(error.details); // Additional context (if available) +} +``` + +**Error categories:** Initialization, Login, Calling, Messages, Groups, Users, Conversations, Receipts, AI, Extensions + + +Every error thrown by the CometChat SDK is a `CometChatException` object with four properties: + +| Property | Type | Description | +|----------|------|-------------| +| `code` | `string \| number` | Machine-readable error code | +| `name` | `string` | Error name (often matches code) | +| `message` | `string` | Human-readable description | +| `details` | `string` | Additional context or troubleshooting info | + +```typescript +try { + const user = await CometChat.login(authToken); +} catch (error: CometChat.CometChatException) { + switch (error.code) { + case "AUTH_ERR_AUTH_TOKEN_NOT_FOUND": + // Token is invalid or expired — prompt re-login + break; + case "MISSING_PARAMETERS": + // A required parameter was not provided + break; + default: + console.error("Unexpected error:", error.message); + } +} +``` + +## Initialization Errors + +| Code | Message | +|------|---------| +| `MISSING_PARAMETERS` | AppID cannot be empty. Please specify a valid appID. | + +## Login & Authentication Errors + +| Code | Message | +|------|---------| +| `COMETCHAT_INITIALIZATION_NOT_DONE` | Please initialize CometChat before using the login method. | +| `USER_NOT_AUTHORISED` | The authToken of the user is not authorised. Please verify again. | +| `AUTH_ERR_AUTH_TOKEN_NOT_FOUND` | The auth token does not exist. Please make sure you are logged in and have a valid auth token. | +| `LOGIN_IN_PROGRESS` | Please wait until the previous login request ends. | +| `WS_CONNECTION_FAIL` | WebSocket connection failed. | +| `WS_CONNECTION_FALLBACK_FAIL` | WebSocket connection fallback failed. | +| `WS_AUTH_FAIL` | WebSocket username/password not correct. | +| `NO_INTERNET_CONNECTION` | You do not have an internet connection. | +| `USER_NOT_LOGGED_IN` | Please log in to CometChat before calling this method. | + +## Calling Errors + +| Code | Message | +|------|---------| +| `CALL_ALREADY_INITIATED` | There is already a call in progress. | +| `CALL_IN_PROGRESS` | There is already a call in progress. | +| `NOT_INITIALIZED` | Please call CometChat.init() before calling any other methods. | +| `NOT_LOGGED_IN` | Please login before starting a call. | +| `SESSION_ID_REQUIRED` | Please make sure you are passing a correct session ID. | +| `CALL_SETTINGS_REQUIRED` | Please make sure you are passing the call settings object. | +| `JWT_NOT_FOUND` | There was an issue while fetching JWT from API. | + +## Message Errors + +| Code | Message | +|------|---------| +| `INVALID_RECEIVER_TYPE` | Receiver type can be `user` or `group`. | +| `REQUEST_IN_PROGRESS` | Request in progress. | +| `NOT_ENOUGH_PARAMETERS` | Timestamp, MessageId, or updatedAfter is required to use fetchNext(). | +| `INVALID_REASON_ID` | Invalid reasonId provided. | + +## User Errors + +| Code | Message | +|------|---------| +| `INVALID_STATUS_VALUE` | The status parameter accepts only `online` or `offline`. | +| `INVALID_DIRECTION_VALUE` | The direction parameter accepts only `both`, `blockedByMe`, or `hasBlockedMe`. | +| `EMPTY_USERS_LIST` | The users list needs to have at least one UID. | + +## Group Errors + +| Code | Message | +|------|---------| +| `NOT_A_GROUP` | Please use the Group class to construct a new group. | +| `INVALID_SCOPE_VALUE` | Scope can be `admin`, `moderator`, or `participant`. | +| `INVALID_GROUP_TYPE` | Group type can be `public`, `private`, `protected`, or `password`. | +| `ERR_EMPTY_GROUP_PASS` | Password is mandatory to join a group. | + +## Conversation Errors + +| Code | Message | +|------|---------| +| `INVALID_CONVERSATION_TYPE` | Conversation type can be `user` or `group`. | +| `CONVERSATION_NOT_FOUND` | Conversation not found. Check the value of conversationWith and conversationType. | + +## Receipt Errors + +| Code | Message | +|------|---------| +| `MISSING_PARAMETERS` | Expected 4 parameters, received 3. | +| `NO_WEBSOCKET_CONNECTION` | Connection to WebSocket server is broken. Please retry after some time. | +| `RECEIPTS_TEMPORARILY_BLOCKED` | Due to high load, receipts have been blocked for your app. | +| `UNKNOWN_ERROR_OCCURRED` | Unknown error occurred while marking a message as read. | + +## AI Feature Errors + +| Code | Message | +|------|---------| +| `NO_CONVERSATION_STARTER` | Unable to get conversation starter for this conversation. | +| `NO_SMART_REPLY` | Unable to get smart reply for this conversation. | +| `NO_CONVERSATION_SUMMARY` | Unable to get summary of the conversation. | +| `EMPTY_RESPONSE` | Unable to get a suggestion. | +| `ERROR_INVALID_AI_FEATURE` | The provided AI Feature cannot be null or empty. | + +## Extension Errors + +| Code | Message | +|------|---------| +| `ERROR_INVALID_EXTENSION` | The provided extension cannot be null or empty. | +| `ERROR_EXTENSION_NOT_FOUND` | The provided extension could not be found. | + +## Feature Restriction Errors + +| Code | Message | +|------|---------| +| `ERROR_INVALID_FEATURE` | The provided feature cannot be null or empty. | +| `ERROR_FEATURE_NOT_FOUND` | The provided feature could not be found. | + +## Network & API Errors + +| Code | Message | +|------|---------| +| `FAILED_TO_FETCH` | There is an unknown issue with the API request. Check your internet connection. | +| `TOO_MANY_REQUEST` | Too many requests. Wait before sending the next request. | +| `ERR_TOO_MANY_REQUESTS` | Rate limiting. See [Rate Limits](/sdk/javascript/rate-limits). | + +## Validation Errors + +These errors use dynamic codes based on the parameter name (e.g., `INVALID_UID`, `UID_IS_COMPULSORY`): + +| Pattern | Message | +|---------|---------| +| `INVALID_{param}` | The parameter should be a string / number / boolean / object / array. | +| `{param}_IS_COMPULSORY` | The parameter cannot be blank. Please provide a valid value. | +| `{param}_NOT_PROVIDED` | Please provide the required parameter. | +| `ERROR_{param}_EXCEEDED` | Limit exceeded max limit. | +| `INVALID_SEARCH_KEYWORD` | Invalid search keyword. Please provide a valid search keyword. | +| `MISSING_KEY` | The key is missing from the object. | + +## Prosody (WebSocket Server) Errors + +| Code | Message | +|------|---------| +| `ERROR_INVALID_SESSIONID` | The provided sessionId cannot be null or empty. | +| `ERROR_INVALID_TYPE` | The provided type cannot be null or empty. | +| `ERROR_INVALID_GROUPLIST` | Grouplist cannot be null or empty. | + +## General Errors + +| Code | Message | +|------|---------| +| `ERROR_IO_EXCEPTION` | I/O exception occurred. | +| `ERROR_JSON_EXCEPTION` | JSON parsing exception. | +| `ERROR_PASSWORD_MISSING` | Password is mandatory for a password group. | +| `ERROR_LIMIT_EXCEEDED` | Limit exceeded max limit. | +| `ERROR_INVALID_GUID` | Please provide a valid GUID. | +| `ERR_SETTINGS_HASH_OUTDATED` | Settings hash is outdated. | +| `ERR_NO_AUTH` | No authentication credentials found. | + +## Server-Side API Errors + +For REST API error codes (returned by the CometChat backend), see the [Error Guide](/articles/error-guide). Common server-side errors you may encounter in SDK responses: + +| Code | Description | +|------|-------------| +| `AUTH_ERR_EMPTY_APPID` | Empty App ID in headers | +| `AUTH_ERR_INVALID_APPID` | Invalid App ID or does not exist in region | +| `ERR_UID_NOT_FOUND` | User does not exist or is soft deleted | +| `ERR_GUID_NOT_FOUND` | Group does not exist | +| `ERR_NOT_A_MEMBER` | User is not a member of the group | +| `ERR_ALREADY_JOINED` | User has already joined the group | +| `ERR_MESSAGE_ID_NOT_FOUND` | Message does not exist | +| `ERR_PLAN_RESTRICTION` | Feature not available with current plan | +| `ERR_TOO_MANY_REQUESTS` | Rate limit exceeded | + +See the full list in the [Error Guide](/articles/error-guide). + +--- + +## Next Steps + + + + Common issues and solutions + + + Understand and handle rate limits + + + Complete server-side error code reference + + + Recommended patterns for error handling + + From f85379d2da2fc0b079cc9136ea61a6d262e64d13 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 18:20:51 +0530 Subject: [PATCH 105/139] Update upgrading-from-v3.mdx --- sdk/javascript/upgrading-from-v3.mdx | 67 ++++++++++------------------ 1 file changed, 23 insertions(+), 44 deletions(-) diff --git a/sdk/javascript/upgrading-from-v3.mdx b/sdk/javascript/upgrading-from-v3.mdx index 51d7e1b01..346153755 100644 --- a/sdk/javascript/upgrading-from-v3.mdx +++ b/sdk/javascript/upgrading-from-v3.mdx @@ -3,7 +3,6 @@ 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 */} Key changes from v3 to v4: @@ -12,65 +11,45 @@ Key changes from v3 to v4: - 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: +Upgrading from v3 to v4 is straightforward — the API surface is the same, only the package names and imports changed. Follow the [v4 setup instructions](/sdk/javascript/setup-sdk) first, then update your dependencies and imports as shown below. -Please follow the [setup](/sdk/javascript/setup-sdk) instructions to upgrade to latest version of V4 before proceeding further +## Update Dependencies -## Dependency Change +| SDK | v3 Package | v4 Package | +| --- | --- | --- | +| Chat SDK | `@cometchat-pro/chat` | `@cometchat/chat-sdk-javascript` | +| Calls SDK | `@cometchat-pro/calls` | `@cometchat/calls-sdk-javascript` | -## Chat SDK - - - ```bash -npm i @cometchat/chat-sdk-javascript -``` - - +# Remove v3 packages +npm uninstall @cometchat-pro/chat @cometchat-pro/calls - - -## Calls SDK - - - -```bash +# Install v4 packages +npm i @cometchat/chat-sdk-javascript npm i @cometchat/calls-sdk-javascript ``` - +## Update Import Statements - +Find and replace all import statements across your project: -## Change The Import Statements +| SDK | v3 Import | v4 Import | +| --- | --- | --- | +| Chat SDK | `import { CometChat } from '@cometchat-pro/chat'` | `import { CometChat } from '@cometchat/chat-sdk-javascript'` | +| Calls SDK | `import { CometChatCalls } from '@cometchat-pro/calls'` | `import { CometChatCalls } from '@cometchat/calls-sdk-javascript'` | -Change the import statements all around the project. - -## Chat SDK - - - ```js -import {CometChat} from '@cometchat/chat-sdk-javascript'; -``` - - +// v4 Chat SDK +import { CometChat } from '@cometchat/chat-sdk-javascript'; - - -## Calls SDK - - - -```js -import {CometChatCalls} from '@cometchat/calls-sdk-javascript'; +// v4 Calls SDK +import { CometChatCalls } from '@cometchat/calls-sdk-javascript'; ``` - - - + +The API methods, class names, and listener interfaces are unchanged between v3 and v4. Once you update the packages and imports, your existing code should work without further modifications. + --- From b7be10731f8df720a2259cbda59421c478d79455 Mon Sep 17 00:00:00 2001 From: PrajwalDhuleCC Date: Thu, 26 Mar 2026 18:21:21 +0530 Subject: [PATCH 106/139] Revert files to match main --- 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 insertions(+) create mode 100644 node_modules/.package-lock.json create mode 100644 node_modules/22/README.md create mode 100644 node_modules/22/package.json create mode 100644 package-lock.json create mode 100644 package.json diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 000000000..b9f3c6ed9 --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,13 @@ +{ + "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 new file mode 100644 index 000000000..311c8dd06 --- /dev/null +++ b/node_modules/22/README.md @@ -0,0 +1 @@ +PLACEHOLDER \ No newline at end of file diff --git a/node_modules/22/package.json b/node_modules/22/package.json new file mode 100644 index 000000000..f3cf8f650 --- /dev/null +++ b/node_modules/22/package.json @@ -0,0 +1,11 @@ +{ + "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 new file mode 100644 index 000000000..e374029e1 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,18 @@ +{ + "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 new file mode 100644 index 000000000..08836e674 --- /dev/null +++ b/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "22": "^0.0.0" + } +} From 6cb6f7e877b32c6b72d771338a0f561541081d6b Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 18:24:56 +0530 Subject: [PATCH 107/139] Update troubleshooting.mdx --- sdk/javascript/troubleshooting.mdx | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/sdk/javascript/troubleshooting.mdx b/sdk/javascript/troubleshooting.mdx index 03a532438..1fe291d2f 100644 --- a/sdk/javascript/troubleshooting.mdx +++ b/sdk/javascript/troubleshooting.mdx @@ -78,6 +78,7 @@ Find solutions to common issues when building with the CometChat JavaScript SDK. | 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 | +| Call ended event not received | Wrong callback | Use `onCallEndedMessageReceived` in `CallListener` for call-end messages, `onCallEnded` in `OngoingCallListener` for session events | | 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 | @@ -92,6 +93,7 @@ Find solutions to common issues when building with the CometChat JavaScript SDK. | 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` | +| `featureThrottled` status | Feature rate-limited | Reduce frequency of the throttled feature. Listen for `onFeatureThrottled` in `ConnectionListener` | | 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 | @@ -115,6 +117,7 @@ Find solutions to common issues when building with the CometChat JavaScript SDK. | 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 | +| `onMessagesDeliveredToAll`/`onMessagesReadByAll` not firing | Not registered | Register these callbacks in `MessageListener` for group-level receipt events | | Reaction not appearing | UI not synced | Call `updateMessageWithReactionInfo()` on events | | Duplicate reactions | No check before adding | Use `getReactedByMe()` first | @@ -155,16 +158,20 @@ Find solutions to common issues when building with the CometChat JavaScript SDK. ## Error Codes +For the complete SDK error code reference, see [Error Codes](/sdk/javascript/error-codes). Common errors you'll encounter: + | 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 | +| `AUTH_ERR_AUTH_TOKEN_NOT_FOUND` | Invalid or expired auth token | Generate new token via REST API | +| `MISSING_PARAMETERS` | Required parameter not provided | Check method signature and pass all required params | +| `NOT_INITIALIZED` | `init()` not called | Call `CometChat.init()` before any other method | +| `USER_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) | +| `ERR_TOO_MANY_REQUESTS` | Rate limit exceeded | See [Rate Limits](/sdk/javascript/rate-limits) | +| `FAILED_TO_FETCH` | Network issue | Check internet connection and API endpoint | +| `NO_WEBSOCKET_CONNECTION` | WebSocket disconnected | Check connection status, wait for reconnect | --- @@ -177,6 +184,9 @@ Find solutions to common issues when building with the CometChat JavaScript SDK. Recommended patterns and practices + + Complete SDK error code reference + AI Agents, Moderation, and Copilot From 3a525c09e537bb26ea9a841bfa402dd4106971ef Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 18:27:43 +0530 Subject: [PATCH 108/139] Update ai-agents.mdx --- sdk/javascript/ai-agents.mdx | 41 ++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/sdk/javascript/ai-agents.mdx b/sdk/javascript/ai-agents.mdx index fadc24086..2baaaa423 100644 --- a/sdk/javascript/ai-agents.mdx +++ b/sdk/javascript/ai-agents.mdx @@ -66,6 +66,29 @@ Events arrive via `onAIAssistantEventReceived` in this order: `Run Start` and `Run Finished` are always emitted. Tool Call events only appear when tools are invoked — there can be multiple tool call cycles in a single run. Text Message events are always emitted and carry the assistant's reply incrementally. +### Event Object Properties + +Every event is an `AIAssistantBaseEvent` with these common properties: + +| Getter | Return Type | Description | +|--------|-------------|-------------| +| `getType()` | `string` | Event type (e.g., `run_started`, `text_message_content`) | +| `getConversationId()` | `string` | The conversation this event belongs to | +| `getMessageId()` | `string` | The message ID associated with the event | +| `getParentMessageId()` | `string` | Parent message ID (for threaded messages) | +| `getRunId()` | `string` | The run ID for this agent execution | +| `getThreadId()` | `string` | The thread ID for this agent execution | +| `getTimestamp()` | `number` | Timestamp of the event | +| `getData()` | `object` | Full event data payload | + +Some events carry additional data: + +| Event | Extra Getter | Description | +|-------|-------------|-------------| +| Text Message Content | `getDelta()` | The streaming text chunk for progressive rendering | +| Tool Call Arguments | `getToolCallId()`, `getDelta()` | Tool call ID and argument chunk | +| Tool Call Result | `getToolCallId()`, `getContent()`, `getRole()` | Tool call ID, result content, and role | + ```ts @@ -109,6 +132,24 @@ After the run completes, these messages arrive via `MessageListener`: | `AIToolResultMessage` | The final output of a tool call | | `AIToolArgumentMessage` | The arguments passed to a tool | +Each message type extends `BaseMessage` and has a typed data accessor: + +| Message Type | Data Getter | Data Properties | +|--------------|-------------|-----------------| +| `AIAssistantMessage` | `getAssistantMessageData()` | `getRunId()`, `getThreadId()`, `getText()` | +| `AIToolResultMessage` | `getToolResultMessageData()` | `getRunId()`, `getThreadId()`, `getText()`, `getToolCallId()` | +| `AIToolArgumentMessage` | `getToolArgumentMessageData()` | `getRunId()`, `getThreadId()`, `getToolCalls()` | + +The `getToolCalls()` method on `AIToolArgumentMessage` returns an array of `AIToolCall` objects, each with: + +| Getter | Return Type | Description | +|--------|-------------|-------------| +| `getId()` | `string` | Unique tool call ID | +| `getType()` | `string` | Tool call type | +| `getFunction()` | `AIToolCallFunction` | Function object with `getName()` and `getArguments()` | +| `getDisplayName()` | `string` | Display name of the tool | +| `getExecutionText()` | `string` | Execution description text | + From 155e908d6c71598e8009c664a223b543124bba70 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 18:33:20 +0530 Subject: [PATCH 109/139] Update ai-moderation.mdx --- sdk/javascript/ai-moderation.mdx | 1 + 1 file changed, 1 insertion(+) diff --git a/sdk/javascript/ai-moderation.mdx b/sdk/javascript/ai-moderation.mdx index b619b46b6..23df41747 100644 --- a/sdk/javascript/ai-moderation.mdx +++ b/sdk/javascript/ai-moderation.mdx @@ -85,6 +85,7 @@ The `getModerationStatus()` method returns one of the following values: | Pending | `CometChat.ModerationStatus.PENDING` | Message is being processed by moderation | | Approved | `CometChat.ModerationStatus.APPROVED` | Message passed moderation and is visible | | Disapproved | `CometChat.ModerationStatus.DISAPPROVED` | Message violated rules and was blocked | +| Unmoderated | `CometChat.ModerationStatus.UNMODERATED` | Message was not subject to moderation (default) | ## Implementation From 55b0fbfa66bb879c686bb46945fa815b850eebda Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 18:52:39 +0530 Subject: [PATCH 110/139] missing methods --- sdk/javascript/all-real-time-listeners.mdx | 130 +++++++++++++++++++++ sdk/javascript/delivery-read-receipts.mdx | 35 ++++++ sdk/javascript/direct-call.mdx | 63 ++++++++++ sdk/javascript/receive-message.mdx | 41 +++++++ 4 files changed, 269 insertions(+) diff --git a/sdk/javascript/all-real-time-listeners.mdx b/sdk/javascript/all-real-time-listeners.mdx index e96649f15..5fca6727d 100644 --- a/sdk/javascript/all-real-time-listeners.mdx +++ b/sdk/javascript/all-real-time-listeners.mdx @@ -879,6 +879,136 @@ CometChatCalls.removeCallEventListener(listenerId); --- +## Login Listener + +Receive events when the user's authentication state changes — login success/failure and logout success/failure. + +| Method | Description | +| ------ | ----------- | +| `loginSuccess(user)` | User logged in successfully. Provides the `User` object. | +| `loginFailure(error)` | Login failed. Provides a `CometChatException`. | +| `logoutSuccess()` | User logged out successfully. | +| `logoutFailure(error)` | Logout failed. Provides a `CometChatException`. | + + + +```typescript +const listenerID: string = "UNIQUE_LISTENER_ID"; +CometChat.addLoginListener( + listenerID, + new CometChat.LoginListener({ + loginSuccess: (user: CometChat.User) => { + console.log("LoginListener :: loginSuccess", user); + }, + loginFailure: (error: CometChat.CometChatException) => { + console.log("LoginListener :: loginFailure", error); + }, + logoutSuccess: () => { + console.log("LoginListener :: logoutSuccess"); + }, + logoutFailure: (error: CometChat.CometChatException) => { + console.log("LoginListener :: logoutFailure", error); + } + }) +); +``` + + +```js +const listenerID = "UNIQUE_LISTENER_ID"; +CometChat.addLoginListener( + listenerID, + new CometChat.LoginListener({ + loginSuccess: (user) => { + console.log("LoginListener :: loginSuccess", user); + }, + loginFailure: (error) => { + console.log("LoginListener :: loginFailure", error); + }, + logoutSuccess: () => { + console.log("LoginListener :: logoutSuccess"); + }, + logoutFailure: (error) => { + console.log("LoginListener :: logoutFailure", error); + } + }) +); +``` + + + +Remove the listener when no longer needed: + +```javascript +CometChat.removeLoginListener("UNIQUE_LISTENER_ID"); +``` + +## Connection Listener + +Receive events when the WebSocket connection state changes. + +| Method | Description | +| ------ | ----------- | +| `onConnected()` | SDK has an active connection to CometChat servers. | +| `inConnecting()` | SDK is attempting to establish or re-establish a connection. | +| `onDisconnected()` | SDK is disconnected due to network issues or other errors. | +| `onFeatureThrottled()` | A feature has been throttled due to rate limiting. | + + + +```typescript +const listenerID: string = "UNIQUE_LISTENER_ID"; +CometChat.addConnectionListener( + listenerID, + new CometChat.ConnectionListener({ + onConnected: () => { + console.log("ConnectionListener :: connected"); + }, + inConnecting: () => { + console.log("ConnectionListener :: connecting"); + }, + onDisconnected: () => { + console.log("ConnectionListener :: disconnected"); + }, + onFeatureThrottled: () => { + console.log("ConnectionListener :: feature throttled"); + } + }) +); +``` + + +```js +const listenerID = "UNIQUE_LISTENER_ID"; +CometChat.addConnectionListener( + listenerID, + new CometChat.ConnectionListener({ + onConnected: () => { + console.log("ConnectionListener :: connected"); + }, + inConnecting: () => { + console.log("ConnectionListener :: connecting"); + }, + onDisconnected: () => { + console.log("ConnectionListener :: disconnected"); + }, + onFeatureThrottled: () => { + console.log("ConnectionListener :: feature throttled"); + } + }) +); +``` + + + +Remove the listener when no longer needed: + +```javascript +CometChat.removeConnectionListener("UNIQUE_LISTENER_ID"); +``` + +--- + ## Next Steps diff --git a/sdk/javascript/delivery-read-receipts.mdx b/sdk/javascript/delivery-read-receipts.mdx index 9f5dc643b..c1a5ae0f7 100644 --- a/sdk/javascript/delivery-read-receipts.mdx +++ b/sdk/javascript/delivery-read-receipts.mdx @@ -614,6 +614,41 @@ The following features require **Enhanced Messaging Status** to be enabled for y - `markMessageAsUnread()` method +## Mark as Unread + +Use `markAsUnread()` to mark a message as unread. This is useful for "mark as unread" functionality in conversation lists. Pass a message object (`TextMessage`, `MediaMessage`, or `CustomMessage`). + + + +```typescript +CometChat.markAsUnread(message).then( + (response: string) => { + console.log("Message marked as unread:", response); + }, + (error: CometChat.CometChatException) => { + console.log("Error marking as unread:", error); + } +); +``` + + +```javascript +CometChat.markAsUnread(message).then( + (response) => { + console.log("Message marked as unread:", response); + }, + (error) => { + console.log("Error marking as unread:", error); + } +); +``` + + + +| Parameter | Type | Description | +|-----------|------|-------------| +| `message` | `BaseMessage` | The message object to mark as unread | + --- ## Next Steps diff --git a/sdk/javascript/direct-call.mdx b/sdk/javascript/direct-call.mdx index 4e2518e91..13dc4a063 100644 --- a/sdk/javascript/direct-call.mdx +++ b/sdk/javascript/direct-call.mdx @@ -713,6 +713,69 @@ CometChatCalls.endSession(); +## Utility Methods + +### Get Active Call + +Returns the current active `Call` object, or `undefined` if no call is in progress. + +```javascript +const activeCall = CometChat.getActiveCall(); +if (activeCall) { + console.log("Active call session:", activeCall.getSessionId()); +} +``` + +### Clear Active Call + +Clears the locally stored active call state. Call this after ending a call session. + +```javascript +CometChat.clearActiveCall(); +``` + +### Get Call Participant Count + +Returns the number of participants currently in a call session. + + + +```typescript +let sessionId: string = "SESSION_ID"; +let type: string = "direct"; // "direct" or "default" + +CometChat.getCallParticipantCount(sessionId, type).then( + (count: number) => { + console.log("Participant count:", count); + }, + (error: CometChat.CometChatException) => { + console.log("Error:", error); + } +); +``` + + +```javascript +let sessionId = "SESSION_ID"; +let type = "direct"; // "direct" or "default" + +CometChat.getCallParticipantCount(sessionId, type).then( + (count) => { + console.log("Participant count:", count); + }, + (error) => { + console.log("Error:", error); + } +); +``` + + + +| Parameter | Type | Description | +|-----------|------|-------------| +| `sessionId` | `string` | The call session ID | +| `type` | `string` | Call type: `"direct"` or `"default"` | + --- ## Next Steps diff --git a/sdk/javascript/receive-message.mdx b/sdk/javascript/receive-message.mdx index 33d4f5776..7944543db 100644 --- a/sdk/javascript/receive-message.mdx +++ b/sdk/javascript/receive-message.mdx @@ -565,6 +565,47 @@ CometChat.getUnreadMessageCountForAllUsers(true); CometChat.getUnreadMessageCountForAllGroups(true); ``` +## Get Message Details + +Use `getMessageDetails()` to fetch a specific message by its ID. Returns the full message object (`TextMessage`, `MediaMessage`, `CustomMessage`, or `InteractiveMessage`). + + + +```typescript +let messageId: string = "MESSAGE_ID"; + +CometChat.getMessageDetails(messageId).then( + (message: CometChat.BaseMessage) => { + console.log("Message details:", message); + }, + (error: CometChat.CometChatException) => { + console.log("Error fetching message details:", error); + } +); +``` + + +```javascript +let messageId = "MESSAGE_ID"; + +CometChat.getMessageDetails(messageId).then( + (message) => { + console.log("Message details:", message); + }, + (error) => { + console.log("Error fetching message details:", error); + } +); +``` + + + +| Parameter | Type | Description | +|-----------|------|-------------| +| `messageId` | `string` | The ID of the message to fetch | + +Returns a [`BaseMessage`](/sdk/reference/messages#basemessage) object (which may be a `TextMessage`, `MediaMessage`, `CustomMessage`, or `InteractiveMessage`). + --- ## Next Steps From 8774649a887d6a628793e8e57edd7e160d4c7430 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 18:58:08 +0530 Subject: [PATCH 111/139] Update receive-message.mdx --- sdk/javascript/receive-message.mdx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/sdk/javascript/receive-message.mdx b/sdk/javascript/receive-message.mdx index 7944543db..f68d9842a 100644 --- a/sdk/javascript/receive-message.mdx +++ b/sdk/javascript/receive-message.mdx @@ -339,6 +339,8 @@ Each method accepts an optional boolean parameter to exclude messages from block ### Single Conversation + + ```typescript // One-on-one let UID: string = "UID"; From 9f81082e770d1eb09058b52370b054e7a4999425 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 19:03:57 +0530 Subject: [PATCH 112/139] Update receive-message.mdx --- sdk/javascript/receive-message.mdx | 216 ++++++----------------------- 1 file changed, 42 insertions(+), 174 deletions(-) diff --git a/sdk/javascript/receive-message.mdx b/sdk/javascript/receive-message.mdx index f68d9842a..3cd25395e 100644 --- a/sdk/javascript/receive-message.mdx +++ b/sdk/javascript/receive-message.mdx @@ -86,7 +86,9 @@ CometChat.removeMessageListener("UNIQUE_LISTENER_ID"); Always remove listeners when they're no longer needed (e.g., on component unmount). Failing to do so can cause memory leaks and duplicate event handling. -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. + +As a sender, you will not receive your own message in a real-time event. However, if a user is logged in on multiple devices, they will receive the event on the other devices. + ## Missed Messages @@ -250,8 +252,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). ## Search Messages @@ -340,7 +340,7 @@ Each method accepts an optional boolean parameter to exclude messages from block ### Single Conversation - + ```typescript // One-on-one let UID: string = "UID"; @@ -349,211 +349,79 @@ CometChat.getUnreadMessageCountForUser(UID).then( (error: CometChat.CometChatException) => console.log("Error:", error) ); - - - -```typescript -let UID: string = "UID"; - -CometChat.getUnreadMessageCountForUser(UID).then( - (unreadMessageCount: Object) => { - console.log("Unread message count fetched", unreadMessageCount); - }, - (error: CometChat.CometChatException) => { - console.log("Error in getting unread message count", error); - } -); -``` - - - - - -The `getUnreadMessageCountForUser()` method returns a count object where the key is the UID and the value is the unread message count (e.g., `{ "UID": 5 }`). - -It will return an object which will contain the UID as the key and the unread message count as the 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: - - - -```javascript -CometChat.getUnreadMessageCountForGroup(GUID); -``` - - - - -```typescript +// Group let GUID: string = "GUID"; CometChat.getUnreadMessageCountForGroup(GUID).then( (count: Object) => console.log("Unread count:", count), (error: CometChat.CometChatException) => console.log("Error:", error) ); ``` - -### All Conversations - -```typescript -let GUID: string = "GUID"; - -CometChat.getUnreadMessageCountForGroup(GUID).then( - (unreadMessageCount: Object) => { - console.log("Unread message count fetched", unreadMessageCount); - }, - (error: CometChat.CometChatException) => { - console.log("Error in getting unread message count", error); - } -); -``` - - - - -The `getUnreadMessageCountForGroup()` method returns a count object where the key is the GUID and the value is the unread message count (e.g., `{ "GUID": 12 }`). - -It will return an object which will contain the GUID as the key and the unread message count as the 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: - - - + ```javascript -CometChat.getUnreadMessageCount(); -``` - - +// One-on-one +let UID = "UID"; +CometChat.getUnreadMessageCountForUser(UID).then( + (count) => console.log("Unread count:", count), + (error) => console.log("Error:", error) +); - -```typescript -CometChat.getUnreadMessageCount(); +// Group +let GUID = "GUID"; +CometChat.getUnreadMessageCountForGroup(GUID).then( + (count) => console.log("Unread count:", count), + (error) => console.log("Error:", error) +); ``` - - -If you wish to ignore the messages from blocked users you can use the below syntax setting the boolean parameter to true: +### All Conversations - -```javascript -CometChat.getUnreadMessageCount(hideMessagesFromBlockedUsers); -``` - - - ```typescript -let hideMessagesFromBlockedUsers: boolean = true; -CometChat.getUnreadMessageCount(hideMessagesFromBlockedUsers); -``` - - - - - - - -```javascript +// All users and groups combined CometChat.getUnreadMessageCount().then( (count: Object) => console.log("Unread count:", count), (error: CometChat.CometChatException) => console.log("Error:", error) ); - - - -```typescript -CometChat.getUnreadMessageCount().then( - (unreadMessageCount: Object) => { - console.log("Unread message count fetched", unreadMessageCount); - }, - (error: CometChat.CometChatException) => { - console.log("Error in getting unread message count", error); - } +// All user conversations only +CometChat.getUnreadMessageCountForAllUsers().then( + (count: Object) => console.log("Unread count:", count), + (error: CometChat.CometChatException) => console.log("Error:", error) ); -``` - - - - - -The `getUnreadMessageCount()` method returns a count object with two keys: `users` (a map of `{ UID: count }`) and `groups` (a map of `{ GUID: count }`), representing unread message counts across all conversations. - -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. - -### 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: - - - -```javascript -CometChat.getUnreadMessageCountForAllUsers(); -``` - - - -```typescript -CometChat.getUnreadMessageCountForAllUsers(); +// All group conversations only +CometChat.getUnreadMessageCountForAllGroups().then( + (count: Object) => console.log("Unread count:", count), + (error: CometChat.CometChatException) => console.log("Error:", error) +); ``` - - - - -If you wish to ignore the messages from blocked users you can use the below syntax setting the boolean parameter to true: - - - + ```javascript -CometChat.getUnreadMessageCountForAllUsers(hideMessagesFromBlockedUsers); -``` - - - - -```typescript -let hideMessagesFromBlockedUsers: boolean = true; -CometChat.getUnreadMessageCountForAllUsers(hideMessagesFromBlockedUsers); -``` - - - - +// All users and groups combined +CometChat.getUnreadMessageCount().then( + (count) => console.log("Unread count:", count), + (error) => console.log("Error:", error) +); - - -```javascript +// All user conversations only CometChat.getUnreadMessageCountForAllUsers().then( - (count: Object) => console.log("Unread count:", count), - (error: CometChat.CometChatException) => console.log("Error:", error) + (count) => console.log("Unread count:", count), + (error) => console.log("Error:", error) ); // All group conversations only CometChat.getUnreadMessageCountForAllGroups().then( - (count: Object) => console.log("Unread count:", count), - (error: CometChat.CometChatException) => console.log("Error:", error) + (count) => console.log("Unread count:", count), + (error) => console.log("Error:", error) ); ``` + + ### Excluding Blocked Users From cef0cc754c8e7f407291470fd2e5d26726b0f3bc Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 19:10:28 +0530 Subject: [PATCH 113/139] fixes the response objects --- sdk/javascript/ai-moderation.mdx | 4 +++- sdk/javascript/reactions.mdx | 4 ++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/sdk/javascript/ai-moderation.mdx b/sdk/javascript/ai-moderation.mdx index 23df41747..412a7d633 100644 --- a/sdk/javascript/ai-moderation.mdx +++ b/sdk/javascript/ai-moderation.mdx @@ -28,6 +28,8 @@ CometChat.addMessageListener("MOD_LISTENER", new CometChat.MessageListener({ AI Moderation automatically reviews messages for inappropriate content in real-time. When a user sends a text, image, or video message, it's held in a `PENDING` state while the moderation service analyzes it, then marked as `APPROVED` or `DISAPPROVED` via the `onMessageModerated` event. +`getModerationStatus()` is available on [`TextMessage`](/sdk/reference/messages#textmessage) and [`MediaMessage`](/sdk/reference/messages#mediamessage) objects. Custom messages are not subject to moderation. + For configuring moderation rules and managing flagged messages from the dashboard, see the [Moderation Overview](/moderation/overview). @@ -146,7 +148,7 @@ When you send a text, image, or video message, check the initial moderation stat ### Step 2: Listen for Moderation Results -Register a message listener to receive moderation results in real-time: +Register a message listener to receive moderation results in real-time. The `onMessageModerated` callback receives a [`BaseMessage`](/sdk/reference/messages#basemessage) object: diff --git a/sdk/javascript/reactions.mdx b/sdk/javascript/reactions.mdx index f79f09d73..06914e6c0 100644 --- a/sdk/javascript/reactions.mdx +++ b/sdk/javascript/reactions.mdx @@ -106,7 +106,7 @@ Any [`BaseMessage`](/sdk/reference/messages#basemessage) exposes reaction data t ### Get All Reactions -Use `getReactions()` to retrieve the list of reactions on a message. Returns an empty array if no one has reacted. +Use `getReactions()` to retrieve the list of reactions on a message. Returns an array of [`ReactionCount`](/sdk/reference/auxiliary#reactioncount) objects, or an empty array if no one has reacted. @@ -124,7 +124,7 @@ message.getReactions() ### Check if the Logged-in User Has Reacted -Call `getReactedByMe()` on any [`ReactionCount`](/sdk/reference/auxiliary#reactioncount) object to check whether the logged-in user has reacted with that particular emoji. +Call `getReactedByMe()` on any [`ReactionCount`](/sdk/reference/auxiliary#reactioncount) object to check whether the logged-in user has reacted with that particular emoji. Returns `true` if they have, `false` otherwise. From 7b5a8e8d0a54a799d27cfe5526900a0e0ce14ae3 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 19:13:59 +0530 Subject: [PATCH 114/139] Update retrieve-groups.mdx --- sdk/javascript/retrieve-groups.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/javascript/retrieve-groups.mdx b/sdk/javascript/retrieve-groups.mdx index 81a27bff5..f8d739267 100644 --- a/sdk/javascript/retrieve-groups.mdx +++ b/sdk/javascript/retrieve-groups.mdx @@ -181,7 +181,7 @@ Relevant fields to access on returned groups: 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. -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. +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`](/sdk/reference/entities#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. From 86fdd993155aad85beaba607830dd2023b0fa2a5 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 19:14:10 +0530 Subject: [PATCH 115/139] Update retrieve-conversations.mdx --- sdk/javascript/retrieve-conversations.mdx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/sdk/javascript/retrieve-conversations.mdx b/sdk/javascript/retrieve-conversations.mdx index fedfba16c..174cd4e6c 100644 --- a/sdk/javascript/retrieve-conversations.mdx +++ b/sdk/javascript/retrieve-conversations.mdx @@ -86,7 +86,7 @@ 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. +When conversations are fetched successfully, the response will include an array of [`Conversation`](/sdk/reference/entities#conversation) objects filtered by the specified type. Relevant fields to access on returned conversations: @@ -651,7 +651,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. +When the conversation is tagged successfully, the response will return a single [`Conversation`](/sdk/reference/entities#conversation) object (not an array) with the `tags` field included. The `tagConversation()` method returns a [`Conversation`](/sdk/reference/entities#conversation) object with the `tags` field populated. @@ -731,13 +731,13 @@ CometChat.getConversation(conversationWith, conversationType).then( -When the conversation is fetched successfully, the response will return a single `Conversation` object (not an array). +When the conversation is fetched successfully, the response will return a single [`Conversation`](/sdk/reference/entities#conversation) object (not an array). The `getConversation()` method 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. +As per our [receive messages](/sdk/javascript/receive-message) guide, for real-time messages, you will always receive `Message` objects and not [`Conversation`](/sdk/reference/entities#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. From f0ab1028db819d6ff0930a374ababd00608c4b83 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 19:27:06 +0530 Subject: [PATCH 116/139] fixes issues related to docs against codebase --- sdk/javascript/advanced-overview.mdx | 4 +- sdk/javascript/delete-group.mdx | 2 +- sdk/javascript/group-add-members.mdx | 2 +- sdk/javascript/group-change-member-scope.mdx | 12 +++--- sdk/javascript/join-group.mdx | 11 +++-- sdk/javascript/leave-group.mdx | 4 +- sdk/javascript/mentions.mdx | 8 ++-- sdk/javascript/rate-limits.mdx | 4 +- sdk/javascript/reactions.mdx | 14 +++---- sdk/javascript/retrieve-conversations.mdx | 2 +- sdk/javascript/retrieve-groups.mdx | 43 ++++---------------- sdk/javascript/retrieve-users.mdx | 2 +- sdk/javascript/threaded-messages.mdx | 1 + sdk/javascript/troubleshooting.mdx | 4 +- 14 files changed, 44 insertions(+), 69 deletions(-) diff --git a/sdk/javascript/advanced-overview.mdx b/sdk/javascript/advanced-overview.mdx index d38b93f35..d09312b42 100644 --- a/sdk/javascript/advanced-overview.mdx +++ b/sdk/javascript/advanced-overview.mdx @@ -19,8 +19,8 @@ CometChat.addConnectionListener("LISTENER_ID", new CometChat.ConnectionListener( // Listen for login events CometChat.addLoginListener("LISTENER_ID", new CometChat.LoginListener({ - onLoginSuccess: (user) => console.log("Logged in:", user), - onLogoutSuccess: () => console.log("Logged out") + loginSuccess: (user) => console.log("Logged in:", user), + logoutSuccess: () => console.log("Logged out") })); ``` diff --git a/sdk/javascript/delete-group.mdx b/sdk/javascript/delete-group.mdx index b2b25382d..c27a4cf31 100644 --- a/sdk/javascript/delete-group.mdx +++ b/sdk/javascript/delete-group.mdx @@ -76,7 +76,7 @@ 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. +On success, the method resolves with `true` (boolean). --- diff --git a/sdk/javascript/group-add-members.mdx b/sdk/javascript/group-add-members.mdx index a08ae2526..110f0cc1f 100644 --- a/sdk/javascript/group-add-members.mdx +++ b/sdk/javascript/group-add-members.mdx @@ -76,7 +76,7 @@ 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. +It will return an Object which will contain the `UID` of the users as keys and the value will either be `"success"` or an error message describing why the operation to add the user to the group failed. The method returns a response object where each key is a `UID` and the value is either `"success"` or an error message. diff --git a/sdk/javascript/group-change-member-scope.mdx b/sdk/javascript/group-change-member-scope.mdx index 8b19506db..a397d6a18 100644 --- a/sdk/javascript/group-change-member-scope.mdx +++ b/sdk/javascript/group-change-member-scope.mdx @@ -33,9 +33,9 @@ let UID: string = "UID"; CometChat.updateGroupMemberScope(GUID, UID, CometChat.GroupMemberScope.Admin).then( (response: boolean) => { - console.log("Group member scopped changed", response); + console.log("Group member scope changed", response); }, (error: CometChat.CometChatException) => { - console.log("Group member scopped changed failed", error); + console.log("Group member scope change failed", error); } ); ``` @@ -50,9 +50,9 @@ let scope = CometChat.GROUP_MEMBER_SCOPE.ADMIN; CometChat.updateGroupMemberScope(GUID, UID, scope).then( response => { - console.log("Group member scopped changed", response); + console.log("Group member scope changed", response); }, error => { - console.log("Group member scopped changed failed", error); + console.log("Group member scope change failed", error); } ); ``` @@ -67,11 +67,11 @@ This method takes the below parameters: | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | | `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` | +| `scope` | The new scope: `CometChat.GROUP_MEMBER_SCOPE.ADMIN`, `CometChat.GROUP_MEMBER_SCOPE.MODERATOR`, or `CometChat.GROUP_MEMBER_SCOPE.PARTICIPANT` | The default scope is `participant`. Only Admins can change member scopes. -On success, the method resolves with a success message string. +On success, the method resolves with `true` (boolean). ## Real-Time Group Member Scope Changed Events diff --git a/sdk/javascript/join-group.mdx b/sdk/javascript/join-group.mdx index 2d7e85894..1f8913200 100644 --- a/sdk/javascript/join-group.mdx +++ b/sdk/javascript/join-group.mdx @@ -32,7 +32,10 @@ Use `joinGroup()` to join a group. ```typescript const GUID: string = "GUID"; -CometChat.joinGroup(GUID, CometChat.GroupType.Public).then( +const password: string = ""; +const groupType: string = CometChat.GroupType.Public; + +CometChat.joinGroup(GUID, groupType, password).then( (group: CometChat.Group) => { console.log("Group joined successfully:", group); }, (error: CometChat.CometChatException) => { @@ -80,7 +83,7 @@ Register a `GroupListener` to receive events when members join. ```typescript CometChat.addGroupListener( - "UNIQUE_LISTNER_ID", + "UNIQUE_LISTENER_ID", new CometChat.GroupListener({ onGroupMemberJoined: (message: CometChat.Action, joinedUser: CometChat.User, joinedGroup: CometChat.Group) => { console.log("User joined", { message, joinedUser, joinedGroup }); @@ -94,7 +97,7 @@ CometChat.addGroupListener( ```javascript CometChat.addGroupListener( - "UNIQUE_LISTNER_ID", + "UNIQUE_LISTENER_ID", new CometChat.GroupListener({ onGroupMemberJoined: (message, joinedUser, joinedGroup) => { console.log("User joined", { message, joinedUser, joinedGroup }); @@ -111,7 +114,7 @@ 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"); +CometChat.removeGroupListener("UNIQUE_LISTENER_ID"); ``` diff --git a/sdk/javascript/leave-group.mdx b/sdk/javascript/leave-group.mdx index caf03152b..7333c82b5 100644 --- a/sdk/javascript/leave-group.mdx +++ b/sdk/javascript/leave-group.mdx @@ -59,11 +59,11 @@ hasLeft => { | Parameter | Description | | --------- | -------------------------------------------- | -| `GUID` | The UID of the group you would like to leave | +| `GUID` | The GUID of the group you would like to leave | 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. +On success, the method resolves with `true` (boolean). ## Real-time Group Member Left Events diff --git a/sdk/javascript/mentions.mdx b/sdk/javascript/mentions.mdx index ef0292b09..e3bd97a2a 100644 --- a/sdk/javascript/mentions.mdx +++ b/sdk/javascript/mentions.mdx @@ -82,10 +82,10 @@ CometChat.sendMessage(textMessage).then( ```typescript -let receiverID: string = "UID", - messageText: string = "Hello <@uid:cometchat-uid-1>"; - receiverType: string = CometChat.RECEIVER_TYPE.USER, - textMessage: CometChat.TextMessage = new CometChat.TextMessage(receiverID, messageText, receiverType); +let receiverID: string = "UID"; +let messageText: string = "Hello <@uid:cometchat-uid-1>"; +let receiverType: string = CometChat.RECEIVER_TYPE.USER; +let textMessage: CometChat.TextMessage = new CometChat.TextMessage(receiverID, messageText, receiverType); CometChat.sendMessage(textMessage).then( (message: CometChat.TextMessage) => { diff --git a/sdk/javascript/rate-limits.mdx b/sdk/javascript/rate-limits.mdx index 4494fe548..10fb9ffd7 100644 --- a/sdk/javascript/rate-limits.mdx +++ b/sdk/javascript/rate-limits.mdx @@ -50,7 +50,7 @@ async function callWithRetry( try { return await apiCall(); } catch (error: any) { - if (error.code === "ERR_TOO_MANY_REQUESTS" && attempt < maxRetries - 1) { + if (error.code === "TOO_MANY_REQUEST" && 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)); @@ -75,7 +75,7 @@ async function callWithRetry(apiCall, maxRetries = 3) { try { return await apiCall(); } catch (error) { - if (error.code === "ERR_TOO_MANY_REQUESTS" && attempt < maxRetries - 1) { + if (error.code === "TOO_MANY_REQUEST" && 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)); diff --git a/sdk/javascript/reactions.mdx b/sdk/javascript/reactions.mdx index 06914e6c0..89009e5a4 100644 --- a/sdk/javascript/reactions.mdx +++ b/sdk/javascript/reactions.mdx @@ -19,10 +19,10 @@ const request = new CometChat.ReactionRequestBuilder() const reactions = await request.fetchNext(); // Listen for reaction events -CometChat.addMessageListener("LISTENER_ID", { +CometChat.addMessageListener("LISTENER_ID", new CometChat.MessageListener({ onMessageReactionAdded: (reaction) => {}, onMessageReactionRemoved: (reaction) => {} -}); +})); ``` @@ -400,13 +400,13 @@ action ```typescript -// The message to which the reaction is related -let message: CometChat.BaseMessage = ...; +// The message to which the reaction is related (obtained from fetchPrevious/fetchNext or a listener) +let message!: CometChat.BaseMessage; -// The reaction event data received in real-time -let messageReaction: CometChat.MessageReaction = ...; +// The reaction event data received in real-time (obtained from onMessageReactionAdded/onMessageReactionRemoved) +let messageReaction!: CometChat.MessageReaction; -// The recieved reaction event real-time action type. Can be CometChatConstants.REACTION_ADDED or CometChatConstants.REACTION_REMOVED +// The received reaction event real-time action type. Can be CometChatConstants.REACTION_ADDED or CometChatConstants.REACTION_REMOVED let action: CometChat.REACTION_ACTION = CometChat.REACTION_ACTION.REACTION_ADDED; let modifiedBaseMessage = CometChat.CometChatHelper.updateMessageWithReactionInfo( diff --git a/sdk/javascript/retrieve-conversations.mdx b/sdk/javascript/retrieve-conversations.mdx index 174cd4e6c..4a17d1ee7 100644 --- a/sdk/javascript/retrieve-conversations.mdx +++ b/sdk/javascript/retrieve-conversations.mdx @@ -20,7 +20,7 @@ const conversation = await CometChat.getConversation("UID", "user"); await CometChat.tagConversation("UID", "user", ["archived"]); // Convert message to conversation -const conversation = await CometChat.CometChatHelper.getConversationFromMessage(message); +const conv = await CometChat.CometChatHelper.getConversationFromMessage(message); ``` diff --git a/sdk/javascript/retrieve-groups.mdx b/sdk/javascript/retrieve-groups.mdx index f8d739267..dfe30e0de 100644 --- a/sdk/javascript/retrieve-groups.mdx +++ b/sdk/javascript/retrieve-groups.mdx @@ -4,7 +4,6 @@ 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." --- -{/* TL;DR for Agents and Quick Reference */} ```javascript @@ -29,14 +28,12 @@ Fetch the list of [`Group`](/sdk/reference/entities#group) objects the logged-in ## 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. - -Fetching using this builder will return [`Group`](/sdk/reference/entities#group) objects - Use `GroupsRequestBuilder` to fetch groups with filtering, searching, and pagination. + +The list only includes public and password-protected groups. Private groups appear only if the user is a member. + + ### Set Limit Sets the number of groups to fetch per request. @@ -179,31 +176,7 @@ Relevant fields to access on returned groups: |-------|--------|-------------|-------------| | tags | `getTags()` | `string[]` | Tags associated with the group | -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. - -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`](/sdk/reference/entities#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. - - - -```javascript -let limit = 30; -let groupsRequest = new CometChat.GroupsRequestBuilder() - .setLimit(limit) - .withTags(true) - .build(); -``` - - - - - -After configuring the builder, call `build()` to get the `GroupsRequest` object, then call `fetchNext()` to retrieve groups. - - -The list only includes public and password-protected groups. Private groups appear only if the user is a member. - +After configuring the builder, call `build()` to get the `GroupsRequest` object, then call `fetchNext()` to retrieve groups. Call `fetchNext()` repeatedly on the same instance to paginate. @@ -296,7 +269,7 @@ Use `getOnlineGroupMemberCount()` to get the number of online members in specifi ```typescript let guids: String[] = ["cometchat-guid-1"]; CometChat.getOnlineGroupMemberCount(guids).then( - (groupMemberCount: number) => { + (groupMemberCount: Object) => { console.log("Total online user for specified groups:", groupMemberCount); }, (error: CometChat.CometChatException) => { console.log("Online group member count fetching failed with error:", error); @@ -322,9 +295,7 @@ groupMemberCount => { -Returns an object with GUIDs as keys and online member counts as values. - -`getOnlineGroupMemberCount()` resolves with a `{ guid: count }` object where each key is a group GUID and its value is the number of currently online members in that group. +Returns an object with GUIDs as keys and online member counts as values (e.g., `{ "cometchat-guid-1": 5 }`). --- diff --git a/sdk/javascript/retrieve-users.mdx b/sdk/javascript/retrieve-users.mdx index 2618b837c..12d177598 100644 --- a/sdk/javascript/retrieve-users.mdx +++ b/sdk/javascript/retrieve-users.mdx @@ -38,7 +38,7 @@ The CometChat SDK provides methods to retrieve the logged-in user, fetch filtere ## Get the Logged-In User -Use `getLoggedinUser()` to get the current user's details. A rejected promise indicates no user is logged in. +Use `getLoggedinUser()` to get the current user's details. Resolves with `null` if no user is logged in. diff --git a/sdk/javascript/threaded-messages.mdx b/sdk/javascript/threaded-messages.mdx index a203f7c1e..8a2bd8561 100644 --- a/sdk/javascript/threaded-messages.mdx +++ b/sdk/javascript/threaded-messages.mdx @@ -53,6 +53,7 @@ CometChat.sendMessage(textMessage).then( ```javascript +let UID = "UID"; let textMessage = new CometChat.TextMessage(UID, "Hello", CometChat.RECEIVER_TYPE.USER); textMessage.setParentMessageId(100); diff --git a/sdk/javascript/troubleshooting.mdx b/sdk/javascript/troubleshooting.mdx index 1fe291d2f..ee5e2671e 100644 --- a/sdk/javascript/troubleshooting.mdx +++ b/sdk/javascript/troubleshooting.mdx @@ -60,7 +60,7 @@ Find solutions to common issues when building with the CometChat JavaScript SDK. | 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 | +| Password join fails | Wrong password | Pass correct password as third 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` | @@ -169,7 +169,7 @@ For the complete SDK error code reference, see [Error Codes](/sdk/javascript/err | `USER_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_TOO_MANY_REQUESTS` | Rate limit exceeded | See [Rate Limits](/sdk/javascript/rate-limits) | +| `TOO_MANY_REQUEST` | Rate limit exceeded | See [Rate Limits](/sdk/javascript/rate-limits) | | `FAILED_TO_FETCH` | Network issue | Check internet connection and API endpoint | | `NO_WEBSOCKET_CONNECTION` | WebSocket disconnected | Check connection status, wait for reconnect | From 8e54e09c6f53a48b5ccc7e6f6007b56f7ea8ec74 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 19:30:21 +0530 Subject: [PATCH 117/139] CometChatException --- sdk/javascript/all-real-time-listeners.mdx | 4 ++-- sdk/javascript/authentication-overview.mdx | 4 ++-- sdk/javascript/error-codes.mdx | 2 +- sdk/javascript/login-listener.mdx | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/sdk/javascript/all-real-time-listeners.mdx b/sdk/javascript/all-real-time-listeners.mdx index 5fca6727d..081a9dfd1 100644 --- a/sdk/javascript/all-real-time-listeners.mdx +++ b/sdk/javascript/all-real-time-listeners.mdx @@ -886,9 +886,9 @@ Receive events when the user's authentication state changes — login success/fa | Method | Description | | ------ | ----------- | | `loginSuccess(user)` | User logged in successfully. Provides the `User` object. | -| `loginFailure(error)` | Login failed. Provides a `CometChatException`. | +| `loginFailure(error)` | Login failed. Provides a [`CometChatException`](/sdk/reference/auxiliary#cometchatexception). | | `logoutSuccess()` | User logged out successfully. | -| `logoutFailure(error)` | Logout failed. Provides a `CometChatException`. | +| `logoutFailure(error)` | Logout failed. Provides a [`CometChatException`](/sdk/reference/auxiliary#cometchatexception). | diff --git a/sdk/javascript/authentication-overview.mdx b/sdk/javascript/authentication-overview.mdx index c300206e9..4de0a68b7 100644 --- a/sdk/javascript/authentication-overview.mdx +++ b/sdk/javascript/authentication-overview.mdx @@ -285,9 +285,9 @@ You can listen for login and logout events in real time using `LoginListener`. T | Callback | Description | | --- | --- | | `loginSuccess(event)` | User logged in successfully. Provides the `User` object. | -| `loginFailure(event)` | Login failed. Provides a `CometChatException`. | +| `loginFailure(event)` | Login failed. Provides a [`CometChatException`](/sdk/reference/auxiliary#cometchatexception). | | `logoutSuccess()` | User logged out successfully. | -| `logoutFailure(event)` | Logout failed. Provides a `CometChatException`. | +| `logoutFailure(event)` | Logout failed. Provides a [`CometChatException`](/sdk/reference/auxiliary#cometchatexception). | ### Add a Listener diff --git a/sdk/javascript/error-codes.mdx b/sdk/javascript/error-codes.mdx index fd3914478..d40e3b6f3 100644 --- a/sdk/javascript/error-codes.mdx +++ b/sdk/javascript/error-codes.mdx @@ -21,7 +21,7 @@ try { **Error categories:** Initialization, Login, Calling, Messages, Groups, Users, Conversations, Receipts, AI, Extensions -Every error thrown by the CometChat SDK is a `CometChatException` object with four properties: +Every error thrown by the CometChat SDK is a [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) object with four properties: | Property | Type | Description | |----------|------|-------------| diff --git a/sdk/javascript/login-listener.mdx b/sdk/javascript/login-listener.mdx index 47dbcaf45..c25a75099 100644 --- a/sdk/javascript/login-listener.mdx +++ b/sdk/javascript/login-listener.mdx @@ -25,9 +25,9 @@ The CometChat SDK provides you with real-time updates for the `login` and `logou | Delegate Method | Information | | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | | loginSuccess(event) | Informs you that the login was successful and provides you with a user object containing the data for the user that logged in. | -| loginFailure(event) | Informs you about the failure while logging in the user and provides you with the reason for the failure wrapped in an object of the `CometChatException` class. | +| loginFailure(event) | Informs you about the failure while logging in the user and provides you with the reason for the failure wrapped in an object of the [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) class. | | logoutSuccess() | Informs you about the user being logged out successfully. | -| logoutFailure(event) | Informs you about the failure while logging out the user. The reason for the failure can be obtained from the object of the `CometChatException` class. | +| logoutFailure(event) | Informs you about the failure while logging out the user. The reason for the failure can be obtained from the object of the [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) class. | To add the `LoginListener`, you need to use the `addLoginListener()` method provided by the SDK which takes a unique identifier for the listener and of the the `LoginListener` class itself. From c6e359a235336d6752ff45be7e146e796b61d046 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 19:34:35 +0530 Subject: [PATCH 118/139] in-private --- sdk/javascript/initialization.mdx | 2 +- sdk/javascript/setup-sdk.mdx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/javascript/initialization.mdx b/sdk/javascript/initialization.mdx index f66032036..4e196d13e 100644 --- a/sdk/javascript/initialization.mdx +++ b/sdk/javascript/initialization.mdx @@ -94,7 +94,7 @@ Replace `APP_ID` with your CometChat App ID and `APP_REGION` with your Region fr | Method | Description | Default | |--------|-------------|---------| -| `setRegion(region)` | Region where your app was created (`us`, `eu`, `in`, `in-private`) | Required | +| `setRegion(region)` | Region where your app was created (`us`, `eu`, `in`) | Required | | `subscribePresenceForAllUsers()` | Subscribe to presence events for all users | — | | `subscribePresenceForRoles(roles)` | Subscribe to presence for specific roles | — | | `subscribePresenceForFriends()` | Subscribe to presence for friends only | — | diff --git a/sdk/javascript/setup-sdk.mdx b/sdk/javascript/setup-sdk.mdx index d0021b41a..50c5b6467 100644 --- a/sdk/javascript/setup-sdk.mdx +++ b/sdk/javascript/setup-sdk.mdx @@ -161,7 +161,7 @@ Replace `APP_ID` and `APP_REGION` with your credentials from the [Dashboard](htt | Method | Description | Default | |--------|-------------|---------| -| `setRegion(region)` | Region where your app was created (`us`, `eu`, `in`, `in-private`) | Required | +| `setRegion(region)` | Region where your app was created (`us`, `eu`, `in`) | Required | | `subscribePresenceForAllUsers()` | Subscribe to presence events for all users | — | | `subscribePresenceForRoles(roles)` | Subscribe to presence for specific roles | — | | `subscribePresenceForFriends()` | Subscribe to presence for friends only | — | From 10f69d15be30a4cfd5f07b48ac35cd8c2247a272 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 19:40:39 +0530 Subject: [PATCH 119/139] adds references to all the links --- sdk/javascript/all-real-time-listeners.mdx | 2 +- sdk/javascript/authentication-overview.mdx | 2 +- sdk/javascript/create-group.mdx | 10 +++++----- sdk/javascript/delete-message.mdx | 4 ++-- sdk/javascript/delivery-read-receipts.mdx | 6 +++--- sdk/javascript/direct-call.mdx | 4 ++-- sdk/javascript/edit-message.mdx | 4 ++-- sdk/javascript/interactive-messages.mdx | 2 +- sdk/javascript/join-group.mdx | 4 ++-- sdk/javascript/leave-group.mdx | 2 +- sdk/javascript/reactions.mdx | 4 ++-- sdk/javascript/receive-message.mdx | 4 ++-- sdk/javascript/retrieve-conversations.mdx | 2 +- sdk/javascript/retrieve-group-members.mdx | 2 +- sdk/javascript/send-message.mdx | 6 +++--- sdk/javascript/transient-messages.mdx | 2 +- sdk/javascript/typing-indicators.mdx | 2 +- sdk/javascript/update-group.mdx | 6 +++--- 18 files changed, 34 insertions(+), 34 deletions(-) diff --git a/sdk/javascript/all-real-time-listeners.mdx b/sdk/javascript/all-real-time-listeners.mdx index 081a9dfd1..eecf34280 100644 --- a/sdk/javascript/all-real-time-listeners.mdx +++ b/sdk/javascript/all-real-time-listeners.mdx @@ -885,7 +885,7 @@ Receive events when the user's authentication state changes — login success/fa | Method | Description | | ------ | ----------- | -| `loginSuccess(user)` | User logged in successfully. Provides the `User` object. | +| `loginSuccess(user)` | User logged in successfully. Provides the [`User`](/sdk/reference/entities#user) object. | | `loginFailure(error)` | Login failed. Provides a [`CometChatException`](/sdk/reference/auxiliary#cometchatexception). | | `logoutSuccess()` | User logged out successfully. | | `logoutFailure(error)` | Logout failed. Provides a [`CometChatException`](/sdk/reference/auxiliary#cometchatexception). | diff --git a/sdk/javascript/authentication-overview.mdx b/sdk/javascript/authentication-overview.mdx index 4de0a68b7..1cd2c4844 100644 --- a/sdk/javascript/authentication-overview.mdx +++ b/sdk/javascript/authentication-overview.mdx @@ -284,7 +284,7 @@ You can listen for login and logout events in real time using `LoginListener`. T | Callback | Description | | --- | --- | -| `loginSuccess(event)` | User logged in successfully. Provides the `User` object. | +| `loginSuccess(event)` | User logged in successfully. Provides the [`User`](/sdk/reference/entities#user) object. | | `loginFailure(event)` | Login failed. Provides a [`CometChatException`](/sdk/reference/auxiliary#cometchatexception). | | `logoutSuccess()` | User logged out successfully. | | `logoutFailure(event)` | Logout failed. Provides a [`CometChatException`](/sdk/reference/auxiliary#cometchatexception). | diff --git a/sdk/javascript/create-group.mdx b/sdk/javascript/create-group.mdx index 4d4ce92ad..9bb9c04e3 100644 --- a/sdk/javascript/create-group.mdx +++ b/sdk/javascript/create-group.mdx @@ -23,7 +23,7 @@ let result = await CometChat.createGroupWithMembers(group, members, []); ## Create a Group -Use `createGroup()` to create a new group. Pass a `Group` object with the group details. +Use `createGroup()` to create a new group. Pass a [`Group`](/sdk/reference/entities#group) object with the group details. Group constructors: - `new Group(GUID, name, groupType, password)` @@ -98,7 +98,7 @@ try { | Parameter | Description | | --------- | ----------- | -| `group` | An instance of `Group` class | +| `group` | An instance of [`Group`](/sdk/reference/entities#group) class | On success, returns a [`Group`](/sdk/reference/entities#group) object with the created group's details. @@ -113,11 +113,11 @@ GUID can be alphanumeric with underscore and hyphen. Spaces, punctuation and oth Use `createGroupWithMembers()` to create a group and add members in one operation. Parameters: -- `group` — The `Group` object -- `members` — Array of `GroupMember` objects to add +- `group` — The [`Group`](/sdk/reference/entities#group) object +- `members` — Array of [`GroupMember`](/sdk/reference/entities#groupmember) objects to add - `bannedMembers` — Array of UIDs to ban (can be empty) -Create a `GroupMember` with: `new CometChat.GroupMember(UID, scope)` +Create a [`GroupMember`](/sdk/reference/entities#groupmember) with: `new CometChat.GroupMember(UID, scope)` diff --git a/sdk/javascript/delete-message.mdx b/sdk/javascript/delete-message.mdx index c0bc598c9..d6c66ad4e 100644 --- a/sdk/javascript/delete-message.mdx +++ b/sdk/javascript/delete-message.mdx @@ -153,9 +153,9 @@ Relevant fields to access on the returned message: ## Missed Message Delete Events -When fetching message history, deleted messages have `deletedAt` and `deletedBy` fields set. Additionally, an `Action` message is created when a message is deleted. +When fetching message history, deleted messages have `deletedAt` and `deletedBy` fields set. Additionally, an [`Action`](/sdk/reference/messages#action) message is created when a message is deleted. -The `Action` object contains: +The [`Action`](/sdk/reference/messages#action) object contains: - `action` — `deleted` - `actionOn` — Deleted message object - `actionBy` — User who deleted the message diff --git a/sdk/javascript/delivery-read-receipts.mdx b/sdk/javascript/delivery-read-receipts.mdx index c1a5ae0f7..67ff45ed9 100644 --- a/sdk/javascript/delivery-read-receipts.mdx +++ b/sdk/javascript/delivery-read-receipts.mdx @@ -485,7 +485,7 @@ You will receive events in the form of [`MessageReceipt`](/sdk/reference/auxilia | `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 `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. +The `markAsDelivered()` and `markAsRead()` methods are fire-and-forget — they do not return a [`MessageReceipt`](/sdk/reference/auxiliary#messagereceipt) object. Use the listener callbacks above to receive delivery and read confirmations. ### Missed Receipts @@ -616,7 +616,7 @@ The following features require **Enhanced Messaging Status** to be enabled for y ## Mark as Unread -Use `markAsUnread()` to mark a message as unread. This is useful for "mark as unread" functionality in conversation lists. Pass a message object (`TextMessage`, `MediaMessage`, or `CustomMessage`). +Use `markAsUnread()` to mark a message as unread. This is useful for "mark as unread" functionality in conversation lists. Pass a message object ([`TextMessage`](/sdk/reference/messages#textmessage), [`MediaMessage`](/sdk/reference/messages#mediamessage), or [`CustomMessage`](/sdk/reference/messages#custommessage)). @@ -647,7 +647,7 @@ CometChat.markAsUnread(message).then( | Parameter | Type | Description | |-----------|------|-------------| -| `message` | `BaseMessage` | The message object to mark as unread | +| `message` | [`BaseMessage`](/sdk/reference/messages#basemessage) | The message object to mark as unread | --- diff --git a/sdk/javascript/direct-call.mdx b/sdk/javascript/direct-call.mdx index 13dc4a063..615f4a25a 100644 --- a/sdk/javascript/direct-call.mdx +++ b/sdk/javascript/direct-call.mdx @@ -77,7 +77,7 @@ CometChatCalls.generateToken(sessionId, authToken).then( | Parameter | Description | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------ | -| `sessionId` | The unique random session ID. In case you are using the ringing flow, the session ID is available in the `Call` object. | +| `sessionId` | The unique random session ID. In case you are using the ringing flow, the session ID is available in the [`Call`](/sdk/reference/messages#call) object. | | `authToken` | The user auth token is the logged-in user auth token which you can get by calling `CometChat.getLoggedinUser().getAuthToken()` | The `Promise` resolves with an object containing a `token` property (string) that you pass to `startSession()`. @@ -717,7 +717,7 @@ CometChatCalls.endSession(); ### Get Active Call -Returns the current active `Call` object, or `undefined` if no call is in progress. +Returns the current active [`Call`](/sdk/reference/messages#call) object, or `undefined` if no call is in progress. ```javascript const activeCall = CometChat.getActiveCall(); diff --git a/sdk/javascript/edit-message.mdx b/sdk/javascript/edit-message.mdx index 6f704b825..347781682 100644 --- a/sdk/javascript/edit-message.mdx +++ b/sdk/javascript/edit-message.mdx @@ -217,9 +217,9 @@ Relevant fields to access on the returned message: ## Missed Message Edit Events -When fetching message history, edited messages have `editedAt` and `editedBy` fields set. Additionally, an `Action` message is created when a message is edited. +When fetching message history, edited messages have `editedAt` and `editedBy` fields set. Additionally, an [`Action`](/sdk/reference/messages#action) message is created when a message is edited. -The `Action` object contains: +The [`Action`](/sdk/reference/messages#action) object contains: - `action` — `edited` - `actionOn` — Updated message object - `actionBy` — User who edited the message diff --git a/sdk/javascript/interactive-messages.mdx b/sdk/javascript/interactive-messages.mdx index b7890c99b..46d53de3f 100644 --- a/sdk/javascript/interactive-messages.mdx +++ b/sdk/javascript/interactive-messages.mdx @@ -8,7 +8,7 @@ description: "Send and receive interactive messages with embedded forms, buttons | Component | Description | | --- | --- | -| `InteractiveMessage` | Message containing interactive UI elements (forms, buttons, etc.) | +| [`InteractiveMessage`](/sdk/reference/messages#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 | diff --git a/sdk/javascript/join-group.mdx b/sdk/javascript/join-group.mdx index 1f8913200..daf422ab1 100644 --- a/sdk/javascript/join-group.mdx +++ b/sdk/javascript/join-group.mdx @@ -71,7 +71,7 @@ group => { | `groupType` | `CometChat.GROUP_TYPE.PUBLIC`, `PASSWORD`, or `PRIVATE` | | `password` | Required for password-protected groups | -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. +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`](/sdk/reference/entities#group) object to verify membership. The method returns a [`Group`](/sdk/reference/entities#group) object with `hasJoined` set to `true`. @@ -120,7 +120,7 @@ CometChat.removeGroupListener("UNIQUE_LISTENER_ID"); ## Missed Group Member Joined Events -When fetching message history, join events appear as `Action` messages with: +When fetching message history, join events appear as [`Action`](/sdk/reference/messages#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 7333c82b5..3f9ed8da5 100644 --- a/sdk/javascript/leave-group.mdx +++ b/sdk/javascript/leave-group.mdx @@ -110,7 +110,7 @@ CometChat.removeGroupListener("UNIQUE_LISTENER_ID"); ## Missed Group Member Left Events -When fetching message history, leave events appear as `Action` messages with: +When fetching message history, leave events appear as [`Action`](/sdk/reference/messages#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/reactions.mdx b/sdk/javascript/reactions.mdx index 89009e5a4..246ad2e4a 100644 --- a/sdk/javascript/reactions.mdx +++ b/sdk/javascript/reactions.mdx @@ -342,7 +342,7 @@ The `getReactions()` method returns an array of [`ReactionCount`](/sdk/reference ## 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. @@ -373,7 +373,7 @@ The `getReactedByMe()` method on a [`ReactionCount`](/sdk/reference/auxiliary#re 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. diff --git a/sdk/javascript/receive-message.mdx b/sdk/javascript/receive-message.mdx index 3cd25395e..b2d307535 100644 --- a/sdk/javascript/receive-message.mdx +++ b/sdk/javascript/receive-message.mdx @@ -437,7 +437,7 @@ CometChat.getUnreadMessageCountForAllGroups(true); ## Get Message Details -Use `getMessageDetails()` to fetch a specific message by its ID. Returns the full message object (`TextMessage`, `MediaMessage`, `CustomMessage`, or `InteractiveMessage`). +Use `getMessageDetails()` to fetch a specific message by its ID. Returns the full message object ([`TextMessage`](/sdk/reference/messages#textmessage), [`MediaMessage`](/sdk/reference/messages#mediamessage), [`CustomMessage`](/sdk/reference/messages#custommessage), or [`InteractiveMessage`](/sdk/reference/messages#interactivemessage)). @@ -474,7 +474,7 @@ CometChat.getMessageDetails(messageId).then( |-----------|------|-------------| | `messageId` | `string` | The ID of the message to fetch | -Returns a [`BaseMessage`](/sdk/reference/messages#basemessage) object (which may be a `TextMessage`, `MediaMessage`, `CustomMessage`, or `InteractiveMessage`). +Returns a [`BaseMessage`](/sdk/reference/messages#basemessage) object (which may be a [`TextMessage`](/sdk/reference/messages#textmessage), [`MediaMessage`](/sdk/reference/messages#mediamessage), [`CustomMessage`](/sdk/reference/messages#custommessage), or [`InteractiveMessage`](/sdk/reference/messages#interactivemessage)). --- diff --git a/sdk/javascript/retrieve-conversations.mdx b/sdk/javascript/retrieve-conversations.mdx index 4a17d1ee7..fb6d04926 100644 --- a/sdk/javascript/retrieve-conversations.mdx +++ b/sdk/javascript/retrieve-conversations.mdx @@ -96,7 +96,7 @@ Relevant fields to access on returned conversations: ### 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`. +This method can be used to fetch the user/group tags in the [`Conversation`](/sdk/reference/entities#conversation) Object. By default the value is `false`. diff --git a/sdk/javascript/retrieve-group-members.mdx b/sdk/javascript/retrieve-group-members.mdx index db20762c9..ba6fd897f 100644 --- a/sdk/javascript/retrieve-group-members.mdx +++ b/sdk/javascript/retrieve-group-members.mdx @@ -176,7 +176,7 @@ Relevant fields to access on returned members: 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 you have the object of the `GroupMembersRequest` class, you need to call the `fetchNext()` method. Calling this method will return a list of [`GroupMember`](/sdk/reference/entities#groupmember) objects containing n number of members where n is the limit set in the builder class. diff --git a/sdk/javascript/send-message.mdx b/sdk/javascript/send-message.mdx index 2d5cffe86..bdb742e3e 100644 --- a/sdk/javascript/send-message.mdx +++ b/sdk/javascript/send-message.mdx @@ -258,7 +258,7 @@ CometChat.sendMessage(textMessage).then( -The `TextMessage` class constructor takes the following parameters: +The [`TextMessage`](/sdk/reference/messages#textmessage) class constructor takes the following parameters: | Parameter | Description | | | ---------------- | -------------------------------------------------------------------------------------------- | -------- | @@ -273,7 +273,7 @@ On success, `sendMessage()` method returns a [`TextMessage`](/sdk/reference/mess *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. +To send a media message to any user or group, you need to use the `sendMediaMessage()` method and pass a [`MediaMessage`](/sdk/reference/messages#mediamessage) object to it. ### Add Metadata @@ -728,7 +728,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 | | | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | diff --git a/sdk/javascript/transient-messages.mdx b/sdk/javascript/transient-messages.mdx index f6ed8783f..f4de3a5dc 100644 --- a/sdk/javascript/transient-messages.mdx +++ b/sdk/javascript/transient-messages.mdx @@ -23,7 +23,7 @@ Transient messages are messages that are sent in real-time only and are not save ## 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. +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`](/sdk/reference/auxiliary#transientmessage) class. diff --git a/sdk/javascript/typing-indicators.mdx b/sdk/javascript/typing-indicators.mdx index 10ad79786..60ce7c0f4 100644 --- a/sdk/javascript/typing-indicators.mdx +++ b/sdk/javascript/typing-indicators.mdx @@ -132,7 +132,7 @@ CometChat.endTyping(typingNotification); `endTyping()` returns `void` — the typing indicator is sent as a fire-and-forget operation. -Use `setMetadata()` on `TypingIndicator` to pass additional custom data. Retrieve it with `getMetadata()` on the receiver side. +Use `setMetadata()` on [`TypingIndicator`](/sdk/reference/auxiliary#typingindicator) to pass additional custom data. Retrieve it with `getMetadata()` on the receiver side. ## Real-time Typing Indicators diff --git a/sdk/javascript/update-group.mdx b/sdk/javascript/update-group.mdx index d29abcc9d..d7082f04a 100644 --- a/sdk/javascript/update-group.mdx +++ b/sdk/javascript/update-group.mdx @@ -16,7 +16,7 @@ const updated = await CometChat.updateGroup(group); ## Update Group -Use `updateGroup()` to modify group details. Pass a `Group` object with the updated values. +Use `updateGroup()` to modify group details. Pass a [`Group`](/sdk/reference/entities#group) object with the updated values. @@ -60,7 +60,7 @@ group => { | Parameter | Description | | --------- | ----------- | -| `group` | An instance of `Group` class with updated values | +| `group` | An instance of [`Group`](/sdk/reference/entities#group) class with updated values | On success, returns a [`Group`](/sdk/reference/entities#group) object with the updated details. @@ -70,7 +70,7 @@ The method returns a [`Group`](/sdk/reference/entities#group) object. There is no real-time event listener available to receive updated group details when the `updateGroup()` method is called. To get the latest group information, you need to fetch the group details again using the appropriate method. -For more information on the `Group` class, please check [here](/sdk/javascript/create-group#create-a-group). +For more information on the [`Group`](/sdk/reference/entities#group) class, please check [here](/sdk/javascript/create-group#create-a-group). --- From 5552457fb11206a6844670aca68b56c48b26a585 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 19:54:18 +0530 Subject: [PATCH 120/139] Update create-group.mdx --- sdk/javascript/create-group.mdx | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/sdk/javascript/create-group.mdx b/sdk/javascript/create-group.mdx index 9bb9c04e3..f6cadc21d 100644 --- a/sdk/javascript/create-group.mdx +++ b/sdk/javascript/create-group.mdx @@ -4,7 +4,6 @@ sidebarTitle: "Create 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 */} ```javascript @@ -21,18 +20,17 @@ let result = await CometChat.createGroupWithMembers(group, members, []); **Member scopes:** `ADMIN` | `MODERATOR` | `PARTICIPANT` +Create groups for multi-user conversations. You can create a group on its own with `createGroup()`, or create one and add members in a single call with `createGroupWithMembers()`. See the [Group Class](#group-class) reference at the bottom for all available fields. + ## Create a Group Use `createGroup()` to create a new group. Pass a [`Group`](/sdk/reference/entities#group) object with the group details. -Group constructors: -- `new Group(GUID, name, groupType, password)` -- `new Group(GUID, name, groupType, password, icon, description)` - -Group types: -- `CometChat.GROUP_TYPE.PUBLIC` -- `CometChat.GROUP_TYPE.PASSWORD` -- `CometChat.GROUP_TYPE.PRIVATE` +| Group Type | Constant | Description | +| --- | --- | --- | +| Public | `CometChat.GROUP_TYPE.PUBLIC` | Any user can join | +| Password | `CometChat.GROUP_TYPE.PASSWORD` | Users must provide the correct password | +| Private | `CometChat.GROUP_TYPE.PRIVATE` | Users must be added by an admin/moderator | @@ -145,7 +143,7 @@ CometChat.createGroupWithMembers(group, members, banMembers).then( -```js +```javascript let GUID = "cometchat-guid-11"; let UID = "cometchat-uid-1"; let groupName = "Hello Group!"; @@ -199,6 +197,8 @@ Returns an object with two keys: ## Group Class +The [`Group`](/sdk/reference/entities#group) object has the following fields. Fields marked "Yes" in the Editable column can be modified after creation using `updateGroup()`. + | Field | Editable | Information | | ------------ | --------------------------------------------------------------- | ------------------------------------------------------------------------- | | guid | Needs to be specified at group creation. Cannot be edited later | A unique identifier for a group | From c6ba2a6deecb9002d0080bacbfa535b18cd880f9 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 19:56:40 +0530 Subject: [PATCH 121/139] Update update-group.mdx --- sdk/javascript/update-group.mdx | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/sdk/javascript/update-group.mdx b/sdk/javascript/update-group.mdx index d7082f04a..e0e1996c9 100644 --- a/sdk/javascript/update-group.mdx +++ b/sdk/javascript/update-group.mdx @@ -4,7 +4,6 @@ sidebarTitle: "Update Group" description: "Update group details such as name, type, icon, and description using the CometChat JavaScript SDK." --- -{/* TL;DR for Agents and Quick Reference */} ```javascript @@ -14,6 +13,8 @@ const updated = await CometChat.updateGroup(group); ``` +Update a group's name, icon, description, or metadata. The GUID and group type cannot be changed after creation. See the [Group Class](/sdk/javascript/create-group#group-class) reference for all editable fields. + ## Update Group Use `updateGroup()` to modify group details. Pass a [`Group`](/sdk/reference/entities#group) object with the updated values. @@ -64,14 +65,10 @@ 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. - -There is no real-time event listener available to receive updated group details when the `updateGroup()` method is called. To get the latest group information, you need to fetch the group details again using the appropriate method. +There is no real-time event listener for group updates. To get the latest group information after calling `updateGroup()`, fetch the group details again using `getGroup()`. -For more information on the [`Group`](/sdk/reference/entities#group) class, please check [here](/sdk/javascript/create-group#create-a-group). - --- ## Next Steps From f33f7da4640068e7ae640ce7d265bcde7d1be957 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 19:58:40 +0530 Subject: [PATCH 122/139] Update join-group.mdx --- sdk/javascript/join-group.mdx | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/sdk/javascript/join-group.mdx b/sdk/javascript/join-group.mdx index daf422ab1..511a6fcee 100644 --- a/sdk/javascript/join-group.mdx +++ b/sdk/javascript/join-group.mdx @@ -4,7 +4,6 @@ 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." --- -{/* TL;DR for Agents and Quick Reference */} ```javascript @@ -21,7 +20,7 @@ CometChat.addGroupListener("listener", new CometChat.GroupListener({ ``` -Join groups to participate in group conversations and receive real-time events when members join. +Join a group to start sending and receiving messages in it. Public groups can be joined freely, password groups require the correct password, and private groups require an admin to add you (no direct join). ## Join a Group @@ -33,7 +32,7 @@ Use `joinGroup()` to join a group. const GUID: string = "GUID"; const password: string = ""; -const groupType: string = CometChat.GroupType.Public; +const groupType: string = CometChat.GROUP_TYPE.PUBLIC; CometChat.joinGroup(GUID, groupType, password).then( (group: CometChat.Group) => { From 0fb93ba7bf2c7a9c76dc1c4861cfaa52dd328ad1 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 20:02:02 +0530 Subject: [PATCH 123/139] Update leave-group.mdx --- sdk/javascript/leave-group.mdx | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/sdk/javascript/leave-group.mdx b/sdk/javascript/leave-group.mdx index 3f9ed8da5..e2ca87c4b 100644 --- a/sdk/javascript/leave-group.mdx +++ b/sdk/javascript/leave-group.mdx @@ -4,7 +4,6 @@ sidebarTitle: "Leave 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 */} ```javascript @@ -18,7 +17,11 @@ CometChat.addGroupListener("listener", new CometChat.GroupListener({ ``` -Leave a group to stop receiving updates and messages from that conversation. +Leave a group to stop receiving messages and updates from it. Once you leave, you'll need to rejoin to participate again. + + +Group owners cannot leave without first transferring ownership to another member. See [Transfer Group Ownership](/sdk/javascript/transfer-group-ownership). + ## Leave a Group From f89c658c4bd94959ff173a0a0b90c33e1d108dc5 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 20:04:22 +0530 Subject: [PATCH 124/139] Update delete-group.mdx --- sdk/javascript/delete-group.mdx | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/sdk/javascript/delete-group.mdx b/sdk/javascript/delete-group.mdx index c27a4cf31..14fbd6b8d 100644 --- a/sdk/javascript/delete-group.mdx +++ b/sdk/javascript/delete-group.mdx @@ -4,24 +4,25 @@ sidebarTitle: "Delete 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 */} ```javascript -// Delete a group (admin only) +// Delete a group (owner only) await CometChat.deleteGroup("GUID"); ``` -**Requirement:** Logged-in user must be an Admin of the group. +**Requirement:** Logged-in user must be the owner of the group. +Permanently delete a group and all its messages. Only the group owner can perform this operation. + This operation is irreversible. Deleted groups and their messages cannot be recovered. ## Delete a Group -Use `deleteGroup()` to permanently delete a group. Only group admins can perform this operation. +Use `deleteGroup()` with the group's GUID. From 88bde6913d1ad0c2d21a07e74d939d9a528c7627 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 23:23:29 +0530 Subject: [PATCH 125/139] Update retrieve-groups.mdx --- sdk/javascript/retrieve-groups.mdx | 43 +++++++++++++++++++++++++----- 1 file changed, 36 insertions(+), 7 deletions(-) diff --git a/sdk/javascript/retrieve-groups.mdx b/sdk/javascript/retrieve-groups.mdx index dfe30e0de..aa8bba5f0 100644 --- a/sdk/javascript/retrieve-groups.mdx +++ b/sdk/javascript/retrieve-groups.mdx @@ -4,6 +4,7 @@ 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." --- +{/* TL;DR for Agents and Quick Reference */} ```javascript @@ -16,7 +17,7 @@ const groups = await request.fetchNext(); const group = await CometChat.getGroup("GUID"); // Fetch only joined groups -const request = new CometChat.GroupsRequestBuilder() +const joinedRequest = new CometChat.GroupsRequestBuilder() .setLimit(30).joinedOnly(true).build(); // Get online member count @@ -28,11 +29,13 @@ Fetch the list of [`Group`](/sdk/reference/entities#group) objects the logged-in ## Retrieve List of Groups -Use `GroupsRequestBuilder` to fetch groups with filtering, searching, and pagination. +*In other words, as a logged-in user, how do I retrieve the list of groups I've joined and groups that are available?* - -The list only includes public and password-protected groups. Private groups appear only if the user is a member. - +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. + +Fetching using this builder will return [`Group`](/sdk/reference/entities#group) objects + +Use `GroupsRequestBuilder` to fetch groups with filtering, searching, and pagination. ### Set Limit @@ -176,7 +179,31 @@ Relevant fields to access on returned groups: |-------|--------|-------------|-------------| | tags | `getTags()` | `string[]` | Tags associated with the group | -After configuring the builder, call `build()` to get the `GroupsRequest` object, then call `fetchNext()` to retrieve groups. Call `fetchNext()` repeatedly on the same instance to paginate. +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. + +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`](/sdk/reference/entities#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. + + + +```javascript +let limit = 30; +let groupsRequest = new CometChat.GroupsRequestBuilder() + .setLimit(limit) + .withTags(true) + .build(); +``` + + + + + +After configuring the builder, call `build()` to get the `GroupsRequest` object, then call `fetchNext()` to retrieve groups. + + +The list only includes public and password-protected groups. Private groups appear only if the user is a member. + @@ -295,7 +322,9 @@ groupMemberCount => { -Returns an object with GUIDs as keys and online member counts as values (e.g., `{ "cometchat-guid-1": 5 }`). +Returns an object with GUIDs as keys and online member counts as values. + +`getOnlineGroupMemberCount()` resolves with a `{ guid: count }` object where each key is a group GUID and its value is the number of currently online members in that group. --- From dcffe0f7befa6936fc16d4c7b335cd877385478f Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 26 Mar 2026 23:25:29 +0530 Subject: [PATCH 126/139] Update retrieve-group-members.mdx --- sdk/javascript/retrieve-group-members.mdx | 53 ++++------------------- 1 file changed, 8 insertions(+), 45 deletions(-) diff --git a/sdk/javascript/retrieve-group-members.mdx b/sdk/javascript/retrieve-group-members.mdx index ba6fd897f..f591d61f8 100644 --- a/sdk/javascript/retrieve-group-members.mdx +++ b/sdk/javascript/retrieve-group-members.mdx @@ -4,7 +4,6 @@ sidebarTitle: "Retrieve 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 */} ```javascript @@ -14,15 +13,17 @@ const request = new CometChat.GroupMembersRequestBuilder("GUID") const members = await request.fetchNext(); // Filter by scope -const request = new CometChat.GroupMembersRequestBuilder("GUID") +const scopeRequest = new CometChat.GroupMembersRequestBuilder("GUID") .setLimit(30).setScopes(["admin", "moderator"]).build(); // Search members -const request = new CometChat.GroupMembersRequestBuilder("GUID") +const searchRequest = new CometChat.GroupMembersRequestBuilder("GUID") .setLimit(30).setSearchKeyword("john").build(); ``` +Fetch the members of a group with filtering by scope, online status, and search keyword. Results are returned as [`GroupMember`](/sdk/reference/entities#groupmember) objects, which extend [`User`](/sdk/reference/entities#user) with group-specific fields like scope. + ## Retrieve the List of Group Members Use `GroupMembersRequestBuilder` to fetch members of a [Group](/sdk/reference/entities#group). The GUID must be specified in the constructor. @@ -119,31 +120,6 @@ Relevant fields to access on returned members: ### 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: - -* 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. - -If this parameter is not set, will return all the group members regardless of their status. - - - -```javascript -let GUID = "GUID"; -let limit = 30; -let scopes = ["admin", "moderator"]; -let groupMembersRequest = new CometChat.GroupMembersRequestBuilder(GUID) - .setLimit(limit) - .setScopes(scopes) - .build(); -``` - - - - - -### Set Status - Filters members by online status: | Value | Description | @@ -166,34 +142,21 @@ let groupMembersRequest: CometChat.GroupMembersRequest = new CometChat.GroupMemb - - -Relevant fields to access on returned members: - -| Field | Getter | Return Type | Description | -|-------|--------|-------------|-------------| -| status | `getStatus()` | `string` | Online status of the member (`"online"` or `"offline"`) | - -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`](/sdk/reference/entities#groupmember) objects containing n number of members where n is the limit set in the builder class. - - ```javascript let GUID = "GUID"; let limit = 30; let groupMembersRequest = new CometChat.GroupMembersRequestBuilder(GUID) - .setLimit(limit) - .setStatus(CometChat.USER_STATUS.ONLINE) - .build(); + .setLimit(limit) + .setStatus(CometChat.USER_STATUS.ONLINE) + .build(); ``` -Once configured, call `build()` to create the request, then `fetchNext()` to retrieve members. +After configuring the builder, call `build()` to create the request, then `fetchNext()` to retrieve members. Call `fetchNext()` repeatedly on the same instance to paginate. From d69d845c643882b0decd5fd090eae1293459cdb7 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Fri, 27 Mar 2026 09:10:36 +0530 Subject: [PATCH 127/139] Update group-add-members.mdx --- sdk/javascript/group-add-members.mdx | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/sdk/javascript/group-add-members.mdx b/sdk/javascript/group-add-members.mdx index 110f0cc1f..543b0e6ba 100644 --- a/sdk/javascript/group-add-members.mdx +++ b/sdk/javascript/group-add-members.mdx @@ -4,7 +4,6 @@ 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." --- -{/* TL;DR for Agents and Quick Reference */} ```javascript @@ -21,7 +20,7 @@ CometChat.addGroupListener("listener", new CometChat.GroupListener({ ``` -You can add members to a group programmatically and listen for real-time events when members are added. +Add users to a group programmatically. Only admins and moderators can add members. The added users receive a notification and are immediately part of the group. ## Add Members to Group @@ -76,9 +75,7 @@ CometChat.addMembersToGroup(GUID, membersList, []).then( -It will return an Object which will contain the `UID` of the users as keys and the value will either be `"success"` or an error message describing why the operation to add the user to the group failed. - -The method returns a response object where each key is a `UID` and the value is either `"success"` or an error message. +The method returns a response object where each key is a UID and the value is either `"success"` or an error message describing why that user couldn't be added. ## Real-Time Group Member Added Events @@ -146,7 +143,7 @@ CometChat.removeGroupListener("UNIQUE_LISTENER_ID"); ``` -## Member Added to Group event in Message History +## Missed Member Added Events When fetching previous messages, member additions appear as [Action](/sdk/reference/messages#action) messages (a subclass of `BaseMessage`). From d329cab0d0904c38d5a83935ea79ea1e84cb3472 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Fri, 27 Mar 2026 09:12:43 +0530 Subject: [PATCH 128/139] minor fixes --- sdk/javascript/ai-moderation.mdx | 2 ++ sdk/javascript/authentication-overview.mdx | 8 ++--- sdk/javascript/call-logs.mdx | 5 +++- sdk/javascript/calling-setup.mdx | 2 +- sdk/javascript/default-call.mdx | 2 ++ sdk/javascript/direct-call.mdx | 9 ++++++ sdk/javascript/edit-message.mdx | 4 +++ sdk/javascript/error-codes.mdx | 3 ++ sdk/javascript/interactive-messages.mdx | 4 +++ sdk/javascript/login-listener.mdx | 4 +-- ...aging-web-sockets-connections-manually.mdx | 6 ++-- sdk/javascript/mentions.mdx | 2 ++ sdk/javascript/message-filtering.mdx | 8 +++-- sdk/javascript/presenter-mode.mdx | 12 ++++++-- sdk/javascript/reactions.mdx | 30 ++++++++++--------- sdk/javascript/recording.mdx | 2 +- sdk/javascript/retrieve-conversations.mdx | 15 +++++----- sdk/javascript/retrieve-users.mdx | 6 ++-- sdk/javascript/typing-indicators.mdx | 8 +++++ sdk/javascript/upgrading-from-v3.mdx | 2 +- 20 files changed, 92 insertions(+), 42 deletions(-) diff --git a/sdk/javascript/ai-moderation.mdx b/sdk/javascript/ai-moderation.mdx index 412a7d633..385a8f573 100644 --- a/sdk/javascript/ai-moderation.mdx +++ b/sdk/javascript/ai-moderation.mdx @@ -7,6 +7,8 @@ description: "Automatically moderate chat messages using AI to detect and block ```javascript +let textMessage = new CometChat.TextMessage("UID", "Hello", CometChat.RECEIVER_TYPE.USER); + // Send message — check moderation status CometChat.sendMessage(textMessage).then(message => { const status = message.getModerationStatus(); diff --git a/sdk/javascript/authentication-overview.mdx b/sdk/javascript/authentication-overview.mdx index 1cd2c4844..3ea45279a 100644 --- a/sdk/javascript/authentication-overview.mdx +++ b/sdk/javascript/authentication-overview.mdx @@ -104,7 +104,7 @@ CometChat.getLoggedinUser().then( -```js +```javascript const UID = "cometchat-uid-1"; const authKey = "AUTH_KEY"; @@ -187,7 +187,7 @@ CometChat.getLoggedinUser().then( -```js +```javascript const authToken = "AUTH_TOKEN"; CometChat.getLoggedinUser().then( @@ -252,7 +252,7 @@ CometChat.logout().then( -```js +```javascript CometChat.logout().then( () => { console.log("Logout completed successfully"); @@ -316,7 +316,7 @@ CometChat.addLoginListener( -```js +```javascript let listenerID = "UNIQUE_LISTENER_ID"; CometChat.addLoginListener( listenerID, diff --git a/sdk/javascript/call-logs.mdx b/sdk/javascript/call-logs.mdx index cc0ad9c2c..3c5819bfc 100644 --- a/sdk/javascript/call-logs.mdx +++ b/sdk/javascript/call-logs.mdx @@ -7,10 +7,13 @@ description: "Fetch, filter, and retrieve call history including duration, parti ```javascript +let loggedInUser = await CometChat.getLoggedinUser(); +let authToken = loggedInUser.getAuthToken(); + // Fetch call logs let request = new CometChatCalls.CallLogRequestBuilder() .setLimit(30) - .setAuthToken(loggedInUser.getAuthToken()) + .setAuthToken(authToken) .setCallCategory("call") .build(); diff --git a/sdk/javascript/calling-setup.mdx b/sdk/javascript/calling-setup.mdx index febf85a63..462f74d7d 100644 --- a/sdk/javascript/calling-setup.mdx +++ b/sdk/javascript/calling-setup.mdx @@ -82,7 +82,7 @@ CometChatCalls.init(callAppSetting).then( -```js +```javascript let appID = "APP_ID"; let region = "REGION"; diff --git a/sdk/javascript/default-call.mdx b/sdk/javascript/default-call.mdx index 5743c6231..707481bac 100644 --- a/sdk/javascript/default-call.mdx +++ b/sdk/javascript/default-call.mdx @@ -8,6 +8,8 @@ description: "Implement a complete calling workflow with ringing, incoming/outgo ```javascript +let sessionId = "SESSION_ID"; + // Initiate a call const call = new CometChat.Call("UID", CometChat.CALL_TYPE.VIDEO, CometChat.RECEIVER_TYPE.USER); await CometChat.initiateCall(call); diff --git a/sdk/javascript/direct-call.mdx b/sdk/javascript/direct-call.mdx index 615f4a25a..5e640c261 100644 --- a/sdk/javascript/direct-call.mdx +++ b/sdk/javascript/direct-call.mdx @@ -7,6 +7,15 @@ description: "Learn how to generate call tokens, start and manage call sessions, ```javascript +let sessionId = "SESSION_ID"; +let authToken = "AUTH_TOKEN"; +let htmlElement = document.getElementById("call-screen"); +let callListener = { + onCallEnded: () => console.log("Call ended"), + onUserJoined: (user) => console.log("User joined:", user), + onUserLeft: (user) => console.log("User left:", user), +}; + // Generate call token const callToken = await CometChatCalls.generateToken(sessionId, authToken); diff --git a/sdk/javascript/edit-message.mdx b/sdk/javascript/edit-message.mdx index 347781682..e7f8d4443 100644 --- a/sdk/javascript/edit-message.mdx +++ b/sdk/javascript/edit-message.mdx @@ -8,6 +8,10 @@ description: "Edit text and custom messages using the CometChat JavaScript SDK." ```javascript +let receiverID = "UID"; +let receiverType = CometChat.RECEIVER_TYPE.USER; +let messageId = "MESSAGE_ID"; + // Edit a text message const textMessage = new CometChat.TextMessage(receiverID, "Updated text", receiverType); textMessage.setId(messageId); diff --git a/sdk/javascript/error-codes.mdx b/sdk/javascript/error-codes.mdx index d40e3b6f3..a6a68c010 100644 --- a/sdk/javascript/error-codes.mdx +++ b/sdk/javascript/error-codes.mdx @@ -7,6 +7,9 @@ description: "Complete reference for CometChat JavaScript SDK error codes, inclu ```javascript +let uid = "UID"; +let authKey = "AUTH_KEY"; + // All errors are CometChatException objects try { await CometChat.login(uid, authKey); diff --git a/sdk/javascript/interactive-messages.mdx b/sdk/javascript/interactive-messages.mdx index 46d53de3f..d4efe0c47 100644 --- a/sdk/javascript/interactive-messages.mdx +++ b/sdk/javascript/interactive-messages.mdx @@ -13,6 +13,10 @@ description: "Send and receive interactive messages with embedded forms, buttons | `Interaction` | Represents a single user action on an interactive element | ```javascript +let receiverId = "UID"; +let receiverType = CometChat.RECEIVER_TYPE.USER; +let interactiveData = {}; + // Create and send an interactive form const interactiveMessage = new CometChat.InteractiveMessage( receiverId, diff --git a/sdk/javascript/login-listener.mdx b/sdk/javascript/login-listener.mdx index c25a75099..36b1c2ede 100644 --- a/sdk/javascript/login-listener.mdx +++ b/sdk/javascript/login-listener.mdx @@ -57,7 +57,7 @@ To add the `LoginListener`, you need to use the `addLoginListener()` method prov -```js +```javascript let listenerID = "UNIQUE_LISTENER_ID"; CometChat.addLoginListener( listenerID, @@ -168,7 +168,7 @@ In order to stop receiving events related to login and logout you need to use th -```js +```javascript const listenerID = "UNIQUE_LISTENER_ID"; CometChat.removeLoginListener(listenerID); ``` diff --git a/sdk/javascript/managing-web-sockets-connections-manually.mdx b/sdk/javascript/managing-web-sockets-connections-manually.mdx index 066f01b34..c1a9ddff4 100644 --- a/sdk/javascript/managing-web-sockets-connections-manually.mdx +++ b/sdk/javascript/managing-web-sockets-connections-manually.mdx @@ -58,7 +58,7 @@ CometChat.init(appID, appSetting).then( -```js +```javascript let appID = "APP_ID"; let region = "APP_REGION"; let appSetting = new CometChat.AppSettingsBuilder() @@ -84,7 +84,7 @@ Once initialized with manual mode, use `connect()` and `disconnect()` to control ### Connect -Establishes the WebSocket connection. The user must be logged in first (check with `CometChat.getLoggedinUser()`). Once connected, real-time events start flowing. +Establishes the WebSocket connection. The user must be logged in first (check with `CometChat.getLoggedinUser()`). Once connected, real-time events start flowing. Returns `void`. @@ -98,7 +98,7 @@ CometChat.connect(); ### Disconnect -Breaks the WebSocket connection. Real-time events stop until you call `connect()` again. +Breaks the WebSocket connection. Real-time events stop until you call `connect()` again. Returns `void`. diff --git a/sdk/javascript/mentions.mdx b/sdk/javascript/mentions.mdx index e3bd97a2a..888dc0521 100644 --- a/sdk/javascript/mentions.mdx +++ b/sdk/javascript/mentions.mdx @@ -9,6 +9,8 @@ description: "Send messages with user mentions, retrieve mentioned users, and fi ```javascript +let message = {}; // obtained from MessageListener or fetchPrevious/fetchNext + // 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); diff --git a/sdk/javascript/message-filtering.mdx b/sdk/javascript/message-filtering.mdx index d372fd2e8..27115177f 100644 --- a/sdk/javascript/message-filtering.mdx +++ b/sdk/javascript/message-filtering.mdx @@ -8,6 +8,8 @@ description: "Advanced filtering options for fetching messages using MessagesReq ```javascript +let parentId = 100; + // Filter by category and type let mediaRequest = new CometChat.MessagesRequestBuilder() .setUID("UID") @@ -31,8 +33,8 @@ let threadRequest = new CometChat.MessagesRequestBuilder() .build(); // Fetch with pagination -messagesRequest.fetchPrevious().then(messages => { }); -messagesRequest.fetchNext().then(messages => { }); +mediaRequest.fetchPrevious().then(messages => { }); +mediaRequest.fetchNext().then(messages => { }); ``` **Key methods:** `setUID()`, `setGUID()`, `setLimit()`, `setCategories()`, `setTypes()`, `setTags()`, `setUnread()`, `setParentMessageId()`, `setMessageId()`, `setTimestamp()`, `hideReplies()`, `hideDeletedMessages()` @@ -69,7 +71,7 @@ let messagesRequest: CometChat.MessagesRequest = -```js +```javascript let messagesRequest = new CometChat.MessagesRequestBuilder() .setLimit(50) .build(); diff --git a/sdk/javascript/presenter-mode.mdx b/sdk/javascript/presenter-mode.mdx index fbe24fac0..882179b7f 100644 --- a/sdk/javascript/presenter-mode.mdx +++ b/sdk/javascript/presenter-mode.mdx @@ -7,6 +7,14 @@ description: "Learn how to implement Presenter Mode for webinars, keynotes, and ```javascript +let callToken = "CALL_TOKEN"; +let htmlElement = document.getElementById("call-screen"); +let callListener = { + onCallEnded: () => console.log("Call ended"), + onUserJoined: (user) => console.log("User joined:", user), + onUserLeft: (user) => console.log("User left:", user), +}; + // Start a presentation session const settings = new CometChatCalls.PresenterSettingsBuilder() .setIsPresenter(true) @@ -36,7 +44,7 @@ Configure the presentation using `PresentationSettingsBuilder`. Set `setIsPresen -```js +```javascript let presenterSettings = new CometChatCalls.PresenterSettingsBuilder() .setIsPresenter(isPresenter) .enableDefaultLayout(defaultLayout) @@ -67,7 +75,7 @@ Always remove listeners when they're no longer needed (e.g., on component unmoun -```js +```javascript useEffect(() => { CometChatCalls.addCallEventListener('UNIQUE_ID', { onUserJoined: user => { diff --git a/sdk/javascript/reactions.mdx b/sdk/javascript/reactions.mdx index 246ad2e4a..40933f8c9 100644 --- a/sdk/javascript/reactions.mdx +++ b/sdk/javascript/reactions.mdx @@ -7,6 +7,8 @@ description: "Add, remove, and fetch message reactions in real-time using the Co ```javascript +let messageId = "MESSAGE_ID"; + // Add a reaction await CometChat.addReaction(messageId, "😊"); @@ -50,7 +52,7 @@ CometChat.addReaction(messageId, emoji) -```js +```javascript let messageId = "1"; let emoji = "😊"; @@ -84,7 +86,7 @@ CometChat.removeReaction(messageId, emoji) -```js +```javascript let messageId = "1"; let emoji = "😊"; @@ -116,7 +118,7 @@ message.getReactions() -```js +```javascript message.getReactions() ``` @@ -137,7 +139,7 @@ reaction.getReactedByMe(); //Return true is logged-in user reacted on that messa -```js +```javascript let reactions = message.getReactions(); reactions.forEach((reaction) => { reaction.getReactedByMe(); //Return true is logged-in user reacted on that message, otherwise false @@ -188,7 +190,7 @@ Fetch Previous The `fetchPrevious()` method fetches the previous set of reaction -```js +```javascript let limit = 10; let messageId = 1; @@ -234,7 +236,7 @@ reactionRequest.fetchPrevious().then( -```js +```javascript let limit = 10; let messageId = 1; @@ -276,7 +278,7 @@ CometChat.addMessageListener(listenerID, new CometChat.MessageListener({ -```js +```javascript let listenerID = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener(listenerID, new CometChat.MessageListener({ @@ -305,7 +307,7 @@ CometChat.removeMessageListener(listenerID); -```js +```javascript let listenerID = "UNIQUE_LISTENER_ID"; CometChat.removeMessageListener(listenerID); @@ -323,7 +325,7 @@ When you receive a real-time reaction event, you'll want to update the correspon -```js +```javascript message.getReactions() ``` @@ -342,11 +344,11 @@ The `getReactions()` method returns an array of [`ReactionCount`](/sdk/reference ## 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`](/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. +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. -```js +```javascript let reactions = message.getReactions(); reactions.forEach((reaction) => { reaction.getReactedByMe(); //Return true is logged-in user reacted on that message, otherwise false @@ -373,13 +375,13 @@ The `getReactedByMe()` method on a [`ReactionCount`](/sdk/reference/auxiliary#re 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`](/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. +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. 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. -```js +```javascript // The message to which the reaction is related let message = ...; @@ -418,7 +420,7 @@ action -```js +```javascript // The message to which the reaction is related let message = ...; diff --git a/sdk/javascript/recording.mdx b/sdk/javascript/recording.mdx index 4ca7df53e..b3270d794 100644 --- a/sdk/javascript/recording.mdx +++ b/sdk/javascript/recording.mdx @@ -56,7 +56,7 @@ CometChatCalls.startSession(callToken, callSettings, htmlElement); -```js +```javascript // Add listeners onRecordingStarted and onRecordingStopped to the startCall method const defaultLayout = true; const audioOnly = false; diff --git a/sdk/javascript/retrieve-conversations.mdx b/sdk/javascript/retrieve-conversations.mdx index fb6d04926..5e3dd8997 100644 --- a/sdk/javascript/retrieve-conversations.mdx +++ b/sdk/javascript/retrieve-conversations.mdx @@ -20,6 +20,7 @@ const conversation = await CometChat.getConversation("UID", "user"); await CometChat.tagConversation("UID", "user", ["archived"]); // Convert message to conversation +let message = {}; // obtained from MessageListener or fetchPrevious/fetchNext const conv = await CometChat.CometChatHelper.getConversationFromMessage(message); ``` @@ -96,7 +97,7 @@ Relevant fields to access on returned conversations: ### With User and Group Tags -This method can be used to fetch the user/group tags in the [`Conversation`](/sdk/reference/entities#conversation) Object. By default the value is `false`. +This method can be used to fetch the user/group tags in the `Conversation` Object. By default the value is `false`. @@ -198,7 +199,7 @@ This method fetches group conversations that have the specified tags. -```js +```javascript let limit = 30; let userTags = ["tag1"]; let conversationRequest = new CometChat.ConversationsRequestBuilder() @@ -362,7 +363,7 @@ let limit: number = 30, -```js +```javascript let limit = 30; let conversationRequest = new CometChat.ConversationsRequestBuilder() .setLimit(limit) @@ -393,7 +394,7 @@ let limit: number = 30, -```js +```javascript let limit = 30; let conversationRequest = new CometChat.ConversationsRequestBuilder() .setLimit(limit) @@ -437,7 +438,7 @@ let limit: number = 30, -```js +```javascript let limit = 30; let conversationRequest = new CometChat.ConversationsRequestBuilder() .setLimit(limit) @@ -474,7 +475,7 @@ let limit: number = 30, -```js +```javascript let limit = 30; let conversationRequest = new CometChat.ConversationsRequestBuilder() .setLimit(limit) @@ -505,7 +506,7 @@ let limit: number = 30, -```js +```javascript let limit = 30; let conversationRequest = new CometChat.ConversationsRequestBuilder() .setLimit(limit) diff --git a/sdk/javascript/retrieve-users.mdx b/sdk/javascript/retrieve-users.mdx index 12d177598..bccdf7f1c 100644 --- a/sdk/javascript/retrieve-users.mdx +++ b/sdk/javascript/retrieve-users.mdx @@ -161,7 +161,7 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() -```js +```javascript let limit = 30; let searchKeyword = "super"; let searchIn = ["uid", "name"]; @@ -461,7 +461,7 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() -```js +```javascript let limit = 30; let UIDs = ["cometchat-uid-1", "cometchat-uid-2"]; let sortBy = "name"; @@ -493,7 +493,7 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() -```js +```javascript let limit = 30; let sortOrder = "desc"; let usersRequest = new CometChat.UsersRequestBuilder() diff --git a/sdk/javascript/typing-indicators.mdx b/sdk/javascript/typing-indicators.mdx index 60ce7c0f4..168e80244 100644 --- a/sdk/javascript/typing-indicators.mdx +++ b/sdk/javascript/typing-indicators.mdx @@ -182,6 +182,14 @@ new CometChat.MessageListener({ The received object is a [`TypingIndicator`](/sdk/reference/auxiliary#typingindicator). + +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 diff --git a/sdk/javascript/upgrading-from-v3.mdx b/sdk/javascript/upgrading-from-v3.mdx index 346153755..ede97b67b 100644 --- a/sdk/javascript/upgrading-from-v3.mdx +++ b/sdk/javascript/upgrading-from-v3.mdx @@ -39,7 +39,7 @@ Find and replace all import statements across your project: | Chat SDK | `import { CometChat } from '@cometchat-pro/chat'` | `import { CometChat } from '@cometchat/chat-sdk-javascript'` | | Calls SDK | `import { CometChatCalls } from '@cometchat-pro/calls'` | `import { CometChatCalls } from '@cometchat/calls-sdk-javascript'` | -```js +```javascript // v4 Chat SDK import { CometChat } from '@cometchat/chat-sdk-javascript'; From ce15ed3d065ede047abfe840963317ca5cd8a976 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Fri, 27 Mar 2026 09:15:51 +0530 Subject: [PATCH 129/139] Update group-kick-ban-members.mdx --- sdk/javascript/group-kick-ban-members.mdx | 86 ++++------------------- 1 file changed, 15 insertions(+), 71 deletions(-) diff --git a/sdk/javascript/group-kick-ban-members.mdx b/sdk/javascript/group-kick-ban-members.mdx index 4050f3a31..a4099d69f 100644 --- a/sdk/javascript/group-kick-ban-members.mdx +++ b/sdk/javascript/group-kick-ban-members.mdx @@ -4,7 +4,6 @@ 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." --- -{/* TL;DR for Agents and Quick Reference */} ```javascript @@ -23,14 +22,7 @@ const bannedMembers = await request.fetchNext(); ``` -There are certain actions that can be performed on the group members: - -1. Kick a member from the group -2. Ban a member from the group -3. Unban a member from the group -4. Update the scope of the member of the group - -Only Admins or Moderators can perform these actions. +Remove members from a group by kicking or banning them. Kicked users can rejoin; banned users cannot until they're unbanned. Only admins and moderators can perform these actions. ## Kick a Group Member @@ -53,35 +45,17 @@ CometChat.kickGroupMember(GUID, UID).then( - - -The `kickGroupMember()` takes following parameters - -| Parameter | Description | -| --------- | ----------------------------------------------------- | -| `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 `boolean` value (`true`) 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. - - ```javascript -const GUID = "GUID"; -const UID = "UID"; +let GUID = "GUID"; +let UID = "UID"; CometChat.kickGroupMember(GUID, UID).then( -response => { - console.log("Group member kicked successfully", response); -}, error => { - console.log("Group member kicking failed with error", error); -} + (response) => { + console.log("Group member kicked successfully", response); + }, (error) => { + console.log("Group member kicking failed with error", error); + } ); ``` @@ -89,14 +63,16 @@ response => { -The `kickGroupMember()` method takes the following parameters: +The `kickGroupMember()` 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 | -On success, the method resolves with a success message string. +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 `boolean` value (`true`) confirming the operation. ## Ban a Group Member @@ -148,7 +124,7 @@ The banned user will be no longer part of the group and can not perform any acti On success, the method resolves with a `boolean` value (`true`) confirming the operation. -## Unban a Banned Group Member from a Group +## Unban a Group Member Admins or Moderators can unban a previously banned member using `unbanGroupMember()`. @@ -290,39 +266,7 @@ bannedGroupMembersRequest.fetchNext().then( The `fetchNext()` method returns an array of [`GroupMember`](/sdk/reference/entities#groupmember) objects representing the banned members of the group. -## 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. - -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. - - - -```javascript -let GUID = "GUID"; -let limit = 30; -let bannedMembersRequest = new CometChat.BannedMembersRequestBuilder(GUID) - .setLimit(limit) - .build(); - -bannedMembersRequest.fetchNext().then( -bannedMembers => { - console.log("Banned Group Member list fetched successfully:", bannedMembers); -}, error => { - console.log("Banned Group Member list fetching failed with exception:", error); -} -); -``` - - - - - -## Real-Time Group Member Kicked/Banned Events +## Real-Time Kick/Ban/Unban Events Implement these `GroupListener` methods to receive real-time notifications: From a671f7350e258627b1d4bbb9887b4abf87f9704c Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Fri, 27 Mar 2026 09:17:52 +0530 Subject: [PATCH 130/139] Update group-change-member-scope.mdx --- sdk/javascript/group-change-member-scope.mdx | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/sdk/javascript/group-change-member-scope.mdx b/sdk/javascript/group-change-member-scope.mdx index a397d6a18..64854db41 100644 --- a/sdk/javascript/group-change-member-scope.mdx +++ b/sdk/javascript/group-change-member-scope.mdx @@ -4,7 +4,6 @@ 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." --- -{/* TL;DR for Agents and Quick Reference */} ```javascript @@ -18,7 +17,7 @@ CometChat.addGroupListener("listener", new CometChat.GroupListener({ ``` -You can change the role of a group member between admin, moderator, and participant. +Promote or demote group members between admin, moderator, and participant roles. Only admins can change member scopes, and only the group owner can change admin scopes. ## Change Scope of a Group Member @@ -31,7 +30,7 @@ let GUID: string = "GUID"; let UID: string = "UID"; -CometChat.updateGroupMemberScope(GUID, UID, CometChat.GroupMemberScope.Admin).then( +CometChat.updateGroupMemberScope(GUID, UID, CometChat.GROUP_MEMBER_SCOPE.ADMIN).then( (response: boolean) => { console.log("Group member scope changed", response); }, (error: CometChat.CometChatException) => { @@ -86,7 +85,7 @@ CometChat.addGroupListener( listenerID, new CometChat.GroupListener({ onGroupMemberScopeChanged: (message: CometChat.Action, changedUser: CometChat.User, newScope: string, oldScope: string, changedGroup: CometChat.Group) => { - console.log("User joined", { message, changedUser, newScope, oldScope, changedGroup }); + console.log("Scope changed", { message, changedUser, newScope, oldScope, changedGroup }); } }) ); @@ -102,7 +101,7 @@ CometChat.addGroupListener( listenerID, new CometChat.GroupListener({ onGroupMemberScopeChanged: (message, changedUser, newScope, oldScope, changedGroup) => { - console.log("User joined", {message, changedUser, newScope, oldScope, changedGroup}); + console.log("Scope changed", {message, changedUser, newScope, oldScope, changedGroup}); } }) ); From ab07c655755a77de94485857d69414c89bc97afc Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Fri, 27 Mar 2026 10:13:49 +0530 Subject: [PATCH 131/139] Update transfer-group-ownership.mdx --- sdk/javascript/transfer-group-ownership.mdx | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/sdk/javascript/transfer-group-ownership.mdx b/sdk/javascript/transfer-group-ownership.mdx index bb50b7896..8fdfbc223 100644 --- a/sdk/javascript/transfer-group-ownership.mdx +++ b/sdk/javascript/transfer-group-ownership.mdx @@ -4,7 +4,6 @@ sidebarTitle: "Transfer Ownership" description: "Transfer ownership of a CometChat group to another member using the JavaScript SDK." --- -{/* TL;DR for Agents and Quick Reference */} ```javascript @@ -15,9 +14,11 @@ 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. -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. +Transfer ownership of a group to another member. Only the current owner can do this, and since owners cannot leave their group, you must transfer ownership first if you want to leave. See [Leave Group](/sdk/javascript/leave-group). -Use `transferGroupOwnership()` to transfer ownership to another member. +## Transfer Ownership + +Use `transferGroupOwnership()` to transfer ownership to another group member. @@ -52,7 +53,12 @@ CometChat.transferGroupOwnership(GUID, UID).then( -On success, the method resolves with a success message string confirming the operation. +| Parameter | Description | +|-----------|-------------| +| `GUID` | The GUID of the group | +| `UID` | The UID of the member to become the new owner | + +On success, the method resolves with a success message string confirming the operation. The new owner gets admin scope and the previous owner becomes a participant. --- From b3033402029409b539e24ae23597ac568d92d76a Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Fri, 27 Mar 2026 10:57:03 +0530 Subject: [PATCH 132/139] Update authentication-overview.mdx --- sdk/javascript/authentication-overview.mdx | 47 ++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/sdk/javascript/authentication-overview.mdx b/sdk/javascript/authentication-overview.mdx index 3ea45279a..639ce41fe 100644 --- a/sdk/javascript/authentication-overview.mdx +++ b/sdk/javascript/authentication-overview.mdx @@ -56,6 +56,53 @@ A user must exist in CometChat before they can log in. - **During development:** Create users from the [CometChat Dashboard](https://app.cometchat.com). Five test users are already available with UIDs `cometchat-uid-1` through `cometchat-uid-5`. - **In production:** Call the [Create User REST API](https://api-explorer.cometchat.com/reference/creates-user) when a user signs up in your app. +You can also create users from the client side using `createUser()` (development only): + + + +```typescript +let authKey: string = "AUTH_KEY"; +let uid: string = "user1"; +let name: string = "Kevin"; + +let user: CometChat.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 +let authKey = "AUTH_KEY"; +let uid = "user1"; +let name = "Kevin"; + +let user = new CometChat.User(uid); +user.setName(name); + +CometChat.createUser(user, authKey).then( + (user) => { + console.log("User created:", user); + }, + (error) => { + console.log("Error:", error); + } +); +``` + + + + +`createUser()` with Auth Key is for development only. In production, create users server-side via the [REST API](https://api-explorer.cometchat.com/reference/creates-user). See [User Management](/sdk/javascript/user-management) for full details. + + ### Check for an Existing Session The SDK persists the logged-in user's session locally. Before calling `login()`, always check whether a session already exists — this avoids unnecessary login calls and keeps your app responsive. From 9cf566690fe95dc99ea2364dd16beef919a3d79e Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Fri, 27 Mar 2026 12:07:36 +0530 Subject: [PATCH 133/139] minor fixes --- sdk/javascript/all-real-time-listeners.mdx | 70 +++++++++++++++------- sdk/javascript/delete-message.mdx | 4 +- sdk/javascript/threaded-messages.mdx | 14 ++++- 3 files changed, 61 insertions(+), 27 deletions(-) diff --git a/sdk/javascript/all-real-time-listeners.mdx b/sdk/javascript/all-real-time-listeners.mdx index eecf34280..1a23c5517 100644 --- a/sdk/javascript/all-real-time-listeners.mdx +++ b/sdk/javascript/all-real-time-listeners.mdx @@ -21,10 +21,16 @@ CometChat.addMessageListener("ID", new CometChat.MessageListener({ })); // Group Listener — member join/leave/kick/ban/scope changes -CometChat.addGroupListener("ID", new CometChat.GroupListener({ ... })); +CometChat.addGroupListener("ID", new CometChat.GroupListener({ + onGroupMemberJoined: (action, joinedUser, joinedGroup) => { }, + onGroupMemberLeft: (action, leftUser, leftGroup) => { } +})); // Call Listener — incoming/outgoing call events -CometChat.addCallListener("ID", new CometChat.CallListener({ ... })); +CometChat.addCallListener("ID", new CometChat.CallListener({ + onIncomingCallReceived: (call) => { }, + onOutgoingCallAccepted: (call) => { } +})); // Always clean up CometChat.removeUserListener("ID"); @@ -88,7 +94,7 @@ CometChat.addUserListener( -```js +```javascript const listenerID = "UNIQUE_LISTENER_ID"; CometChat.addUserListener( listenerID, @@ -119,7 +125,7 @@ CometChat.removeUserListener(listenerID); -```js +```javascript let listenerID = "UNIQUE_LISTENER_ID"; CometChat.removeUserListener(listenerID); ``` @@ -238,7 +244,7 @@ CometChat.addGroupListener( -```js +```javascript CometChat.addGroupListener( "UNIQUE_LISTENER_ID", new CometChat.GroupListener({ @@ -320,7 +326,7 @@ CometChat.removeGroupListener(listenerID); -```js +```javascript let listenerID = "UNIQUE_LISTENER_ID"; CometChat.removeGroupListener(listenerID); ``` @@ -359,7 +365,7 @@ To add the `MessageListener`, you need to use the `addMessageListener()` method -```js +```javascript CometChat.addMessageListener( "UNIQUE_LISTENER_ID", new CometChat.MessageListener({ @@ -384,7 +390,7 @@ CometChat.addMessageListener( onTypingEnded: (typingIndicator) => { console.log("Typing Ended", typingIndicator); }, - onMessagesDeleted: (message) => { + onMessageDeleted: (message) => { console.log("Message Deleted", message); }, onMessageEdited: (message) => { @@ -501,7 +507,7 @@ CometChat.addMessageListener( -```js +```javascript CometChat.addMessageListener( "UNIQUE_LISTENER_ID", new CometChat.MessageListener({ @@ -526,7 +532,7 @@ CometChat.addMessageListener( onTypingEnded: (typingIndicator) => { console.log("Typing Ended", typingIndicator); }, - onMessagesDeleted: (message) => { + onMessageDeleted: (message) => { console.log("Message Deleted", message); }, onMessageEdited: (message) => { @@ -550,6 +556,21 @@ CometChat.addMessageListener( onMessageModerated: (message) => { console.log("Message Moderated", message); }, + onMessagesDeliveredToAll: (messageReceipt) => { + console.log("Message Delivered to All", messageReceipt); + }, + onMessagesReadByAll: (messageReceipt) => { + console.log("Message Read by All", messageReceipt); + }, + onAIAssistantMessageReceived: (message) => { + console.log("AI Assistant message received", message); + }, + onAIToolResultReceived: (message) => { + console.log("AI Tool result received", message); + }, + onAIToolArgumentsReceived: (message) => { + console.log("AI Tool arguments received", message); + }, }) ); ``` @@ -570,7 +591,7 @@ CometChat.removeMessageListener(listenerID); -```js +```javascript let listenerID = "UNIQUE_LISTENER_ID"; CometChat.removeMessageListener(listenerID); ``` @@ -595,7 +616,7 @@ To add the `CallListener`: -```js +```javascript CometChat.addCallListener( "UNIQUE_LISTENER_ID", new CometChat.CallListener({ @@ -647,7 +668,7 @@ CometChat.addCallListener( -```js +```javascript CometChat.addCallListener( "UNIQUE_LISTENER_ID", new CometChat.CallListener({ @@ -663,6 +684,9 @@ CometChat.addCallListener( onIncomingCallCancelled(call) { console.log("Incoming call canceled:", call); }, + onCallEndedMessageReceived(call) { + console.log("Call ended message:", call); + }, }) ); ``` @@ -683,7 +707,7 @@ CometChat.removeCallListener(listenerID); -```js +```javascript let listenerID = "UNIQUE_LISTENER_ID"; CometChat.removeCallListener(listenerID); ``` @@ -705,15 +729,15 @@ The `AIAssistantListener` provides real-time streaming events from AI Agent runs -```js +```javascript const listenerID = "UNIQUE_LISTENER_ID"; CometChat.addAIAssistantListener( listenerID, - { + new CometChat.AIAssistantListener({ onAIAssistantEventReceived: (event) => { console.log("AI Assistant event:", event.getType(), event); }, - } + }) ); ``` @@ -722,11 +746,11 @@ CometChat.addAIAssistantListener( const listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addAIAssistantListener( listenerID, - { + new CometChat.AIAssistantListener({ onAIAssistantEventReceived: (event: CometChat.AIAssistantBaseEvent) => { console.log("AI Assistant event:", event.getType(), event); }, - } + }) ); ``` @@ -736,7 +760,7 @@ To remove the listener: -```js +```javascript CometChat.removeAIAssistantListener("UNIQUE_LISTENER_ID"); ``` @@ -824,7 +848,7 @@ All three calling flows — [Call Session](/sdk/javascript/direct-call), [Standa -```js +```javascript const listenerId = "UNIQUE_LISTENER_ID"; CometChatCalls.addCallEventListener(listenerId, { @@ -914,7 +938,7 @@ CometChat.addLoginListener( ``` -```js +```javascript const listenerID = "UNIQUE_LISTENER_ID"; CometChat.addLoginListener( listenerID, @@ -978,7 +1002,7 @@ CometChat.addConnectionListener( ``` -```js +```javascript const listenerID = "UNIQUE_LISTENER_ID"; CometChat.addConnectionListener( listenerID, diff --git a/sdk/javascript/delete-message.mdx b/sdk/javascript/delete-message.mdx index d6c66ad4e..74c8c90bc 100644 --- a/sdk/javascript/delete-message.mdx +++ b/sdk/javascript/delete-message.mdx @@ -8,6 +8,8 @@ description: "Delete messages using the CometChat JavaScript SDK." ```javascript +let messageId = "MESSAGE_ID"; + // Delete a message await CometChat.deleteMessage(messageId); @@ -39,7 +41,7 @@ Use `deleteMessage()` with the message ID. ```typescript -let messageId: number = 1; +let messageId: string = "1"; CometChat.deleteMessage(messageId).then( (message: CometChat.BaseMessage) => { diff --git a/sdk/javascript/threaded-messages.mdx b/sdk/javascript/threaded-messages.mdx index 8a2bd8561..fd557ea0c 100644 --- a/sdk/javascript/threaded-messages.mdx +++ b/sdk/javascript/threaded-messages.mdx @@ -14,12 +14,12 @@ msg.setParentMessageId(100); await CometChat.sendMessage(msg); // Fetch thread messages -const request = new CometChat.MessagesRequestBuilder() +const threadRequest = new CometChat.MessagesRequestBuilder() .setParentMessageId(100).setLimit(30).build(); -const messages = await request.fetchPrevious(); +const messages = await threadRequest.fetchPrevious(); // Exclude thread replies from main conversation -const request = new CometChat.MessagesRequestBuilder() +const mainRequest = new CometChat.MessagesRequestBuilder() .setUID("UID").setLimit(30).hideReplies(true).build(); ``` @@ -279,6 +279,14 @@ messagesRequest.fetchPrevious().then( The response is an array of [`BaseMessage`](/sdk/reference/messages#basemessage) objects, excluding any messages that are replies within a thread. Only top-level messages in the conversation are returned. + +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 From 42c3eddeaa889d71566acf7bdb3186743f345d44 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Fri, 27 Mar 2026 12:12:35 +0530 Subject: [PATCH 134/139] Update ai-agents.mdx --- sdk/javascript/ai-agents.mdx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/sdk/javascript/ai-agents.mdx b/sdk/javascript/ai-agents.mdx index a9790996c..05c692013 100644 --- a/sdk/javascript/ai-agents.mdx +++ b/sdk/javascript/ai-agents.mdx @@ -14,16 +14,16 @@ description: "Integrate AI Agents, AI Moderation, and AI User Copilot into your ```javascript // Listen for real-time AI Agent events (streaming) -CometChat.addAIAssistantListener("LISTENER_ID", { +CometChat.addAIAssistantListener("LISTENER_ID", new CometChat.AIAssistantListener({ onAIAssistantEventReceived: (event) => console.log("Event:", event) -}); +})); // Listen for persisted agentic messages -CometChat.addMessageListener("LISTENER_ID", { +CometChat.addMessageListener("LISTENER_ID", new CometChat.MessageListener({ 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"); @@ -154,7 +154,7 @@ After the run completes, these messages arrive via `MessageListener`: | `AIToolResultMessage` | The final output of a tool call | | `AIToolArgumentMessage` | The arguments passed to a tool | -Each message type extends `BaseMessage` and has a typed data accessor: +Each message type extends [`BaseMessage`](/sdk/reference/messages#basemessage) and has a typed data accessor: | Message Type | Data Getter | Data Properties | |--------------|-------------|-----------------| From d9d375167c535838b68664bb388b2cf5ffe6bf26 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Mon, 30 Mar 2026 22:02:32 +0530 Subject: [PATCH 135/139] AI Integration Quick Reference --- sdk/android/additional-message-filtering.mdx | 8 +- sdk/android/advanced-overview.mdx | 5 +- sdk/android/ai-agents.mdx | 6 +- sdk/android/ai-chatbots-overview.mdx | 1 + sdk/android/ai-moderation.mdx | 6 +- sdk/android/ai-user-copilot-overview.mdx | 1 + sdk/android/android-overview.mdx | 6 +- sdk/android/authentication-overview.mdx | 7 +- sdk/android/block-users.mdx | 6 +- sdk/android/call-logs.mdx | 6 +- sdk/android/calling-overview.mdx | 5 +- sdk/android/calling-setup.mdx | 6 +- sdk/android/changelog.mdx | 2 + sdk/android/connection-behaviour.mdx | 6 +- sdk/android/connection-status.mdx | 6 +- sdk/android/create-group.mdx | 6 +- sdk/android/default-calling.mdx | 6 +- sdk/android/delete-conversation.mdx | 8 +- sdk/android/delete-group.mdx | 6 +- sdk/android/delete-message.mdx | 8 +- sdk/android/delivery-read-receipts.mdx | 8 +- sdk/android/direct-calling.mdx | 6 +- sdk/android/edit-message.mdx | 8 +- sdk/android/extensions-overview.mdx | 6 +- sdk/android/flag-message.mdx | 6 +- sdk/android/group-add-members.mdx | 6 +- sdk/android/group-change-member-scope.mdx | 6 +- sdk/android/group-kick-member.mdx | 6 +- sdk/android/groups-overview.mdx | 5 +- sdk/android/interactive-messages.mdx | 8 +- sdk/android/join-group.mdx | 6 +- sdk/android/key-concepts.mdx | 6 +- sdk/android/leave-group.mdx | 6 +- sdk/android/login-listeners.mdx | 6 +- sdk/android/mentions.mdx | 8 +- .../message-structure-and-hierarchy.mdx | 6 +- sdk/android/messaging-overview.mdx | 5 +- sdk/android/overview.mdx | 348 +++--------------- sdk/android/presenter-mode.mdx | 6 +- sdk/android/publishing-app-on-playstore.mdx | 6 +- sdk/android/rate-limits.mdx | 6 +- sdk/android/reactions.mdx | 8 +- sdk/android/real-time-listeners.mdx | 6 +- sdk/android/receive-messages.mdx | 2 + sdk/android/recording.mdx | 6 +- sdk/android/resources-overview.mdx | 6 +- sdk/android/retrieve-conversations.mdx | 8 +- sdk/android/retrieve-group-members.mdx | 6 +- sdk/android/retrieve-groups.mdx | 6 +- sdk/android/retrieve-users.mdx | 6 +- sdk/android/send-message.mdx | 8 + sdk/android/session-timeout.mdx | 6 +- sdk/android/setup.mdx | 10 +- sdk/android/standalone-calling.mdx | 6 +- sdk/android/threaded-messages.mdx | 8 +- sdk/android/transfer-group-ownership.mdx | 6 +- sdk/android/transient-messages.mdx | 8 +- sdk/android/typing-indicators.mdx | 8 +- sdk/android/update-group.mdx | 6 +- sdk/android/upgrading-from-v3-guide.mdx | 6 +- sdk/android/user-management.mdx | 6 +- sdk/android/user-presence.mdx | 6 +- sdk/android/users-overview.mdx | 5 +- sdk/android/video-view-customisation.mdx | 6 +- sdk/android/webhooks-overview.mdx | 6 +- 65 files changed, 261 insertions(+), 479 deletions(-) diff --git a/sdk/android/additional-message-filtering.mdx b/sdk/android/additional-message-filtering.mdx index 8b2866e81..dfb2d79a8 100644 --- a/sdk/android/additional-message-filtering.mdx +++ b/sdk/android/additional-message-filtering.mdx @@ -1,10 +1,10 @@ --- title: "Additional Message Filtering" -description: "Filter messages by category, type, timestamp, tags, and other parameters using MessagesRequest in the Android SDK" +sidebarTitle: "Message Filtering" +description: "Filter messages by category, type, timestamp, tags, and other parameters using MessagesRequest in the CometChat Android SDK." --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Build filtered message request @@ -22,7 +22,7 @@ val messagesRequest = MessagesRequestBuilder() messagesRequest.fetchNext(callback) messagesRequest.fetchPrevious(callback) ``` - + 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/android/advanced-overview.mdx b/sdk/android/advanced-overview.mdx index 272b0c4f2..816fc34a8 100644 --- a/sdk/android/advanced-overview.mdx +++ b/sdk/android/advanced-overview.mdx @@ -4,8 +4,7 @@ sidebarTitle: "Overview" description: "Advanced features and customization options for the CometChat Android SDK" --- - -**Quick Reference for AI Agents & Developers** + Explore advanced features: - **Real-Time Listeners** → [real-time-listeners](/sdk/android/real-time-listeners) - Handle all SDK events @@ -13,7 +12,7 @@ Explore advanced features: - **Additional Filtering** → [additional-message-filtering](/sdk/android/additional-message-filtering) - Advanced message queries - **Connection Status** → [connection-status](/sdk/android/connection-status) - Monitor SDK connectivity - **Login Listeners** → [login-listeners](/sdk/android/login-listeners) - Track authentication events - + Advanced features provide deeper control and customization of the CometChat SDK. These guides cover event handling, message filtering, connection management, and other sophisticated capabilities for building robust chat applications. diff --git a/sdk/android/ai-agents.mdx b/sdk/android/ai-agents.mdx index 895ea8ad2..85d44a229 100644 --- a/sdk/android/ai-agents.mdx +++ b/sdk/android/ai-agents.mdx @@ -1,10 +1,10 @@ --- title: "AI Agents" +sidebarTitle: "AI Agents" description: "Integrate AI-powered agents for intelligent, automated interactions in the Android SDK" --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Listen for real-time AI events @@ -21,7 +21,7 @@ CometChat.addMessageListener("LISTENER_ID", object : CometChat.MessageListener() override fun onAIToolArgumentsReceived(message: AIToolArgumentMessage) { } }) ``` - + **Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) | [Dashboard](https://app.cometchat.com) diff --git a/sdk/android/ai-chatbots-overview.mdx b/sdk/android/ai-chatbots-overview.mdx index cb5d74dc1..55776d032 100644 --- a/sdk/android/ai-chatbots-overview.mdx +++ b/sdk/android/ai-chatbots-overview.mdx @@ -1,5 +1,6 @@ --- title: "AI Chatbots" +sidebarTitle: "AI Chatbots" description: "Implement custom AI chatbots for automated conversations in your Android application" url: "/ai-chatbots/overview" --- diff --git a/sdk/android/ai-moderation.mdx b/sdk/android/ai-moderation.mdx index 80c9390f6..5ae822941 100644 --- a/sdk/android/ai-moderation.mdx +++ b/sdk/android/ai-moderation.mdx @@ -1,10 +1,10 @@ --- title: "AI Moderation" +sidebarTitle: "AI Moderation" description: "Automatically review messages for inappropriate content using AI moderation in the Android SDK" --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Send message (automatically moderated) @@ -25,7 +25,7 @@ CometChat.addMessageListener("LISTENER_ID", object : CometChat.MessageListener() } }) ``` - + **Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) | [Dashboard](https://app.cometchat.com) diff --git a/sdk/android/ai-user-copilot-overview.mdx b/sdk/android/ai-user-copilot-overview.mdx index f3f59149b..20da34677 100644 --- a/sdk/android/ai-user-copilot-overview.mdx +++ b/sdk/android/ai-user-copilot-overview.mdx @@ -1,5 +1,6 @@ --- title: "AI User Copilot" +sidebarTitle: "AI User Copilot" description: "Enhance user experience with AI-powered assistance and suggestions in the Android SDK" url: "/fundamentals/ai-user-copilot/overview" --- \ No newline at end of file diff --git a/sdk/android/android-overview.mdx b/sdk/android/android-overview.mdx index a62b764f7..40827427f 100644 --- a/sdk/android/android-overview.mdx +++ b/sdk/android/android-overview.mdx @@ -1,11 +1,11 @@ --- title: "Java UI Kit" +sidebarTitle: "Android Overview" description: "Pre-built UI components for Android chat applications using CometChat" url: "/ui-kit/android/overview" --- - -**Quick Reference for AI Agents & Developers** + The CometChat Android UI Kit provides pre-built UI components for rapid chat app development: - **Pre-built Chat UI** - Ready-to-use chat screens and components @@ -15,7 +15,7 @@ The CometChat Android UI Kit provides pre-built UI components for rapid chat app - **Calling UI** - Voice and video call interfaces **Learn more:** [Android UI Kit Overview](/ui-kit/android/overview) - + The Android UI Kit is a collection of pre-built UI components that accelerate chat application development. It provides ready-to-use screens for conversations, user lists, group management, and calling interfaces. diff --git a/sdk/android/authentication-overview.mdx b/sdk/android/authentication-overview.mdx index bf7ed504a..c6c481654 100644 --- a/sdk/android/authentication-overview.mdx +++ b/sdk/android/authentication-overview.mdx @@ -1,11 +1,10 @@ --- title: "Authentication" -sidebarTitle: "Overview" +sidebarTitle: "Authentication" description: "Log users into CometChat using Auth Key for development or Auth Token for production" --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Check if user is already logged in @@ -32,7 +31,7 @@ CometChat.logout(object : CometChat.CallbackListener() { **Required Credentials:** App ID (from init), Auth Key (dev) or Auth Token (prod) **Get from:** [CometChat Dashboard](https://app.cometchat.com) → Your App → API & Auth Keys - + ### Create User diff --git a/sdk/android/block-users.mdx b/sdk/android/block-users.mdx index 745c03489..a5221149a 100644 --- a/sdk/android/block-users.mdx +++ b/sdk/android/block-users.mdx @@ -1,10 +1,10 @@ --- title: "Block Users" +sidebarTitle: "Block Users" description: "Block and unblock users to control communication in your Android app" --- - -**Quick Reference for AI Agents & Developers** + @@ -70,7 +70,7 @@ request.fetchNext(new CometChat.CallbackListener>() { ``` - + **Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) diff --git a/sdk/android/call-logs.mdx b/sdk/android/call-logs.mdx index b53b30265..8d729b4bc 100644 --- a/sdk/android/call-logs.mdx +++ b/sdk/android/call-logs.mdx @@ -1,10 +1,10 @@ --- title: "Call Logs" +sidebarTitle: "Call Logs" description: "Retrieve and display call history for users and groups using the Android SDK" --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Build call log request @@ -23,7 +23,7 @@ callLogRequest.fetchNext(object : CometChatCalls.CallbackListener> // Get specific call details CometChatCalls.getCallDetails(sessionID, callback) ``` - + **Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [Dashboard](https://app.cometchat.com) diff --git a/sdk/android/calling-overview.mdx b/sdk/android/calling-overview.mdx index 214df245b..23f030dba 100644 --- a/sdk/android/calling-overview.mdx +++ b/sdk/android/calling-overview.mdx @@ -4,8 +4,7 @@ sidebarTitle: "Overview" description: "Implement voice and video calling in your Android application with CometChat" --- - -**Quick Reference for AI Agents & Developers** + Choose your calling implementation: - **Default Calling** → [default-calling](/sdk/android/default-calling) - Complete ringing flow with UI @@ -14,7 +13,7 @@ Choose your calling implementation: - **Calling Setup** → [calling-setup](/sdk/android/calling-setup) - Install and initialize Calls SDK - **Call Logs** → [call-logs](/sdk/android/call-logs) - Retrieve call history - **Recording** → [recording](/sdk/android/recording) - Record call sessions - + ## Overview diff --git a/sdk/android/calling-setup.mdx b/sdk/android/calling-setup.mdx index 20c96c03e..d1f4af080 100644 --- a/sdk/android/calling-setup.mdx +++ b/sdk/android/calling-setup.mdx @@ -1,10 +1,10 @@ --- title: "Setup" +sidebarTitle: "Setup" description: "Install and initialize the CometChat Calls SDK for Android applications" --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Add dependency to build.gradle @@ -24,7 +24,7 @@ CometChatCalls.init(context, callAppSettings, object : CometChatCalls.CallbackLi **Required Credentials:** App ID, Region **Get from:** [CometChat Dashboard](https://app.cometchat.com) → Your App → API & Auth Keys - + diff --git a/sdk/android/changelog.mdx b/sdk/android/changelog.mdx index 2512bedbb..6a6ff2d48 100644 --- a/sdk/android/changelog.mdx +++ b/sdk/android/changelog.mdx @@ -1,4 +1,6 @@ --- title: "Changelog" +sidebarTitle: "Changelog" +description: "Release notes and version history for the CometChat Android SDK" url: "https://github.com/cometchat/chat-sdk-android/releases" --- \ No newline at end of file diff --git a/sdk/android/connection-behaviour.mdx b/sdk/android/connection-behaviour.mdx index 5a5ef2036..5f4839a45 100644 --- a/sdk/android/connection-behaviour.mdx +++ b/sdk/android/connection-behaviour.mdx @@ -1,10 +1,10 @@ --- title: "Connection Behaviour" +sidebarTitle: "Connection Behaviour" description: "Understand and configure WebSocket connection management in the CometChat Android SDK" --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Auto mode (default) - SDK manages connection automatically @@ -27,7 +27,7 @@ CometChat.ping(callback) // Keep alive (call within 30 seconds) **Default:** Auto mode - SDK handles connection automatically **Manual mode:** Requires explicit connect/disconnect calls - + diff --git a/sdk/android/connection-status.mdx b/sdk/android/connection-status.mdx index 88654ff53..ad9a407c1 100644 --- a/sdk/android/connection-status.mdx +++ b/sdk/android/connection-status.mdx @@ -1,10 +1,10 @@ --- title: "Connection Status" +sidebarTitle: "Connection Status" description: "Monitor real-time connection status to CometChat web-socket servers in the Android SDK" --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Add connection listener @@ -23,7 +23,7 @@ val status = CometChat.getConnectionStatus() // Remove listener CometChat.removeConnectionListener("LISTENER_ID") ``` - + CometChat SDK provides you with a mechanism to get real-time status of the connection to CometChat web-socket servers. To achieve this you need to use the `ConnectionListener` class provided by the CometChat SDK diff --git a/sdk/android/create-group.mdx b/sdk/android/create-group.mdx index 7e71ceb3b..a4fd14c76 100644 --- a/sdk/android/create-group.mdx +++ b/sdk/android/create-group.mdx @@ -1,10 +1,10 @@ --- title: "Create A Group" +sidebarTitle: "Create Group" description: "Create public, private, and password-protected groups using the Android SDK" --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Create a public group @@ -21,7 +21,7 @@ val groupMembers = listOf( ) CometChat.createGroupWithMembers(group, groupMembers, emptyList(), callback) ``` - + **Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) diff --git a/sdk/android/default-calling.mdx b/sdk/android/default-calling.mdx index 1c02aaea8..7659d2a14 100644 --- a/sdk/android/default-calling.mdx +++ b/sdk/android/default-calling.mdx @@ -1,10 +1,10 @@ --- title: "Ringing" +sidebarTitle: "Ringing" description: "Implement complete calling workflow with ringing, call acceptance, rejection, and cancellation in the Android SDK" --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Initiate call @@ -23,7 +23,7 @@ CometChat.acceptCall(sessionID, object : CometChat.CallbackListener() { // Reject/Cancel call CometChat.rejectCall(sessionID, CometChatConstants.CALL_STATUS_REJECTED, callback) ``` - + **Available via:** SDK | [UI Kits](/ui-kit/android/overview) diff --git a/sdk/android/delete-conversation.mdx b/sdk/android/delete-conversation.mdx index 605e71466..a8ee43545 100644 --- a/sdk/android/delete-conversation.mdx +++ b/sdk/android/delete-conversation.mdx @@ -1,10 +1,10 @@ --- title: "Delete A Conversation" -description: "Delete conversations from the recent chats list using the Android SDK" +sidebarTitle: "Delete Conversation" +description: "Delete user or group conversations using the CometChat Android SDK." --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Delete user conversation @@ -19,7 +19,7 @@ CometChat.deleteConversation("GUID", CometChatConstants.RECEIVER_TYPE_GROUP, cal ``` **Note:** This deletes the conversation only for the logged-in user. To delete for all users, use the [REST API](https://api-explorer.cometchat.com/reference/deletes-conversation). - + **Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) diff --git a/sdk/android/delete-group.mdx b/sdk/android/delete-group.mdx index e57bacc7d..df2907022 100644 --- a/sdk/android/delete-group.mdx +++ b/sdk/android/delete-group.mdx @@ -1,10 +1,10 @@ --- title: "Delete A Group" +sidebarTitle: "Delete Group" description: "Permanently delete groups as an admin using the Android SDK" --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Delete a group (admin only) @@ -15,7 +15,7 @@ CometChat.deleteGroup("GUID", object : CometChat.CallbackListener() { ``` **Note:** Only group admins can delete groups. This action is permanent and cannot be undone. - + **Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) diff --git a/sdk/android/delete-message.mdx b/sdk/android/delete-message.mdx index f9f2c83b8..75f8d61d8 100644 --- a/sdk/android/delete-message.mdx +++ b/sdk/android/delete-message.mdx @@ -1,10 +1,10 @@ --- title: "Delete A Message" -description: "Delete messages from conversations using the Android SDK with real-time event handling" +sidebarTitle: "Delete Message" +description: "Delete messages using the CometChat Android SDK." --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Delete a message by ID @@ -22,7 +22,7 @@ CometChat.addMessageListener("LISTENER_ID", object : CometChat.MessageListener() override fun onMessageDeleted(message: BaseMessage?) { } }) ``` - + **Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) diff --git a/sdk/android/delivery-read-receipts.mdx b/sdk/android/delivery-read-receipts.mdx index cf55b7c1b..3cc2e692c 100644 --- a/sdk/android/delivery-read-receipts.mdx +++ b/sdk/android/delivery-read-receipts.mdx @@ -1,10 +1,10 @@ --- title: "Delivery & Read Receipts" -description: "Track message delivery and read status using the Android SDK" +sidebarTitle: "Delivery & Read Receipts" +description: "Mark messages as delivered, read, or unread and receive real-time receipt events using the CometChat Android SDK." --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Mark messages as delivered @@ -21,7 +21,7 @@ CometChat.addMessageListener("LISTENER_ID", object : MessageListener() { override fun onMessagesRead(receipt: MessageReceipt) { } }) ``` - + **Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) diff --git a/sdk/android/direct-calling.mdx b/sdk/android/direct-calling.mdx index 696493e23..10d138d70 100644 --- a/sdk/android/direct-calling.mdx +++ b/sdk/android/direct-calling.mdx @@ -1,10 +1,10 @@ --- title: "Call Session" +sidebarTitle: "Call Session" description: "Start and manage call sessions with video and audio controls in the Android SDK" --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Generate token @@ -25,7 +25,7 @@ CometChatCalls.startSession(token, callSettings, callback) // End session CometChatCalls.endSession() ``` - + **Available via:** SDK | [UI Kits](/ui-kit/android/overview) diff --git a/sdk/android/edit-message.mdx b/sdk/android/edit-message.mdx index 079443db8..9e9db0b65 100644 --- a/sdk/android/edit-message.mdx +++ b/sdk/android/edit-message.mdx @@ -1,10 +1,10 @@ --- title: "Edit A Message" -description: "Edit text and custom messages sent to users and groups using the Android SDK" +sidebarTitle: "Edit Message" +description: "Edit text and custom messages using the CometChat Android SDK." --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Edit a text message @@ -25,7 +25,7 @@ CometChat.addMessageListener("LISTENER_ID", object : CometChat.MessageListener() override fun onMessageEdited(message: BaseMessage) { } }) ``` - + **Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) diff --git a/sdk/android/extensions-overview.mdx b/sdk/android/extensions-overview.mdx index 23b1f6552..b9b79ce04 100644 --- a/sdk/android/extensions-overview.mdx +++ b/sdk/android/extensions-overview.mdx @@ -1,11 +1,11 @@ --- title: "Extensions" +sidebarTitle: "Extensions" description: "Enhance your Android app with CometChat extensions for moderation, translation, and more" url: "/fundamentals/extensions-overview" --- - -**Quick Reference for AI Agents & Developers** + CometChat Extensions add powerful features to your chat application: - **Content Moderation** - Filter inappropriate content automatically @@ -17,7 +17,7 @@ CometChat Extensions add powerful features to your chat application: - **Link Preview** - Display rich previews for URLs **Learn more:** [Extensions Overview](/fundamentals/extensions-overview) - + Extensions are server-side features that enhance your CometChat implementation without requiring additional client-side code. They are configured through the [CometChat Dashboard](https://app.cometchat.com) and work automatically once enabled. diff --git a/sdk/android/flag-message.mdx b/sdk/android/flag-message.mdx index 992be0b12..9a123624c 100644 --- a/sdk/android/flag-message.mdx +++ b/sdk/android/flag-message.mdx @@ -1,10 +1,10 @@ --- title: "Flag Message" +sidebarTitle: "Flag Message" description: "Report inappropriate messages to moderators using the Android SDK flagging system" --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Get available flag reasons @@ -25,7 +25,7 @@ CometChat.flagMessage(messageId, flagDetail, object : CometChat.CallbackListener override fun onError(e: CometChatException?) { } }) ``` - + ## Overview diff --git a/sdk/android/group-add-members.mdx b/sdk/android/group-add-members.mdx index a3d8f717b..36c75b5dc 100644 --- a/sdk/android/group-add-members.mdx +++ b/sdk/android/group-add-members.mdx @@ -1,10 +1,10 @@ --- title: "Add Members To A Group" +sidebarTitle: "Add Members" description: "Add members to groups with specific roles using the Android SDK" --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Add members to a group @@ -21,7 +21,7 @@ CometChat.addMembersToGroup("GUID", members, null, ``` **Note:** Only admins and moderators can add members. The result HashMap contains UID as key and "success" or error message as value. - + **Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) diff --git a/sdk/android/group-change-member-scope.mdx b/sdk/android/group-change-member-scope.mdx index c3d1a7a17..efcd38245 100644 --- a/sdk/android/group-change-member-scope.mdx +++ b/sdk/android/group-change-member-scope.mdx @@ -1,10 +1,10 @@ --- title: "Change Member Scope" +sidebarTitle: "Change Scope" description: "Update group member roles and permissions using the Android SDK" --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Change member scope (admin only) @@ -24,7 +24,7 @@ CometChat.updateGroupMemberScope( - `SCOPE_PARTICIPANT` - Regular member (default) **Note:** Only group admins can change member scopes. - + **Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) diff --git a/sdk/android/group-kick-member.mdx b/sdk/android/group-kick-member.mdx index d8ce9d656..9e2f1290a 100644 --- a/sdk/android/group-kick-member.mdx +++ b/sdk/android/group-kick-member.mdx @@ -1,10 +1,10 @@ --- title: "Ban/Kick Member From A Group" +sidebarTitle: "Kick Member" description: "Kick, ban, and unban group members using the Android SDK" --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Kick a member (can rejoin) @@ -21,7 +21,7 @@ CometChat.unbanGroupMember("UID", "GUID", callback) ``` **Note:** Only admins and moderators can kick, ban, or unban members. - + **Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) diff --git a/sdk/android/groups-overview.mdx b/sdk/android/groups-overview.mdx index e2abf72e2..bb693358c 100644 --- a/sdk/android/groups-overview.mdx +++ b/sdk/android/groups-overview.mdx @@ -4,15 +4,14 @@ sidebarTitle: "Overview" description: "Manage group creation, membership, and permissions in the Android SDK" --- - -**Quick Reference for AI Agents & Developers** + Choose your path: - **Create Groups** → [create-group](/sdk/android/create-group) - Public, private, password-protected groups - **Join Groups** → [join-group](/sdk/android/join-group) - Participate in group conversations - **Retrieve Groups** → [retrieve-groups](/sdk/android/retrieve-groups) - Fetch groups list - **Manage Members** → [group-add-members](/sdk/android/group-add-members) - Add, remove, update members - + Groups help your users converse together in a single space. You can have three types of groups: private, public, and password protected. diff --git a/sdk/android/interactive-messages.mdx b/sdk/android/interactive-messages.mdx index 90efb6ec1..24767f30b 100644 --- a/sdk/android/interactive-messages.mdx +++ b/sdk/android/interactive-messages.mdx @@ -1,10 +1,10 @@ --- title: "Interactive Messages" -description: "Send messages with embedded interactive content like forms and buttons for enhanced user engagement" +sidebarTitle: "Interactive Messages" +description: "Send and receive interactive messages with embedded forms, buttons, and other UI elements using the CometChat Android SDK." --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Create interactive message with form @@ -28,7 +28,7 @@ CometChat.sendInteractiveMessage(interactiveMessage, object : CallbackListener + **Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) diff --git a/sdk/android/join-group.mdx b/sdk/android/join-group.mdx index c88c6ce0d..7b739f24c 100644 --- a/sdk/android/join-group.mdx +++ b/sdk/android/join-group.mdx @@ -1,10 +1,10 @@ --- title: "Join A Group" +sidebarTitle: "Join Group" description: "Join public, private, and password-protected groups using the Android SDK" --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Join a public group @@ -17,7 +17,7 @@ CometChat.joinGroup("GUID", CometChatConstants.GROUP_TYPE_PUBLIC, "", // Join a password-protected group CometChat.joinGroup("GUID", CometChatConstants.GROUP_TYPE_PASSWORD, "password123", callback) ``` - + **Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) diff --git a/sdk/android/key-concepts.mdx b/sdk/android/key-concepts.mdx index 6d7f2c34d..04c575f4e 100644 --- a/sdk/android/key-concepts.mdx +++ b/sdk/android/key-concepts.mdx @@ -1,10 +1,10 @@ --- title: "Key Concepts" +sidebarTitle: "Key Concepts" description: "Understand core CometChat concepts including users, groups, authentication, and messaging" --- - -**Quick Reference for AI Agents & Developers** + **Core Entities:** - **Users**: Identified by UID (alphanumeric with underscore/hyphen) @@ -25,7 +25,7 @@ description: "Understand core CometChat concepts including users, groups, authen **Message Categories:** message, custom, action, call **Connection Modes:** Auto (WebSocket in foreground only) | Manual (explicit connect/disconnect) - + ### CometChat Dashboard diff --git a/sdk/android/leave-group.mdx b/sdk/android/leave-group.mdx index 401194164..73233cfd3 100644 --- a/sdk/android/leave-group.mdx +++ b/sdk/android/leave-group.mdx @@ -1,10 +1,10 @@ --- title: "Leave A Group" +sidebarTitle: "Leave Group" description: "Leave groups to stop receiving messages and updates using the Android SDK" --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Leave a group @@ -18,7 +18,7 @@ CometChat.addGroupListener("LISTENER_ID", object : GroupListener() { override fun onGroupMemberLeft(action: Action?, leftUser: User?, leftGroup: Group?) { } }) ``` - + **Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) diff --git a/sdk/android/login-listeners.mdx b/sdk/android/login-listeners.mdx index e074b3382..35944e747 100644 --- a/sdk/android/login-listeners.mdx +++ b/sdk/android/login-listeners.mdx @@ -1,10 +1,10 @@ --- title: "Login Listeners" +sidebarTitle: "Login Listeners" description: "Receive real-time updates for login and logout events in the Android SDK" --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Add login listener @@ -18,7 +18,7 @@ CometChat.addLoginListener("LISTENER_ID", object : LoginListener() { // Remove 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/android/mentions.mdx b/sdk/android/mentions.mdx index 68cbf206d..802b32666 100644 --- a/sdk/android/mentions.mdx +++ b/sdk/android/mentions.mdx @@ -1,10 +1,10 @@ --- title: "Mentions" -description: "Mention specific users in messages to enhance engagement and collaboration in group conversations" +sidebarTitle: "Mentions" +description: "Send messages with user mentions, retrieve mentioned users, and filter messages by mention metadata using the CometChat Android SDK." --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Send message with mention to user @@ -20,7 +20,7 @@ val wasMentioned = message.hasMentionedMe() // Get list of mentioned users val mentionedUsers = message.mentionedUsers ``` - + **Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) diff --git a/sdk/android/message-structure-and-hierarchy.mdx b/sdk/android/message-structure-and-hierarchy.mdx index 441e3c2a0..19cc9c56d 100644 --- a/sdk/android/message-structure-and-hierarchy.mdx +++ b/sdk/android/message-structure-and-hierarchy.mdx @@ -1,10 +1,10 @@ --- title: "Message Structure And Hierarchy" +sidebarTitle: "Message Structure" description: "Understand message categories, types, and hierarchy in the CometChat Android SDK" --- - -**Quick Reference for AI Agents & Developers** + **Message Categories:** - **Message**: text, image, video, audio, file @@ -22,7 +22,7 @@ when (message.category) { CometChatConstants.CATEGORY_CALL -> { /* Handle call */ } } ``` - + The below diagram helps you better understand the various message categories and types that a CometChat message can belong to. diff --git a/sdk/android/messaging-overview.mdx b/sdk/android/messaging-overview.mdx index 836438887..8368261bd 100644 --- a/sdk/android/messaging-overview.mdx +++ b/sdk/android/messaging-overview.mdx @@ -4,8 +4,7 @@ sidebarTitle: "Overview" description: "Send, receive, and manage messages with CometChat's Android SDK messaging features" --- - -**Quick Reference for AI Agents & Developers** + Choose your messaging path: - **Send Messages** → [send-message](/sdk/android/send-message) - Text, media, and custom messages @@ -16,7 +15,7 @@ Choose your messaging path: - **Reactions** → [reactions](/sdk/android/reactions) - Add emoji reactions - **Mentions** → [mentions](/sdk/android/mentions) - Tag users in messages - **Interactive Messages** → [interactive-messages](/sdk/android/interactive-messages) - Buttons and forms - + diff --git a/sdk/android/overview.mdx b/sdk/android/overview.mdx index 80ce77425..b9c769133 100644 --- a/sdk/android/overview.mdx +++ b/sdk/android/overview.mdx @@ -1,10 +1,10 @@ --- title: "Overview" +sidebarTitle: "Overview" description: "Get started with the CometChat Android SDK - install, initialize, and add real-time chat to your Android application" --- - -**Quick Setup Reference** + ```kotlin // 1. Add dependency to build.gradle @@ -23,7 +23,7 @@ CometChat.login("UID", "AUTH_KEY", callback) // Dev only **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 - + `CometChat.init()` must be called before any other SDK method. Calling `login()`, `sendMessage()`, or registering listeners before `init()` will fail. @@ -35,299 +35,73 @@ CometChat.login("UID", "AUTH_KEY", callback) // Dev only This guide demonstrates how to add chat to an Android application. Before you begin, we strongly recommend reading the [Key Concepts](/sdk/android/key-concepts) guide. -#### **I want to integrate with my app** +## Getting Started + + + + [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/android/setup). + + + Log in users with Auth Key (development) or Auth Token (production). See [Authentication](/sdk/android/authentication-overview). + + + Send your first message, make a call, or manage users and groups. + + + +## Features -1. [Get your application keys](./overview#get-your-application-keys) -2. [Add the CometChat dependency](./overview#add-the-cometchat-dependency) -3. [Initialize CometChat](./overview#initialise-cometchat) -4. [Register and Login your user](./overview#register-and-login-your-user) -5. [Integrate our UI Kits](./overview#integrate-our-ui-kits) + + + 1:1 and group chat, threads, reactions, typing indicators, read receipts, file sharing, and interactive messages. + + + Ringing flows, direct call sessions, standalone calling, recording, and screen sharing. + + + Create, retrieve, and manage users. Track online/offline presence and block/unblock users. + + + Public, private, and password-protected groups with member management, roles, and ownership transfer. + + -#### **I want to explore a sample app (includes UI)** +## Sample Apps Import the app into Android Studio and follow the steps mentioned in the `README.md` file. -[Java Chat App](https://github.com/cometchat-pro/android-java-chat-app/) - -[Kotlin Chat App](https://github.com/cometchat-pro/android-kotlin-chat-app) - -### Get your Application Keys - -[Sign up for CometChat](https://app.cometchat.com) and then: - -1. Create a new app -2. Head over to the **API Keys** section and note the **Auth Key**, **App ID** & **Region** - - -Minimum Requirements - -* Android API Level 21 -* Android API Level 24 (if you are using the Calls SDK) -* AndroidX Compatibility - - - -### Add the CometChat Dependency - -First, add the repository URL to the **project level** `build.gradle` file in the `repositories` block under the `allprojects` section. - - - -```groovy -allprojects { - repositories { - maven { - url "https://dl.cloudsmith.io/public/cometchat/cometchat/maven/" - } - } -} -``` - - - - - -Then, add CometChat to the **app level** `build.gradle` file in the `dependencies` section. - - - -```groovy -dependencies { - implementation "com.cometchat:chat-sdk-android:4.1.8" -} -``` - - - - - - - -Starting from v2.4+, Voice & Video Calling functionality has been moved to a separate library. If you plan to use the calling feature, add the Calling dependency `implementation 'com.cometchat:calls-sdk-android:4.3.3'` in the dependencies section of the app-level `build.gradle` file. - - - -Finally, add the following lines to the `android` section of the **app level** gradle file. - - - -```groovy -android { - compileOptions { - sourceCompatibility JavaVersion.VERSION_1_8 - targetCompatibility JavaVersion.VERSION_1_8 - } -} -``` - - - - - -### Initialise CometChat - -The `init()` method initializes the settings required for CometChat. This method takes the following parameters: - -1. `appID` - Your CometChat App ID -2. `appSettings` - An object of the `AppSettings` class 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/android/user-presence)**: Represents the subscription type for user presence (real-time online/offline status). -* **autoEstablishSocketConnection(boolean value)**: When set to `true`, the SDK manages the WebSocket connection internally. When set to `false`, you must manage the WebSocket connection manually. The default value is `true`. For more information, see the Managing Web-Socket connections manually section. -* **overrideAdminHost(adminHost: string)**: Takes the admin URL as input and uses it instead of the default admin URL. This is useful for dedicated deployments of CometChat. -* **overrideClientHost(clientHost: string)**: Takes the client URL as input and uses it instead of the default client URL. This is useful for dedicated deployments of CometChat. - - - -```java -String appID = "APP_ID"; // Replace with your App ID -String region = "REGION"; // Replace with your App Region ("eu" or "us") - -AppSettings appSettings = new AppSettings.AppSettingsBuilder() - .subscribePresenceForAllUsers() - .setRegion(region) - .autoEstablishSocketConnection(true) - .build(); - -CometChat.init(this, appID, appSettings, new CometChat.CallbackListener () { - @Override - public void onSuccess(String successMessage) { - Log.d(TAG, "Initialization completed successfully"); - } - - @Override - public void onError(CometChatException e) { - Log.d(TAG, "Initialization failed with exception: " + e.getMessage()); - } -}); -``` - - - - -```kotlin -val appID: String = "APP_ID" // Replace with your App ID -val region: String = "REGION" // Replace with your App Region ("eu" or "us") - -val appSettings = AppSettings.AppSettingsBuilder() - .subscribePresenceForAllUsers() - .setRegion(region) - .autoEstablishSocketConnection(true) - .build() - -CometChat.init( - this, - appID, - appSettings, - object : CometChat.CallbackListener() { - override fun onSuccess(p0: String?) { - Log.d(TAG, "Initialization completed successfully") - } - - override fun onError(p0: CometChatException?) { - Log.d(TAG, "Initialization failed with exception: " + p0?.message) - } - } -) -``` - - - - - -Make sure you replace `APP_ID` with your CometChat **App ID** and `region` with your **App Region** in the above code. - -### Register and Login your User - -Once initialization is successful, you need to create a user. - -To create users on the fly, 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. - - - -```java -String authKey = "AUTH_KEY"; // Replace with your App Auth Key -User user = new User(); -user.setUid("USER_UID"); // Replace with the UID for the user to be created -user.setName("USER_NAME"); // Replace with the name of the user - -CometChat.createUser(user, authKey, new CometChat.CallbackListener () { - @Override - public void onSuccess(User user) { - Log.d("createUser", user.toString()); - } - - @Override - public void onError(CometChatException e) { - Log.e("createUser", e.getMessage()); - } -}); -``` - - - - -```kotlin -val authKey = "AUTH_KEY" // Replace with your App Auth Key -val user = User() -user.uid = "USER_UID" // Replace with the UID for the user to be created -user.name = "USER_NAME" // Replace with the name of the user - -CometChat.createUser(user, authKey, object : CometChat.CallbackListener() { - override fun onSuccess(user: User) { - Log.d("createUser", user.toString()) - } - - override fun onError(e: CometChatException) { - Log.e("createUser", e.message) - } -}) -``` - - - - - -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 need to log the user into CometChat using the `login()` method. - -We recommend calling the CometChat `login()` method once your user logs into your app. The `login()` method only needs to be called 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/android/authentication-overview#login-using-auth-token) instead of an Auth Key to ensure enhanced security. - - - - - -```java -String UID = "user1"; // Replace with the UID of the user to login -String authKey = "AUTH_KEY"; // Replace with your App Auth Key - -if (CometChat.getLoggedInUser() == null) { - CometChat.login(UID, authKey, new CometChat.CallbackListener () { - @Override - public void onSuccess(User user) { - Log.d(TAG, "Login Successful : " + user.toString()); - } - - @Override - public void onError(CometChatException e) { - Log.d(TAG, "Login failed with exception: " + e.getMessage()); - } - }); -} else { - // User already logged in -} -``` - - - - -```kotlin -val UID: String = "user1" // Replace with the UID of the user to login -val authKey: String = "AUTH_KEY" // Replace with your App Auth Key - -if (CometChat.getLoggedInUser() == null) { - CometChat.login( - UID, - authKey, - object : CometChat.CallbackListener() { - override fun onSuccess(p0: User?) { - Log.d(TAG, "Login Successful : " + p0?.toString()) - } - - override fun onError(p0: CometChatException?) { - Log.d(TAG, "Login failed with exception: " + p0?.message) - } - } - ) -} else { - // User already logged in -} -``` - - - - - -Make sure you replace `AUTH_KEY` with your App **Auth Key** in the above code. - -The `login()` method returns the `User` object containing all the information of the logged-in user. - - + + + Java sample app + + + Kotlin sample app + + -UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. +## UI Kits - +Refer to the [Android UI Kit](/ui-kit/android/overview) for pre-built, customizable components. -### Integrate our UI Kits +## Resources -* Refer to the [Android Java UI Kit](/ui-kit/android/overview) section to integrate the Android Java UI Kit into your app. + + + UIDs, GUIDs, auth tokens, and core SDK concepts + + + Message categories, types, and hierarchy + + + Latest SDK version and release notes + + + Migration guide for V3 users + + --- diff --git a/sdk/android/presenter-mode.mdx b/sdk/android/presenter-mode.mdx index 7902745e6..262e2589f 100644 --- a/sdk/android/presenter-mode.mdx +++ b/sdk/android/presenter-mode.mdx @@ -1,10 +1,10 @@ --- title: "Presenter Mode" +sidebarTitle: "Presenter Mode" description: "Create webinar-style calling experiences with presenters and viewers using the Android SDK" --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Join as presenter @@ -22,7 +22,7 @@ CometChatCalls.joinPresentation(callToken, presenterSettings, videoContainer, ob **Use Cases:** Webinars, online classes, keynote speeches, all-hands meetings **Capacity:** Up to 5 presenters + 95 viewers (100 total) - + diff --git a/sdk/android/publishing-app-on-playstore.mdx b/sdk/android/publishing-app-on-playstore.mdx index a105d210f..8df05acb9 100644 --- a/sdk/android/publishing-app-on-playstore.mdx +++ b/sdk/android/publishing-app-on-playstore.mdx @@ -1,10 +1,10 @@ --- title: "Publishing App On PlayStore" +sidebarTitle: "Publishing to Play Store" description: "Guide to preparing and publishing your CometChat Android app on Google Play Store" --- - -**Quick Reference for AI Agents & Developers** + Publishing checklist: 1. **Reduce app size** - Remove unused resources, enable ProGuard/R8 @@ -15,7 +15,7 @@ Publishing checklist: **Key tools:** Android Studio → Build → Generate Signed Bundle/APK **Play Console:** [https://play.google.com/console](https://play.google.com/console) - + diff --git a/sdk/android/rate-limits.mdx b/sdk/android/rate-limits.mdx index da5c9aa0b..6172b69ae 100644 --- a/sdk/android/rate-limits.mdx +++ b/sdk/android/rate-limits.mdx @@ -1,10 +1,10 @@ --- title: "Rate Limits" +sidebarTitle: "Rate Limits" description: "Understand CometChat REST API rate limits and how to handle rate limit responses" --- - -**Quick Reference for AI Agents & Developers** + **Rate Limits:** - **Core Operations:** 10,000 requests/minute (login, create/delete user, create/join group) @@ -15,7 +15,7 @@ description: "Understand CometChat REST API rate limits and how to handle rate l - **Headers:** `Retry-After`, `X-Rate-Limit-Reset`, `X-Rate-Limit`, `X-Rate-Limit-Remaining` **Best Practice:** Monitor `X-Rate-Limit-Remaining` header and implement exponential backoff when approaching limits. - + diff --git a/sdk/android/reactions.mdx b/sdk/android/reactions.mdx index b3172ac36..69fb85902 100644 --- a/sdk/android/reactions.mdx +++ b/sdk/android/reactions.mdx @@ -1,10 +1,10 @@ --- title: "Reactions" -description: "Add, remove, and manage emoji reactions on messages in your Android chat application" +sidebarTitle: "Reactions" +description: "Add, remove, and fetch message reactions in real-time using the CometChat Android SDK. Includes listener events and helper methods for updating UI." --- - -**Quick Reference for AI Agents & Developers** + @@ -70,7 +70,7 @@ CometChat.addMessageListener(listenerID, new MessageReactionListener() { ``` - + **Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) diff --git a/sdk/android/real-time-listeners.mdx b/sdk/android/real-time-listeners.mdx index 4f9d80073..42b5a82fd 100644 --- a/sdk/android/real-time-listeners.mdx +++ b/sdk/android/real-time-listeners.mdx @@ -1,10 +1,10 @@ --- title: "All Real Time Listeners" +sidebarTitle: "Real-Time Listeners" description: "Register and manage real-time event listeners for users, groups, messages, and calls in the Android SDK" --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // User listener @@ -23,7 +23,7 @@ CometChat.addMessageListener("LISTENER_ID", object : CometChat.MessageListener() CometChat.removeUserListener("LISTENER_ID") CometChat.removeMessageListener("LISTENER_ID") ``` - + CometChat provides 4 listeners viz. diff --git a/sdk/android/receive-messages.mdx b/sdk/android/receive-messages.mdx index efa082ef8..78c56cacc 100644 --- a/sdk/android/receive-messages.mdx +++ b/sdk/android/receive-messages.mdx @@ -1,5 +1,7 @@ --- title: "Receive A Message" +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 Android SDK." --- diff --git a/sdk/android/recording.mdx b/sdk/android/recording.mdx index 661a739a4..d8c374832 100644 --- a/sdk/android/recording.mdx +++ b/sdk/android/recording.mdx @@ -1,10 +1,10 @@ --- title: "Recording" +sidebarTitle: "Recording" description: "Record calls and access recordings from the Dashboard using the Android SDK" --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Configure call settings with recording @@ -20,7 +20,7 @@ CallManager.getInstance().startRecording() // Stop recording CallManager.getInstance().stopRecording() ``` - + **Available via:** SDK | [Dashboard](https://app.cometchat.com) diff --git a/sdk/android/resources-overview.mdx b/sdk/android/resources-overview.mdx index f35a268b5..03c061b4c 100644 --- a/sdk/android/resources-overview.mdx +++ b/sdk/android/resources-overview.mdx @@ -1,10 +1,10 @@ --- title: "Resources" +sidebarTitle: "Overview" description: "Additional resources, guides, and references for the CometChat Android SDK" --- - -**Quick Reference for AI Agents & Developers** + Helpful resources: - **Real-Time Listeners** → [real-time-listeners](/sdk/android/real-time-listeners) - Complete event handling guide @@ -12,7 +12,7 @@ Helpful resources: - **Rate Limits** → [rate-limits](/sdk/android/rate-limits) - API rate limiting information - **Webhooks** → [webhooks-overview](/sdk/android/webhooks-overview) - Server-side event notifications - **Connection Behaviour** → [connection-behaviour](/sdk/android/connection-behaviour) - SDK connectivity patterns - + diff --git a/sdk/android/retrieve-conversations.mdx b/sdk/android/retrieve-conversations.mdx index 95808087b..33c3030df 100644 --- a/sdk/android/retrieve-conversations.mdx +++ b/sdk/android/retrieve-conversations.mdx @@ -1,10 +1,10 @@ --- title: "Retrieve Conversations" -description: "Fetch and manage conversation lists for recent chats using the Android SDK" +sidebarTitle: "Retrieve Conversations" +description: "Fetch, filter, tag, and search conversations using the CometChat Android SDK." --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Fetch conversations with filters @@ -21,7 +21,7 @@ conversationsRequest.fetchNext(object : CallbackListener>() { // Get specific conversation CometChat.getConversation("UID_or_GUID", "user", callback) ``` - + **Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) diff --git a/sdk/android/retrieve-group-members.mdx b/sdk/android/retrieve-group-members.mdx index 02d776014..6abdf21cb 100644 --- a/sdk/android/retrieve-group-members.mdx +++ b/sdk/android/retrieve-group-members.mdx @@ -1,10 +1,10 @@ --- title: "Retrieve Group Members" +sidebarTitle: "Retrieve Members" description: "Fetch and filter group members list using the Android SDK" --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Fetch group members with filters @@ -19,7 +19,7 @@ groupMembersRequest.fetchNext(object : CallbackListener>() { override fun onError(e: CometChatException) { } }) ``` - + **Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) diff --git a/sdk/android/retrieve-groups.mdx b/sdk/android/retrieve-groups.mdx index e2ca4adea..96047af62 100644 --- a/sdk/android/retrieve-groups.mdx +++ b/sdk/android/retrieve-groups.mdx @@ -1,10 +1,10 @@ --- title: "Retrieve Groups" +sidebarTitle: "Retrieve Groups" description: "Fetch and filter groups list using the Android SDK" --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Fetch groups with filters @@ -22,7 +22,7 @@ groupsRequest.fetchNext(object : CallbackListener>() { // Get specific group details CometChat.getGroup("GUID", callback) ``` - + **Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) diff --git a/sdk/android/retrieve-users.mdx b/sdk/android/retrieve-users.mdx index 5bf29b847..9be57b9f2 100644 --- a/sdk/android/retrieve-users.mdx +++ b/sdk/android/retrieve-users.mdx @@ -1,10 +1,10 @@ --- title: "Retrieve Users" +sidebarTitle: "Retrieve Users" description: "Fetch user details, retrieve user lists with filters, and get online user counts using the Android SDK" --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Get logged-in user @@ -28,7 +28,7 @@ CometChat.getUser("UID", object : CometChat.CallbackListener() { override fun onError(e: CometChatException) { } }) ``` - + **Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) diff --git a/sdk/android/send-message.mdx b/sdk/android/send-message.mdx index ccb25bcc2..e35a867a2 100644 --- a/sdk/android/send-message.mdx +++ b/sdk/android/send-message.mdx @@ -1,5 +1,7 @@ --- title: "Send A Message" +sidebarTitle: "Send Messages" +description: "Send text, media, and custom messages to users and groups using the CometChat Android SDK." --- @@ -13,6 +15,12 @@ Using CometChat, you can send three types of messages: You can also send metadata along with a text or media message. Think, for example, if you'd want to share the user's location with every message, you can use the metadata field. +| 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 | + ## Text Message How do I send a text message? diff --git a/sdk/android/session-timeout.mdx b/sdk/android/session-timeout.mdx index de1f55ab0..7c39dd808 100644 --- a/sdk/android/session-timeout.mdx +++ b/sdk/android/session-timeout.mdx @@ -1,10 +1,10 @@ --- title: "Session Timeout Flow" +sidebarTitle: "Session Timeout" description: "Configure idle timeout and auto-termination for inactive call sessions in Android" --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Configure idle timeout (default: 180 seconds) @@ -21,7 +21,7 @@ val callSettings = CometChatCalls.CallSettingsBuilder(context, videoContainer) **Available since:** v4.1.0 **Default timeout:** 180 seconds (3 minutes alone) **Warning shown:** 60 seconds before auto-termination - + diff --git a/sdk/android/setup.mdx b/sdk/android/setup.mdx index 4fc231653..a579958d4 100644 --- a/sdk/android/setup.mdx +++ b/sdk/android/setup.mdx @@ -1,10 +1,10 @@ --- title: "Setup" +sidebarTitle: "Setup" description: "Install and initialize the CometChat Android SDK in your application" --- - -**Quick Setup Reference** + ```kotlin // 1. Add dependency to build.gradle @@ -23,13 +23,13 @@ CometChat.login("UID", "AUTH_KEY", callback) // Dev only **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 - + Skip the create new app step. Your existing v2 app can be migrated to v3. Follow the steps mentioned in the **Add the CometChat dependency** section below to upgrade to the latest version of v3. -### Get your Application Keys +## Get your Application Keys [Sign up for CometChat](https://app.cometchat.com) and then: @@ -45,7 +45,7 @@ Minimum Requirements -### Add the CometChat Dependency +## Add the CometChat Dependency ### Gradle diff --git a/sdk/android/standalone-calling.mdx b/sdk/android/standalone-calling.mdx index 2d167bea0..5cbc2438c 100644 --- a/sdk/android/standalone-calling.mdx +++ b/sdk/android/standalone-calling.mdx @@ -1,10 +1,10 @@ --- title: "Standalone Calling" +sidebarTitle: "Standalone Calling" description: "Implement calling functionality using only the CometChat Calls SDK without the Chat SDK" --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Generate call token @@ -29,7 +29,7 @@ CometChatCalls.endSession() ``` **Prerequisites:** [Calls SDK setup](/sdk/android/calling-setup), User auth token from REST API - + ## Overview diff --git a/sdk/android/threaded-messages.mdx b/sdk/android/threaded-messages.mdx index c0d7a1b3b..f58676ee7 100644 --- a/sdk/android/threaded-messages.mdx +++ b/sdk/android/threaded-messages.mdx @@ -1,10 +1,10 @@ --- title: "Threaded Messages" -description: "Send and receive threaded messages to organize conversations around specific topics in the Android SDK" +sidebarTitle: "Threaded Messages" +description: "Send, receive, and fetch threaded messages using the CometChat Android SDK." --- - -**Quick Reference for AI Agents & Developers** + @@ -58,7 +58,7 @@ MessagesRequest messagesRequest = new MessagesRequest.MessagesRequestBuilder() ``` - + **Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) diff --git a/sdk/android/transfer-group-ownership.mdx b/sdk/android/transfer-group-ownership.mdx index f9185e652..520fe54c1 100644 --- a/sdk/android/transfer-group-ownership.mdx +++ b/sdk/android/transfer-group-ownership.mdx @@ -1,10 +1,10 @@ --- title: "Transfer Group Ownership" +sidebarTitle: "Transfer Ownership" description: "Transfer group ownership to another member using the Android SDK" --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Transfer ownership to another member (owner only) @@ -20,7 +20,7 @@ CometChat.transferGroupOwnership("GUID", "NEW_OWNER_UID", - The new owner must be an existing group member - Original owner becomes a regular admin after transfer - Required before owner can leave the group - + **Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) diff --git a/sdk/android/transient-messages.mdx b/sdk/android/transient-messages.mdx index 5f6c6e61a..fa6e13bdf 100644 --- a/sdk/android/transient-messages.mdx +++ b/sdk/android/transient-messages.mdx @@ -1,10 +1,10 @@ --- title: "Transient Messages" -description: "Send ephemeral real-time messages that are not stored or tracked using the Android SDK" +sidebarTitle: "Transient Messages" +description: "Send and receive ephemeral real-time messages that are not stored on the server using the CometChat Android SDK. Ideal for live reactions and temporary indicators." --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Send transient message to user @@ -20,7 +20,7 @@ CometChat.addMessageListener("LISTENER_ID", object : 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. diff --git a/sdk/android/typing-indicators.mdx b/sdk/android/typing-indicators.mdx index 4c9bd1783..cb0cf82e2 100644 --- a/sdk/android/typing-indicators.mdx +++ b/sdk/android/typing-indicators.mdx @@ -1,10 +1,10 @@ --- title: "Typing Indicators" -description: "Show real-time typing status in conversations using the Android SDK" +sidebarTitle: "Typing Indicators" +description: "Send and receive real-time typing indicators using the CometChat Android SDK." --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Start typing indicator @@ -20,7 +20,7 @@ CometChat.addMessageListener("LISTENER_ID", object : MessageListener() { override fun onTypingEnded(indicator: TypingIndicator) { } }) ``` - + **Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) diff --git a/sdk/android/update-group.mdx b/sdk/android/update-group.mdx index ccc647f20..1429c5f49 100644 --- a/sdk/android/update-group.mdx +++ b/sdk/android/update-group.mdx @@ -1,10 +1,10 @@ --- title: "Update A Group" +sidebarTitle: "Update Group" description: "Modify group details, settings, and metadata using the Android SDK" --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Update group details @@ -19,7 +19,7 @@ CometChat.updateGroup(group, object : CometChat.CallbackListener() { ``` **Note:** Only admins and moderators can update group details. See [Group Class](/sdk/android/create-group#group-class) for editable fields. - + **Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) diff --git a/sdk/android/upgrading-from-v3-guide.mdx b/sdk/android/upgrading-from-v3-guide.mdx index db82e9519..8d5954cf7 100644 --- a/sdk/android/upgrading-from-v3-guide.mdx +++ b/sdk/android/upgrading-from-v3-guide.mdx @@ -1,10 +1,10 @@ --- title: "Upgrading From V3" +sidebarTitle: "Upgrading from V3" description: "Migration guide for upgrading from CometChat Android SDK v3 to v4" --- - -**Quick Reference for AI Agents & Developers** + **Migration Steps:** 1. Update Maven URL to `https://dl.cloudsmith.io/public/cometchat/cometchat/maven/` @@ -18,7 +18,7 @@ description: "Migration guide for upgrading from CometChat Android SDK v3 to v4" - API remains largely compatible with v3 **Full guide:** Follow the [setup](/sdk/android/setup) instructions for detailed v4 setup. - + diff --git a/sdk/android/user-management.mdx b/sdk/android/user-management.mdx index a80e05c99..625135e26 100644 --- a/sdk/android/user-management.mdx +++ b/sdk/android/user-management.mdx @@ -1,10 +1,10 @@ --- title: "User Management" +sidebarTitle: "User Management" description: "Create, update, and delete user accounts in CometChat using the Android SDK" --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Create user (use API Key - dev/testing only) @@ -29,7 +29,7 @@ CometChat.updateCurrentUserDetails(updatedUser, object : CallbackListener( ``` **Note:** User creation/updates should ideally happen on your backend using [REST API](https://api-explorer.cometchat.com). - + **Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) diff --git a/sdk/android/user-presence.mdx b/sdk/android/user-presence.mdx index c523864ab..962ac8307 100644 --- a/sdk/android/user-presence.mdx +++ b/sdk/android/user-presence.mdx @@ -1,10 +1,10 @@ --- title: "User Presence" +sidebarTitle: "User Presence" description: "Track and subscribe to user online/offline status and presence updates in your Android app" --- - -**Quick Reference for AI Agents & Developers** + @@ -54,7 +54,7 @@ CometChat.removeUserListener("LISTENER_ID"); ``` - + **Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) diff --git a/sdk/android/users-overview.mdx b/sdk/android/users-overview.mdx index 5f01a4d9a..dbf62eda6 100644 --- a/sdk/android/users-overview.mdx +++ b/sdk/android/users-overview.mdx @@ -4,15 +4,14 @@ sidebarTitle: "Overview" description: "Manage users, retrieve user lists, and track user presence in your Android application" --- - -**Quick Reference for AI Agents & Developers** + Choose your user management path: - **User Management** → [user-management](/sdk/android/user-management) - Create and sync users - **Retrieve Users** → [retrieve-users](/sdk/android/retrieve-users) - Fetch user lists with filters - **User Presence** → [user-presence](/sdk/android/user-presence) - Track online/offline status - **Block Users** → [block-users](/sdk/android/block-users) - Block and unblock users - + The primary aim of our users functionality is to allow you to quickly retrieve and add users to CometChat. diff --git a/sdk/android/video-view-customisation.mdx b/sdk/android/video-view-customisation.mdx index 9fa286eac..323ef5132 100644 --- a/sdk/android/video-view-customisation.mdx +++ b/sdk/android/video-view-customisation.mdx @@ -1,10 +1,10 @@ --- title: "Video View Customisation" +sidebarTitle: "Video View Customisation" description: "Customize the main video container appearance, aspect ratio, and UI controls in Android calls" --- - -**Quick Reference for AI Agents & Developers** + ```kotlin // Customize main video container @@ -21,7 +21,7 @@ val callSettings = CometChatCalls.CallSettingsBuilder(context, videoContainer) ``` **Prerequisites:** [Default Calling](/sdk/android/default-calling) or [Direct Calling](/sdk/android/direct-calling) setup - + diff --git a/sdk/android/webhooks-overview.mdx b/sdk/android/webhooks-overview.mdx index a0a9fd005..59e15a8c5 100644 --- a/sdk/android/webhooks-overview.mdx +++ b/sdk/android/webhooks-overview.mdx @@ -1,11 +1,11 @@ --- title: "Webhooks" +sidebarTitle: "Webhooks" description: "Configure server-side event notifications with CometChat webhooks" url: "/fundamentals/webhooks-overview" --- - -**Quick Reference for AI Agents & Developers** + Webhooks send real-time HTTP notifications to your server when events occur in CometChat: - **Message Events** - New messages, edits, deletions @@ -15,7 +15,7 @@ Webhooks send real-time HTTP notifications to your server when events occur in C **Configuration:** [CometChat Dashboard](https://app.cometchat.com) → Your App → Webhooks **Learn more:** [Webhooks Overview](/fundamentals/webhooks-overview) - + Webhooks allow your server to receive real-time notifications when events occur in CometChat. This enables server-side processing, logging, analytics, and integration with other systems without polling the API. From d3585354501530dddef83e2b0c430650c8dbe1fc Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Mon, 30 Mar 2026 22:03:03 +0530 Subject: [PATCH 136/139] Update overview.mdx --- ui-kit/android/v4/overview.mdx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ui-kit/android/v4/overview.mdx b/ui-kit/android/v4/overview.mdx index 25c5e7a82..a9f7d2e3f 100644 --- a/ui-kit/android/v4/overview.mdx +++ b/ui-kit/android/v4/overview.mdx @@ -2,18 +2,18 @@ title: "Overview" --- -With CometChat's UI Kit for Android, you can effortlessly build a chat app equipped with all the essential messaging features, along with customizable options tailored to your application requirements. This UI Kit comprises prebuilt UI components organized into smaller modules and components, each configurable to meet your specific needs. +With CometChat's **UI Kit** for Android, you can effortlessly build a chat app equipped with all the essential messaging features, along with customizable options tailored to your application requirements. This **UI Kit** comprises prebuilt UI components organized into smaller modules and components, each configurable to meet your specific needs. -[Android Sample App](https://github.com/cometchat-pro/cometchat-chat-sample-app-android-java/tree/v4) + -## Before Getting Started +#### **Before Getting Started** Before you begin, it's essential to grasp the fundamental concepts and features offered by CometChat's APIs, SDK, and UI Kit. You can find detailed information in [Key Concepts](/fundamentals/key-concepts) documentation. -The UI Kit library comprises pre-built Android Views for effortless integration and is built on top of the [Android Chat SDK](/sdk/android/overview). Installing it will also include the core Chat SDK. +The **UI Kit** library comprises pre-built Android Views for effortless integration and is built on top of the [Android Chat SDK](/sdk/android/overview). Installing it will also include the core Chat SDK. To ensure the best possible start and to familiarize yourself with our platform, we encourage you to begin by reviewing our [Getting Started](/ui-kit/android/v4/getting-started) guide. This comprehensive guide will provide you with all the essential information and steps you need to seamlessly navigate through our system. From dba811b401a7873bdcb50fa5e67d14db8842ce9e Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Tue, 31 Mar 2026 11:40:53 +0530 Subject: [PATCH 137/139] android SDK docs rewamp --- docs.json | 42 +- sdk/android/additional-message-filtering.mdx | 176 +++-- sdk/android/advanced-overview.mdx | 38 -- sdk/android/ai-agents.mdx | 11 +- sdk/android/ai-moderation.mdx | 8 +- sdk/android/android-overview.mdx | 41 -- sdk/android/authentication-overview.mdx | 125 +++- sdk/android/best-practices.mdx | 178 ++++++ sdk/android/block-users.mdx | 28 +- sdk/android/call-logs.mdx | 17 +- sdk/android/calling-overview.mdx | 42 +- sdk/android/calling-setup.mdx | 35 +- sdk/android/create-group.mdx | 23 +- sdk/android/default-calling.mdx | 8 +- sdk/android/delete-conversation.mdx | 23 +- sdk/android/delete-group.mdx | 8 +- sdk/android/delete-message.mdx | 34 +- sdk/android/delivery-read-receipts.mdx | 25 +- sdk/android/direct-calling.mdx | 17 +- sdk/android/edit-message.mdx | 37 +- sdk/android/error-codes.mdx | 274 ++++++++ sdk/android/flag-message.mdx | 4 - sdk/android/group-add-members.mdx | 29 +- sdk/android/group-change-member-scope.mdx | 16 +- sdk/android/group-kick-member.mdx | 43 +- sdk/android/groups-overview.mdx | 24 +- sdk/android/interactive-messages.mdx | 24 +- sdk/android/join-group.mdx | 18 +- sdk/android/key-concepts.mdx | 70 +- sdk/android/leave-group.mdx | 18 +- sdk/android/login-listeners.mdx | 87 ++- sdk/android/mentions.mdx | 18 +- .../message-structure-and-hierarchy.mdx | 145 +++-- sdk/android/messaging-overview.mdx | 68 +- sdk/android/overview.mdx | 12 + sdk/android/presenter-mode.mdx | 37 +- sdk/android/rate-limits.mdx | 78 ++- sdk/android/reactions.mdx | 8 +- sdk/android/real-time-listeners.mdx | 61 +- sdk/android/receive-messages.mdx | 604 ++++++------------ sdk/android/recording.mdx | 16 +- sdk/android/resources-overview.mdx | 42 -- sdk/android/retrieve-conversations.mdx | 96 ++- sdk/android/retrieve-group-members.mdx | 20 +- sdk/android/retrieve-groups.mdx | 32 +- sdk/android/retrieve-users.mdx | 42 +- sdk/android/send-message.mdx | 362 +++++------ sdk/android/session-timeout.mdx | 22 +- sdk/android/setup.mdx | 42 +- sdk/android/threaded-messages.mdx | 37 +- sdk/android/transfer-group-ownership.mdx | 10 +- sdk/android/transient-messages.mdx | 8 +- sdk/android/troubleshooting.mdx | 229 +++++++ sdk/android/typing-indicators.mdx | 35 +- sdk/android/update-group.mdx | 10 +- sdk/android/user-management.mdx | 28 +- sdk/android/users-overview.mdx | 11 +- sdk/android/video-view-customisation.mdx | 10 +- sdk/reference/auxiliary.mdx | 1 + sdk/reference/calls.mdx | 1 + 60 files changed, 1915 insertions(+), 1693 deletions(-) delete mode 100644 sdk/android/advanced-overview.mdx delete mode 100644 sdk/android/android-overview.mdx create mode 100644 sdk/android/best-practices.mdx create mode 100644 sdk/android/error-codes.mdx delete mode 100644 sdk/android/resources-overview.mdx create mode 100644 sdk/android/troubleshooting.mdx diff --git a/docs.json b/docs.json index 795deb0d0..b4eb397e3 100644 --- a/docs.json +++ b/docs.json @@ -3589,23 +3589,9 @@ { "group": " ", "pages": [ - { - "group": "Overview", - "pages": [ - "sdk/android/overview", - "sdk/android/key-concepts", - "sdk/android/message-structure-and-hierarchy", - "sdk/android/rate-limits" - ] - }, + "sdk/android/overview", "sdk/android/setup", - { - "group": "Authentication", - "pages": [ - "sdk/android/authentication-overview", - "sdk/android/login-listeners" - ] - }, + "sdk/android/authentication-overview", { "group": "Messaging", "pages": [ @@ -3674,25 +3660,33 @@ { "group": "Resources", "pages": [ - "sdk/android/resources-overview", + "sdk/android/key-concepts", + "sdk/android/message-structure-and-hierarchy", "sdk/android/real-time-listeners", - "sdk/android/upgrading-from-v3-guide" + "sdk/android/rate-limits", + "sdk/android/connection-status", + "sdk/android/connection-behaviour" ] }, { - "group": "Advanced", + "group": "Reference", "pages": [ - "sdk/android/advanced-overview", - "sdk/android/connection-status", - "sdk/android/publishing-app-on-playstore", - "sdk/android/connection-behaviour" + "sdk/reference/messages", + "sdk/reference/entities", + "sdk/reference/auxiliary", + "sdk/reference/calls" ] }, + "sdk/android/login-listeners", + "sdk/android/upgrading-from-v3-guide", + "sdk/android/publishing-app-on-playstore", + "sdk/android/best-practices", + "sdk/android/error-codes", + "sdk/android/troubleshooting", "sdk/android/extensions-overview", "sdk/android/ai-user-copilot-overview", "sdk/android/ai-chatbots-overview", "sdk/android/webhooks-overview", - "sdk/android/android-overview", "sdk/android/changelog" ] } diff --git a/sdk/android/additional-message-filtering.mdx b/sdk/android/additional-message-filtering.mdx index dfb2d79a8..fd86f1ec4 100644 --- a/sdk/android/additional-message-filtering.mdx +++ b/sdk/android/additional-message-filtering.mdx @@ -24,32 +24,52 @@ messagesRequest.fetchPrevious(callback) ``` -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 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. - -The `MessagesRequestBuilder` class allows you to set various parameters to the `MessagesRequest` class based on which the messages are fetched. - -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: +The `MessagesRequest` class fetches messages based on various parameters using the Builder design pattern. + +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 + +| Method | Description | +| --- | --- | +| `fetchNext()` | Returns messages after the specified parameters | +| `fetchPrevious()` | Returns messages before the specified parameters | + +Messages are paginated with a maximum of 100 per request. Call `fetchPrevious()`/`fetchNext()` repeatedly on the same object to get subsequent pages. + +## Filter Reference + +| Method | Description | Default | +| --- | --- | --- | +| `setUID(uid)` | Fetch messages for a one-on-one conversation | — | +| `setGUID(guid)` | Fetch messages for a group conversation | — | +| `setLimit(n)` | Number of messages per request (max 100) | — | +| `setMessageId(id)` | Fetch messages before/after a message ID | — | +| `setTimestamp(ts)` | Fetch messages before/after a Unix timestamp | — | +| `setUnread(bool)` | Fetch only unread messages | `false` | +| `setCategories(list)` | Filter by message categories | all | +| `setTypes(list)` | Filter by message types | all | +| `setParentMessageId(id)` | Fetch messages in a specific thread | — | +| `hideReplies(bool)` | Exclude threaded messages | `false` | +| `hideDeletedMessages(bool)` | Exclude deleted messages | `false` | +| `hideQuotedMessages(bool)` | Exclude quoted messages | `false` | +| `hideMessagesFromBlockedUsers(bool)` | Exclude messages from blocked users | `false` | +| `setUpdatedAfter(ts)` | Fetch messages updated after a timestamp | — | +| `updatesOnly(bool)` | Only updated messages (use with `setUpdatedAfter`) | `false` | +| `setTags(list)` | Filter by message tags | — | +| `withTags(bool)` | Include tag data in response | `false` | +| `hasLinks(bool)` | Only messages with links *(Advanced Search)* | `false` | +| `hasAttachments(bool)` | Only messages with attachments *(Advanced Search)* | `false` | +| `hasReactions(bool)` | Only messages with reactions *(Advanced Search)* | `false` | +| `hasMentions(bool)` | Only messages with mentions *(Advanced Search)* | `false` | +| `setMentionedUIDs(list)` | Only messages mentioning specific users *(Advanced Search)* | — | +| `setAttachmentTypes(list)` | Only messages with specific attachment types *(Advanced Search)* | — | ## Number of messages fetched -How do I set the number of messages fetched in a single iteration? - -To achieve this, 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. @@ -104,9 +124,7 @@ val messagesRequest = MessagesRequestBuilder() ## Messages for a user conversation -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 returns 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. @@ -133,11 +151,7 @@ val messagesRequest = MessagesRequestBuilder() ## Messages for a group conversation -How do I fetch messages for any 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 returns all the messages that are a part of the group conversation. Note that the logged-in user must be a member of the group to fetch the messages for that group. - -MessagesRequest messagesRequest = new MessagesRequest.MessagesRequestBuilder() .setGUID("cometchat-guid-1") .setLimit(50) .build(); +Use `setGUID()` to fetch messages from a group. The logged-in user must be a member of the group. @@ -164,9 +178,7 @@ val messagesRequest = MessagesRequestBuilder() ## Messages before/after a message -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 whether 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. @@ -223,13 +235,11 @@ val messagesRequest = MessagesRequestBuilder() -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. ## Messages before/after a given time -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 whether fetchNext() or fetchPrevious() method is triggered. +Use `setTimestamp()` with a Unix timestamp to fetch messages before or after a specific time. @@ -286,13 +296,11 @@ val messagesRequest = MessagesRequestBuilder() -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. ## Unread messages -How do I fetch unread messages? - -This can easily be achieved by setting the unread flag to true. For this, use the `setUnread()` method. This method takes a boolean value as input. If the value is set to true, the SDK returns just the unread messages. +Use `setUnread(true)` to fetch only unread messages. @@ -353,9 +361,7 @@ This method along with `setGUID()` or `setUID()` can be used to fetch unread mes ## Exclude messages from blocked users -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 of 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, meaning 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`. @@ -412,13 +418,11 @@ val messagesRequest = MessagesRequestBuilder() -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. +This also works in group conversations where both users are members. ## Updated and received messages -How do I fetch messages that have been received or updated after a particular date or time? - -This method accepts a Unix timestamp value and returns 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. @@ -475,13 +479,11 @@ val messagesRequest = MessagesRequestBuilder() -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. ## Updated messages only -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, use the `updatesOnly()` method. This method takes a boolean input and can be used with the `setUpdatedAfter()` method to get just 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()`. @@ -544,11 +546,7 @@ val messagesRequest = MessagesRequestBuilder() ## Messages for multiple categories -How do I fetch messages belonging to multiple categories? - -We recommend before trying this, you refer to the [Message structure and hierarchy guide](/sdk/android/message-structure-and-hierarchy) to get familiar with the various categories of messages. - -For this, 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 a list of category names to filter by message category. See [Message structure and hierarchy](/sdk/android/message-structure-and-hierarchy) for available categories. @@ -617,15 +615,11 @@ val messagesRequest = MessagesRequestBuilder() -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`. This along with `setGUID()` and `setUID()` can help display only the messages you wish to display avoiding the other category of messages. +The above snippet fetches only messages in the `message` and `custom` categories. Use this to exclude categories like `call` and `action`. ## Messages for multiple types -How do I fetch messages belonging to multiple types? - -We recommend before trying this, you refer to the [Message structure and hierarchy guide](/sdk/android/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. +Use `setTypes()` with a list of type names to filter by message type. See [Message structure and hierarchy](/sdk/android/message-structure-and-hierarchy) for available types. @@ -714,13 +708,11 @@ val messagesRequest = MessagesRequestBuilder() -Using the above code snippet, you can fetch all the media messages. This along with setUID() or setGUID() can be used to fetch media messages for any particular conversation. This can be useful in many other scenarios as well. +The above snippet fetches all media messages (image, video, audio, file). ## Messages for a specific thread -How do I fetch messages that are a part of a thread and not directly a user/group conversation? - -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 returns the messages only belonging to the thread with the specified parent Id. +Use `setParentMessageId()` to fetch messages belonging to a specific thread. @@ -780,9 +772,7 @@ The above code snippet returns the messages that belong to the thread with paren ## Hide threaded messages in user/group conversations -How do I exclude threaded messages from the normal user/group conversations? - -To do this, use the `hideReplies()` method. This method is also related to threaded conversations. This method takes a boolean as input. This boolean when set to true ensures that the messages that belong to threads are not fetched. If set to false, which is also the default value, the messages belonging 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`. @@ -841,9 +831,7 @@ val messagesRequest = MessagesRequestBuilder() ## Hide deleted messages in user/group conversations -How do I exclude deleted messages from a user/group conversation? - -To do this, use the `hideDeletedMessages()` method. This method takes a boolean as input. This boolean when set to true ensures 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`. @@ -902,9 +890,7 @@ val messagesRequest = MessagesRequestBuilder() ## Hide quoted messages in user/group conversations -How do I exclude quoted messages in a user/group conversation? - -To do this, use the `hideQuotedMessages()` method. This method takes a boolean as input. This boolean when set to true ensures 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`. @@ -963,9 +949,7 @@ val messagesRequest = MessagesRequestBuilder() ## Messages by tags -How do I fetch messages belonging to specific tags? - -To do this, 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 a list of tag names to fetch only messages with those tags. @@ -1002,9 +986,13 @@ val messagesRequest = MessagesRequestBuilder() ## Messages with tags -How do I fetch messages with the tags information? +Use `withTags(true)` to include tag information in the response. Default is `false`. + +When `withTags(true)` is set, each message's `tags` field will be populated. Access tags using `getTags()`. -To do this, use the `withTags()` method. This method accepts a boolean as input. When set to `true`, the SDK fetches messages along with the tags information. When set to `false`, the SDK does not fetch tags information associated with messages. The default value for this parameter is `false`. +| Additional Field | Getter | Return Type | Description | +| --- | --- | --- | --- | +| tags | `getTags()` | `List` | Tags associated with the message | @@ -1037,9 +1025,7 @@ val messagesRequest = MessagesRequestBuilder() ## 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`. @@ -1078,9 +1064,7 @@ val messagesRequest = MessagesRequestBuilder() ## 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`. @@ -1119,9 +1103,7 @@ val messagesRequest = MessagesRequestBuilder() ## Messages with reactions -In other words, as a logged-in user, how do I fetch messages that contains 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`. @@ -1160,9 +1142,7 @@ val messagesRequest = MessagesRequestBuilder() ## Messages with mentions -In other words, as a logged-in user, how do I fetch messages that contains 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`. @@ -1201,9 +1181,7 @@ val messagesRequest = MessagesRequestBuilder() ## Messages with particular user mentions -In other words, as a logged-in user, how do I fetch messages that mentions specific users? - -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 a list of UIDs to fetch only messages that mention those specific users. @@ -1246,9 +1224,7 @@ val messagesRequest = MessagesRequestBuilder() ## Messages with specific attachment types -In other words, as a logged-in user, how do I fetch messages that contain specific types of attachments? - -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 a list of `AttachmentType` enum values to fetch only messages with specific attachment types. diff --git a/sdk/android/advanced-overview.mdx b/sdk/android/advanced-overview.mdx deleted file mode 100644 index 816fc34a8..000000000 --- a/sdk/android/advanced-overview.mdx +++ /dev/null @@ -1,38 +0,0 @@ ---- -title: "Advanced" -sidebarTitle: "Overview" -description: "Advanced features and customization options for the CometChat Android SDK" ---- - - - -Explore advanced features: -- **Real-Time Listeners** → [real-time-listeners](/sdk/android/real-time-listeners) - Handle all SDK events -- **Message Structure** → [message-structure-and-hierarchy](/sdk/android/message-structure-and-hierarchy) - Understand message types -- **Additional Filtering** → [additional-message-filtering](/sdk/android/additional-message-filtering) - Advanced message queries -- **Connection Status** → [connection-status](/sdk/android/connection-status) - Monitor SDK connectivity -- **Login Listeners** → [login-listeners](/sdk/android/login-listeners) - Track authentication events - - -Advanced features provide deeper control and customization of the CometChat SDK. These guides cover event handling, message filtering, connection management, and other sophisticated capabilities for building robust chat applications. - ---- - -## Next Steps - - - - Handle all SDK events with comprehensive listeners - - - Understand message types and hierarchy - - - Advanced message queries and filtering options - - - Monitor and handle SDK connectivity changes - - - - diff --git a/sdk/android/ai-agents.mdx b/sdk/android/ai-agents.mdx index 85d44a229..bc2197df2 100644 --- a/sdk/android/ai-agents.mdx +++ b/sdk/android/ai-agents.mdx @@ -23,16 +23,11 @@ CometChat.addMessageListener("LISTENER_ID", object : CometChat.MessageListener() ``` - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/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). -> **Note:** -> Currently, an Agent only responds to **Text Messages**. + +Currently, an Agent only responds to **Text Messages**. + ## Agent Run Lifecycle and Message Flow diff --git a/sdk/android/ai-moderation.mdx b/sdk/android/ai-moderation.mdx index 5ae822941..070158769 100644 --- a/sdk/android/ai-moderation.mdx +++ b/sdk/android/ai-moderation.mdx @@ -27,13 +27,7 @@ CometChat.addMessageListener("LISTENER_ID", object : CometChat.MessageListener() ``` - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/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. +AI Moderation automatically reviews messages for inappropriate content, reducing manual intervention. Messages are sent with a `PENDING` status and updated to `APPROVED` or `DISAPPROVED` after processing. For a broader understanding of moderation features, configuring rules, and managing flagged messages, see the [Moderation Overview](/moderation/overview). diff --git a/sdk/android/android-overview.mdx b/sdk/android/android-overview.mdx deleted file mode 100644 index 40827427f..000000000 --- a/sdk/android/android-overview.mdx +++ /dev/null @@ -1,41 +0,0 @@ ---- -title: "Java UI Kit" -sidebarTitle: "Android Overview" -description: "Pre-built UI components for Android chat applications using CometChat" -url: "/ui-kit/android/overview" ---- - - - -The CometChat Android UI Kit provides pre-built UI components for rapid chat app development: -- **Pre-built Chat UI** - Ready-to-use chat screens and components -- **Customizable Themes** - Match your app's design language -- **Message Types** - Text, media, custom messages supported -- **Group Chat** - Built-in group conversation UI -- **Calling UI** - Voice and video call interfaces - -**Learn more:** [Android UI Kit Overview](/ui-kit/android/overview) - - -The Android UI Kit is a collection of pre-built UI components that accelerate chat application development. It provides ready-to-use screens for conversations, user lists, group management, and calling interfaces. - -For detailed information about the UI Kit, installation instructions, customization options, and implementation guides, visit the [Android UI Kit Overview](/ui-kit/android/overview). - ---- - -## Next Steps - - - - Explore the complete Android UI Kit documentation - - - Build custom UI with the Android SDK - - - Install and initialize the Android SDK - - - Start building messaging features - - \ No newline at end of file diff --git a/sdk/android/authentication-overview.mdx b/sdk/android/authentication-overview.mdx index c6c481654..4e2a2a6c6 100644 --- a/sdk/android/authentication-overview.mdx +++ b/sdk/android/authentication-overview.mdx @@ -33,32 +33,50 @@ CometChat.logout(object : CometChat.CallbackListener() { **Get from:** [CometChat Dashboard](https://app.cometchat.com) → Your App → API & Auth Keys -### Create User +After [initializing](/sdk/android/setup) the SDK, the next step is to authenticate your user. CometChat provides two login methods — Auth Key for quick development, and Auth Token for production — both accessed through the `login()` method. -Before you log in a user, you must add the user to CometChat. +## Before You Log In -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. +### Create a User - -Sample Users +A user must exist in CometChat before they can log in. -We have set up 5 users for testing with UIDs: `cometchat-uid-1`, `cometchat-uid-2`, `cometchat-uid-3`, `cometchat-uid-4`, and `cometchat-uid-5`. +- **During development:** Create users from the [CometChat Dashboard](https://app.cometchat.com). Five test users are already available with UIDs `cometchat-uid-1` through `cometchat-uid-5`. +- **In production:** Call the [Create User REST API](https://api-explorer.cometchat.com/reference/creates-user) when a user signs up in your app. + +We have set up 5 users for testing with UIDs: `cometchat-uid-1`, `cometchat-uid-2`, `cometchat-uid-3`, `cometchat-uid-4`, and `cometchat-uid-5`. -Once initialization is successful, you need to log the user into CometChat using the `login()` method. +### Check for an Existing Session + +The SDK persists the logged-in user's session locally. Before calling `login()`, always check whether a session already exists — this avoids unnecessary login calls. + + + +```java +if (CometChat.getLoggedInUser() != null) { + // User is already logged in — proceed to your app +} +``` + + +```kotlin +if (CometChat.getLoggedInUser() != null) { + // User is already logged in — proceed to your app +} +``` + + -We recommend calling the CometChat `login()` method once your user logs into your app. The `login()` method only needs to be called once. +If `getLoggedInUser()` returns `null`, no active session exists and you need to call `login()`. `CometChat.init()` must be called before any other SDK method. Calling `login()`, `sendMessage()`, or registering listeners before `init()` will fail. - -The CometChat SDK maintains the session of the logged-in user within the SDK. You do not need to call the login method for every session. Use the `CometChat.getLoggedInUser()` method to check if there is any existing session in the SDK. This method should return the details of the logged-in user. If this method returns `null`, it means there is no session present within the SDK and you need to log the user into CometChat. - +The CometChat SDK maintains the session of the logged-in user within the SDK. You do not need to call the login method for every session. Use `CometChat.getLoggedInUser()` to check for an existing session first. ## Login using Auth Key @@ -214,6 +232,89 @@ CometChat.logout(object : CometChat.CallbackListener() { --- +## Login Listener + +You can listen for login and logout events in real time using `LoginListener`. This is useful for updating UI state or triggering side effects when the auth state changes. + +| Callback | Description | +| --- | --- | +| `loginSuccess(User user)` | User logged in successfully. Provides the `User` object. | +| `loginFailure(CometChatException e)` | Login failed. Provides the exception with the reason. | +| `logoutSuccess()` | User logged out successfully. | +| `logoutFailure(CometChatException e)` | Logout failed. Provides the exception with the reason. | + +### Add a Listener + + + +```java +CometChat.addLoginListener("UNIQUE_ID", new CometChat.LoginListener() { + @Override + public void loginSuccess(User user) { + Log.d("LoginListener", "loginSuccess " + user.toString()); + } + + @Override + public void loginFailure(CometChatException e) { + Log.d("LoginListener", "loginFailure " + e.getMessage()); + } + + @Override + public void logoutSuccess() { + Log.d("LoginListener", "logoutSuccess"); + } + + @Override + public void logoutFailure(CometChatException e) { + Log.d("LoginListener", "logoutFailure " + e.getMessage()); + } +}); +``` + + +```kotlin +CometChat.addLoginListener("UNIQUE_ID", object : LoginListener() { + override fun loginSuccess(user: User) { + Log.d("LoginListener", "loginSuccess $user") + } + + override fun loginFailure(e: CometChatException) { + Log.d("LoginListener", "loginFailure " + e.message) + } + + override fun logoutSuccess() { + Log.d("LoginListener", "logoutSuccess") + } + + override fun logoutFailure(e: CometChatException) { + Log.d("LoginListener", "logoutFailure " + e.message) + } +}) +``` + + + +### Remove a Listener + + + +```java +CometChat.removeLoginListener("UNIQUE_ID"); +``` + + +```kotlin +CometChat.removeLoginListener("UNIQUE_ID") +``` + + + + +Always remove login listeners when they're no longer needed (e.g., in `onDestroy()`). Failing to remove listeners can cause memory leaks and duplicate event handling. + + +--- + ## Next Steps diff --git a/sdk/android/best-practices.mdx b/sdk/android/best-practices.mdx new file mode 100644 index 000000000..50aa2d1aa --- /dev/null +++ b/sdk/android/best-practices.mdx @@ -0,0 +1,178 @@ +--- +title: "Best Practices" +sidebarTitle: "Best Practices" +description: "Recommended patterns and practices for building with the CometChat Android SDK." +--- + +Follow these best practices to build reliable, performant, and secure applications with the CometChat Android SDK. Organized by topic — jump to what's relevant for your current work. + +## Initialization & Authentication + +| Practice | Description | +|----------|-------------| +| Initialize once at app startup | Call `CometChat.init()` in your `Application` class `onCreate()`. It only needs to be called once per session. | +| Store credentials in `local.properties` | Keep App ID, Region, and Auth Key out of source control. Read them via `BuildConfig` fields set in `build.gradle`. | +| 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/android/authentication-overview#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. | + +## Activity & Fragment Lifecycle + +| Practice | Description | +|----------|-------------| +| Register listeners in `onResume()` | Re-register message and call listeners when the Activity or Fragment becomes visible. | +| Remove listeners in `onPause()` | Remove listeners in `onPause()` to avoid processing events while the screen is not visible. | +| Clean up in `onDestroy()` | Remove all remaining listeners and cancel pending requests in `onDestroy()` to prevent memory leaks. | +| Use `ViewModel` for SDK state | Hold SDK data (messages, users, groups) in a `ViewModel` so it survives configuration changes like screen rotation. | +| Avoid SDK calls in `onCreate()` before `init()` | Ensure `CometChat.init()` has completed (in your `Application` class) before making any SDK calls in an Activity. | + +## Listeners + +| Practice | Description | +|----------|-------------| +| Use unique listener IDs | Use descriptive IDs like `"MESSAGE_LISTENER_CHAT_SCREEN"` to avoid accidental overwrites. | +| Register after login, remove on cleanup | Register listeners after `login()` succeeds. Remove them in `onPause()` or `onDestroy()` to prevent memory leaks. | +| Keep callbacks lightweight | Avoid heavy processing inside listener callbacks. Post updates to your `ViewModel` or `LiveData`. | +| Use specific listeners | Only register the listener types you need. Don't register a `GroupListener` if your screen 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 in your `ViewModel` or a local Room database to reduce API calls. | + +## Rate Limits + +| 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. | + +## Messaging + +| 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 `onError()` 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 + +| Practice | Description | +|----------|-------------| +| Track active thread ID | Store the current thread's `parentMessageId` to filter incoming messages. | +| Use `hideReplies(true)` | Exclude thread replies from the 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 the 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 using `SpannableString`. | + +## Typing Indicators + +| Practice | Description | +|----------|-------------| +| Debounce typing events | Don't call `startTyping()` on every keystroke — debounce to ~300ms intervals using a `Handler` or `debounce` operator. | +| Auto-stop typing | Call `endTyping()` after 3–5 seconds of inactivity or when the user sends a message. | + +## Delivery & Read Receipts + +| 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 or scrolls to a message. | +| Batch receipts | Mark the last message in a batch — all previous messages are automatically marked. | + +## Groups + +| 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 + +| 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 for `"success"` or an error message. | +| Use scope constants | Use `CometChatConstants.SCOPE_ADMIN` instead of raw strings. | +| Kick vs. Ban | Use kick when the user can rejoin. Use ban for permanent removal until unbanned. | + +## Calling + +| 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, and 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. | +| Request permissions before calling | Check and request `CAMERA` and `RECORD_AUDIO` permissions at runtime before initiating a call. | +| 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. | + +## Permissions + +| Practice | Description | +|----------|-------------| +| Request permissions at the right time | Request `CAMERA`, `RECORD_AUDIO`, and `READ_EXTERNAL_STORAGE` permissions contextually, not at app launch. | +| Handle permission denial gracefully | Show a rationale dialog if the user denies a permission, and disable the relevant feature rather than crashing. | +| Use `ActivityResultContracts` | Use the modern `registerForActivityResult` API instead of the deprecated `onRequestPermissionsResult`. | + +## Connection & WebSocket + +| 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 | Call `CometChat.connect()` in `onResume()` if you disconnect in the background. | + +## AI Features + +| 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 + +| Practice | Description | +|----------|-------------| +| Follow the setup guide first | Complete the v4 [setup instructions](/sdk/android/setup) before changing dependencies. | +| Update Gradle dependency | Replace the v3 artifact with `com.cometchat:chat-sdk-android:4.x.x` in your `build.gradle`. | +| Test incrementally | Test each feature area (messaging, calling, groups) individually after updating. | +| Remove old packages | Remove the v3 dependency from `build.gradle` and sync to avoid conflicts. | + +--- + +## Next Steps + + + + Common issues and solutions + + + Installation and initialization guide + + diff --git a/sdk/android/block-users.mdx b/sdk/android/block-users.mdx index a5221149a..328e2e2c9 100644 --- a/sdk/android/block-users.mdx +++ b/sdk/android/block-users.mdx @@ -72,15 +72,9 @@ request.fetchNext(new CometChat.CallbackListener>() { - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) - - ## Block Users -*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 communication to and from that user will be completely blocked. You can block multiple users in a single operation. The `blockUsers()` method takes a `List` as a parameter which holds the list of `UIDs` to be blocked. +Use `blockUsers()` to block one or more users. All communication to and from blocked users is stopped. Pass a `List` of UIDs to block. @@ -130,9 +124,7 @@ In the `onSuccess()` callback, you receive a HashMap which contains `UIDs` as th ## Unblock Users -*As a logged-in user, how do I unblock a user I previously blocked?* - -You can unblock previously blocked users using the `unblockUsers()` method. You can unblock multiple users in a single operation. The `unblockUsers()` method takes a `List` as a parameter which holds the list of `UIDs` to be unblocked. +Use `unblockUsers()` to unblock previously blocked users. Pass a `List` of UIDs to unblock. @@ -182,17 +174,13 @@ In the `onSuccess()` callback, you receive a HashMap which contains `UIDs` as th --- -## Get list of blocked users - -*As a logged-in user, how do I get a list of all users I've blocked?* - -To fetch the list of blocked users, you can use the `BlockedUsersRequest` class. 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. +## Get List of Blocked Users -The `BlockedUsersRequestBuilder` class allows you to set the following parameters: +Use `BlockedUsersRequestBuilder` to fetch blocked users with optional filters. ### Set Limit -This method sets the limit i.e. the number of blocked users that should be fetched in a single iteration. +Set the number of blocked users to fetch per request. @@ -217,7 +205,7 @@ val blockedUsersRequest = BlockedUsersRequestBuilder() ### Set Search Keyword -This method allows you to set the search string based on which the blocked users are to be fetched. +Filter blocked users by a search string. @@ -267,9 +255,9 @@ val blockedUsersRequest = BlockedUsersRequestBuilder() -Finally, once all the parameters are set in the builder class, you need to call the `build()` method to get the object of the `BlockedUsersRequest` class. +### Fetch Blocked Users -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()` then `fetchNext()` to retrieve blocked users. diff --git a/sdk/android/call-logs.mdx b/sdk/android/call-logs.mdx index 8d729b4bc..d94021fd6 100644 --- a/sdk/android/call-logs.mdx +++ b/sdk/android/call-logs.mdx @@ -25,19 +25,9 @@ CometChatCalls.getCallDetails(sessionID, callback) ``` - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [Dashboard](https://app.cometchat.com) - +Call logs let you retrieve and display call history — who called whom, when, how long, and whether it was recorded. Use `CallLogRequestBuilder` to fetch and filter logs, and `getCallDetails()` to get details for a specific session. -## Overview - -CometChat's Android Call SDK provides a comprehensive way to integrate call logs into your application, helping users keep track of their communication history. Call logs provide crucial information such as call duration, participants, and more. - -This feature allows users to review past interactions and revisit important conversation details. With the flexibility to fetch call logs, filter them by specific parameters, and obtain detailed information about individual calls, you can build a more robust and interactive communication framework. - -The following sections walk you through working with call logs and how to use this feature effectively in your Android application. - -## Fetching Call Logs +## Fetch Call Logs To fetch call logs in your Android application, use the `CallLogRequestBuilder`. This builder allows you to customize the call log fetching process according to your needs. @@ -206,8 +196,9 @@ CometChatCalls.getCallDetails(sessionID, new CometChatCalls.CallbackListener -Note: Replace `"SESSION_ID"` with the ID of the session you are interested in. +Returns a list of `CallLog` objects for the specified session. +--- ## Best Practices diff --git a/sdk/android/calling-overview.mdx b/sdk/android/calling-overview.mdx index 23f030dba..d8ccf2b1d 100644 --- a/sdk/android/calling-overview.mdx +++ b/sdk/android/calling-overview.mdx @@ -15,9 +15,7 @@ Choose your calling implementation: - **Recording** → [recording](/sdk/android/recording) - Record call sessions -## Overview - -CometChat provides voice and video calling capabilities for your Android application. This guide helps you choose the right implementation approach based on your use case. +CometChat provides three ways to add voice and video calling to your Android app. Which one you pick depends on how much of the call flow you want CometChat to handle vs. building yourself. ## Prerequisites @@ -32,9 +30,7 @@ dependencies { For detailed setup instructions, see the [Calls SDK Setup](/sdk/android/calling-setup) guide. -## Choose Your Implementation - -CometChat offers three approaches to implement calling: +## Choose Your Approach @@ -48,40 +44,6 @@ CometChat offers three approaches to implement calling: -### Ringing - -Use this when you need a complete calling experience with: -- Incoming and outgoing call UI -- Call accept/reject/cancel functionality -- Call notifications via push notifications -- Integration with CometChat messaging - -**Flow:** Initiate call → Receiver gets notified → Accept/Reject → Start session - -[Get started with Ringing →](/sdk/android/default-calling) - -### Call Session - -Use this when you need to: -- Start a call session after the Ringing flow completes -- Implement custom call initiation logic with your own UI -- Join participants to a shared session using a session ID - -**Flow:** Generate token → Start session → Manage call → End session - -[Get started with Call Session →](/sdk/android/direct-calling) - -### Standalone Calling - -Use this when you want: -- Calling functionality without the Chat SDK -- Your own user authentication system -- Minimal SDK footprint - -**Flow:** Get auth token via REST API → Generate call token → Start session - -[Get started with Standalone Calling →](/sdk/android/standalone-calling) - ## Features diff --git a/sdk/android/calling-setup.mdx b/sdk/android/calling-setup.mdx index d1f4af080..6ace23b53 100644 --- a/sdk/android/calling-setup.mdx +++ b/sdk/android/calling-setup.mdx @@ -28,20 +28,14 @@ CometChatCalls.init(context, callAppSettings, object : CometChatCalls.CallbackLi -## Get your Application Keys +## Prerequisites -[Sign up for CometChat](https://app.cometchat.com/signup) and then: - -1. Create a new app -2. Head over to the API Keys section and note the Auth Key, App ID & Region +Get your credentials from the [CometChat Dashboard](https://app.cometchat.com): +- App ID +- Region -Minimum Requirement - -* Android API Level 21 -* Android API level 24 (in case you are using the calls SDKS) -* Androidx Compatibility - +Minimum requirements: Android API Level 21 (API Level 24 with Calls SDK), AndroidX ## Add the CometChatCalls Dependency @@ -82,18 +76,19 @@ dependencies { ## Initialize CometChatCalls -The `init()` method initializes the settings required for CometChatCalls. The `init()` method takes the following parameters: - -- `context` - Your activity context -- `callAppSettings` - An object of the `CallAppSettings` class created using the `CallAppSettingBuilder` class. The `appId` and `region` fields are mandatory and can be set using the `setAppId()` and `setRegion()` methods. +Call `CometChatCalls.init()` on app startup, after the Chat SDK has initialized (if you're using it). The method takes a `CallAppSettings` object built with `CallAppSettingBuilder`. -The `CallAppSettings` class allows you to configure three settings: +### CallAppSettings Options -- App ID: CometChat app ID. -- Region: The region where your app was created. -- Host (host: 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. +| Method | Description | +| --- | --- | +| `setAppId(appId)` | Your CometChat App ID. Required. | +| `setRegion(region)` | The region where your app was created. Required. | +| `setHost(host)` | Custom client URL for dedicated deployments. Optional. | -We recommend calling the `init()` method in the activity's `onCreate()` method. + +`CometChatCalls.init()` must be called before any other Calls SDK method. + diff --git a/sdk/android/create-group.mdx b/sdk/android/create-group.mdx index a4fd14c76..2fe780ca8 100644 --- a/sdk/android/create-group.mdx +++ b/sdk/android/create-group.mdx @@ -1,5 +1,5 @@ --- -title: "Create A Group" +title: "Create Group" sidebarTitle: "Create Group" description: "Create public, private, and password-protected groups using the Android SDK" --- @@ -23,26 +23,13 @@ CometChat.createGroupWithMembers(group, groupMembers, emptyList(), callback) ``` - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) - - ## Create a Group -*As a logged-in user, how do I create a public, private, or password-protected group?* - -You can create a group using the `createGroup()` method. This method takes a `Group` object as input. - -To create an object of the `Group` class, you can use either of the following 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 one of the following values: +Use `createGroup()` with a `Group` object. The `groupType` must be one of: -1. `CometChatConstants.GROUP_TYPE_PUBLIC` (public) -2. `CometChatConstants.GROUP_TYPE_PASSWORD` (password) -3. `CometChatConstants.GROUP_TYPE_PRIVATE` (private) +1. `CometChatConstants.GROUP_TYPE_PUBLIC` +2. `CometChatConstants.GROUP_TYPE_PASSWORD` +3. `CometChatConstants.GROUP_TYPE_PRIVATE` diff --git a/sdk/android/default-calling.mdx b/sdk/android/default-calling.mdx index 7659d2a14..8f63dd515 100644 --- a/sdk/android/default-calling.mdx +++ b/sdk/android/default-calling.mdx @@ -25,13 +25,7 @@ CometChat.rejectCall(sessionID, CometChatConstants.CALL_STATUS_REJECTED, callbac ``` - -**Available via:** SDK | [UI Kits](/ui-kit/android/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**. +This page covers the complete calling workflow with ringing — incoming/outgoing call UI, accept/reject/cancel, and starting the call session. Previously known as **Default Calling**. After the call is accepted, you need to start the call session. See the [Call Session](/sdk/android/direct-calling#start-call-session) guide for details on starting and managing the actual call. diff --git a/sdk/android/delete-conversation.mdx b/sdk/android/delete-conversation.mdx index a8ee43545..2796008d4 100644 --- a/sdk/android/delete-conversation.mdx +++ b/sdk/android/delete-conversation.mdx @@ -1,5 +1,5 @@ --- -title: "Delete A Conversation" +title: "Delete Conversation" sidebarTitle: "Delete Conversation" description: "Delete user or group conversations using the CometChat Android SDK." --- @@ -21,13 +21,12 @@ CometChat.deleteConversation("GUID", CometChatConstants.RECEIVER_TYPE_GROUP, cal **Note:** This deletes the conversation only for the logged-in user. To delete for all users, use the [REST API](https://api-explorer.cometchat.com/reference/deletes-conversation). - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) - +Use `deleteConversation()` to delete a conversation for the logged-in user. -To delete a conversation, use the `deleteConversation()` method. - -This method takes two parameters: the unique id (UID/GUID) of the conversation to be deleted and the type (user/group) of conversation to be deleted. +| 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 | @@ -96,15 +95,7 @@ CometChat.deleteConversation(GUID, CometChatConstants.RECEIVER_TYPE_GROUP, objec -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/deletes-conversation). - -The `deleteConversation()` method takes the following parameters: - -| 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 | - +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/deletes-conversation). ## Best Practices diff --git a/sdk/android/delete-group.mdx b/sdk/android/delete-group.mdx index df2907022..22c4e40f7 100644 --- a/sdk/android/delete-group.mdx +++ b/sdk/android/delete-group.mdx @@ -1,5 +1,5 @@ --- -title: "Delete A Group" +title: "Delete Group" sidebarTitle: "Delete Group" description: "Permanently delete groups as an admin using the Android SDK" --- @@ -17,13 +17,9 @@ CometChat.deleteGroup("GUID", object : CometChat.CallbackListener() { **Note:** Only group admins can delete groups. This action is permanent and cannot be undone. - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) - - ## Delete Group -To delete a group, 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 delete groups. diff --git a/sdk/android/delete-message.mdx b/sdk/android/delete-message.mdx index 75f8d61d8..8a195aa2a 100644 --- a/sdk/android/delete-message.mdx +++ b/sdk/android/delete-message.mdx @@ -1,5 +1,5 @@ --- -title: "Delete A Message" +title: "Delete Message" sidebarTitle: "Delete Message" description: "Delete messages using the CometChat Android SDK." --- @@ -24,20 +24,14 @@ CometChat.addMessageListener("LISTENER_ID", object : CometChat.MessageListener() ``` - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) - +Deleting a message is straightforward. Receiving delete events has two parts: -While [deleting a message](/sdk/android/delete-message#delete-a-message) is straightforward, receiving events for deleted messages with CometChat has two parts: - -1. Adding a listener to receive [real-time message deletes](/sdk/android/delete-message#real-time-message-delete-events) when your app is running. -2. Calling a method to retrieve [missed message delete events](/sdk/android/delete-message#missed-message-delete-events)-me 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 -How do I delete a message? - -To delete a message, use the `deleteMessage()` method. This method takes the message ID of the message to be deleted. For more details on message properties, see [Message Structure & Hierarchy](/sdk/android/message-structure-and-hierarchy). +Use `deleteMessage()` with the message ID. @@ -78,6 +72,11 @@ CometChat.deleteMessage(messageId,object : CometChat.CallbackListener +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| deletedAt | `getDeletedAt()` | `long` | Timestamp when the message was deleted | +| deletedBy | `getDeletedBy()` | `String` | UID of the user who deleted the message | + 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. By default, CometChat allows certain roles to delete a message. @@ -91,9 +90,7 @@ By default, CometChat allows certain roles to delete a message. ## Real-time Message Delete Events -How do I know when someone deletes a message while my app is running? - -To receive real-time events for a message being deleted, override the `onMessageDeleted()` method of the `MessageListener` class. For more information on message listeners, see [Real-Time Listeners](/sdk/android/real-time-listeners). +Use `onMessageDeleted` in `MessageListener` to receive real-time delete events. @@ -121,6 +118,11 @@ CometChat.addMessageListener(listenerID, object : CometChat.MessageListener() { +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| deletedAt | `getDeletedAt()` | `long` | Timestamp when the message was deleted | +| deletedBy | `getDeletedBy()` | `String` | UID of the user who deleted the message | + Always remove listeners when they're no longer needed (e.g., in `onDestroy()` or when navigating away). Failing to remove listeners can cause memory leaks and duplicate event handling. @@ -131,9 +133,7 @@ CometChat.removeMessageListener("LISTENER_ID") ## Missed Message Delete Events -How do I know if someone deleted a message while 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. For example, if the total number of messages for a conversation is 100, and the message with message ID 50 was deleted, the message with ID 50 will have the `deletedAt` and the `deletedBy` fields set whenever it is pulled from the history. Additionally, the 101st message will be an `Action` message informing you that the message with ID 50 has been deleted. +When fetching message history, deleted messages have `deletedAt` and `deletedBy` fields set. Additionally, an `Action` message is created when a message is deleted. For the message deleted event, in the `Action` object received, the following fields can help you get the relevant information- diff --git a/sdk/android/delivery-read-receipts.mdx b/sdk/android/delivery-read-receipts.mdx index 3cc2e692c..b5386abcc 100644 --- a/sdk/android/delivery-read-receipts.mdx +++ b/sdk/android/delivery-read-receipts.mdx @@ -23,14 +23,8 @@ CometChat.addMessageListener("LISTENER_ID", object : MessageListener() { ``` - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) - - ## Mark Messages as Delivered -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 following parameters as input: | Parameter | Information | @@ -149,19 +143,19 @@ CometChat.markAsDelivered(message.id, receiverUID, CometChatConstants.RECEIVER_T -Another option the CometChat SDK provides is to pass the entire message object to the markAsDelivered() method. +Another option the CometChat SDK provides is to pass the entire message object to the `markAsDelivered()` method. ```java -CometChat.markAsRead(baseMessage) +CometChat.markAsDelivered(baseMessage) ``` ```kotlin -CometChat.markAsRead(baseMessage) +CometChat.markAsDelivered(baseMessage) ``` @@ -213,8 +207,6 @@ Starting v3, the messages will not be marked delivered internally by the SDK. Yo ## Mark Messages as Read -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 following parameters as input: | Parameter | Information | @@ -403,8 +395,6 @@ The Mark as Unread feature allows users to designate specific messages or conver 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? - You can mark the messages for a particular conversation as unread using the `markAsUnread()` method. This method takes the below parameters as input: | Parameter | Information | @@ -489,10 +479,15 @@ CometChat.markAsUnread(message, object : CometChat.CallbackListener() { ## Receive Delivery & Read Receipts -How do I know when a message I sent has been delivered or read by someone? - ### Real-time 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 | + 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. diff --git a/sdk/android/direct-calling.mdx b/sdk/android/direct-calling.mdx index 10d138d70..fdeb94521 100644 --- a/sdk/android/direct-calling.mdx +++ b/sdk/android/direct-calling.mdx @@ -27,21 +27,9 @@ CometChatCalls.endSession() ``` - -**Available via:** SDK | [UI Kits](/ui-kit/android/overview) - - -## Overview - -This section demonstrates how to start a call session in an Android application. Previously known as **Direct Calling**. - -Before you begin, we strongly recommend you read the [calling setup guide](/sdk/android/calling-setup). +A call session is the active media connection between participants — camera, microphone, and the call UI. Whether you arrive here from the [Ringing flow](/sdk/android/default-calling), your own custom UI, or [Standalone Calling](/sdk/android/standalone-calling), this page covers how to manage the session itself. Previously known as **Direct Calling**. - - -If you want to implement a complete calling experience with ringing functionality (incoming/outgoing call UI), follow the [Ringing](/sdk/android/default-calling) guide first. Once the call is accepted, return here to start the call session. - - +Before you begin, complete the [Calls SDK Setup](/sdk/android/calling-setup). ## Generate Call Token @@ -569,7 +557,6 @@ CometChatCalls.setAudioMode(audioMode) ### Enter PIP Mode -### Enter PIP Mode Enters Picture-in-Picture mode, rendering the call view in a small floating window. This allows users to multitask while staying on the call. Ensure your app has PIP support enabled in the manifest. diff --git a/sdk/android/edit-message.mdx b/sdk/android/edit-message.mdx index 9e9db0b65..f843e6b6e 100644 --- a/sdk/android/edit-message.mdx +++ b/sdk/android/edit-message.mdx @@ -1,5 +1,5 @@ --- -title: "Edit A Message" +title: "Edit Message" sidebarTitle: "Edit Message" description: "Edit text and custom messages using the CometChat Android SDK." --- @@ -27,20 +27,9 @@ CometChat.addMessageListener("LISTENER_ID", object : CometChat.MessageListener() ``` - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) - - -While [editing a message](/sdk/android/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 edit events](/sdk/android/edit-message#real-time-message-edit-events) when your app is running -2. Calling a method to retrieve [missed message edit events](/sdk/android/edit-message#missed-message-edit-events) when your app was not running - ## Edit a Message -How do I edit a message? - -To edit a message, use the `editMessage()` method. This method takes an object of the `BaseMessage` class. Currently, you can only edit `TextMessage` and `CustomMessage`. Thus, the `BaseMessage` object must either be a Text or a Custom Message. For more details on message types, see [Message Structure & Hierarchy](/sdk/android/message-structure-and-hierarchy). +Use `editMessage()` with a `TextMessage` or `CustomMessage` object. Set the message ID using `setId()`. ### Add/Update Tags @@ -67,9 +56,7 @@ textMessage.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()`. @@ -116,6 +103,11 @@ CometChat.editMessage(updatedMessage, object: CometChat.CallbackListener @@ -165,11 +155,14 @@ CometChat.removeMessageListener("LISTENER_ID") ``` -## Missed Message Edit Events +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| editedAt | `getEditedAt()` | `long` | Timestamp when the message was edited | +| editedBy | `getEditedBy()` | `String` | UID of the user who edited the message | -How do I know when someone edited their message while my app was not running? +## Missed Message Edit Events -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, if the total number of messages for a conversation is 100, and the message with message ID 50 was edited, the message with ID 50 will have the `editedAt` and the `editedBy` fields set whenever it is pulled from the history. Additionally, the 101st message will be an `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- diff --git a/sdk/android/error-codes.mdx b/sdk/android/error-codes.mdx new file mode 100644 index 000000000..ba925eb37 --- /dev/null +++ b/sdk/android/error-codes.mdx @@ -0,0 +1,274 @@ +--- +title: "Error Codes" +sidebarTitle: "Error Codes" +description: "Complete reference for CometChat Android SDK error codes, including client-side validation errors, server-side API errors, and how to handle them." +--- + + + + + +```kotlin +// All errors are CometChatException objects +CometChat.login(uid, authKey, object : CometChat.CallbackListener() { + override fun onSuccess(user: User?) { } + override fun onError(e: CometChatException?) { + Log.e(TAG, "Code: ${e?.code}") // e.g., "AUTH_ERR_AUTH_TOKEN_NOT_FOUND" + Log.e(TAG, "Message: ${e?.message}") // Human-readable description + Log.e(TAG, "Details: ${e?.details}") // Additional context (if available) + } +}) +``` + + +```java +CometChat.login(uid, authKey, new CometChat.CallbackListener() { + @Override + public void onSuccess(User user) { } + + @Override + public void onError(CometChatException e) { + Log.e(TAG, "Code: " + e.getCode()); // e.g., "AUTH_ERR_AUTH_TOKEN_NOT_FOUND" + Log.e(TAG, "Message: " + e.getMessage()); // Human-readable description + Log.e(TAG, "Details: " + e.getDetails()); // Additional context (if available) + } +}); +``` + + + +**Error categories:** Initialization, Login, Calling, Messages, Groups, Users, Conversations, Receipts, AI, Extensions + + +Every error returned by the CometChat Android SDK is a `CometChatException` object. Access its properties via getters in Java or properties in Kotlin: + +| Property | Type | Description | +|----------|------|-------------| +| `code` | `String` | Machine-readable error code | +| `message` | `String` | Human-readable description | +| `details` | `String` | Additional context or troubleshooting info | + + + +```kotlin +CometChat.login(authToken, object : CometChat.CallbackListener() { + override fun onSuccess(user: User?) { + // proceed + } + override fun onError(e: CometChatException?) { + when (e?.code) { + "AUTH_ERR_AUTH_TOKEN_NOT_FOUND" -> { + // Token is invalid or expired — prompt re-login + } + "MISSING_PARAMETERS" -> { + // A required parameter was not provided + } + else -> { + Log.e(TAG, "Unexpected error: ${e?.message}") + } + } + } +}) +``` + + +```java +CometChat.login(authToken, new CometChat.CallbackListener() { + @Override + public void onSuccess(User user) { + // proceed + } + + @Override + public void onError(CometChatException e) { + switch (e.getCode()) { + case "AUTH_ERR_AUTH_TOKEN_NOT_FOUND": + // Token is invalid or expired — prompt re-login + break; + case "MISSING_PARAMETERS": + // A required parameter was not provided + break; + default: + Log.e(TAG, "Unexpected error: " + e.getMessage()); + } + } +}); +``` + + + +## Initialization Errors + +| Code | Message | +|------|---------| +| `MISSING_PARAMETERS` | AppID cannot be empty. Please specify a valid appID. | + +## Login & Authentication Errors + +| Code | Message | +|------|---------| +| `COMETCHAT_INITIALIZATION_NOT_DONE` | Please initialize CometChat before using the login method. | +| `USER_NOT_AUTHORISED` | The authToken of the user is not authorised. Please verify again. | +| `AUTH_ERR_AUTH_TOKEN_NOT_FOUND` | The auth token does not exist. Please make sure you are logged in and have a valid auth token. | +| `LOGIN_IN_PROGRESS` | Please wait until the previous login request ends. | +| `WS_CONNECTION_FAIL` | WebSocket connection failed. | +| `WS_CONNECTION_FALLBACK_FAIL` | WebSocket connection fallback failed. | +| `WS_AUTH_FAIL` | WebSocket username/password not correct. | +| `NO_INTERNET_CONNECTION` | You do not have an internet connection. | +| `USER_NOT_LOGGED_IN` | Please log in to CometChat before calling this method. | + +## Calling Errors + +| Code | Message | +|------|---------| +| `CALL_ALREADY_INITIATED` | There is already a call in progress. | +| `CALL_IN_PROGRESS` | There is already a call in progress. | +| `NOT_INITIALIZED` | Please call CometChat.init() before calling any other methods. | +| `NOT_LOGGED_IN` | Please login before starting a call. | +| `SESSION_ID_REQUIRED` | Please make sure you are passing a correct session ID. | +| `CALL_SETTINGS_REQUIRED` | Please make sure you are passing the call settings object. | +| `JWT_NOT_FOUND` | There was an issue while fetching JWT from API. | + +## Message Errors + +| Code | Message | +|------|---------| +| `INVALID_RECEIVER_TYPE` | Receiver type can be `user` or `group`. | +| `REQUEST_IN_PROGRESS` | Request in progress. | +| `NOT_ENOUGH_PARAMETERS` | Timestamp, MessageId, or updatedAfter is required to use fetchNext(). | +| `INVALID_REASON_ID` | Invalid reasonId provided. | + +## User Errors + +| Code | Message | +|------|---------| +| `INVALID_STATUS_VALUE` | The status parameter accepts only `online` or `offline`. | +| `INVALID_DIRECTION_VALUE` | The direction parameter accepts only `both`, `blockedByMe`, or `hasBlockedMe`. | +| `EMPTY_USERS_LIST` | The users list needs to have at least one UID. | + +## Group Errors + +| Code | Message | +|------|---------| +| `NOT_A_GROUP` | Please use the Group class to construct a new group. | +| `INVALID_SCOPE_VALUE` | Scope can be `admin`, `moderator`, or `participant`. | +| `INVALID_GROUP_TYPE` | Group type can be `public`, `private`, `protected`, or `password`. | +| `ERR_EMPTY_GROUP_PASS` | Password is mandatory to join a group. | + +## Conversation Errors + +| Code | Message | +|------|---------| +| `INVALID_CONVERSATION_TYPE` | Conversation type can be `user` or `group`. | +| `CONVERSATION_NOT_FOUND` | Conversation not found. Check the value of conversationWith and conversationType. | + +## Receipt Errors + +| Code | Message | +|------|---------| +| `MISSING_PARAMETERS` | Expected 4 parameters, received 3. | +| `NO_WEBSOCKET_CONNECTION` | Connection to WebSocket server is broken. Please retry after some time. | +| `RECEIPTS_TEMPORARILY_BLOCKED` | Due to high load, receipts have been blocked for your app. | +| `UNKNOWN_ERROR_OCCURRED` | Unknown error occurred while marking a message as read. | + +## AI Feature Errors + +| Code | Message | +|------|---------| +| `NO_CONVERSATION_STARTER` | Unable to get conversation starter for this conversation. | +| `NO_SMART_REPLY` | Unable to get smart reply for this conversation. | +| `NO_CONVERSATION_SUMMARY` | Unable to get summary of the conversation. | +| `EMPTY_RESPONSE` | Unable to get a suggestion. | +| `ERROR_INVALID_AI_FEATURE` | The provided AI Feature cannot be null or empty. | + +## Extension Errors + +| Code | Message | +|------|---------| +| `ERROR_INVALID_EXTENSION` | The provided extension cannot be null or empty. | +| `ERROR_EXTENSION_NOT_FOUND` | The provided extension could not be found. | + +## Feature Restriction Errors + +| Code | Message | +|------|---------| +| `ERROR_INVALID_FEATURE` | The provided feature cannot be null or empty. | +| `ERROR_FEATURE_NOT_FOUND` | The provided feature could not be found. | + +## Network & API Errors + +| Code | Message | +|------|---------| +| `FAILED_TO_FETCH` | There is an unknown issue with the API request. Check your internet connection. | +| `TOO_MANY_REQUEST` | Too many requests. Wait before sending the next request. | +| `ERR_TOO_MANY_REQUESTS` | Rate limiting. See [Rate Limits](/sdk/android/rate-limits). | + +## Validation Errors + +These errors use dynamic codes based on the parameter name (e.g., `INVALID_UID`, `UID_IS_COMPULSORY`): + +| Pattern | Message | +|---------|---------| +| `INVALID_{param}` | The parameter should be a string / number / boolean / object / array. | +| `{param}_IS_COMPULSORY` | The parameter cannot be blank. Please provide a valid value. | +| `{param}_NOT_PROVIDED` | Please provide the required parameter. | +| `ERROR_{param}_EXCEEDED` | Limit exceeded max limit. | +| `INVALID_SEARCH_KEYWORD` | Invalid search keyword. Please provide a valid search keyword. | +| `MISSING_KEY` | The key is missing from the object. | + +## Prosody (WebSocket Server) Errors + +| Code | Message | +|------|---------| +| `ERROR_INVALID_SESSIONID` | The provided sessionId cannot be null or empty. | +| `ERROR_INVALID_TYPE` | The provided type cannot be null or empty. | +| `ERROR_INVALID_GROUPLIST` | Grouplist cannot be null or empty. | + +## General Errors + +| Code | Message | +|------|---------| +| `ERROR_IO_EXCEPTION` | I/O exception occurred. | +| `ERROR_JSON_EXCEPTION` | JSON parsing exception. | +| `ERROR_PASSWORD_MISSING` | Password is mandatory for a password group. | +| `ERROR_LIMIT_EXCEEDED` | Limit exceeded max limit. | +| `ERROR_INVALID_GUID` | Please provide a valid GUID. | +| `ERR_SETTINGS_HASH_OUTDATED` | Settings hash is outdated. | +| `ERR_NO_AUTH` | No authentication credentials found. | + +## Server-Side API Errors + +For REST API error codes (returned by the CometChat backend), see the [Error Guide](/articles/error-guide). Common server-side errors you may encounter in SDK responses: + +| Code | Description | +|------|-------------| +| `AUTH_ERR_EMPTY_APPID` | Empty App ID in headers | +| `AUTH_ERR_INVALID_APPID` | Invalid App ID or does not exist in region | +| `ERR_UID_NOT_FOUND` | User does not exist or is soft deleted | +| `ERR_GUID_NOT_FOUND` | Group does not exist | +| `ERR_NOT_A_MEMBER` | User is not a member of the group | +| `ERR_ALREADY_JOINED` | User has already joined the group | +| `ERR_MESSAGE_ID_NOT_FOUND` | Message does not exist | +| `ERR_PLAN_RESTRICTION` | Feature not available with current plan | +| `ERR_TOO_MANY_REQUESTS` | Rate limit exceeded | + +See the full list in the [Error Guide](/articles/error-guide). + +--- + +## Next Steps + + + + Common issues and solutions + + + Understand and handle rate limits + + + Complete server-side error code reference + + + Recommended patterns for error handling + + diff --git a/sdk/android/flag-message.mdx b/sdk/android/flag-message.mdx index 9a123624c..18e84ef0f 100644 --- a/sdk/android/flag-message.mdx +++ b/sdk/android/flag-message.mdx @@ -31,10 +31,6 @@ CometChat.flagMessage(messageId, flagDetail, object : CometChat.CallbackListener 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](https://app.cometchat.com) - - For a complete understanding of how flagged messages are reviewed and managed, see the [Flagged Messages](/moderation/flagged-messages) documentation. diff --git a/sdk/android/group-add-members.mdx b/sdk/android/group-add-members.mdx index 36c75b5dc..244c4a5e4 100644 --- a/sdk/android/group-add-members.mdx +++ b/sdk/android/group-add-members.mdx @@ -1,5 +1,5 @@ --- -title: "Add Members To A Group" +title: "Add Members" sidebarTitle: "Add Members" description: "Add members to groups with specific roles using the Android SDK" --- @@ -23,18 +23,9 @@ CometChat.addMembersToGroup("GUID", members, null, **Note:** Only admins and moderators can add members. The result HashMap contains UID as key and "success" or error message as value. - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) - - ## Add Members to Group -You can add members to the group using the `addMembersToGroup()` method. This method takes the below parameters: - -1. `GUID` - GUID of the group users are to be added to. -2. `List 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. `List bannedMembers` - This is the list of `UIDs` that need to be banned from the group. This can be set to `null` if there are no members to be banned. -4. Callback +Use `addMembersToGroup()` with the group GUID, a list of `GroupMember` objects, and an optional list of UIDs to ban. @@ -83,18 +74,12 @@ In the `onSuccess()` method of the `CallbackListener`, you will receive a HashMa ## Real-Time Group Member Added Events -How do I know when someone is added to the group while my app is running? +When a member is added to a group, existing members receive a real-time event in `onMemberAddedToGroup()` of the `GroupListener` class. - -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. - +When a member is added by another user, `onMemberAddedToGroup()` fires. When a user joins on their own, `onGroupMemberJoined()` fires instead. -To receive real-time events whenever a new member is added to a group, implement the `onMemberAddedToGroup()` method of the `GroupListener` class. - -* `onMemberAddedToGroup()` - This method is triggered when any user is added to the group, informing the logged-in user of the other members added to the group. - ```java @@ -123,11 +108,7 @@ CometChat.addGroupListener("UNIQUE_ID", object : CometChat.GroupListener() { ## Member Added to Group event in Message History -How do I know when someone is added to the group while 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 the `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 message history, if a member was added to a group the logged-in user is part of, the list will contain an `Action` message with these fields: 1. `action` - `added` 2. `actionOn` - User object containing the details of the user who was added to the group diff --git a/sdk/android/group-change-member-scope.mdx b/sdk/android/group-change-member-scope.mdx index efcd38245..057bc3443 100644 --- a/sdk/android/group-change-member-scope.mdx +++ b/sdk/android/group-change-member-scope.mdx @@ -26,13 +26,9 @@ CometChat.updateGroupMemberScope( **Note:** Only group admins can change member scopes. - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) - - ## Change Scope of a Group Member -To change the scope of a group member, use the `changeGroupMemberScope()` method. +Use `updateGroupMemberScope()` to change a member's role. Only group **Admins** can change scopes. @@ -89,9 +85,7 @@ The default scope of any member is `participant`. Only the **Admin** of the grou ## Real-Time Group Member Scope Changed Events -How do I know when someone's scope is changed while my app is running? - -To receive real-time events whenever a group member's scope changes, override the `onGroupMemberScopeChanged()` method of the `GroupListener` class. +When a member's scope changes, group members receive a real-time event in `onGroupMemberScopeChanged()` of the `GroupListener` class. @@ -121,11 +115,7 @@ CometChat.addGroupListener("ListenerID", object : CometChat.GroupListener() { ## Missed Group Member Scope Changed Events -How do I know when someone's scope is changed while 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 the `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 message history, scope changes appear as `Action` messages with these fields: 1. `action` - `scopeChanged` 2. `actionOn` - User object containing the details of the user whos scope has been changed diff --git a/sdk/android/group-kick-member.mdx b/sdk/android/group-kick-member.mdx index 9e2f1290a..ab68edbdc 100644 --- a/sdk/android/group-kick-member.mdx +++ b/sdk/android/group-kick-member.mdx @@ -1,5 +1,5 @@ --- -title: "Ban/Kick Member From A Group" +title: "Kick/Ban Member" sidebarTitle: "Kick Member" description: "Kick, ban, and unban group members using the Android SDK" --- @@ -23,18 +23,7 @@ CometChat.unbanGroupMember("UID", "GUID", callback) **Note:** Only admins and moderators can kick, ban, or unban members. - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) - - -There are certain actions that can be performed on the group members: - -1. Kick a member from the group -2. Ban a member from the group -3. Unban a member from the group -4. Update the scope of the member of the group - -All of the above actions can only be performed by the **Admin** or the **Moderator** of the group. +Admins and moderators can kick, ban, or unban group members. Kicked users can rejoin; banned users cannot until unbanned. ## Kick a Group Member @@ -194,15 +183,11 @@ The unbanned user can now rejoin the group. ## Get List of Banned Members for a Group -To fetch the list of banned group members for a group, use the `BannedGroupMembersRequest` class. 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 fetched. - -The `BannedGroupMembersRequestBuilder` class allows you to set the following 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 `BannedGroupMembersRequestBuilder` with the group GUID to fetch banned members. ### Set Limit -This method sets the limit i.e. the number of banned members that should be fetched in a single iteration. +Set the number of banned members to fetch per request. @@ -227,7 +212,7 @@ val bannedGroupMembersRequest = BannedGroupMembersRequestBuilder(GUID) ### Set Search Keyword -This method allows you to set the search string based on which the banned group members are to be fetched. +Filter banned members by a search string. @@ -250,9 +235,9 @@ val bannedGroupMembersRequest = BannedGroupMembersRequestBuilder(GUID) -Finally, once all the parameters are set on the builder class, call the `build()` method to get the object of the `BannedGroupMembersRequest` class. +### Fetch Banned Members -Once you have the object of the `BannedGroupMembersRequest` class, call the `fetchNext()` method. This method returns a list of `GroupMember` objects containing n number of banned members where n is the limit set in the builder class. +After configuring the builder, call `build()` then `fetchNext()` to retrieve banned members. @@ -301,13 +286,7 @@ bannedGroupMembersRequest?.fetchNext(object :CometChat.CallbackListener @@ -350,11 +329,7 @@ CometChat.addGroupListener(MainActivity::class.java.simpleName, object : GroupLi ## Missed Group Member Kicked/Banned Events -How do I know when someone is banned or kicked while 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 the `BaseMessage` class. - -For group member kicked event, the details can be obtained using the below fields of the `Action` class- +When fetching message history, kick/ban/unban actions appear as `Action` messages with these fields: 1. `action` - `kicked` 2. `actionBy` - User object containing the details of the user who has kicked the member diff --git a/sdk/android/groups-overview.mdx b/sdk/android/groups-overview.mdx index bb693358c..ff74d1727 100644 --- a/sdk/android/groups-overview.mdx +++ b/sdk/android/groups-overview.mdx @@ -13,13 +13,23 @@ Choose your path: - **Manage Members** → [group-add-members](/sdk/android/group-add-members) - Add, remove, update members -Groups help your users converse together in a single space. You can have three types of groups: private, public, and password protected. - - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) - - -Each group includes three kinds of users: admin, moderator, and member. +Groups let your users converse together in a single space. CometChat supports three group types — public, private, and password-protected — with three member roles: admin, moderator, and participant. + +## Features + +| Feature | Description | Guide | +| --- | --- | --- | +| Create Group | Create public, private, or password-protected groups | [Create Group](/sdk/android/create-group) | +| Retrieve Groups | Fetch groups list with filters and search | [Retrieve Groups](/sdk/android/retrieve-groups) | +| Join Group | Join groups to participate in conversations | [Join Group](/sdk/android/join-group) | +| Leave Group | Leave groups to stop receiving updates | [Leave Group](/sdk/android/leave-group) | +| Delete Group | Permanently delete groups (admin only) | [Delete Group](/sdk/android/delete-group) | +| Update Group | Modify group details and settings | [Update Group](/sdk/android/update-group) | +| Retrieve Members | Fetch group members with filters | [Retrieve Members](/sdk/android/retrieve-group-members) | +| Add Members | Add users to groups with specific roles | [Add Members](/sdk/android/group-add-members) | +| Kick/Ban Members | Remove or ban members from groups | [Kick Member](/sdk/android/group-kick-member) | +| Change Scope | Update member roles and permissions | [Change Scope](/sdk/android/group-change-member-scope) | +| Transfer Ownership | Transfer group ownership to another member | [Transfer Ownership](/sdk/android/transfer-group-ownership) | --- diff --git a/sdk/android/interactive-messages.mdx b/sdk/android/interactive-messages.mdx index 24767f30b..f54a7b14e 100644 --- a/sdk/android/interactive-messages.mdx +++ b/sdk/android/interactive-messages.mdx @@ -30,13 +30,9 @@ CometChat.markAsInteracted(messageId, "elementId", callback) ``` - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) - - 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. This enhances user engagement by making the chat experience more interactive and responsive to user input. -### InteractiveMessage +## InteractiveMessage `InteractiveMessage` is a chat message with embedded interactive content. It can contain various properties: @@ -49,14 +45,14 @@ An `InteractiveMessage` is a specialized object that encapsulates an interactive | `allowSenderInteraction` | A boolean determining whether the message sender can interact with the message. Default is set to false. | | | `interactionGoal` | An `InteractionGoal` object encapsulating the intended outcome of interacting with the `InteractiveMessage`. Default is set to none. | | -### Interaction +## Interaction An Interaction represents a user action involved with an `InteractiveMessage`. It includes: * `elementId`: An identifier for a specific interactive element. * `interactedAt`: A timestamp indicating when the interaction occurred. -### Mark as Interacted +## Mark as Interacted This method marks a message as interacted by identifying it with the provided Id. it also logs the interactive element associated with the interaction. @@ -96,7 +92,7 @@ CometChat.markAsInteracted(messageId, elementId, new CometChat.CallbackListener< -### Goal Completion +## Goal Completion A key feature of `InteractiveMessage` is checking whether a user's interactions with the message meet the defined `InteractionGoal` @@ -109,14 +105,14 @@ You would be tracking every interaction users perform on an `InteractiveMessage` | 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 | -### InteractionGoal +## InteractionGoal The `InteractionGoal` represents the desired outcome of an interaction with an InteractiveMessage. It includes: * `elementIds`: A list of identifiers for the interactive elements. * `type`: The type of interaction goal from the `CometChatConstants`. -### Sending InteractiveMessages +## Send an Interactive Message 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. @@ -211,7 +207,7 @@ CometChat.sendInteractiveMessage(interactiveMessage, new CometChat.CallbackListe -### Event Listeners +## Real-time Events CometChat SDK provides event listeners to handle real-time events related to `InteractiveMessage`. For more details on listener management, see [Real-Time Listeners](/sdk/android/real-time-listeners). @@ -247,7 +243,7 @@ CometChat.addMessageListener("UNIQUE_ID", new CometChat.MessageListener() { Always remove listeners when they're no longer needed (e.g., in `onDestroy()` or when navigating away). Failing to remove listeners can cause memory leaks and duplicate event handling. -### On Interaction Goal Completed +## On Interaction Goal Completed The `onInteractionGoalCompleted` event listener is invoked when an interaction goal is achieved. @@ -279,10 +275,6 @@ CometChat.addMessageListener("UNIQUE_ID", new CometChat.MessageListener() { 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. -## 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. - ## InteractiveMessage Payload Structure diff --git a/sdk/android/join-group.mdx b/sdk/android/join-group.mdx index 7b739f24c..91734f86d 100644 --- a/sdk/android/join-group.mdx +++ b/sdk/android/join-group.mdx @@ -1,5 +1,5 @@ --- -title: "Join A Group" +title: "Join Group" sidebarTitle: "Join Group" description: "Join public, private, and password-protected groups using the Android SDK" --- @@ -19,13 +19,9 @@ CometChat.joinGroup("GUID", CometChatConstants.GROUP_TYPE_PASSWORD, "password123 ``` - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) - - ## Join a Group -To start participating in group conversations, you need to join a group. You can do so using the `joinGroup()` method. +Use `joinGroup()` to start participating in a group conversation. @@ -85,9 +81,7 @@ You can identify if a group is joined using the `hasJoined` parameter in the `Gr ## Real-Time Group Member Joined Events -*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. +When a user joins a group, members receive a real-time event in `onGroupMemberJoined()` of the `GroupListener` class. @@ -117,11 +111,7 @@ CometChat.addGroupListener(UNIQUE_LISTENER_ID, object : GroupListener() { ## Missed Group Member Joined Events -*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 the `BaseMessage` class. - -For the group member joined event, in the `Action` object received, the following fields can help you get the relevant information: +When fetching message history, if a member joined a group the logged-in user is part of, the list will contain an `Action` message with these fields: 1. `action` - `joined` 2. `actionBy` - User object containing the details of the user who joined the group diff --git a/sdk/android/key-concepts.mdx b/sdk/android/key-concepts.mdx index 04c575f4e..740a3a871 100644 --- a/sdk/android/key-concepts.mdx +++ b/sdk/android/key-concepts.mdx @@ -27,7 +27,7 @@ description: "Understand core CometChat concepts including users, groups, authen **Connection Modes:** Auto (WebSocket in foreground only) | Manual (explicit connect/disconnect) -### CometChat Dashboard +## CometChat Dashboard The CometChat Dashboard enables you to create new apps (projects) and manage your existing apps. @@ -43,7 +43,7 @@ Do not create separate apps for every platform. If you do, your users on differe * 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 need to create an Auth Key (from the Dashboard) which can be used for user authentication. -### Auth & Rest API Keys +## Auth & Rest API Keys You can generate two types of keys from the dashboard. @@ -52,11 +52,11 @@ You can generate two types of keys from the dashboard. | 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 | -### Users +## Users A user is anyone who uses CometChat. -### UID +## UID * Each user is uniquely identified using UID. * The UID is typically the primary ID of the user from your database. @@ -67,13 +67,13 @@ UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and othe -### Auth Token +## Auth Token * A single user can have multiple auth tokens. Auth tokens should be per user per device. * Auth tokens should ideally be generated via a server-to-server API call. The auth token should then be passed to CometChat for login. * An Auth Token can only be deleted via the dashboard or using the REST API. -### Authentication +## Authentication To allow a user to use CometChat, the user must log in to CometChat. @@ -81,7 +81,7 @@ To allow a user to use CometChat, the user must log in to CometChat. **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), you can associate them as friends in CometChat. -### Typical Workflow +## Typical Workflow | Your App | Your Server | CometChat | | ----------------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | @@ -90,20 +90,20 @@ To allow a user to use CometChat, the user must log in to CometChat. | 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 | -### User Roles +## User Roles 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 +## 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 +## Groups A group can be used for multiple users to communicate with each other on a particular topic/interest. -### GUID +## 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. @@ -114,7 +114,7 @@ GUID can be alphanumeric with underscore and hyphen. Spaces, punctuation and oth -### Types +## Group Types CometChat supports three different types of groups: @@ -124,10 +124,12 @@ CometChat supports three different types of groups: | 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 | -### Members +## Members 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: | Member | Default | Privileges | @@ -136,18 +138,20 @@ CometChat supports three different types of member scopes in a 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 | -### Messaging +## Messaging + +Any message in CometChat can belong to either one of the below categories. -Any message in CometChat can belong to either one of the below categories +## Message 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 sent to users/groups that does not fit default categories (e.g., location, polls) | +| `action` | `groupMember`, `message` | System-generated messages when an action is performed on a group member or a message | +| `call` | `audio`, `video` | Call-related messages | -### Auto Mode Connection +## Auto Mode Connection @@ -160,7 +164,7 @@ Know more about auto mode connection [click here](/sdk/android/connection-behavi | App in foreground | Connected with WebSocket | | App in background | Immediately disconnected with WebSocket | -### Manual Mode Connection +## Manual Mode Connection @@ -173,6 +177,26 @@ Know more about manual mode connection [click here](/sdk/android/connection-beha | App in foreground | Call `CometChat.connect()` to create the WebSocket connection | | App in background | Disconnect the WebSocket connection if no ping is received within 30 seconds after the app goes in the background. | +## Glossary + +| Term | Definition | Learn More | +| ---- | ---------- | ---------- | +| UID | Unique User Identifier — alphanumeric string you assign to each user | [Users Overview](/sdk/android/users-overview) | +| GUID | Group Unique Identifier — alphanumeric string you assign to each group | [Groups Overview](/sdk/android/groups-overview) | +| Auth Key | Development-only credential for quick testing. Never use in production | [Authentication](/sdk/android/authentication-overview) | +| Auth Token | Secure, per-user token generated via REST API. Use in production | [Authentication](/sdk/android/authentication-overview) | +| 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/android/send-message) | +| Scope | Group member scope: `admin`, `moderator`, or `participant` | [Change Member Scope](/sdk/android/change-member-scope) | +| Listener | Callback handler for real-time events (messages, presence, calls, groups) | [All Real-Time Listeners](/sdk/android/all-real-time-listeners) | +| Conversation | A chat thread between two users or within a group | [Retrieve Conversations](/sdk/android/retrieve-conversations) | +| Metadata | Custom JSON data attached to users, groups, or messages | [Send Message](/sdk/android/send-message) | +| Tags | String labels for categorizing users, groups, conversations, or messages | [Message Filtering](/sdk/android/message-filtering) | +| RequestBuilder | Builder pattern class for constructing filtered/paginated queries | [Message Filtering](/sdk/android/message-filtering) | +| AppSettings | Configuration object for initializing the SDK (App ID, Region, presence) | [Setup SDK](/sdk/android/setup) | +| Transient Message | Ephemeral message not stored on server (typing indicators, live reactions) | [Transient Messages](/sdk/android/transient-messages) | +| Interactive Message | Message with actionable UI elements (forms, cards, buttons) | [Interactive Messages](/sdk/android/interactive-messages) | + --- ## Next Steps diff --git a/sdk/android/leave-group.mdx b/sdk/android/leave-group.mdx index 73233cfd3..559410a35 100644 --- a/sdk/android/leave-group.mdx +++ b/sdk/android/leave-group.mdx @@ -1,5 +1,5 @@ --- -title: "Leave A Group" +title: "Leave Group" sidebarTitle: "Leave Group" description: "Leave groups to stop receiving messages and updates using the Android SDK" --- @@ -20,13 +20,9 @@ CometChat.addGroupListener("LISTENER_ID", object : GroupListener() { ``` - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) - - ## Leave a Group -To stop receiving updates and messages for any particular joined group, you need to leave the group using the `leaveGroup()` method. +Use `leaveGroup()` to stop receiving updates and messages for a group. @@ -75,9 +71,7 @@ Once a group is left, the user will no longer receive any updates or messages pe ## Real-Time Group Member Left Events -*As a member of a group, how do I know if someone has left it when my app is running?* - -If a user leaves a group, the members of the group receive a real-time event in the `onGroupMemberLeft()` method of the `GroupListener` class. +When a user leaves a group, members receive a real-time event in `onGroupMemberLeft()` of the `GroupListener` class. @@ -107,11 +101,7 @@ CometChat.addGroupListener(UNIQUE_LISTENER_ID, object : GroupListener() { ## Missed Group Member Left Events -*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 the `BaseMessage` class. - -For the group member left event, in the `Action` object received, the following fields can help you get the relevant information: +When fetching message history, if a member left a group the logged-in user is part of, the list will contain an `Action` message with these fields: 1. `action` - `left` 2. `actionBy` - User object containing the details of the user who left the group diff --git a/sdk/android/login-listeners.mdx b/sdk/android/login-listeners.mdx index 35944e747..4804ebe5d 100644 --- a/sdk/android/login-listeners.mdx +++ b/sdk/android/login-listeners.mdx @@ -84,7 +84,92 @@ CometChat.addLoginListener("UNIQUE_ID", object : LoginListener() { -In order to stop receiving events related to login and logout you need to use the `removeLoginListener()` method provided by the SDK and pas the ID of the listener that needs to be removed. +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. + +### Android Activity/Fragment Example + +Register the listener in `onCreate()` and remove it in `onDestroy()` to follow the Android lifecycle: + + + +```java +public class MainActivity extends AppCompatActivity { + + private static final String LISTENER_ID = "LOGIN_LISTENER"; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + CometChat.addLoginListener(LISTENER_ID, new CometChat.LoginListener() { + @Override + public void loginSuccess(User user) { + Log.d("LoginListener", "loginSuccess: " + user.getName()); + // Initialize user-specific data, navigate to main screen, etc. + } + + @Override + public void loginFailure(CometChatException e) { + Log.d("LoginListener", "loginFailure: " + e.getMessage()); + } + + @Override + public void logoutSuccess() { + Log.d("LoginListener", "logoutSuccess"); + // Clean up resources, navigate to login screen, etc. + } + + @Override + public void logoutFailure(CometChatException e) { + Log.d("LoginListener", "logoutFailure: " + e.getMessage()); + } + }); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + CometChat.removeLoginListener(LISTENER_ID); + } +} +``` + + +```kotlin +class MainActivity : AppCompatActivity() { + + private val LISTENER_ID = "LOGIN_LISTENER" + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + CometChat.addLoginListener(LISTENER_ID, object : LoginListener() { + override fun loginSuccess(user: User) { + Log.d("LoginListener", "loginSuccess: ${user.name}") + // Initialize user-specific data, navigate to main screen, etc. + } + + override fun loginFailure(e: CometChatException) { + Log.d("LoginListener", "loginFailure: ${e.message}") + } + + override fun logoutSuccess() { + Log.d("LoginListener", "logoutSuccess") + // Clean up resources, navigate to login screen, etc. + } + + override fun logoutFailure(e: CometChatException) { + Log.d("LoginListener", "logoutFailure: ${e.message}") + } + }) + } + + override fun onDestroy() { + super.onDestroy() + CometChat.removeLoginListener(LISTENER_ID) + } +} +``` + + diff --git a/sdk/android/mentions.mdx b/sdk/android/mentions.mdx index 802b32666..01b4a9bb9 100644 --- a/sdk/android/mentions.mdx +++ b/sdk/android/mentions.mdx @@ -22,21 +22,11 @@ val mentionedUsers = message.mentionedUsers ``` - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) - - -## Mentions - -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. - -Mentions in messages enable users to refer to specific individuals within a conversation. +Mentions let users refer to specific individuals in a conversation using the `<@uid:UID>` format. They're especially useful in group chats for directing messages at particular participants. ## Send Mentioned Messages -Every User object has a String unique identifier associated with them which can be found in a property called uid. To mention a user in a message, the message text should contain the uid in following format:` <@uid:UID_OF_THE_USER>`. For example, to mention the user with UID cometchat-uid-1 in a text message, your text should be `"<@uid:cometchat-uid-1>"` - -Before sending messages with mentions, ensure you have [initialized the SDK](/sdk/android/setup) and [logged in a user](/sdk/android/authentication-overview). +To mention a user, embed `<@uid:UID>` in your message text. For example: `"Hello <@uid:cometchat-uid-1>"` @@ -390,9 +380,9 @@ messagesRequest.fetchPrevious(new CometChat.CallbackListener>( -## Get Users Mentioned In a Particular Message +## Get Mentioned Users from a Message -To retrieve the list of users mentioned in the particular message, you can use the `message.getMentionedUsers()` method. This method will return an array containing the mentioned users, or an empty array if no users were mentioned in the message. +Use `getMentionedUsers()` on any message object to retrieve the list of users mentioned in it. Returns an empty list if no users were mentioned. diff --git a/sdk/android/message-structure-and-hierarchy.mdx b/sdk/android/message-structure-and-hierarchy.mdx index 19cc9c56d..9abac689e 100644 --- a/sdk/android/message-structure-and-hierarchy.mdx +++ b/sdk/android/message-structure-and-hierarchy.mdx @@ -1,5 +1,5 @@ --- -title: "Message Structure And Hierarchy" +title: "Message Structure and Hierarchy" sidebarTitle: "Message Structure" description: "Understand message categories, types, and hierarchy in the CometChat Android SDK" --- @@ -24,87 +24,126 @@ when (message.category) { ``` -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 within that category. Understanding this hierarchy helps you handle different message types correctly. + +## Message Hierarchy -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. +## 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 | + +## Checking Message Category and Type + +Use `getCategory()` and `getType()` to determine how to handle a received message: + + + +```java +String category = message.getCategory(); +String type = message.getType(); + +switch (category) { + case CometChatConstants.CATEGORY_MESSAGE: + if (type.equals(CometChatConstants.MESSAGE_TYPE_TEXT)) { + TextMessage textMsg = (TextMessage) message; + Log.d(TAG, "Text: " + textMsg.getText()); + } else if (type.equals(CometChatConstants.MESSAGE_TYPE_IMAGE)) { + MediaMessage mediaMsg = (MediaMessage) message; + Log.d(TAG, "Image URL: " + mediaMsg.getAttachment().getFileUrl()); + } + break; + case CometChatConstants.CATEGORY_CUSTOM: + CustomMessage customMsg = (CustomMessage) message; + Log.d(TAG, "Custom type: " + type + ", data: " + customMsg.getCustomData()); + break; + case CometChatConstants.CATEGORY_ACTION: + Action actionMsg = (Action) message; + Log.d(TAG, "Action: " + actionMsg.getAction()); + break; + case CometChatConstants.CATEGORY_CALL: + Call callMsg = (Call) message; + Log.d(TAG, "Call status: " + callMsg.getCallStatus()); + break; +} +``` + + +```kotlin +val category = message.category +val type = message.type + +when (category) { + CometChatConstants.CATEGORY_MESSAGE -> { + if (type == CometChatConstants.MESSAGE_TYPE_TEXT) { + val textMsg = message as TextMessage + Log.d(TAG, "Text: ${textMsg.text}") + } else if (type == CometChatConstants.MESSAGE_TYPE_IMAGE) { + val mediaMsg = message as MediaMessage + Log.d(TAG, "Image URL: ${mediaMsg.attachment?.fileUrl}") + } + } + CometChatConstants.CATEGORY_CUSTOM -> { + val customMsg = message as CustomMessage + Log.d(TAG, "Custom type: $type, data: ${customMsg.customData}") + } + CometChatConstants.CATEGORY_ACTION -> { + val actionMsg = message as Action + Log.d(TAG, "Action: ${actionMsg.action}") + } + CometChatConstants.CATEGORY_CALL -> { + val callMsg = message as Call + Log.d(TAG, "Call status: ${callMsg.callStatus}") + } +} +``` + + ## Message -A message belonging to the category `message` can be classified into either 1 of the below types: - -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 +Standard user messages. Types: `text`, `image`, `video`, `audio`, `file`. ## Custom -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`. +Developer-defined messages for content that doesn't fit standard categories (e.g., location sharing, polls). Set your own `type` string to identify the 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. This enhances user engagement by making the chat experience more interactive and responsive to user input. +Messages with embedded UI elements users can interact with directly in chat. -1. form- for interactive form -2. card- for interactive card -3. customInteractive- for custom interaction messages +Types: `form`, `card`, `customInteractive`. - -to know about Interactive messages please [click here](/sdk/android/interactive-messages) - +See [Interactive Messages](/sdk/android/interactive-messages) for full details. ## Action -Action messages are system-generated messages. Messages belonging to the `action` category can further be classified into one of the below types: +System-generated messages triggered by actions on group members or messages. -1. groupMember - action performed on a group member. -2. message - action performed on a message. +Types: `groupMember`, `message`. -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: +The `action` property specifies what happened: -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. +**For `groupMember`:** `joined`, `left`, `kicked`, `banned`, `unbanned`, `added`, `scopeChanged` -For the type `message`, the action can be either one of the below: - -1. edited - when a message is edited. -2. deleted - when a message is deleted. +**For `message`:** `edited`, `deleted` ## Call -Messages with the category `call` are Calling related messages. These can belong to either one of the 2 types - -1. audio -2. video - -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: +Call-related messages. Types: `audio`, `video`. -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. +The `status` property indicates the call state: `initiated`, `ongoing`, `canceled`, `rejected`, `unanswered`, `busy`, `ended`. ## Best Practices diff --git a/sdk/android/messaging-overview.mdx b/sdk/android/messaging-overview.mdx index 8368261bd..4923d2c82 100644 --- a/sdk/android/messaging-overview.mdx +++ b/sdk/android/messaging-overview.mdx @@ -6,24 +6,60 @@ description: "Send, receive, and manage messages with CometChat's Android SDK me -Choose your messaging path: -- **Send Messages** → [send-message](/sdk/android/send-message) - Text, media, and custom messages -- **Receive Messages** → [receive-messages](/sdk/android/receive-messages) - Real-time message handling -- **Edit Messages** → [edit-message](/sdk/android/edit-message) - Modify sent messages -- **Delete Messages** → [delete-message](/sdk/android/delete-message) - Remove messages -- **Threaded Messages** → [threaded-messages](/sdk/android/threaded-messages) - Organize conversations -- **Reactions** → [reactions](/sdk/android/reactions) - Add emoji reactions -- **Mentions** → [mentions](/sdk/android/mentions) - Tag users in messages -- **Interactive Messages** → [interactive-messages](/sdk/android/interactive-messages) - Buttons and forms +```kotlin +// Send a text message +val textMessage = TextMessage("UID", "Hello!", CometChatConstants.RECEIVER_TYPE_USER) +CometChat.sendMessage(textMessage, callback) + +// Register a message listener +CometChat.addMessageListener("LISTENER_ID", object : CometChat.MessageListener() { + override fun onTextMessageReceived(message: TextMessage) { } + override fun onMediaMessageReceived(message: MediaMessage) { } + override fun onCustomMessageReceived(message: CustomMessage) { } +}) + +// Remove listener +CometChat.removeMessageListener("LISTENER_ID") +``` + +Key paths: +- **Send** → Text, media, custom messages +- **Receive** → Real-time listeners +- **Advanced** → Threads, reactions, mentions, interactive messages +Messaging is one of the core features of CometChat. The SDK provides methods to send, receive, edit, delete, and fetch message history for both one-on-one and group conversations. + +At minimum, implement [sending messages](/sdk/android/send-message) and [receiving messages](/sdk/android/receive-messages). Once those are working, layer in advanced features as needed. + +## Features + +| Feature | Description | Guide | +| --- | --- | --- | +| Send Messages | Send text, media, and custom messages to users and groups | [Send Message](/sdk/android/send-message) | +| Receive Messages | Listen for real-time incoming messages using `MessageListener` | [Receive Messages](/sdk/android/receive-messages) | +| Edit Message | Modify a sent message after delivery | [Edit Message](/sdk/android/edit-message) | +| Delete Message | Remove a message from a conversation | [Delete Message](/sdk/android/delete-message) | +| Threaded Messages | Reply to a specific message to create a thread | [Threaded Messages](/sdk/android/threaded-messages) | +| Typing Indicators | Show when a user is actively typing | [Typing Indicators](/sdk/android/typing-indicators) | +| Delivery & Read Receipts | Track when messages are delivered and read | [Delivery & Read Receipts](/sdk/android/delivery-read-receipts) | +| Reactions | Add emoji reactions to any message | [Reactions](/sdk/android/reactions) | +| Mentions | Tag users in group conversations with `@` | [Mentions](/sdk/android/mentions) | +| Transient Messages | Send ephemeral messages not stored on the server | [Transient Messages](/sdk/android/transient-messages) | +| Interactive Messages | Send messages with embedded forms, cards, and buttons | [Interactive Messages](/sdk/android/interactive-messages) | +| Message Filtering | Fetch messages with filters by type, category, and more | [Message Filtering](/sdk/android/additional-message-filtering) | +## Message Types -Messaging is one of the core features of CometChat. We've created methods to help you send, receive, and fetch message history. +CometChat supports three message types out of the box: -At minimum, you must add code for [sending messages](/sdk/android/send-message) and [receiving messages](/sdk/android/receive-messages). +| Type | Class | Use Case | +| --- | --- | --- | +| Text | `TextMessage` | Plain text chat | +| Media | `MediaMessage` | Images, videos, audio, files | +| Custom | `CustomMessage` | Location, polls, or any JSON data | -Once you've implemented that, you can proceed to more advanced features like [typing indicators](/sdk/android/typing-indicators) and [delivery & read receipts](/sdk/android/delivery-read-receipts). +For a full breakdown of message categories and hierarchy, see [Message Structure](/sdk/android/message-structure-and-hierarchy). --- @@ -36,11 +72,11 @@ Once you've implemented that, you can proceed to more advanced features like [ty Handle real-time incoming messages with listeners - - Modify sent messages after delivery + + Understand message categories, types, and hierarchy - - Remove messages from conversations + + Show real-time typing status in conversations Create organized conversation threads diff --git a/sdk/android/overview.mdx b/sdk/android/overview.mdx index b9c769133..93d1c075f 100644 --- a/sdk/android/overview.mdx +++ b/sdk/android/overview.mdx @@ -35,6 +35,15 @@ CometChat.login("UID", "AUTH_KEY", callback) // Dev only This guide demonstrates how to add chat to an Android application. Before you begin, we strongly recommend reading the [Key Concepts](/sdk/android/key-concepts) guide. +## Requirements + +| Requirement | Minimum Version | +| --- | --- | +| Android API Level | 21 | +| Android API Level (with Calls SDK) | 24 | +| Java | 8 | +| AndroidX | Required | + ## Getting Started @@ -101,6 +110,9 @@ Refer to the [Android UI Kit](/ui-kit/android/overview) for pre-built, customiza Migration guide for V3 users + + Steps to publish your Android app + --- diff --git a/sdk/android/presenter-mode.mdx b/sdk/android/presenter-mode.mdx index 262e2589f..90ef33505 100644 --- a/sdk/android/presenter-mode.mdx +++ b/sdk/android/presenter-mode.mdx @@ -26,41 +26,18 @@ CometChatCalls.joinPresentation(callToken, presenterSettings, videoContainer, ob -## Overview +Presenter Mode enables broadcast-style calling — up to 5 presenters share content with passive viewers (up to 100 total participants). Use it for webinars, keynotes, all-hands meetings, online classes, or talk shows. -The Presenter Mode feature allows developers to create a calling service experience in which: +| 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 | -1. There are one or more users who are presenting their video, audio, and/or screen (maximum 5) -2. Viewers 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. are enabled only for the Presenter in this mode -5. Other call participants do not get these features, so they act like passive viewers in the call - -Using this feature, developers can create experiences such as: - -1. All hands calls -2. Keynote speeches -3. Webinars -4. Talk shows -5. Online classes and many more - -## About This Guide - -This guide demonstrates how to start a presentation in an Android application. Before you begin, we strongly recommend you read the calling setup guide. - -Before starting a call session, you need to generate a call token. You need to call this method for the call token. +Before starting a presentation, generate a call token using `generateToken()` as described in [Call Session](/sdk/android/direct-calling#generate-call-token). ## Start Presentation Session -The most important class used in the implementation is the `PresentationSettings` class. This class allows you to set the various parameters for Presenter Mode. To set the various parameters of the `PresentationSettings` class, use the `PresentationSettingsBuilder` class. Below are the various options available with the `PresentationSettings` class. - -The `PresentationSettingsBuilder` class takes 1 mandatory parameter as part of the constructor: - -1. Context of the application - -You also need to set the User Type. There are 2 types of users in Presenter Mode: `Presenter` and `Participant`. You can set this in `PresentationSettingsBuilder` by using the method `isPresenter(true/false)`. - -Here is a basic example of how to start a Presentation: +Configure the presentation using `PresentationSettingsBuilder`. Set `setIsPresenter(true)` for presenters or `setIsPresenter(false)` for viewers. diff --git a/sdk/android/rate-limits.mdx b/sdk/android/rate-limits.mdx index 6172b69ae..8a0484814 100644 --- a/sdk/android/rate-limits.mdx +++ b/sdk/android/rate-limits.mdx @@ -19,17 +19,21 @@ description: "Understand CometChat REST API rate limits and how to handle rate l -### CometChat REST API Rate Limits +CometChat applies rate limits to REST API requests to ensure fair usage and platform stability. Understanding them helps you build applications that handle high traffic gracefully. + +## Rate Limit Tiers + +| 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 | -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 login a user, add a user to a group, remove a user from a group, etc., for a total of 100 requests per minute. +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. Rate limits can be adjusted on a per-need basis depending on your use case and plan. -1. **Core Operations:** Core operations are rate limited to `10,000` requests per minute. Core operations include user login, create/delete user, and 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 the Rate Limit Is Reached? The request isn't processed and a response is sent containing a 429 response code. Along with the response code, a couple of headers are sent that specify the time in seconds you must wait before you can try the request again. @@ -38,16 +42,74 @@ The request isn't processed and a response is sent containing a 429 response cod `X-Rate-Limit-Reset: 1625143246` -## Is There an Endpoint That Returns Rate Limits for 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) | + +## Rate Limit Endpoint + +CometChat does not provide a dedicated rate-limit endpoint. Use the response headers below to monitor your current limit and remaining requests: `X-Rate-Limit: 700` `X-Rate-Limit-Remaining: 699` +## Handling Rate Limits + +When you exceed the rate limit, CometChat returns HTTP `429 Too Many Requests`. Implement exponential backoff to handle this gracefully: + + + +```java +private void callWithRetry(Runnable apiCall, int maxRetries, int attempt) { + try { + apiCall.run(); + } catch (Exception e) { + if (e instanceof CometChatException && + ((CometChatException) e).getCode().equals("TOO_MANY_REQUEST") && + attempt < maxRetries) { + long waitTime = (long) Math.pow(2, attempt) * 1000; + Log.d(TAG, "Rate limited. Retrying in " + (waitTime / 1000) + "s..."); + new Handler(Looper.getMainLooper()).postDelayed( + () -> callWithRetry(apiCall, maxRetries, attempt + 1), + waitTime + ); + } else { + Log.e(TAG, "Max retries exceeded or non-rate-limit error: " + e.getMessage()); + } + } +} +``` + + +```kotlin +fun callWithRetry(apiCall: () -> Unit, maxRetries: Int = 3, attempt: Int = 0) { + try { + apiCall() + } catch (e: CometChatException) { + if (e.code == "TOO_MANY_REQUEST" && attempt < maxRetries) { + val waitTime = (2.0.pow(attempt) * 1000).toLong() + Log.d(TAG, "Rate limited. Retrying in ${waitTime / 1000}s...") + Handler(Looper.getMainLooper()).postDelayed( + { callWithRetry(apiCall, maxRetries, attempt + 1) }, + waitTime + ) + } else { + Log.e(TAG, "Max retries exceeded or non-rate-limit error: ${e.message}") + } + } +} +``` + + + --- ## Best Practices diff --git a/sdk/android/reactions.mdx b/sdk/android/reactions.mdx index 69fb85902..ffc173372 100644 --- a/sdk/android/reactions.mdx +++ b/sdk/android/reactions.mdx @@ -72,11 +72,7 @@ CometChat.addMessageListener(listenerID, new MessageReactionListener() { - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) - - -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 Android SDK. +Reactions let users respond to messages with emoji. You can add or remove reactions, fetch all reactions on a message, listen for reaction events in real time, and update your UI when reactions change. ## Add a Reaction @@ -183,7 +179,7 @@ To get all reactions for a specific message, first create a `ReactionRequest` us | `setMessageId(int value)` | Specifies the unique identifier of the message for which you want to fetch reactions. This parameter is mandatory as it tells the SDK which message's reactions are being requested. | | `setReaction(String value)` | Filters the reactions fetched by the specified reaction type (e.g., "😊", "😂", "👍"). When set, this method will cause the ReactionRequest to only retrieve details of the provided reaction for the given message. | -## Fetch Next +### Fetch Next The `fetchNext()` method fetches the next set of reactions for the message. diff --git a/sdk/android/real-time-listeners.mdx b/sdk/android/real-time-listeners.mdx index 42b5a82fd..bb7aad396 100644 --- a/sdk/android/real-time-listeners.mdx +++ b/sdk/android/real-time-listeners.mdx @@ -1,5 +1,5 @@ --- -title: "All Real Time Listeners" +title: "All Real-Time Listeners" sidebarTitle: "Real-Time Listeners" description: "Register and manage real-time event listeners for users, groups, messages, and calls in the Android SDK" --- @@ -41,7 +41,7 @@ The `UserListener` class provides you with live events related to users. Below a | `onUserOnline(User user)` | This method is triggered when a user comes online and is available to chat. The details of the user can be obtained from the user object received as the method parameter. | | `onUserOffline(User user)` | This method is triggered when a user goes offline. The details of the user can be obtained from the User object received as the parameter. | -To add the `UserListener`, you need to use the `addUserListener()` method provided by the `CometChat` class. +Use `addUserListener()` to register and `removeUserListener()` to unregister. Call remove in `onPause()`. @@ -78,27 +78,6 @@ CometChat.addUserListener(UNIQUE_LISTENER_ID, object : CometChat.UserListener() -where `UNIQUE_LISTENER_ID` is the unique identifier for the listener. Please make sure that no two listeners are added with the same listener id as this could lead to unexpected behavior resulting in loss of events. - -Once the activity/fragment where the `UserListener` is declared is not in use, you need to remove the listener using the `removeUserListener()` method which takes the id of the listener to be removed as the parameter. We suggest you call this method in the `onPause()` method of the activity/fragment. - - - -```java -CometChat.removeUserListener(UNIQUE_LISTENER_ID) -``` - - - - -```kotlin -CometChat.removeUserListener(UNIQUE_LISTENER_ID) -``` - - - - - Always remove listeners when they're no longer needed (e.g., in `onDestroy()` or when navigating away). Failing to remove listeners can cause memory leaks and duplicate event handling. @@ -117,7 +96,7 @@ The `GroupListener` class provides you with all the real-time events related to | `onGroupMemberScopeChanged(Action action, User updatedBy, User updatedUser, String scopeChangedTo, String scopeChangedFrom, Group group)` | This method is triggered when the scope of any Group Member has been changed. All the members that are a part of that group receive this event | | `onMemberAddedToGroup(Action action, User addedby, User userAdded, Group addedTo)` | This method is triggered when a user is added to any group. All the members including the user himself receive this event. | -To add the `GroupListener`, you need to use the `addGroupListener()` method provided by the `CometChat` class. +Use `addGroupListener()` to register and `removeGroupListener()` to unregister. Call remove in `onPause()`. @@ -185,27 +164,6 @@ CometChat.addGroupListener("UNIQUE_ID", object : CometChat.GroupListener() { -where `UNIQUE_LISTENER_ID` is the unique identifier for the listener. Please make sure that no two listeners are added with the same listener id as this could lead to unexpected behavior resulting in loss of events. - -Once the activity/fragment where the `GroupListener` is declared is not in use, you need to remove the listener using the `removeGroupListener()` method which takes the id of the listener to be removed as the parameter. We suggest you call this method in the `onPause()` method of the activity/fragment. - - - -```java -CometChat.removeGroupListener(UNIQUE_LISTENER_ID); -``` - - - - -```kotlin -CometChat.removeGroupListener(UNIQUE_LISTENER_ID) -``` - - - - - ## Message Listener The `MessageListener` class provides you with live events related to messages. Below are the callback methods provided by the `MessageListener` class. @@ -227,7 +185,7 @@ The `MessageListener` class provides you with live events related to messages. B | `onMessageReactionAdded(ReactionEvent reactionEvent)` | This event is triggered when a reaction is added to a message in a user/group conversation. | | `onMessageReactionRemoved(ReactionEvent reactionEvent)` | This event is triggered when a reaction is remove from a message in a user/group conversation. | -To add the `MessageListener`, you need to use the `addMessageListener()` method provided by the `CometChat` class. +Use `addMessageListener()` to register and `removeMessageListener()` to unregister. Call remove in `onPause()`. @@ -359,10 +317,6 @@ CometChat.addMessageListener(UNIQUE_LISTENER_ID, object : CometChat.MessageListe -where `UNIQUE_LISTENER_ID` is the unique identifier for the listener. Please make sure that no two listeners are added with the same listener id as this could lead to unexpected behavior resulting in loss of events. - -Once the activity/fragment where the `MessageListener` is declared is not in use, you need to remove the listener using the `removeMessageListener()` method which takes the id of the listener to be removed as the parameter. We suggest you call this method in the `onPause()` method of the activity/fragment. - ## Call Listener The `CallListener` class provides you with live events related to calls. Below are the callback methods provided by the `CallListener` class. @@ -374,7 +328,7 @@ The `CallListener` class provides you with live events related to calls. Below a | `onOutgoingCallRejected(Call call)` | This event is triggered when the call initiated by the logged-in user is rejected by the recipient. The details of the call can be obtained from the Call object received as the method parameter | | `onIncomingCallCancelled(Call call)` | This event is triggered when an incoming call is canceled by the initiator of the call. The details of the call can be obtained from the Call object received as the method parameter | -To add the `CallListener`, you need to use the `addCallListener()` method provided by the `CometChat` class. +Use `addCallListener()` to register and `removeCallListener()` to unregister. Call remove in `onPause()`. @@ -429,11 +383,6 @@ CometChat.addCallListener(UNIQUE_LISTENER_ID, object : CometChat.CallListener() -Where `UNIQUE_LISTENER_ID` is the unique identifier for the listener. Make sure that no two listeners are added with the same listener ID as this could lead to unexpected behavior resulting in loss of events. - -Once the activity/fragment where the `MessageListener` is declared is not in use, you need to remove the listener using the `removeMessageListener()` method which takes the id of the listener to be removed as the parameter. We suggest you call this method in the `onPause()` method of the activity/fragment. - - ## Best Practices diff --git a/sdk/android/receive-messages.mdx b/sdk/android/receive-messages.mdx index 78c56cacc..f025cd587 100644 --- a/sdk/android/receive-messages.mdx +++ b/sdk/android/receive-messages.mdx @@ -4,20 +4,25 @@ 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 Android SDK." --- + +| Field | Value | +| --- | --- | +| Key Classes | `CometChat.MessageListener`, `MessagesRequestBuilder` | +| Key Methods | `addMessageListener()`, `fetchPrevious()`, `fetchNext()`, `getUnreadMessageCount()` | +| 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/android/receive-messages#real-time-messages) when your app is running -2. Calling a method to retrieve [Missed Messages](/sdk/android/receive-messages#missed-messages) when your app was not running + -## Real-time Messages +Receiving messages with CometChat has two parts: -How do I receive messages when my app is running? +1. Adding a [real-time listener](#real-time-messages) to receive messages while your app is running +2. Fetching [missed](#missed-messages), [unread](#unread-messages), or [historical](#message-history) messages when your app starts up or the user scrolls back -For every activity or fragment you wish to receive messages in, register the `MessageListener` using the `addMessageListener()` method. +## Real-Time Messages -We suggest adding the listener in the `onResume()` method of the activity or fragment where you wish to receive these events. +Register a `MessageListener` to receive incoming messages as they arrive. For every activity or fragment you wish to receive messages in, register the listener using `addMessageListener()`. We suggest adding it in the `onResume()` method. @@ -41,9 +46,7 @@ CometChat.addMessageListener(listenerID, new CometChat.MessageListener() { } }); ``` - - ```kotlin val listenerID:String = "UNIQUE_LISTENER_ID" @@ -62,16 +65,14 @@ CometChat.addMessageListener(listenerID, object : MessageListener() { } }) ``` - - | Parameter | Description | | ------------ | ---------------------------------------------------------------------------------------------- | | `listenerID` | An ID that uniquely identifies that listener. We recommend using the activity or fragment name | -We recommend you remove the listener once the activity or fragment is not in use. Typically, this can be added in the `onPause()` method. +Remove the listener when you no longer need it. Typically, this can be added in the `onPause()` method. @@ -80,40 +81,30 @@ private String listenerID = "UNIQUE_LISTENER_ID"; CometChat.removeMessageListener(listenerID); ``` - - ```kotlin val listenerID:String = "UNIQUE_LISTENER_ID" CometChat.removeMessageListener(listenerID) ``` - - +Always remove listeners when they're no longer needed (e.g., in `onPause()`). Failing to do so can cause memory leaks and duplicate event handling. + + 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. - ## Missed Messages -How do I receive messages that I missed when my app was not running? - -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 the message history (say, last 100 messages) instead. - -Using the same `MessagesRequest` class and the filters provided by the `MessagesRequestBuilder` class, you can fetch the message that we sent to the logged-in user but were not delivered to them as they were 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 they were offline. - -Calling the `fetchNext()` method on the same object repeatedly allows you to fetch all the offline messages for the logged in user in a paginated manner - -### Fetch Missed Messages of a particular one-on-one conversation +Fetch messages that arrived while your app was offline. Use `getLastDeliveredMessageId()` to find where you left off, then call `fetchNext()` to get everything after that point. Call `fetchNext()` repeatedly on the same request object to paginate. + + ```java @@ -145,11 +136,9 @@ messagesRequest.fetchNext(new CometChat.CallbackListener>() { public void onError(CometChatException e) { Log.d(TAG, "Message fetching failed with exception: " + e.getMessage()); } -}); +}); ``` - - ```kotlin lateinit var messagesRequest: MessagesRequest @@ -185,13 +174,10 @@ messagesRequest.fetchNext(object : CallbackListener>() { } }) ``` - - - -### Fetch Missed Messages of a particular group conversation - + + ```java @@ -223,12 +209,10 @@ messagesRequest.fetchNext(new CometChat.CallbackListener>() { } }); ``` - - ```kotlin -lateinit var messagesRequest: MessagesReques +lateinit var messagesRequest: MessagesRequest val latestId = CometChat.getLastDeliveredMessageId() val limit: Int = 30 val GUID: String = "cometchat-uid-1" @@ -259,21 +243,20 @@ messagesRequest.fetchNext(object : CallbackListener>() { override fun onError(e: CometChatException) { Log.d(TAG, "Message fetching failed with exception: " + e.message) } -}) +}) ``` - - + + -## Unread Messages - -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. To achieve this, set the `unread` variable in the builder to `true` using the `setUnread()` method so that only the unread messages are fetched. +## Unread Messages -### Fetch Unread Messages of a particular one-on-one conversation +Fetch unread messages by adding `setUnread(true)` to the builder. Use `fetchPrevious()` to retrieve them. + + ```java @@ -303,9 +286,7 @@ messagesRequest.fetchPrevious(new CometChat.CallbackListener>( } }); ``` - - ```kotlin val UID:String = "cometchat-uid-1" @@ -332,13 +313,10 @@ messagesRequest.fetchPrevious(object : CallbackListener>() { } }) ``` - - - -### Fetch Unread Messages of a particular group conversation - + + ```java @@ -368,9 +346,7 @@ messagesRequest.fetchPrevious(new CometChat.CallbackListener>( } }); ``` - - ```kotlin val GUID:String = "cometchat-guid-1" @@ -397,26 +373,22 @@ messagesRequest.fetchPrevious(object : CallbackListener>() { } }) ``` - - + + -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. - -## Message History - -How do I fetch the message history for a user or a group conversation? -### Fetch Message History of a particular one-on-one conversation +## Message History -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. +Fetch the full conversation history using `fetchPrevious()`. Call it repeatedly on the same request object to paginate — useful for implementing upward scrolling. + + ```java @@ -444,11 +416,9 @@ messagesRequest.fetchPrevious(new CometChat.CallbackListener>( public void onError(CometChatException e) { Log.d(TAG, "Message fetching failed with exception: " + e.getMessage()); } -}); +}); ``` - - ```kotlin val limit: Int = 30 @@ -473,19 +443,12 @@ messagesRequest.fetchPrevious(object : CallbackListener>() { override fun onError(e: CometChatException) { Log.d(TAG, "Message fetching failed with exception: " + e.message) } -}) +}) ``` - - - -Calling the `fetchPrevious()` method on the same object repeatedly allows you to fetch all the previous messages in a paginated way. - -### 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. - + + ```java @@ -515,9 +478,7 @@ messagesRequest.fetchPrevious(new CometChat.CallbackListener>( } }); ``` - - ```kotlin val limit: Int = 30 @@ -544,36 +505,18 @@ messagesRequest.fetchPrevious(object : CallbackListener>() { } }) ``` - - + + -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. ## Search Messages -How do I search for a message? - -To search messages, use the `setSearchKeyword()` method. This method accepts a string as input. When set, the SDK will fetch messages that match the `searchKeyword`. - - - -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 | -| ---------------- | ------------ | -------------- | -| Text search | ✅ | ✅ | -| File name search | ❌ | ✅ | -| Mentions search | ❌ | ✅ | -| Mime type search | ❌ | ✅ | - -### Search Messages in a particular one-on-one conversation +Add `setSearchKeyword()` to the builder to filter messages by keyword. + + ```java @@ -600,9 +543,7 @@ messagesRequest.fetchPrevious(new CometChat.CallbackListener>( } }); ``` - - ```kotlin val limit: Int = 30 @@ -626,13 +567,10 @@ messagesRequest.fetchPrevious(object : CallbackListener>() { } }) ``` - - - -### Search Messages in a particular group conversation - + + ```java @@ -659,9 +597,7 @@ messagesRequest.fetchPrevious(new CometChat.CallbackListener>( } }); ``` - - ```kotlin val limit = 30 @@ -685,65 +621,65 @@ messagesRequest.fetchPrevious(object : CallbackListener>() { } }) ``` - - + + -## Unread Messages Count - -How do I find out the number of unread messages that I have? - -### Fetch Unread Message Count of a particular one-on-one conversation +### Search Capabilities -How do I find out the number of unread messages I have from a particular user? +By default, search only matches message text. With `Conversation & Advanced Search` enabled, it also matches file names, mentions, and MIME types. -To get the unread message count for a particular user (with respect to the logged-in user), use the `getUnreadMessageCountForUser()` method. +| Feature | Basic Search | Advanced Search | +| ---------------- | ------------ | --------------- | +| Text search | ✅ | ✅ | +| File name search | ❌ | ✅ | +| Mentions search | ❌ | ✅ | +| Mime type search | ❌ | ✅ | -This method has the two variants: + +`Conversation & Advanced Search` is available on `Advanced` and `Custom` [plans](https://www.cometchat.com/pricing). Enable it from the [CometChat Dashboard](https://app.cometchat.com) under Chats → Settings → General Configuration. + - - -```java -CometChat.getUnreadMessageCountForUser(String UID, Callbacks); -``` - +## Unread Message Count - -```kotlin -CometChat.getUnreadMessageCountForUser(UID: String, Callbacks) -``` +CometChat provides several methods to get unread counts at different scopes. All return results via a callback listener with a `HashMap` mapping IDs to counts. - +Each method accepts an optional boolean parameter to exclude messages from blocked users. - +| Method | Scope | Returns | +| --- | --- | --- | +| `getUnreadMessageCountForUser(UID)` | Single user conversation | `HashMap` | +| `getUnreadMessageCountForGroup(GUID)` | Single group conversation | `HashMap` | +| `getUnreadMessageCountForAllUsers()` | All user conversations | `HashMap` | +| `getUnreadMessageCountForAllGroups()` | All group conversations | `HashMap` | +| `getUnreadMessageCount()` | Everything | `HashMap<"user"/"group", HashMap>` | -If you wish to ignore the messages from blocked users you can use the below syntax setting the boolean parameter to `true`: +### Single Conversation ```java -CometChat.getUnreadMessageCountForUser(String UID, boolean hideMessagesFromBlockedUsers, Callbacks); -``` - - - - -```kotlin -CometChat.getUnreadMessageCountForUser(UID: String, hideMessagesFromBlockedUsers: Boolean, Callbacks) -``` +// One-on-one +private String UID = "cometchat-uid-1"; - +CometChat.getUnreadMessageCountForUser(UID, new CometChat.CallbackListener>() { + @Override + public void onSuccess(HashMap stringIntegerHashMap) { + // handle success + } - + @Override + public void onError(CometChatException e) { + // handle error + } +}); - - -```java -private String UID = "cometchat-uid-1" +// Group +private String GUID = "cometchat-guid-1"; -CometChat.getUnreadMessageCountForUser(UID, new CometChat.CallbackListener>() { +CometChat.getUnreadMessageCountForGroup(GUID, new CometChat.CallbackListener>(){ @Override public void onSuccess(HashMap stringIntegerHashMap) { // handle success @@ -755,13 +691,12 @@ CometChat.getUnreadMessageCountForUser(UID, new CometChat.CallbackListener - ```kotlin +// One-on-one val UID: String = "cometchat-uid-1" - + CometChat.getUnreadMessageCountForUser(UID, object : CallbackListener?>() { override fun onSuccess(stringIntegerHashMap: HashMap?) { // handle success @@ -771,66 +706,32 @@ CometChat.getUnreadMessageCountForUser(UID, object : CallbackListener - - - -In the `onSuccess()` callback, you will receive a Hashmap which will contain the `UID` of the user as the key and the unread message count as the value. - -### Fetch Unread Message Count of a particular group conversation - -How do I find out the number of unread messages I have in a single group? - -To get the unread message count for a particular group, use the `getUnreadMessageCountForGroup()` method. -This method has two variants: - - - -```java -CometChat.getUnreadMessageCountForGroup(String GUID, Callbacks); -``` +// Group +val GUID: String = "cometchat-guid-1" - +CometChat.getUnreadMessageCountForGroup(GUID, object : CallbackListener?>() { + override fun onSuccess(stringIntegerHashMap: HashMap?) { + // handle success + } - -```kotlin -CometChat.getUnreadMessageCountForUser(GUID: String, Callbacks) + override fun onError(e: CometChatException) { + // handle error + } +}) ``` - - -If you wish to ignore the messages from blocked users you can use the following syntax setting the boolean parameter to `true`: +### All Conversations ```java -CometChat.getUnreadMessageCountForGroup(String GUID, boolean hideMessagesFromBlockedUsers, Callbacks); -``` - - - - -```kotlin -CometChat.getUnreadMessageCountForUser(GUID: String, hideMessagesFromBlockedUsers: Boolean, Callbacks) -``` - - - - - - - -```java -private String GUID = "cometchat-guid-1" - -CometChat.getUnreadMessageCountForGroup(GUID, new CometChat.CallbackListener>(){ +// All users and groups combined +CometChat.getUnreadMessageCount(new CometChat.CallbackListener>>() { @Override - public void onSuccess(HashMap stringIntegerHashMap) { + public void onSuccess(HashMap> stringHashMapHashMap) { // handle success } @@ -839,94 +740,37 @@ CometChat.getUnreadMessageCountForGroup(GUID, new CometChat.CallbackListener - - -```kotlin -val GUID: String = "cometchat-guid-1" -CometChat.getUnreadMessageCountForGroup(GUID, object : CallbackListener?>() { - override fun onSuccess(stringIntegerHashMap: HashMap?) { - // handle success - } - - override fun onError(e: CometChatException) { - // handle error - } +// All user conversations only +CometChat.getUnreadMessageCountForAllUsers(new CometChat.CallbackListener>() { + @Override + public void onSuccess(HashMap stringIntegerHashMap) { + // Handle Success } -) -``` - - - - - -In the `onSuccess()` callback, you will receive a Hashmap which will contain the `GUID` of the group as the key and the unread message count as the value. - -### Fetch Unread Message Count of all one-on-one & group conversations - -How do I find out the number of unread messages for every one-on-one and group conversation? - -To get all the unread message counts, use the `getUnreadMessageCount()` method. This method has two variants: - - - -```java -CometChat.getUnreadMessageCount(Callbacks); -``` - - - - -```kotlin -CometChat.getUnreadMessageCount(Callbacks) -``` - - - - - -If you wish to ignore the messages from blocked users you can use the following syntax setting the boolean parameter to `true`: - - - -```java -CometChat.getUnreadMessageCount(boolean hideMessagesFromBlockedUsers, Callbacks); -``` - - - - -```kotlin -CometChat.getUnreadMessageCount(hideMessagesFromBlockedUsers: Boolean, Callbacks) -``` - - - + @Override + public void onError(CometChatException e) { + // Handle Error + } +}); - - -```java -CometChat.getUnreadMessageCount(new CometChat.CallbackListener>>() { +// All group conversations only +CometChat.getUnreadMessageCountForAllGroups(new CometChat.CallbackListener>() { @Override - public void onSuccess(HashMap> stringHashMapHashMap) { - // handle success + public void onSuccess(HashMap stringIntegerHashMap) { + // Handle success } @Override public void onError(CometChatException e) { - // handle error + // Handle Error } -}); +}); ``` - - ```kotlin +// All users and groups combined CometChat.getUnreadMessageCount(object : CallbackListener?>?>() { override fun onSuccess(stringHashMapHashMap: HashMap?>?) { // handle success @@ -936,178 +780,120 @@ CometChat.getUnreadMessageCount(object : CallbackListener - - - -In the `onSuccess()` callback, you will receive a hashmap having two keys: - -1. `user` - The value for this key holds another hashmap that holds the `UIDs` of users and their corresponding unread message counts. -2. `group` - The value for this key holds another hashmap that holds the `GUIDs` of groups and their corresponding unread message counts. - -### Fetch Unread Message Count of all one-on-one conversations - -How do I find out the number of unread messages I have for every user? - -To fetch the unread message counts for just the users, use the `getUnreadMessageCountForAllUsers()` method. - -This method, just like others, has two variants: - - - -```java -CometChat.getUnreadMessageCountForAllUsers(Callbacks); -``` - - - - -```kotlin -CometChat.getUnreadMessageCountForAllUsers(Callbacks) -``` - - - - - -If you wish to ignore the messages from blocked users you can use the following syntax setting the boolean parameter to `true`: - - - -```java -CometChat.getUnreadMessageCountForAllUsers(boolean hideMessagesFromBlockedUsers, Callbacks); -``` - - - -```kotlin -CometChat.getUnreadMessageCountForAllUsers(hideMessagesFromBlockedUsers: Boolean, Callbacks) -``` - - - - - - - -```java -CometChat.getUnreadMessageCountForAllUsers(new CometChat.CallbackListener>() { -@Override - public void onSuccess(HashMap stringIntegerHashMap) { - // Handle Success -} - -@Override - public void onError(CometChatException e) { - // Handle Error -} -}); -``` +// All user conversations only +CometChat.getUnreadMessageCountForAllUsers(object : CometChat.CallbackListener>() { + override fun onSuccess(stringIntegerHashMap: HashMap) { + Log.d(TAG,"onSuccess: ${stringIntegerHashMap.size}") + } - + override fun onError(e: CometChatException) { + Log.d(TAG,"onError: ${e.message}") + } +}) - -```kotlin -CometChat.getUnreadMessageCountForAllUsers(object : CometChat.CallbackListener>() { -override fun onSuccess(stringIntegerHashMap: HashMap) { - Log.d(TAG,"onSuccess: ${stringIntegerHashMap.size}") -} +// All group conversations only +CometChat.getUnreadMessageCountForAllGroups(object : CometChat.CallbackListener>() { + override fun onSuccess(stringIntegerHashMap: HashMap) { + Log.d(TAG,"onSuccess: ${stringIntegerHashMap.size}") + } -override fun onError(e: CometChatException) { - Log.d(TAG,"onError: ${e.message}") -} + override fun onError(e: CometChatException) { + Log.e(TAG,"onError: ${e.message}") + } }) ``` - - -In the `onSuccess()` callback, you will receive a Hashmap that will contain the `UIDs` of users as the key and the unread message counts as the values. - -### Fetch Unread Message Count of all group conversations - -How do I find out the number of unread messages for every group? - -To fetch the unread message counts for all groups, use the `getUnreadMessageCountForAllGroups()` method. +### Excluding Blocked Users -This method has two variants: +Pass `true` as the second argument to any of the methods above to ignore messages from blocked users: ```java -CometChat.getUnreadMessageCountForAllGroups(Callbacks); +CometChat.getUnreadMessageCountForUser(UID, true, Callbacks); +CometChat.getUnreadMessageCountForGroup(GUID, true, Callbacks); +CometChat.getUnreadMessageCount(true, Callbacks); +CometChat.getUnreadMessageCountForAllUsers(true, Callbacks); +CometChat.getUnreadMessageCountForAllGroups(true, Callbacks); ``` - - ```kotlin -CometChat.getUnreadMessageCountForAllGroups(Callbacks) +CometChat.getUnreadMessageCountForUser(UID, true, Callbacks) +CometChat.getUnreadMessageCountForGroup(GUID, true, Callbacks) +CometChat.getUnreadMessageCount(true, Callbacks) +CometChat.getUnreadMessageCountForAllUsers(true, Callbacks) +CometChat.getUnreadMessageCountForAllGroups(true, Callbacks) ``` - - -If you wish to ignore the messages from blocked users you can use the below syntax setting the boolean parameter to `true`: - - - -```java -CometChat.getUnreadMessageCountForAllGroups(boolean hideMessagesFromBlockedUsers, Callbacks); -``` - - - - -```kotlin -CometChat.getUnreadMessageCountForAllGroups(hideMessagesFromBlockedUsers: Boolean, Callbacks) -``` - +## Get Message Details - +Use `getMessageDetails()` to fetch a specific message by its ID. Returns the full message object (`TextMessage`, `MediaMessage`, `CustomMessage`, or other `BaseMessage` subclass). ```java -CometChat.getUnreadMessageCountForAllGroups(new CometChat.CallbackListener>() { -@Override - public void onSuccess(HashMap stringIntegerHashMap) { - // Handle success -} +int messageId = MESSAGE_ID; + +CometChat.getMessageDetails(messageId, new CometChat.CallbackListener() { + @Override + public void onSuccess(BaseMessage message) { + Log.d(TAG, "Message details fetched: " + message.toString()); + } -@Override + @Override public void onError(CometChatException e) { - // Handle Error -} + Log.d(TAG, "Error fetching message details: " + e.getMessage()); + } }); ``` - - ```kotlin -CometChat.getUnreadMessageCountForAllGroups(object : CometChat.CallbackListener>() { -override fun onSuccess(stringIntegerHashMap: HashMap) { - Log.d(TAG,"onSuccess: ${stringIntegerHashMap.size}") -} +val messageId: Int = MESSAGE_ID -override fun onError(e: CometChatException) { - Log.e(TAG,"onError: ${e.message}") -} +CometChat.getMessageDetails(messageId, object : CometChat.CallbackListener() { + override fun onSuccess(message: BaseMessage) { + Log.d(TAG, "Message details fetched: $message") + } + + override fun onError(e: CometChatException) { + Log.d(TAG, "Error fetching message details: ${e.message}") + } }) ``` - - -In the `onSuccess()` callback, you will receive a hashmap which will contain the `GUIDs` of the groups as the key and the unread message counts as the values. +| Parameter | Type | Description | +| ----------- | ----- | -------------------------------- | +| `messageId` | `int` | The ID of the message to fetch | + +--- + +## Next Steps + + + + Track when messages are delivered and read by recipients + + + Show real-time typing status in conversations + + + Advanced filtering options for message history + + + Send text, media, and custom messages + + + ## Message Payload Structure diff --git a/sdk/android/recording.mdx b/sdk/android/recording.mdx index d8c374832..e37887fd5 100644 --- a/sdk/android/recording.mdx +++ b/sdk/android/recording.mdx @@ -22,19 +22,11 @@ CallManager.getInstance().stopRecording() ``` - -**Available via:** SDK | [Dashboard](https://app.cometchat.com) - - -This section guides you through implementing the call recording feature for voice and video calls. +Record voice and video calls for playback, compliance, or archival purposes. Recording is built on top of the [Call Session](/sdk/android/direct-calling) — add recording listeners to your call settings and optionally control recording programmatically. ## Implementation -Once you have decided to implement [Default Calling](/sdk/android/default-calling) or [Direct Calling](/sdk/android/direct-calling) and followed the steps to implement them, a few additional listeners and methods will help you quickly implement call recording in your app. - -You need to make changes in the `CometChat.startCall` method and add the required listeners for recording. Make sure your `callSettings` is configured accordingly for [Default Calling](/sdk/android/default-calling) or [Direct Calling](/sdk/android/direct-calling). - -Here is a basic example of how to implement recording for a direct/default call: +Add `onRecordingStarted` and `onRecordingStopped` callbacks to your `OngoingCallListener` when building call settings. These fire for all participants when any user starts or stops recording. @@ -89,8 +81,6 @@ The options available for recording calls are: ### Start Recording -You can use the startRecording() method to start call recording. - ```java @@ -110,8 +100,6 @@ CallManager.getInstance().startRecording() ### Stop Recording -You can use the stopRecording() method to stop call recording. - ```java diff --git a/sdk/android/resources-overview.mdx b/sdk/android/resources-overview.mdx deleted file mode 100644 index 03c061b4c..000000000 --- a/sdk/android/resources-overview.mdx +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: "Resources" -sidebarTitle: "Overview" -description: "Additional resources, guides, and references for the CometChat Android SDK" ---- - - - -Helpful resources: -- **Real-Time Listeners** → [real-time-listeners](/sdk/android/real-time-listeners) - Complete event handling guide -- **Upgrading from v3** → [upgrading-from-v3-guide](/sdk/android/upgrading-from-v3-guide) - Migration guide -- **Rate Limits** → [rate-limits](/sdk/android/rate-limits) - API rate limiting information -- **Webhooks** → [webhooks-overview](/sdk/android/webhooks-overview) - Server-side event notifications -- **Connection Behaviour** → [connection-behaviour](/sdk/android/connection-behaviour) - SDK connectivity patterns - - - - -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/android/real-time-listeners) guide. - -If you're upgrading from v1, we recommend reading our [upgrading from v3](/sdk/android/upgrading-from-v3-guide) guide. - ---- - -## Next Steps - - - - Complete guide to handling all SDK events - - - Migration guide for v3 to v4 upgrade - - - Understand API rate limiting and quotas - - - Configure server-side event notifications - - diff --git a/sdk/android/retrieve-conversations.mdx b/sdk/android/retrieve-conversations.mdx index 33c3030df..8f1454178 100644 --- a/sdk/android/retrieve-conversations.mdx +++ b/sdk/android/retrieve-conversations.mdx @@ -23,23 +23,15 @@ CometChat.getConversation("UID_or_GUID", "user", callback) ``` - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) - - 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. ## Retrieve List of Conversations -How do I retrieve the latest conversations that I've been a part of? - -To fetch the list of conversations, use the `ConversationsRequest` class. 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 fetched. - -The `ConversationsRequestBuilder` class allows you to set the following parameters: +Use `ConversationsRequestBuilder` to configure filters, then call `fetchNext()` to retrieve up to 50 conversations per request. ### 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. @@ -64,12 +56,7 @@ val conversationRequest = ConversationsRequestBuilder() ### 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. @@ -96,7 +83,7 @@ val conversationsRequest = ConversationsRequestBuilder() ### 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`. @@ -123,7 +110,7 @@ val conversationsRequest = ConversationsRequestBuilder() ### Set User Tags -This method fetches user conversations that have the specified tags. +Fetch user conversations where the user has specific tags. @@ -154,6 +141,8 @@ conversationsRequest = ConversationsRequestBuilder() ### Set Group Tags +Fetch group conversations where the group has specific tags. + ```java @@ -185,7 +174,13 @@ This method fetches group conversations that have 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`. + +When `withTags(true)` is set, each conversation's `tags` field will be populated. Access tags using `getTags()`. + +| Additional Field | Getter | Return Type | Description | +| --- | --- | --- | --- | +| tags | `getTags()` | `List` | Tags associated with the conversation | @@ -212,7 +207,7 @@ val conversationsRequest = ConversationsRequestBuilder() ### Set Tags -This method helps you fetch the conversations based on the specified tags. +Fetch conversations that have specific tags. @@ -243,7 +238,7 @@ val conversationsRequest = ConversationsRequestBuilder() ### Include Blocked Users -This method helps you fetch the conversations of users whom the logged-in user has blocked. +Use `includeBlockedUsers(true)` to include conversations with users you've blocked. @@ -270,7 +265,7 @@ val conversationsRequest = ConversationsRequestBuilder() ### With Blocked Info -This method helps you fetch the conversations of users whom the logged-in user has blocked. +Use `withBlockedInfo(true)` to include blocked user information in the response. @@ -297,7 +292,7 @@ val conversationsRequest = ConversationsRequestBuilder() ### 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. @@ -330,7 +325,7 @@ val conversationsRequest = ConversationsRequestBuilder() ### Unread Conversations -This method helps you fetch unread conversations. +Use `setUnread(true)` to fetch only conversations with unread messages. @@ -361,11 +356,9 @@ val conversationsRequest = ConversationsRequestBuilder() -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 conversations depending on the limit set. +### Fetch Conversations -A Maximum of only 50 Conversations can be fetched at once. +After configuring the builder, call `build()` to create the request, then `fetchNext()` to retrieve conversations. Maximum 50 per request. Call `fetchNext()` repeatedly on the same object to paginate. @@ -375,38 +368,33 @@ ConversationsRequest conversationsRequest = new ConversationsRequest.Conversatio conversationsRequest.fetchNext(new CometChat.CallbackListener>() { @Override public void onSuccess(List conversations) { - // Hanlde list of conversations - + // Handle list of conversations } @Override public void onError(CometChatException e) { - // Hanlde failure + // Handle failure } }); ``` - - ```kotlin var conversationRequest: ConversationsRequest? = null -val LIMIT:Int=30 +val LIMIT: Int = 30 conversationRequest = ConversationsRequest.ConversationsRequestBuilder().setLimit(LIMIT).build() conversationRequest?.fetchNext(object : CometChat.CallbackListener>() { override fun onSuccess(p0: List?) { - //Handle List of Conversations + // Handle List of Conversations } override fun onError(p0: CometChatException?) { - //Handle Failure + // Handle Failure } }) ``` - - The `Conversation` object consists of the following fields: @@ -421,18 +409,13 @@ The `Conversation` object consists of the following fields: ## Tag Conversation -How do I tag a conversation? - -To tag a specific conversation, use the `tagConversation()` method. The `tagConversation()` method accepts three parameters. +Use `tagConversation()` to add tags to a conversation. -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. - -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` | List of tags to add | @@ -489,15 +472,12 @@ The tags for conversations are one-way. This means that if user A tags a convers ## Retrieve Single Conversation -How do I retrieve a specific conversation? - -To fetch a specific conversation, use the `getConversation` method. The `getConversation` method accepts two 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: +Use `getConversation()` to fetch a specific conversation. -* user - Only fetches user conversation. -* group - Only fetches group conversations. +| Parameter | Description | +| --- | --- | +| `conversationWith` | UID or GUID of the user/group | +| `conversationType` | `user` or `group` | @@ -538,7 +518,7 @@ CometChat.getConversation(conversationWith, conversationType, new CometChat.Call ## Convert Messages to Conversations -As per our [Receive Messages](/sdk/android/receive-messages) 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 a `Conversation` object. You can use the `getConversationFromMessage` method for this purpose. +Use `CometChatHelper.getConversationFromMessage()` to convert a received message into a `Conversation` object. Useful for updating your Recent Chats list when receiving real-time messages. diff --git a/sdk/android/retrieve-group-members.mdx b/sdk/android/retrieve-group-members.mdx index 6abdf21cb..c4735260c 100644 --- a/sdk/android/retrieve-group-members.mdx +++ b/sdk/android/retrieve-group-members.mdx @@ -21,21 +21,13 @@ groupMembersRequest.fetchNext(object : CallbackListener>() { ``` - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) - - ## Retrieve the List of Group Members -To fetch the list of group members for a group, use the `GroupMembersRequest` class. 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 group members are fetched. - -The `GroupMembersRequestBuilder` class allows you to set the following 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` with the group's GUID to configure filters, then call `fetchNext()`. ### Set Limit -This method sets the limit i.e. the number of members that should be fetched in a single iteration. +Set the number of members to fetch per request. @@ -60,7 +52,7 @@ val groupMembersRequest = GroupMembersRequestBuilder(GUID) ### Set Search Keyword -This method allows you to set the search string based on which the group members are to be fetched. +Filter members by a search string. @@ -85,7 +77,7 @@ val groupMembersRequest = GroupMembersRequestBuilder(GUID) ### Set Scopes -This method allows you to fetch group members based on the specified scopes. +Filter members by scope (e.g., `"admin"`, `"moderator"`, `"participant"`). @@ -114,9 +106,9 @@ val groupMembersRequest = GroupMembersRequestBuilder(GUID) -Finally, once all the parameters are set on the builder class, call the `build()` method to get the object of the `GroupMembersRequest` class. +### Fetch Members -Once you have the object of the `GroupMembersRequest` class, call the `fetchNext()` method. This method returns a list of `GroupMember` objects containing N number of members depending on the limit set. +After configuring the builder, call `build()` then `fetchNext()` to retrieve members. diff --git a/sdk/android/retrieve-groups.mdx b/sdk/android/retrieve-groups.mdx index 96047af62..0d67b011f 100644 --- a/sdk/android/retrieve-groups.mdx +++ b/sdk/android/retrieve-groups.mdx @@ -24,19 +24,13 @@ CometChat.getGroup("GUID", callback) ``` - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) - - ## Retrieve List of Groups -How do I retrieve the list of groups I've joined and groups that are available? - -To fetch the list of groups, use the `GroupsRequest` class. 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 fetched. +Use `GroupsRequestBuilder` to configure filters, then call `fetchNext()` to retrieve groups. ### Set Limit -This method sets the limit i.e. the number of groups that should be fetched in a single iteration. +Set the number of groups to fetch per request. @@ -61,7 +55,7 @@ val groupsRequest = GroupsRequestBuilder() ### Set Search Keyword -This method allows you to set the search string based on which the groups are to be fetched. +Filter groups by a search string. @@ -86,7 +80,7 @@ val groupsRequest = GroupsRequestBuilder() ### Joined Only -This method tells CometChat to only return the groups that the user has joined or is a part of. +Return only groups the logged-in user has joined. @@ -111,7 +105,7 @@ val groupsRequest = 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. +Filter groups by tags. Only groups tagged with the specified tags are returned. @@ -144,7 +138,7 @@ val groupsRequest = GroupsRequestBuilder() ### With Tags -This property when set to true will fetch tags data along with the list of groups. +Include tag data in the response when set to `true`. @@ -169,11 +163,9 @@ val groupsRequest = GroupsRequestBuilder() -Finally, once all the parameters are set on the builder class, call the `build()` method to get the object of the `GroupsRequest` class. +### Fetch Groups -Once you have the object of the `GroupsRequest` class, call the `fetchNext()` method. This method returns a list of `Group` objects containing N number of groups depending on the limit set. - -The list of groups fetched will only include public and password type groups. Private groups are only included if the user is a member of that private group. +After configuring the builder, call `build()` then `fetchNext()` to retrieve groups. Public and password-protected groups are always included. Private groups only appear if the user is a member. @@ -219,9 +211,7 @@ override fun onError(e: CometChatException) { ## Retrieve Particular Group Details -How do I retrieve information for a specific group? - -To get the information of a group, use the `getGroup()` method. +Use `getGroup()` to fetch details for a specific group by GUID. @@ -268,9 +258,9 @@ override fun onError(p0: CometChatException?) { On success, the `Group` object containing the details of the group is returned. -## 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 count of online members for specific groups. diff --git a/sdk/android/retrieve-users.mdx b/sdk/android/retrieve-users.mdx index 9be57b9f2..815fcd793 100644 --- a/sdk/android/retrieve-users.mdx +++ b/sdk/android/retrieve-users.mdx @@ -30,13 +30,9 @@ CometChat.getUser("UID", object : CometChat.CallbackListener() { ``` - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/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 `null`, it indicates that the user is not logged in and you need to log the user into CometChat. +Use `getLoggedInUser()` to get the details of the logged-in user. Returns `null` if no user is logged in. @@ -59,13 +55,11 @@ This method will return a `User` object containing all the information related t ## Retrieve List of Users -To fetch the list of users, you can use the `UsersRequest` class. 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 following parameters: +Use `UsersRequestBuilder` to configure filters, then call `fetchNext()` to retrieve users. ### Set Limit -This method sets the limit i.e. the number of users that should be fetched in a single iteration. +Set the number of users to fetch per request. @@ -90,7 +84,7 @@ val usersRequest = UsersRequestBuilder() ### Set Search Keyword -This method allows you to set the search string based on which the users are to be fetched. +Filter users by a search string. @@ -117,7 +111,7 @@ val usersRequest = UsersRequestBuilder() ### Search In -This method allows you to define in which user property the `searchKeyword` should be searched. This method only works in combination with `setSearchKeyword()`. By default, the keyword is searched in both UID and Name. +Define which user property the `searchKeyword` should be searched in. Works only with `setSearchKeyword()`. By default, searches both UID and Name. @@ -186,7 +180,7 @@ If this parameter is not set, all users will be returned. ### Hide Blocked Users -This method determines if blocked users should be returned as part of the user list. If set to `true`, the user list will not contain users blocked by the logged-in user. +Exclude users blocked by the logged-in user from the results. Default is `false`. @@ -213,7 +207,7 @@ val usersRequest = UsersRequestBuilder() ### Set Roles -This method allows you to fetch the users based on multiple roles. +Filter users by one or more roles. @@ -246,7 +240,7 @@ val usersRequest = UsersRequestBuilder() ### Friends Only -This property when set to true will return only the friends of the logged-in user. +Return only friends of the logged-in user when set to `true`. @@ -273,7 +267,7 @@ val usersRequest = 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. +Filter users by tags. Only users tagged with the specified tags are returned. @@ -306,7 +300,7 @@ val usersRequest = UsersRequestBuilder() ### With Tags -This property when set to true will fetch tags data along with the list of users. +Include tag data in the response when set to `true`. @@ -333,7 +327,7 @@ val usersRequest = 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. +Fetch specific users by their UIDs. Maximum 25 UIDs per request. @@ -366,7 +360,7 @@ val usersRequest = 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 passed to the `sortBy()` method, the user list will be sorted by `name => UID`. +Sort the user list by a specific property. Default sort order is `status => name => UID`. @@ -393,7 +387,7 @@ val usersRequest = 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. +Sort the user list in ascending or descending order. Default is ascending. @@ -418,9 +412,9 @@ val usersRequest = 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. +### Fetch Users -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 X number of users depending on the limit set. +After configuring the builder, call `build()` then `fetchNext()` to retrieve users. Call `fetchNext()` repeatedly on the same object to paginate. @@ -468,7 +462,7 @@ override fun onError(e: CometChatException) { ## Retrieve Particular User Details -To get the information of a user, you can use the `getUser()` method. +Use `getUser()` to fetch details for a specific user by UID. @@ -516,9 +510,9 @@ The `getUser()` method takes the following parameters: On success, the `User` object containing the details of the user is returned. -## 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 count of online users for your app. diff --git a/sdk/android/send-message.mdx b/sdk/android/send-message.mdx index e35a867a2..dc412ca27 100644 --- a/sdk/android/send-message.mdx +++ b/sdk/android/send-message.mdx @@ -1,19 +1,44 @@ --- -title: "Send A Message" +title: "Send Messages" sidebarTitle: "Send Messages" description: "Send text, media, and custom messages to users and groups using the CometChat Android SDK." --- + +```kotlin +// Text message +val textMessage = TextMessage("UID", "Hello!", CometChatConstants.RECEIVER_TYPE_USER) +CometChat.sendMessage(textMessage, object : CallbackListener() { + override fun onSuccess(msg: TextMessage) { } + override fun onError(e: CometChatException) { } +}) -Using CometChat, you can send three types of messages: +// Media message (file upload) +val mediaMessage = MediaMessage("UID", File("/path/to/file.jpg"), + CometChatConstants.MESSAGE_TYPE_IMAGE, CometChatConstants.RECEIVER_TYPE_USER) +CometChat.sendMediaMessage(mediaMessage, object : CallbackListener() { + override fun onSuccess(msg: MediaMessage) { } + override fun onError(e: CometChatException) { } +}) -1. A [Text Message](/sdk/android/send-message#text-message), the most common and standard message type. -2. A [Media Message](/sdk/android/send-message#media-message), for sending photos, videos and files. -3. A [Custom Message](/sdk/android/send-message#custom-message), for sending completely custom data using JSON structures. -4. A [Interactive Messages](/sdk/android/interactive-messages), for sending end-user interactive messages of type form, card and custom Interactive +// Custom message +val customData = JSONObject().apply { put("latitude", "19.07"); put("longitude", "72.87") } +val customMessage = CustomMessage("UID", CometChatConstants.RECEIVER_TYPE_USER, "LOCATION", customData) +CometChat.sendCustomMessage(customMessage, object : CallbackListener() { + override fun onSuccess(msg: CustomMessage) { } + override fun onError(e: CometChatException) { } +}) +``` + +| Type | Method | Receiver Types | +| --- | --- | --- | +| Text | `sendMessage()` | `RECEIVER_TYPE_USER`, `RECEIVER_TYPE_GROUP` | +| Media | `sendMediaMessage()` | `RECEIVER_TYPE_USER`, `RECEIVER_TYPE_GROUP` | +| Custom | `sendCustomMessage()` | `RECEIVER_TYPE_USER`, `RECEIVER_TYPE_GROUP` | + -You can also send metadata along with a text or media message. Think, for example, if you'd want to share the user's location with every message, you can use the metadata field. +CometChat supports three types of messages: | Type | Method | Use Case | | --- | --- | --- | @@ -21,94 +46,17 @@ You can also send metadata along with a text or media message. Think, for exampl | [Media](#media-message) | `sendMediaMessage()` | Images, videos, audio, files | | [Custom](#custom-message) | `sendCustomMessage()` | Location, polls, or any JSON data | -## Text Message - -How do I send a text message? - -To send a text message to a single user or group, 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 `JSONObject` to it. - - - -```java -JSONObject metadata = new JSONObject(); -metadata.put("latitude", "50.6192171633316"); -metadata.put("longitude", "-72.68182268750002"); -textMessage.setMetadata(metadata); -``` - - - - -```kotlin -val metadata = JSONObject() -metadata.put("latitude", "50.6192171633316") -metadata.put("longitude", "-72.68182268750002") -textMessage.setMetadata(metadata) -``` - - +You can also send [Interactive Messages](/sdk/android/interactive-messages) for forms, cards, and custom UI elements. - - -### 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. - - - -```java -List tags = new ArrayList<>(); -tags.add("pinned"); -textMessage.setTags(tags); -``` - - - - -```kotlin -val tags: MutableList = ArrayList() -tags.add("pinned") -textMessage.setTags(tags) -``` - - - - - -### Set Quoted Message - -To set a quoted message for a message, use the `setQuotedMessageId()` and `setQuotedMessage()` method of the TextMessage class. This method accepts the ID of the message to be quoted. - - - -```java -textMessage.setQuotedMessageId(10); -textMessage.setQuotedMessage(); // Pass base message object here that you want to quote. -``` - - - - -```kotlin -textMessage.quotedMessageId = 0 -textMessage.quotedMessage = // Pass base message object here that you want to quote. -``` - - - - +## Text Message -Once the text message object is ready, you need to use the `sendMessage()` method to send the text message to the recipient. +Send a text message using `sendMessage()` with a `TextMessage` object. ```java private String receiverID = "UID"; -private String messageText = "Hello CoemtChat!"; +private String messageText = "Hello CometChat!"; private String receiverType = CometChatConstants.RECEIVER_TYPE_USER; TextMessage textMessage = new TextMessage(receiverID, messageText, receiverType); @@ -125,9 +73,7 @@ CometChat.sendMessage(textMessage, new CometChat.CallbackListener() } }); ``` - - ```kotlin private val receiverID = "UID" @@ -146,9 +92,7 @@ CometChat.sendMessage(textMessage, object : CallbackListener() { } }) ``` - - ```java private String receiverID = "GUID"; @@ -169,9 +113,7 @@ CometChat.sendMessage(textMessage, new CometChat.CallbackListener() } }); ``` - - ```kotlin private val receiverID = "GUID" @@ -189,31 +131,90 @@ CometChat.sendMessage(textMessage, object : CallbackListener() { } }) ``` + + + +The `TextMessage` class constructor takes the following parameters: + +| Parameter | Description | Required | +| --- | --- | --- | +| `receiverID` | `UID` of the user or `GUID` of the group receiving the message | Yes | +| `messageText` | The text message content | Yes | +| `receiverType` | `CometChatConstants.RECEIVER_TYPE_USER` or `RECEIVER_TYPE_GROUP` | Yes | + +On success, `sendMessage()` returns a `TextMessage` object containing all information about the sent message. + +### Add Metadata + +Attach custom JSON data to the message: + + +```java +JSONObject metadata = new JSONObject(); +metadata.put("latitude", "50.6192171633316"); +metadata.put("longitude", "-72.68182268750002"); +textMessage.setMetadata(metadata); +``` + +```kotlin +val metadata = JSONObject() +metadata.put("latitude", "50.6192171633316") +metadata.put("longitude", "-72.68182268750002") +textMessage.setMetadata(metadata) +``` + + + +### Add Tags +Tag messages for easy filtering later: + + + +```java +List tags = new ArrayList<>(); +tags.add("pinned"); +textMessage.setTags(tags); +``` + + +```kotlin +val tags: MutableList = ArrayList() +tags.add("pinned") +textMessage.setTags(tags) +``` + -The `TextMessage` class constructor takes the following parameters: +### Quote a Message -| 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- `CometChatConstants.RECEIVER_TYPE_USER` (user) or `CometChatConstants.RECEIVER_TYPE_GROUP` (group) | Required | +Reply to a specific message by setting its ID: -When a text message is sent successfully, the response will include a `TextMessage` object which includes all information related to the sent message. + + +```java +textMessage.setQuotedMessageId(10); +``` + + +```kotlin +textMessage.quotedMessageId = 10 +``` + + ## Media Message -How do I send a media message like photos, videos, and files? +Send images, videos, audio, or files using `sendMediaMessage()`. -To send a media message to any user or group, use the `sendMediaMessage()` method and pass a `MediaMessage` object to it. +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 ### Add Metadata -To send custom data along with a media message, you can use the `setMetadata` method and pass a `JSONObject` to it. - ```java @@ -222,9 +223,7 @@ metadata.put("latitude", "50.6192171633316"); metadata.put("longitude", "-72.68182268750002"); mediaMessage.setMetadata(metadata); ``` - - ```kotlin val metadata = JSONObject() @@ -232,36 +231,28 @@ metadata.put("latitude", "50.6192171633316") metadata.put("longitude", "-72.68182268750002") mediaMessage.setMetadata(metadata) ``` - - -### Add Caption(Text along with Media Message) +### Add Caption -To send a caption with a media message, you can use `setCaption` method and pass text to it. +Add text along with the media: ```java mediaMessage.setCaption("Message Caption"); ``` - - ```kotlin mediaMessage.setCaption("Message 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. - ```java @@ -269,23 +260,19 @@ List tags = new ArrayList<>(); tags.add("pinned"); mediaMessage.setTags(tags); ``` - - ```kotlin val tags: MutableList = ArrayList() tags.add("pinned") mediaMessage.setTags(tags) ``` - - -There are 2 ways you can send Media Messages using the CometChat SDK: +### Upload a File -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. +Pass a `File` object directly. CometChat uploads it to its servers and returns the URL in the success response. @@ -309,9 +296,7 @@ CometChat.sendMediaMessage(mediaMessage, new CometChat.CallbackListener - ```kotlin private val receiverID = "UID" @@ -330,9 +315,7 @@ CometChat.sendMediaMessage(mediaMessage, object : CallbackListener } }) ``` - - ```java private String receiverID = "GUID"; @@ -354,9 +337,7 @@ CometChat.sendMediaMessage(mediaMessage, new CometChat.CallbackListener - ```kotlin private val receiverID = "GUID" @@ -375,21 +356,21 @@ CometChat.sendMediaMessage(mediaMessage, object : CallbackListener } }) ``` - - 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. Options:
1. `CometChatConstants.MESSAGE_TYPE_IMAGE` (image)
2. `CometChatConstants.MESSAGE_TYPE_VIDEO` (video)
3. `CometChatConstants.MESSAGE_TYPE_AUDIO` (audio)
4. `CometChatConstants.MESSAGE_TYPE_FILE` (file) | Required | -| `receiverType` | The type of the receiver to whom the message is to be sent. Options: `CometChatConstants.RECEIVER_TYPE_USER` (user) or `CometChatConstants.RECEIVER_TYPE_GROUP` (group) | Optional | +| Parameter | Description | Required | +| --- | --- | --- | +| `receiverId` | The UID or GUID of the recipient | Yes | +| `file` | The `File` object to upload | Yes | +| `messageType` | `MESSAGE_TYPE_IMAGE`, `MESSAGE_TYPE_VIDEO`, `MESSAGE_TYPE_AUDIO`, or `MESSAGE_TYPE_FILE` | Yes | +| `receiverType` | `RECEIVER_TYPE_USER` or `RECEIVER_TYPE_GROUP` | Yes | + +### Send a URL -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 that is available in the MediaMessage class. For more information, you can refer to the below code snippet: +Send media hosted on your server or cloud storage using the `Attachment` class: @@ -417,9 +398,7 @@ CometChat.sendMediaMessage(mediaMessage, new CometChat.CallbackListener - ```kotlin val receiverId = "recipient_UID" @@ -443,9 +422,7 @@ CometChat.sendMediaMessage(mediaMessage, object : CallbackListener - ```java String receiverId = "recipient_GUID"; @@ -471,9 +448,7 @@ CometChat.sendMediaMessage(mediaMessage, new CometChat.CallbackListener - ```kotlin val receiverId = "recipient_GUID" @@ -497,20 +472,16 @@ CometChat.sendMediaMessage(mediaMessage, object : CallbackListener - -When a media message is sent successfully, the response will include a `MediaMessage` object which includes all information related to the sent message. - -If you wish to send a caption or some text along with the Media Message, you can use the `caption field` provided by the MediaMessage class. To set the caption you can use the `setCaption()` method and at the receiver end, you can obtain the caption using the `getCaption()` method. As with text messages, the metadata field can be used with media messages as well. Any additional information can be passed along with the media message as a `JSONObject`. +On success, `sendMediaMessage()` returns a `MediaMessage` object. -## Multiple Attachments in a Media Message +## Multiple Attachments -Starting version 3.0.9 & above the SDK supports sending of multiple attachments in a single media message. As in case for single attachment in a media message, there are two ways you can send Media Messages using the CometChat SDK: +Starting version 3.0.9, the SDK supports sending multiple attachments in a single media message. -1. **By providing an array of files:** You can now share a List 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 are sent in the success response of the `sendMediaMessage()` method. +### Upload Multiple Files @@ -616,14 +587,14 @@ CometChat.sendMediaMessage(mediaMessage, object : CallbackListener1. `CometChatConstants.MESSAGE_TYPE_IMAGE`
2. `CometChatConstants.MESSAGE_TYPE_VIDEO`
3. `CometChatConstants.MESSAGE_TYPE_AUDIO`
4. `CometChatConstants.MESSAGE_TYPE_FILE` | -| **receiverType** | The type of the receiver to whom the message is to be sent.
1. `CometChatConstants.RECEIVER_TYPE_USER`
2. `CometChatConstants.RECEIVER_TYPE_GROUP` | +| Parameter | Description | Required | +| --- | --- | --- | +| `receiverId` | The `UID` or `GUID` of the recipient | Yes | +| `files` | A `List` of files to upload | Yes | +| `messageType` | `MESSAGE_TYPE_IMAGE`, `MESSAGE_TYPE_VIDEO`, `MESSAGE_TYPE_AUDIO`, or `MESSAGE_TYPE_FILE` | Yes | +| `receiverType` | `RECEIVER_TYPE_USER` or `RECEIVER_TYPE_GROUP` | Yes | -2. **By providing the URL of the multiple files:** The second way to send multiple attachments using the CometChat SDK is to provide the SDK with the URL of multiple files 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: +### Send Multiple URLs @@ -756,50 +727,36 @@ CometChat.sendMediaMessage(mediaMessage, object : CallbackListener ```java -CustomMessage customMessage = new CustomMessage(receiverId, receiverType,customType, customData) +CustomMessage customMessage = new CustomMessage(receiverId, receiverType, customType, customData) ``` - - ```kotlin val customMessage = CustomMessage(receiverId, receiverType, customType, customData) ``` - - -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` - 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 JSONObject. +| Parameter | Description | Required | +| --- | --- | --- | +| `receiverId` | UID of the user or GUID of the group | Yes | +| `receiverType` | `RECEIVER_TYPE_USER` or `RECEIVER_TYPE_GROUP` | Yes | +| `customType` | Developer-defined type string (e.g., `"LOCATION"`, `"POLL"`) | Yes | +| `customData` | The payload as a `JSONObject` | Yes | -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. +You can also set a subtype using `setSubtype()` to further classify the custom message. ### Add Tags -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. - ```java @@ -821,7 +778,7 @@ customMessage.setTags(tags) -Once the object of `CustomMessage` class is ready you can send the custom message using the `sendCustomMessage()` method. +Once the message object is ready, call `sendCustomMessage()`. @@ -924,15 +881,11 @@ CometChat.sendCustomMessage(customMessage, object : CallbackListener -The above sample explains how custom messages can be used to share the location with a user. Similarly, you can send custom messages to groups. +On success, `sendCustomMessage()` returns a `CustomMessage` object. -On success, you will receive an object of `CustomMessage` class. +### Control Conversation Update -### Update Conversation - -How can I decide whether the custom message should update the last message of a conversation? - -By default, a custom message will update the last message of a conversation. If you do not want to update the last message of the conversation when a custom message is sent, use the `shouldUpdateConversation(boolean value)` method of the Custom Message. +By default, a custom message updates the conversation's last message. To prevent this: @@ -1041,11 +994,9 @@ CometChat.sendCustomMessage(customMessage, object : CallbackListener -### Custom Notification Body - -How can I customize the notification body of a custom message? +### Custom Notification Text -To add a custom notification body for `Push, Email & SMS` notification of a custom message, use the `setConversationText(text: string)` method of the Custom Message class. +Set custom text for push, email, and SMS notifications: @@ -1156,10 +1107,29 @@ CometChat.sendCustomMessage(customMessage, object : CallbackListener -It is also possible to send interactive messages from CometChat , to know more [click here](/sdk/android/interactive-messages) +It is also possible to send interactive messages from CometChat, to know more [click here](/sdk/android/interactive-messages)
+--- + +## Next Steps + + + + Listen for incoming messages in real time + + + Modify sent messages after delivery + + + Remove messages from conversations + + + Send messages with embedded forms and buttons + + + ## Message Payload Structure diff --git a/sdk/android/session-timeout.mdx b/sdk/android/session-timeout.mdx index 7c39dd808..914448860 100644 --- a/sdk/android/session-timeout.mdx +++ b/sdk/android/session-timeout.mdx @@ -1,5 +1,5 @@ --- -title: "Session Timeout Flow" +title: "Session Timeout" sidebarTitle: "Session Timeout" description: "Configure idle timeout and auto-termination for inactive call sessions in Android" --- @@ -25,24 +25,18 @@ val callSettings = CometChatCalls.CallSettingsBuilder(context, videoContainer) -Available since v4.1.0 +*Available since v4.1.0* -## Overview +The Calls SDK automatically terminates call sessions when a participant is alone for too long, preventing abandoned calls from consuming resources. -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: +When a participant is alone in a session: -1. After 120 seconds of being alone in the session, the participant sees a dialog box +1. After 120 seconds, a dialog appears with "Stay" or "Leave" options +2. If no action is taken within 60 seconds, the call auto-terminates and `onSessionTimeout` fires -2. This dialog provides options to either: +The default timeout is 180 seconds (3 minutes). - * Stay in the call - * Leave immediately - -3. If no action is taken within the next 60 seconds, the call automatically ends - -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. - -### Session Timeout Flow +## Session Timeout Flow diff --git a/sdk/android/setup.mdx b/sdk/android/setup.mdx index a579958d4..1ce5ff43b 100644 --- a/sdk/android/setup.mdx +++ b/sdk/android/setup.mdx @@ -25,25 +25,23 @@ CometChat.login("UID", "AUTH_KEY", callback) // Dev only **Get from:** [CometChat Dashboard](https://app.cometchat.com) → Your App → API & Auth Keys - -Skip the create new app step. Your existing v2 app can be migrated to v3. Follow the steps mentioned in the **Add the CometChat dependency** section below to upgrade to the latest version of v3. - +## Prerequisites -## Get your Application Keys +| Requirement | Minimum Version | +| --- | --- | +| Android API Level | 21 | +| Android API Level (with Calls SDK) | 24 | +| Java | 8 | +| AndroidX | Required | -[Sign up for CometChat](https://app.cometchat.com) and then: +Get your credentials from the [CometChat Dashboard](https://app.cometchat.com): +- App ID +- Region +- Auth Key (for development) -1. Create a new app -2. Head over to the **API Keys** section and note the **Auth Key**, **App ID** & **Region** - - -Minimum Requirements - -* Android API Level 21 -* Android API Level 24 (if you are using the Calls SDK) -* AndroidX Compatibility - - + +**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. + ## Add the CometChat Dependency @@ -185,6 +183,18 @@ CometChat.init(this,appID,appSetting, object : CometChat.CallbackListener diff --git a/sdk/android/threaded-messages.mdx b/sdk/android/threaded-messages.mdx index f58676ee7..06367b7cd 100644 --- a/sdk/android/threaded-messages.mdx +++ b/sdk/android/threaded-messages.mdx @@ -60,27 +60,11 @@ MessagesRequest messagesRequest = new MessagesRequest.MessagesRequestBuilder()
- -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) - - 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. ## Send Message in a Thread -As mentioned in the [Send a Message](/sdk/android/send-message) section, you can send a message to a User or a Group by mentioning the receiver (uid/guid) and `receiverType`(user/group). - -A message can be categorized as: - -1. Text Message -2. Media Message -3. Custom Message. - -Any of the above messages can be sent in a thread. As a thread is identified with a parent message, the `parentMessageId` must be set for the message. This will indicate that the message to be sent has to be a part of the thread of the message 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. For more details on message types, see [Message Structure & Hierarchy](/sdk/android/message-structure-and-hierarchy). - -**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. @@ -123,13 +107,11 @@ CometChat.sendMessage(textMessage, object : CallbackListener() { -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. +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/android/receive-messages). This can be achieved using the `MessageListener` class provided by the SDK. 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 `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()`. @@ -193,16 +175,9 @@ CometChat.addMessageListener(listenerID, object : MessageListener() { -### Fetch all the messages for any particular thread. - -You can fetch all the messages belonging to a particular thread by using the `MessagesRequest` class. For more information on message filtering, see [Additional Message Filtering](/sdk/android/additional-message-filtering). - -The `MessageRequestBuilder` builds the `MessageRequest` object using the following functions: - -1. setParentMessageId(): Takes the parentId of the message as argument whose thread needs to be requested. -2. build(): returns the MessageRequest object. +### Fetch Thread Messages -Once you have the `MessagesRequest` object, you can call the `fetchPrevious()` method to get the latest messages in the thread. In one iteration, 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). @@ -251,7 +226,7 @@ messagesRequest.fetchPrevious(object : CallbackListener?>() { ## 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. diff --git a/sdk/android/transfer-group-ownership.mdx b/sdk/android/transfer-group-ownership.mdx index 520fe54c1..dd2a0e863 100644 --- a/sdk/android/transfer-group-ownership.mdx +++ b/sdk/android/transfer-group-ownership.mdx @@ -22,15 +22,7 @@ CometChat.transferGroupOwnership("GUID", "NEW_OWNER_UID", - Required before owner can leave the group - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) - - -How do I transfer the ownership of a group if I am the owner? - -To transfer the ownership of any group, you must first be the owner of the group. If you are the owner, use the `transferGroupOwnership()` method provided by the `CometChat` class. - -This is useful because the owner is not allowed to leave the group. If you want to leave the group as the owner, you must first transfer your ownership to another member of the group, and only then can you leave. +Use `transferGroupOwnership()` to transfer ownership to another group member. Only the current owner can do this. The owner must transfer ownership before they can leave the group. diff --git a/sdk/android/transient-messages.mdx b/sdk/android/transient-messages.mdx index fa6e13bdf..36edb4a3f 100644 --- a/sdk/android/transient-messages.mdx +++ b/sdk/android/transient-messages.mdx @@ -24,10 +24,6 @@ CometChat.addMessageListener("LISTENER_ID", object : 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/android/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. @@ -63,9 +59,7 @@ CometChat.sendTransientMessage(transientMessage) ## Real-time Transient Messages -How do I know when someone sends a transient message? - -You will receive the transient message in the `onTransientMessageReceived()` method of the registered `MessageListener` class. +Use `onTransientMessageReceived` in `MessageListener` to receive transient messages. diff --git a/sdk/android/troubleshooting.mdx b/sdk/android/troubleshooting.mdx new file mode 100644 index 000000000..04c3e59a9 --- /dev/null +++ b/sdk/android/troubleshooting.mdx @@ -0,0 +1,229 @@ +--- +title: "Troubleshooting" +sidebarTitle: "Troubleshooting" +description: "Common failure modes and fixes for the CometChat Android SDK." +--- + +Find solutions to common issues when building with the CometChat Android SDK. + + + +| 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 | +| Build fails | Check Gradle dependency version and repository URL | + + + +--- + +## Initialization & Authentication + +| Symptom | Cause | Fix | +|---------|-------|-----| +| `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 non-null strings | +| "CometChat not initialized" | `init()` not awaited | Ensure `init()` callback's `onSuccess` fires 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 start 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` | + +--- + +## Gradle & Build Issues + +| Symptom | Cause | Fix | +|---------|-------|-----| +| `Could not resolve com.cometchat:chat-sdk-android` | Missing repository | Add `https://dl.cloudsmith.io/public/cometchat/cometchat/maven/` to your project-level `build.gradle` repositories block | +| Duplicate class errors at compile time | Multiple versions of a dependency | Run `./gradlew dependencies` to find conflicts. Use `exclude group:` or force a single version | +| `Manifest merger failed` | Conflicting `minSdkVersion` | Set `minSdkVersion` to at least 21 (24 if using the Calls SDK) in your app-level `build.gradle` | +| `Java 8 features not supported` | Missing compile options | Add `compileOptions { sourceCompatibility JavaVersion.VERSION_1_8; targetCompatibility JavaVersion.VERSION_1_8 }` to your `android` block | +| Build succeeds but crashes on launch | AndroidX not enabled | Add `android.useAndroidX=true` and `android.enableJetifier=true` to `gradle.properties` | +| Calls SDK not found | Not added to Gradle | Add `implementation 'com.cometchat:calls-sdk-android:4.x.x'` to your app-level `build.gradle` | + +--- + +## Permissions + +| Symptom | Cause | Fix | +|---------|-------|-----| +| App crashes when sending media | Missing storage permission | Request `READ_EXTERNAL_STORAGE` / `READ_MEDIA_IMAGES` at runtime before file access | +| No audio in calls | `RECORD_AUDIO` not granted | Request `RECORD_AUDIO` permission before initiating or joining a call | +| No video in calls | `CAMERA` not granted | Request `CAMERA` permission before initiating or joining a video call | +| Permission dialog never appears | Permission not declared in manifest | Add the required `` tags to `AndroidManifest.xml` | +| Permission permanently denied | User selected "Don't ask again" | Use `shouldShowRequestPermissionRationale()` to detect this and direct the user to app settings | + +--- + +## ProGuard & Release Builds + +| Symptom | Cause | Fix | +|---------|-------|-----| +| App works in debug but crashes in release | ProGuard stripping SDK classes | Add CometChat ProGuard rules (see below) to your `proguard-rules.pro` | +| `ClassNotFoundException` in release build | Obfuscation removing required class | Ensure `-keep class com.cometchat.**` rules are applied | +| JSON parsing errors in release | Model class fields renamed by ProGuard | Add `-keepclassmembers` rules for SDK model classes | +| Calls SDK crashes in release | Calls SDK classes obfuscated | Add `-keep class com.cometchat.calls.**` to your ProGuard rules | + +Add these rules to your `proguard-rules.pro`: + +``` +-keep class com.cometchat.** { *; } +-keep class com.cometchat.calls.** { *; } +-dontwarn com.cometchat.** +``` + +--- + +## Messaging + +| Symptom | Cause | Fix | +|---------|-------|-----| +| `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 with same ID | Use unique listener IDs. Remove old listeners before re-registering | +| Wrong conversation | Wrong receiver type | Use `CometChatConstants.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 | 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 an admin to add you | +| Owner can't leave | Ownership not transferred | Call `transferGroupOwnership()` first | +| Password join fails | Wrong password | Pass correct password as the third parameter | +| `fetchNext()` returns same results | New request object | Reuse the same `GroupsRequest` instance | +| Scope filter returns nothing | Invalid strings | Use `"admin"`, `"moderator"`, `"participant"` | +| Cannot demote admin | Not owner | Only the 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 | Not added to Gradle | Add `implementation 'com.cometchat:calls-sdk-android:4.x.x'` | +| No audio/video | Permissions denied | Request `CAMERA` and `RECORD_AUDIO` permissions at runtime before the call | +| Call not connecting | Session ID mismatch | Verify both participants use the same session ID | +| One-way audio | Firewall blocking WebRTC | Check network config. Corporate networks may block WebRTC ports | +| Incoming call not showing | Listener not registered | Register `addCallListener()` at the Application or root Activity level | +| Call ended event not received | Wrong callback | Use `onCallEndedMessageReceived` in `CallListener` for call-end messages, `onCallEnded` in `OngoingCallListener` for session events | +| Black screen after joining | View not visible or sized | Ensure the call container `View` has non-zero dimensions and is visible | +| Calls crash in release build | ProGuard stripping classes | Add `-keep class com.cometchat.calls.** { *; }` to `proguard-rules.pro` | + +--- + +## WebSocket & Connection + +| Symptom | Cause | Fix | +|---------|-------|-----| +| Real-time events not received | WebSocket disconnected | Check `getConnectionStatus()`. Reconnect if needed | +| WebSocket fails | Firewall blocking | Check network config. Corporate firewalls may block WebSocket connections | +| Connection drops frequently | Network instability | Use `addConnectionListener()` to monitor and reconnect | +| Stuck in "connecting" | Network or config issue | Verify network, `appId`, and `region` | +| `featureThrottled` status | Feature rate-limited | Reduce frequency of the throttled feature. Listen for `onFeatureThrottled` in `ConnectionListener` | +| 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 & Lifecycle + +| Symptom | Cause | Fix | +|---------|-------|-----| +| Events not firing | Registered before init | Register after `init()` and `login()` complete | +| Duplicate events | Multiple listeners with same ID | Remove old listeners before adding new ones | +| Missing events after navigation | Listeners removed on `onPause()` | Re-register in `onResume()` when the screen becomes active | +| Events fire after screen is closed | Listeners not removed | Remove listeners in `onPause()` or `onDestroy()` | +| Receipt events not triggering | Receipts not sent | Call `markAsDelivered()`/`markAsRead()` explicitly | +| Memory leaks | Listeners holding Activity reference | Always remove listeners in `onDestroy()` | + +--- + +## Typing, Receipts & Reactions + +| Symptom | Cause | Fix | +|---------|-------|-----| +| Typing indicator stuck | `endTyping()` not called | Call on send, focus loss, or after 3–5s timeout using a `Handler` | +| 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 | +| `onMessagesDeliveredToAll`/`onMessagesReadByAll` not firing | Not registered | Register these callbacks in `MessageListener` for group-level receipt events | +| Reaction not appearing | UI not synced | Call `updateMessageWithReactionInfo()` on events | +| Duplicate reactions | No check before adding | Use `getReactedByMe()` first | + +--- + +## AI Features + +| Symptom | Cause | Fix | +|---------|-------|-----| +| 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` | + +--- + +## Upgrading from V3 + +| Symptom | Cause | Fix | +|---------|-------|-----| +| Build fails after upgrade | Old artifact still in Gradle | Replace `com.cometchat:chat-sdk-android:3.x.x` with `com.cometchat:chat-sdk-android:4.x.x` | +| Calls SDK not working | Wrong artifact version | Use `com.cometchat:calls-sdk-android:4.x.x` | +| Both versions installed | Gradle conflict | Remove the v3 dependency and sync project | + +--- + +## Error Codes + +For the complete SDK error code reference, see [Error Codes](/sdk/android/error-codes). Common errors you'll encounter: + +| Code | Description | Resolution | +|------|-------------|------------| +| `ERR_UID_NOT_FOUND` | User doesn't exist | Create user via Dashboard or REST API | +| `AUTH_ERR_AUTH_TOKEN_NOT_FOUND` | Invalid or expired auth token | Generate new token via REST API | +| `MISSING_PARAMETERS` | Required parameter not provided | Check method signature and pass all required params | +| `NOT_INITIALIZED` | `init()` not called | Call `CometChat.init()` before any other method | +| `USER_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 | +| `TOO_MANY_REQUEST` | Rate limit exceeded | See [Rate Limits](/sdk/android/rate-limits) | +| `FAILED_TO_FETCH` | Network issue | Check internet connection and API endpoint | +| `NO_WEBSOCKET_CONNECTION` | WebSocket disconnected | Check connection status, wait for reconnect | + +--- + +## Next Steps + + + + Installation and initialization guide + + + Recommended patterns and practices + + + Complete SDK error code reference + + + AI Agents, Moderation, and Copilot + + + Open a support ticket + + diff --git a/sdk/android/typing-indicators.mdx b/sdk/android/typing-indicators.mdx index cb0cf82e2..ace6930f7 100644 --- a/sdk/android/typing-indicators.mdx +++ b/sdk/android/typing-indicators.mdx @@ -22,20 +22,14 @@ CometChat.addMessageListener("LISTENER_ID", object : MessageListener() { ``` - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) - - ## Send a Typing Indicator -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. - + ```java TypingIndicator typingIndicator = new TypingIndicator(UID, CometChatConstants.RECEIVER_TYPE_USER); @@ -44,7 +38,7 @@ CometChat.startTyping(typingIndicator); - + ```kotlin val typingIndicator =TypingIndicator(UID,CometChatConstants.RECEIVER_TYPE_USER) @@ -53,7 +47,7 @@ CometChat.startTyping(typingIndicator) - + ```java TypingIndicator typingIndicator = new TypingIndicator(GUID, CometChatConstants.RECEIVER_TYPE_GROUP); @@ -62,7 +56,7 @@ CometChat.startTyping(typingIndicator); - + ```kotlin val typingIndicator = TypingIndicator(GUID,CometChatConstants.RECEIVER_TYPE_GROUP) @@ -75,10 +69,10 @@ CometChat.startTyping(typingIndicator) ### 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. - + ```java TypingIndicator typingIndicator = new TypingIndicator(UID, CometChatConstants.RECEIVER_TYPE_USER); @@ -87,7 +81,7 @@ CometChat.endtyping(typingIndicator); - + ```kotlin val typingIndicator = TypingIndicator(UID,CometChatConstants.RECEIVER_TYPE_USER) @@ -96,7 +90,7 @@ CometChat.endTyping(typingIndicator) - + ```java TypingIndicator typingIndicator = new TypingIndicator(GUID, CometChatConstants.RECEIVER_TYPE_GROUP); @@ -105,7 +99,7 @@ CometChat.endTyping(typingIndicator); - + ```kotlin val typingIndicator = TypingIndicator(GUID,CometChatConstants.RECEIVER_TYPE_GROUP) @@ -117,17 +111,12 @@ CometChat.endTyping(typingIndicator) -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 -How do I know when someone is typing? - -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. diff --git a/sdk/android/update-group.mdx b/sdk/android/update-group.mdx index 1429c5f49..c1ab73da6 100644 --- a/sdk/android/update-group.mdx +++ b/sdk/android/update-group.mdx @@ -1,5 +1,5 @@ --- -title: "Update A Group" +title: "Update Group" sidebarTitle: "Update Group" description: "Modify group details, settings, and metadata using the Android SDK" --- @@ -21,15 +21,9 @@ CometChat.updateGroup(group, object : CometChat.CallbackListener() { **Note:** Only admins and moderators can update group details. See [Group Class](/sdk/android/create-group#group-class) for editable fields. - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) - - ## Update Group -*As a group owner, how can I update the group details?* - -You can update the existing details of a group using the `updateGroup()` method. +Use `updateGroup()` with a `Group` object containing the fields you want to update. diff --git a/sdk/android/user-management.mdx b/sdk/android/user-management.mdx index 625135e26..68f820954 100644 --- a/sdk/android/user-management.mdx +++ b/sdk/android/user-management.mdx @@ -31,31 +31,11 @@ CometChat.updateCurrentUserDetails(updatedUser, object : CallbackListener( **Note:** User creation/updates should ideally happen on your backend using [REST API](https://api-explorer.cometchat.com). - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) - - -When a user logs into your app, you need to programmatically log the user into CometChat. But before you log in the user to CometChat, you need to create the user. - -In summary: - -**When a user registers in your app** - -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 to CometChat](/sdk/android/authentication-overview) (programmatically) +When a user registers in your app, create them in CometChat. When they log in, [log them into CometChat](/sdk/android/authentication-overview) as well. ## Creating a user -Ideally, user creation should take place at your backend. Refer to 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. - -However, if you wish to create users on the fly, you can use the `createUser()` method. This method takes a `User` object and the `API Key` as input parameters and returns the created `User` object if the request is successful. - -For more details on the fields present in the User class, see the [User Class](/sdk/android/user-management#user-class) section. +Ideally, user creation should happen on your backend using the [REST API](https://api-explorer.cometchat.com/reference/creates-user). For on-the-fly creation during development, use the `createUser()` method with a `User` object and your API Key. @@ -114,7 +94,7 @@ UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and othe ## Updating a user -Updating a user, similar to creating a user, should ideally be achieved at your backend using the RESTful APIs. For more information, see the [update a user](https://api-explorer.cometchat.com/reference/update-user) section. However, this can also be achieved on the fly using the `updateUser()` method. This method takes a `User` object and the API Key as inputs and returns the updated `User` object on successful execution of the request. +Use `updateUser()` with a `User` object and API Key. Ideally done on your backend via the [REST API](https://api-explorer.cometchat.com/reference/update-user). @@ -165,7 +145,7 @@ Please make sure the `User` object provided to the `updateUser()` method has the ## Updating logged-in user -Updating a logged-in user is similar to updating a user. The only difference is that this method does not require an Auth Key. This method takes a `User` object as input and returns the updated `User` object on successful execution of the request. +Use `updateCurrentUserDetails()` to update the currently logged-in user's profile. No API Key required. diff --git a/sdk/android/users-overview.mdx b/sdk/android/users-overview.mdx index dbf62eda6..a58443988 100644 --- a/sdk/android/users-overview.mdx +++ b/sdk/android/users-overview.mdx @@ -13,9 +13,16 @@ Choose your user management path: - **Block Users** → [block-users](/sdk/android/block-users) - Block and unblock users -The primary aim of our users functionality is to allow you to quickly retrieve and add users to CometChat. +Users in CometChat map directly to users in your app. Start with [user management](/sdk/android/user-management) to sync your users, then [retrieve users](/sdk/android/retrieve-users) to display them. -You can begin with [user management](/sdk/android/user-management) to sync your users to CometChat. Once that is done, you can [retrieve users](/sdk/android/retrieve-users) and display them in your app. +## Features + +| Feature | Description | Guide | +| --- | --- | --- | +| User Management | Create, update, and sync users with CometChat | [User Management](/sdk/android/user-management) | +| Retrieve Users | Fetch user lists with filters, search, and pagination | [Retrieve Users](/sdk/android/retrieve-users) | +| User Presence | Track real-time online/offline status | [User Presence](/sdk/android/user-presence) | +| Block Users | Block and unblock users to control communication | [Block Users](/sdk/android/block-users) | --- diff --git a/sdk/android/video-view-customisation.mdx b/sdk/android/video-view-customisation.mdx index 323ef5132..da5f2bc7d 100644 --- a/sdk/android/video-view-customisation.mdx +++ b/sdk/android/video-view-customisation.mdx @@ -23,15 +23,7 @@ val callSettings = CometChatCalls.CallSettingsBuilder(context, videoContainer) **Prerequisites:** [Default Calling](/sdk/android/default-calling) or [Direct Calling](/sdk/android/direct-calling) setup - - -This section guides you through customizing the main video container. - -## Implementation - -Once you have decided to implement [Default Calling](/sdk/android/default-calling) or [Direct Calling](/sdk/android/direct-calling) and followed the steps to implement them, a few additional methods will help you quickly customize the main video container. - -Make sure your `callSettings` is configured accordingly for [Default Calling](/sdk/android/default-calling) or [Direct Calling](/sdk/android/direct-calling). +Customize the main video container in your call UI — aspect ratio, button positions, and label visibility. Create a `MainVideoContainerSetting` instance, configure it, and pass it to `CallSettingsBuilder.setMainVideoContainerSetting()`. ## Main Video Container Setting diff --git a/sdk/reference/auxiliary.mdx b/sdk/reference/auxiliary.mdx index ea1107012..59a49e3a3 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, Reaction, ReactionCount, ReactionEvent, TypingIndicator, TransientMessage, Attachment, and CometChatException." --- diff --git a/sdk/reference/calls.mdx b/sdk/reference/calls.mdx index 04ea85a3f..07fbf5689 100644 --- a/sdk/reference/calls.mdx +++ b/sdk/reference/calls.mdx @@ -1,5 +1,6 @@ --- title: "Calls" +sidebarTitle: "Calls" description: "Class reference for objects returned by the CometChat Calls SDK. Covers CallLog, CallUser, CallGroup, Participant, Recording, OngoingCallListener, CometChatCallsException, and MediaDeviceInfo." --- From ce99ff33ef3f5b1cea128da9206372e1352c4892 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Tue, 31 Mar 2026 11:42:33 +0530 Subject: [PATCH 138/139] android SDK docs rewamp --- sdk/android/connection-behaviour.mdx | 70 +++++++++------------------- sdk/android/connection-status.mdx | 22 ++++----- 2 files changed, 30 insertions(+), 62 deletions(-) diff --git a/sdk/android/connection-behaviour.mdx b/sdk/android/connection-behaviour.mdx index 5f4839a45..b8701bb86 100644 --- a/sdk/android/connection-behaviour.mdx +++ b/sdk/android/connection-behaviour.mdx @@ -33,23 +33,11 @@ CometChat.ping(callback) // Keep alive (call within 30 seconds) ## Default SDK Behaviour on Login -When the login method of the SDK is called, the SDK performs the following operations: - -1. Logs the user into the SDK -2. Saves the details of the logged-in user locally -3. Creates a WebSocket connection for the logged-in user - -This ensures that the logged-in user starts receiving real-time messages sent to them or any groups they are a part of as soon as they log in. - -When the app is reopened and the `init()` method is called, the WebSocket connection to the server is established automatically. - -This is the default behaviour of the CometChat SDKs. However, if you want to take control of the WebSocket connection (connect and disconnect manually), refer to the Managing WebSocket Connection section. +On login, the SDK logs the user in, saves their details locally, and creates a WebSocket connection. When the app is reopened and `init()` is called, the WebSocket reconnects automatically. ## Auto Mode -CometChat SDK's default connection behaviour is auto mode. In auto mode, the SDK automatically establishes and maintains the WebSocket connection. You do not need to explicitly call any methods to do this. - -To enable auto mode, set the `autoEstablishSocketConnection()` method of the `AppSettings` builder class to `true`. If you do not set this, the SDK automatically applies auto mode as the default behaviour for the WebSocket connection. +The default mode. The SDK automatically establishes and maintains the WebSocket connection. Set `autoEstablishSocketConnection(true)` (or omit it — auto mode is the default). @@ -66,13 +54,9 @@ If the app is in the foreground and there is no internet connection, the SDK wil ## Manual Mode -In manual mode, you must explicitly establish and disconnect the WebSocket connection. To do this, set the `autoEstablishSocketConnection()` method to `false` and then call the `CometChat.connect()` method to establish the connection and the `CometChat.disconnect()` method to disconnect. +Set `autoEstablishSocketConnection(false)` to take control of the WebSocket connection. Call `CometChat.connect()` to establish and `CometChat.disconnect()` to break it. -By default, if manual mode is activated, the SDK disconnects the WebSocket connection after 30 seconds if the app goes into the background. This means the WebSocket connection remains alive for 30 seconds after the app goes into the background, but it disconnects after that time if no pings are received. - -To keep the WebSocket connection alive even if your app goes into the background, call the `CometChat.ping()` method from your app within 30 seconds. This method sends a ping message to the CometChat server, which tells the server that the app is still active. - -If you do not call the `CometChat.ping()` method within 30 seconds, the SDK disconnects the WebSocket connection. This means you will lose any messages sent to your app while it is in the background. +By default in manual mode, the SDK disconnects after 30 seconds in the background if no pings are received. Call `CometChat.ping()` within 30 seconds to keep the connection alive. @@ -83,13 +67,9 @@ If you do not call the `CometChat.ping()` method within 30 seconds, the SDK disc | App in foreground | Call `CometChat.connect()` to create the WebSocket connection | | App in background | Disconnect the WebSocket connection if no ping is received within 30 seconds after the app goes in the background | -## Managing Manually - -The CometChat SDK also allows you to modify the default behaviour and take control of the WebSocket connection yourself. To achieve this, follow the steps below. - ## Enable Manual Mode -While calling the `init()` function on app startup, you need to inform the SDK that you will be managing the WebSocket connection. You can do so by using the `autoEstablishSocketConnection()` method provided by the `AppSettingsBuilder` class. This method takes a boolean value as input. If set to `true`, the SDK manages the WebSocket connection internally based on the default behaviour mentioned above. If set to `false`, the WebSocket connection is not managed by the SDK and you must handle it manually. Refer to the code snippet below: +Set `autoEstablishSocketConnection(false)` during `init()` to take control of the WebSocket connection: @@ -119,25 +99,23 @@ CometChat.init(this, appId, appSettings, new CometChat.CallbackListener( ```kotlin -String appId = "YOUR_APP_ID"; -String region = "us"; +val appId = "YOUR_APP_ID" +val region = "us" -AppSettings appSettings = new AppSettings.AppSettingsBuilder() +val appSettings = AppSettings.AppSettingsBuilder() .setRegion(region) - .autoEstablishSocketConnection(false) //set it as false for manual mode - .build(); + .autoEstablishSocketConnection(false) // set to false for manual mode + .build() -CometChat.init(this, appId, appSettings, new CometChat.CallbackListener() { - @Override - public void onSuccess(String s) { - Log.d(TAG, "Init successful!"); +CometChat.init(this, appId, appSettings, object : CometChat.CallbackListener() { + override fun onSuccess(s: String) { + Log.d(TAG, "Init successful!") } - @Override - public void onError(CometChatException e) { - Log.d(TAG, "Error occurred : " + e.getMessage()); + override fun onError(e: CometChatException) { + Log.d(TAG, "Error occurred : " + e.message) } -}); +}) ``` @@ -148,7 +126,7 @@ You can manage the connection to the WebSocket server using the `connect()`, `di ## Connect to the WebSocket Server -Use the `connect()` method provided by the `CometChat` class to establish the connection to the WebSocket server. Make sure the user is logged in to the SDK before calling this method. You can use the `CometChat.getLoggedInUser()` method to check this. Once the connection is established, you start receiving all real-time events for the logged-in user. +Call `connect()` to establish the connection. Ensure the user is logged in first (`CometChat.getLoggedInUser()`). @@ -187,7 +165,7 @@ CometChat.connect(object : CallbackListener() { ## Disconnect from the WebSocket Server -Use the `disconnect()` method provided by the `CometChat` class to break the established connection. Once the connection is broken, you stop receiving all real-time events for the logged-in user. +Call `disconnect()` to break the connection. Real-time events stop until reconnected. @@ -226,13 +204,7 @@ CometChat.disconnect(object : CallbackListener() { ## Maintain Long-Standing Background Connection - - -To ensure that the WebSocket connection is always alive, you can create a service or background service that calls the `CometChat.ping()` method in a loop. This ensures that the ping message is sent to the server every 30 seconds, even if the app is not in the foreground. - - - -You can maintain a long-standing background connection even when your app is in the background by calling the `CometChat.ping()` method within 30 seconds of your app entering the background or after the previous `ping()` call. +Call `CometChat.ping()` within 30 seconds of the app entering the background to keep the connection alive. @@ -269,7 +241,9 @@ CometChat.ping(object : CallbackListener() { -Reconnection: If manual mode is enabled and the app is in the foreground, the SDK automatically reconnects the WebSocket if the internet connection is lost. However, if the app is in the background and the WebSocket is disconnected or you called `CometChat.disconnect()`, you need to call the `CometChat.connect()` method to create a new WebSocket connection. + +In manual mode with the app in the foreground, the SDK auto-reconnects if the internet drops. If the app is in the background and the connection was disconnected, call `CometChat.connect()` to reconnect. + --- diff --git a/sdk/android/connection-status.mdx b/sdk/android/connection-status.mdx index ad9a407c1..bdd5943ff 100644 --- a/sdk/android/connection-status.mdx +++ b/sdk/android/connection-status.mdx @@ -25,20 +25,14 @@ CometChat.removeConnectionListener("LISTENER_ID") ``` -CometChat SDK provides you with a mechanism to get real-time status of the connection to CometChat web-socket servers. To achieve this you need to use the `ConnectionListener` class provided by the CometChat SDK - -Connection Status provides you with the below 3 methods to get the status of the connection to CometChat web-socket servers: - -| Delegate Method | Information | -| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------ | -| onConnecting | This method is triggered when CometChat SDK is trying to establish a connection to the web-socket server. | -| onConnected | This method is called when CometChat SDK has successfully established a connection and now is connected. | -| onDisconnected | This method is called when the CometChat SDK gets disconnected due to any issue while maintaining the connection like network fluctuations, etc. | -| onFeatureThrottled | CometChat automatically toggles off certain features to prevent performance loss for end-users under various circumstances | - -Once the connection is broken, the disconnected callback is triggered, the SDK automatically tries to establish the connection again, thus going into the connecting state and triggering the `connecting` method. Once the attempt to connect is successful, the `connected` method is triggered thus letting the developer know that the connection is established and is active. - -In order to use the ConnectionListeners, you need to add the ConnectionListeners using the `addConnectionListener` method provided by the SDK. You can add multiple listeners as shown below. Just make sure you add listeners with unique IDs. +Use `ConnectionListener` to monitor real-time WebSocket connection state. The SDK automatically attempts to reconnect when disconnected. + +| Callback | Description | +| --- | --- | +| `onConnecting` | SDK is attempting to establish a WebSocket connection | +| `onConnected` | Connection successfully established | +| `onDisconnected` | Connection lost (network fluctuation, etc.) | +| `onFeatureThrottled` | CometChat toggled off certain features to prevent performance loss | From 53c036fcaad86c8d62a32e722362e2fb21a81936 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Tue, 31 Mar 2026 12:07:52 +0530 Subject: [PATCH 139/139] SDK fixes --- sdk/android/ai-chatbots-overview.mdx | 299 +----------------------- sdk/android/authentication-overview.mdx | 4 +- sdk/android/connection-status.mdx | 19 +- sdk/android/login-listeners.mdx | 102 +------- sdk/android/upgrading-from-v3-guide.mdx | 4 +- sdk/android/user-presence.mdx | 42 +--- 6 files changed, 36 insertions(+), 434 deletions(-) diff --git a/sdk/android/ai-chatbots-overview.mdx b/sdk/android/ai-chatbots-overview.mdx index 55776d032..d77b05e36 100644 --- a/sdk/android/ai-chatbots-overview.mdx +++ b/sdk/android/ai-chatbots-overview.mdx @@ -5,303 +5,6 @@ description: "Implement custom AI chatbots for automated conversations in your A url: "/ai-chatbots/overview" --- -# AI Chatbots Overview - AI Chatbots enable automated conversations within your application. They can process user messages and respond with contextually relevant information. For a broader introduction, see the [AI Chatbots section](/ai-chatbots). -## Agentic Message Payload Structures - - - -The `AIAssistantMessage` object contains the AI assistant's response: - -| Parameter | Type | Description | -|-----------|------|-------------| -| `id` | long | Unique message identifier | -| `muid` | String | Developer-defined message ID | -| `sender` | [User](#user-object-chatbot) | User who sent the message | -| `receiver` | AppEntity | Message receiver ([User](#user-object-chatbot) or Group) | -| `receiverUid` | String | Receiver's unique identifier | -| `type` | String | Message type. Value: `"assistant"` | -| `receiverType` | String | Type of receiver. Values: `"user"`, `"group"` | -| `category` | String | Message category. Value: `"agentic"` | -| `sentAt` | long | Unix timestamp when sent | -| `deliveredAt` | long | Unix timestamp when delivered | -| `readAt` | long | Unix timestamp when read | -| `metadata` | JSONObject | Custom message metadata | -| `readByMeAt` | long | When logged-in user read message | -| `deliveredToMeAt` | long | When delivered to logged-in user | -| `deletedAt` | long | Unix timestamp when deleted (0 if not deleted) | -| `editedAt` | long | Unix timestamp when edited (0 if not edited) | -| `deletedBy` | String | UID of user who deleted (null if not deleted) | -| `editedBy` | String | UID of user who edited (null if not edited) | -| `updatedAt` | long | Unix timestamp of last update | -| `conversationId` | String | Associated conversation ID | -| `runId` | long | AI run identifier | -| `threadId` | String | AI thread identifier | -| `text` | String | AI response text | -| `tags` | Array\ | Message tags | - -**Sample AIAssistantMessage Object:** - -```json -{ - "id": 12345, - "muid": "msg_abc123", - "sender": { - "uid": "user_123", - "name": "John Doe", - "avatar": "https://example.com/avatar.png", - "status": "online", - "role": "default" - }, - "receiver": { - "uid": "user_456", - "name": "Jane Smith" - }, - "receiverUid": "user_456", - "type": "assistant", - "receiverType": "user", - "category": "agentic", - "sentAt": 1699900000, - "deliveredAt": 1699900001, - "readAt": 1699900002, - "metadata": {"priority": "high"}, - "readByMeAt": 1699900002, - "deliveredToMeAt": 1699900001, - "deletedAt": 0, - "editedAt": 0, - "deletedBy": null, - "editedBy": null, - "updatedAt": 1699900000, - "conversationId": "user_123_user_456", - "runId": 98765, - "threadId": "thread_abc", - "text": "Here's the answer...", - "tags": ["ai-response"] -} -``` - - - - - -The `AIToolArgumentMessage` object contains the arguments passed to a tool: - -| Parameter | Type | Description | -|-----------|------|-------------| -| `id` | long | Unique message identifier | -| `muid` | String | Developer-defined message ID | -| `sender` | [User](#user-object-chatbot) | User who sent the message | -| `receiver` | AppEntity | Message receiver ([User](#user-object-chatbot) or Group) | -| `receiverUid` | String | Receiver's unique identifier | -| `type` | String | Message type. Value: `"tool_arguments"` | -| `receiverType` | String | Type of receiver. Values: `"user"`, `"group"` | -| `category` | String | Message category. Value: `"agentic"` | -| `sentAt` | long | Unix timestamp when sent | -| `deliveredAt` | long | Unix timestamp when delivered | -| `readAt` | long | Unix timestamp when read | -| `metadata` | JSONObject | Custom message metadata | -| `readByMeAt` | long | When logged-in user read message | -| `deliveredToMeAt` | long | When delivered to logged-in user | -| `deletedAt` | long | Unix timestamp when deleted (0 if not deleted) | -| `editedAt` | long | Unix timestamp when edited (0 if not edited) | -| `deletedBy` | String | UID of user who deleted (null if not deleted) | -| `editedBy` | String | UID of user who edited (null if not edited) | -| `updatedAt` | long | Unix timestamp of last update | -| `conversationId` | String | Associated conversation ID | -| `runId` | long | AI run identifier | -| `threadId` | String | AI thread identifier | -| `toolCalls` | Array\<[AIToolCall](#aitoolcall-object-chatbot)\> | List of tool calls | -| `tags` | Array\ | Message tags | - -**Sample AIToolArgumentMessage Object:** - -```json -{ - "id": 12346, - "muid": "msg_tool_arg_123", - "sender": { - "uid": "user_123", - "name": "John Doe", - "avatar": "https://example.com/avatar.png", - "status": "online", - "role": "default" - }, - "receiver": { - "uid": "user_456", - "name": "Jane Smith" - }, - "receiverUid": "user_456", - "type": "tool_arguments", - "receiverType": "user", - "category": "agentic", - "sentAt": 1699900000, - "deliveredAt": 1699900001, - "readAt": 1699900002, - "metadata": {"priority": "high"}, - "readByMeAt": 1699900002, - "deliveredToMeAt": 1699900001, - "deletedAt": 0, - "editedAt": 0, - "deletedBy": null, - "editedBy": null, - "updatedAt": 1699900000, - "conversationId": "user_123_user_456", - "runId": 98765, - "threadId": "thread_abc", - "toolCalls": [ - { - "id": "call_abc123", - "name": "search_flights", - "arguments": {"origin": "NYC", "destination": "LA"} - } - ], - "tags": ["tool-arguments"] -} -``` - - - - - -The `AIToolResultMessage` object contains the result from a tool execution: - -| Parameter | Type | Description | -|-----------|------|-------------| -| `id` | long | Unique message identifier | -| `muid` | String | Developer-defined message ID | -| `sender` | [User](#user-object-chatbot) | User who sent the message | -| `receiver` | AppEntity | Message receiver ([User](#user-object-chatbot) or Group) | -| `receiverUid` | String | Receiver's unique identifier | -| `type` | String | Message type. Value: `"tool_result"` | -| `receiverType` | String | Type of receiver. Values: `"user"`, `"group"` | -| `category` | String | Message category. Value: `"agentic"` | -| `sentAt` | long | Unix timestamp when sent | -| `deliveredAt` | long | Unix timestamp when delivered | -| `readAt` | long | Unix timestamp when read | -| `metadata` | JSONObject | Custom message metadata | -| `readByMeAt` | long | When logged-in user read message | -| `deliveredToMeAt` | long | When delivered to logged-in user | -| `deletedAt` | long | Unix timestamp when deleted (0 if not deleted) | -| `editedAt` | long | Unix timestamp when edited (0 if not edited) | -| `deletedBy` | String | UID of user who deleted (null if not deleted) | -| `editedBy` | String | UID of user who edited (null if not edited) | -| `updatedAt` | long | Unix timestamp of last update | -| `conversationId` | String | Associated conversation ID | -| `runId` | long | AI run identifier | -| `threadId` | String | AI thread identifier | -| `text` | String | Tool result text | -| `toolCallId` | String | ID of the tool call that produced this result | -| `tags` | Array\ | Message tags | - -**Sample AIToolResultMessage Object:** - -```json -{ - "id": 12347, - "muid": "msg_tool_result_123", - "sender": { - "uid": "user_123", - "name": "John Doe", - "avatar": "https://example.com/avatar.png", - "status": "online", - "role": "default" - }, - "receiver": { - "uid": "user_456", - "name": "Jane Smith" - }, - "receiverUid": "user_456", - "type": "tool_result", - "receiverType": "user", - "category": "agentic", - "sentAt": 1699900000, - "deliveredAt": 1699900001, - "readAt": 1699900002, - "metadata": {"priority": "high"}, - "readByMeAt": 1699900002, - "deliveredToMeAt": 1699900001, - "deletedAt": 0, - "editedAt": 0, - "deletedBy": null, - "editedBy": null, - "updatedAt": 1699900000, - "conversationId": "user_123_user_456", - "runId": 98765, - "threadId": "thread_abc", - "text": "Flight found: NYC to LA...", - "toolCallId": "call_abc123", - "tags": ["tool-result"] -} -``` - - - - - -The `AIToolCall` object represents a single tool invocation: - -| Parameter | Type | Description | -|-----------|------|-------------| -| `id` | String | Unique identifier for the tool call | -| `name` | String | Name of the tool being called | -| `arguments` | JSONObject | Arguments passed to the tool | - -**Sample AIToolCall Object:** - -```json -{ - "id": "call_abc123", - "name": "search_flights", - "arguments": { - "origin": "NYC", - "destination": "LA", - "date": "2024-01-15" - } -} -``` - - - - - -The nested `User` object in `sender` contains: - -| Parameter | Type | Description | -|-----------|------|-------------| -| `uid` | String | Unique identifier of the user | -| `name` | String | Display name of the user | -| `avatar` | String | URL to user's profile picture | -| `link` | String | URL to user's profile page | -| `role` | String | User role for access control | -| `metadata` | JSONObject | Custom data set by developer | -| `status` | String | User online status. Values: `"online"`, `"offline"` | -| `statusMessage` | String | Custom status message | -| `lastActiveAt` | long | Unix timestamp of last activity | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | -| `blockedByMe` | boolean | Whether the logged-in user has blocked this user | -| `tags` | Array\ | List of tags for user identification | -| `deactivatedAt` | long | Unix timestamp when user was deactivated (0 if active) | - -**Sample User Object:** - -```json -{ - "uid": "user_123", - "name": "John Doe", - "avatar": "https://example.com/avatar.png", - "link": "https://example.com/profile/user_123", - "role": "default", - "metadata": {"department": "engineering"}, - "status": "online", - "statusMessage": "Available", - "lastActiveAt": 1699900000, - "hasBlockedMe": false, - "blockedByMe": false, - "tags": ["premium"], - "deactivatedAt": 0 -} -``` - - \ No newline at end of file +For message payload structures (AIAssistantMessage, AIToolArgumentMessage, AIToolResultMessage), see the [AI Agents](/sdk/android/ai-agents#agentic-message-payload-structures) page. diff --git a/sdk/android/authentication-overview.mdx b/sdk/android/authentication-overview.mdx index 4e2a2a6c6..c98607794 100644 --- a/sdk/android/authentication-overview.mdx +++ b/sdk/android/authentication-overview.mdx @@ -324,8 +324,8 @@ Always remove login listeners when they're no longer needed (e.g., in `onDestroy Retrieve and manage users in your application - - Review SDK installation and initialization steps + + Monitor the SDK connection state in real time Understand core CometChat concepts and terminology diff --git a/sdk/android/connection-status.mdx b/sdk/android/connection-status.mdx index bdd5943ff..e333d3a6a 100644 --- a/sdk/android/connection-status.mdx +++ b/sdk/android/connection-status.mdx @@ -96,7 +96,9 @@ CometChat.addConnectionListener("UNIQUE_LISTENER_ID", object : ConnectionListene -You can also get the current connection status by using `getConnectionStatus` property provided by CometChat SDK +## Get Current Status + +Use `getConnectionStatus()` to check the current connection state at any time: @@ -115,15 +117,14 @@ val connectionStatus = CometChat.getConnectionStatus() -The above method will return either of the below 3 values: - -1. `CometChatConstants.WS_STATE_CONNECTED` (connected); - -2. `CometChatConstants.WS_STATE_CONNECTING`(connecting) +Returns one of: -3. `CometChatConstants.WS_STATE_DISCONNECTED`(disconnected) - -4. `CometChatConstants.WS_STATE_FEATURE_THROTTLED`(featureThrottled) +| Value | Description | +| --- | --- | +| `CometChatConstants.WS_STATE_CONNECTED` | Active connection | +| `CometChatConstants.WS_STATE_CONNECTING` | Attempting to connect | +| `CometChatConstants.WS_STATE_DISCONNECTED` | No connection | +| `CometChatConstants.WS_STATE_FEATURE_THROTTLED` | Feature throttled | diff --git a/sdk/android/login-listeners.mdx b/sdk/android/login-listeners.mdx index 4804ebe5d..3e837035b 100644 --- a/sdk/android/login-listeners.mdx +++ b/sdk/android/login-listeners.mdx @@ -1,7 +1,7 @@ --- title: "Login Listeners" sidebarTitle: "Login Listeners" -description: "Receive real-time updates for login and logout events in the Android SDK" +description: "Android Activity and Fragment lifecycle patterns for CometChat login and logout event handling" --- @@ -20,73 +20,9 @@ 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: +This page covers Android-specific lifecycle patterns for `LoginListener`. For the basic add/remove API, see [Authentication](/sdk/android/authentication-overview#login-listener). -| Callback Method | Information | -| ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| loginSuccess(User user) | Informs you that the login was successful and provides you with a user object containing the data for the user that logged in | -| loginFailure(CometChatException e) | Informs you about the failure while logging in the user and provides you with the reason for the failure wrapped in an object of the `CometChatException` class | -| logoutSuccess() | Informs you about the user being logged out successfully. | -| logoutFailure(CometChatException e) | Informs you about the failure while logging out the user. The reason for the failure can be obtained from the object of the `CometChatException` class provided. | - -To add the `LoginListener`, you need to use the `addLoginListener()` method provided by the SDK which takes a unique identifier for the listener and of the the `LoginListener` class itself. - - - -```java -CometChat.addLoginListener("UNIQUE_ID", new CometChat.LoginListener() { - @Override - public void loginSuccess(User user) { - Log.d("LoginListener", "loginSuccess " + user.toString()); - } - - @Override - public void loginFailure(CometChatException e) { - Log.d("LoginListener", "loginFailure " + e.getMessage()); - } - - @Override - public void logoutSuccess() { - Log.d("LoginListener", "logoutSuccess "); - } - - @Override - public void logoutFailure(CometChatException e) { - Log.d("LoginListener", "logoutFailure "); - } -}); -``` - - - - -```kotlin -CometChat.addLoginListener("UNIQUE_ID", object : LoginListener() { - override fun loginSuccess(user: User) { - Log.d("LoginListener", "loginSuccess $user") - } - - override fun loginFailure(e: CometChatException) { - Log.d("LoginListener", "loginFailure " + e.message) - } - - override fun logoutSuccess() { - Log.d("LoginListener", "logoutSuccess ") - } - - override fun logoutFailure(e: CometChatException) { - Log.d("LoginListener", "logoutFailure ") - } -}) -``` - - - - - -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. - -### Android Activity/Fragment Example +## Android Activity/Fragment Example Register the listener in `onCreate()` and remove it in `onDestroy()` to follow the Android lifecycle: @@ -171,24 +107,6 @@ class MainActivity : AppCompatActivity() { - - -```java -CometChat.removeLoginListener("UNIQUE_ID"); -``` - - - - -```kotlin -CometChat.removeLoginListener("UNIQUE_ID") -``` - - - - - - Always remove login listeners when they're no longer needed (e.g., in `onDestroy()` or when navigating away). Failing to remove listeners can cause memory leaks and duplicate event handling. @@ -215,16 +133,16 @@ Always remove login listeners when they're no longer needed (e.g., in `onDestroy ## Next Steps - - Initialize the SDK before logging in users + + Login methods, Auth Key vs Auth Token, and logout - - Learn about authentication methods and best practices + + Register listeners for messages, users, groups, and calls - + Monitor connection status to CometChat servers - - Register listeners for messages, users, groups, and calls + + Initialize the SDK before logging in users diff --git a/sdk/android/upgrading-from-v3-guide.mdx b/sdk/android/upgrading-from-v3-guide.mdx index 8d5954cf7..82d783b4f 100644 --- a/sdk/android/upgrading-from-v3-guide.mdx +++ b/sdk/android/upgrading-from-v3-guide.mdx @@ -22,9 +22,7 @@ description: "Migration guide for upgrading from CometChat Android SDK v3 to v4" -Upgrading from v3.x to v4 is straightforward. Below are the major changes released as part of CometChat v4: - -Follow the [setup](/sdk/android/setup) instructions to upgrade to the latest V4 version. +Upgrading from v3.x to v4 is straightforward. The API surface is the same — only the Maven URL, dependency artifact, and import package names changed. ## Maven URL Change diff --git a/sdk/android/user-presence.mdx b/sdk/android/user-presence.mdx index 962ac8307..4b82b55a4 100644 --- a/sdk/android/user-presence.mdx +++ b/sdk/android/user-presence.mdx @@ -56,31 +56,21 @@ CometChat.removeUserListener("LISTENER_ID"); - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/android/overview) - - -User Presence helps you understand if a user is available to chat or not. +User Presence lets you know if a user is available to chat. Configure presence subscription during `init()`, then listen for online/offline events via `UserListener`. ## Real-time Presence -*As a logged-in user, how do I know if a user is online or offline?* - -Based on the settings provided in the `AppSettings` class while initializing CometChat using the `init()` method, the logged-in user will receive the presence for other users in the app. - -In the `AppSettings` class, you can set the type of presence you wish to receive. - -For presence subscription, the `AppSettingsBuilder` provides 3 methods: +Based on the `AppSettings` configured during `init()`, the logged-in user receives presence updates for other users. -* `subscribePresenceForAllUsers()` - Informs the logged-in user when any user in the app comes online or goes offline. -* `subscribePresenceForRoles(List roles)` - Informs the logged-in user only when users with the specified roles come online or go offline. -* `subscribePresenceForFriends()` - Informs the logged-in user when any of their friends come online or go offline. +`AppSettingsBuilder` provides three subscription options: -If none of the above methods are set, no presence will be sent to the logged-in user. +* `subscribePresenceForAllUsers()` — Receive presence for all users in the app. +* `subscribePresenceForRoles(List roles)` — Receive presence only for users with specified roles. +* `subscribePresenceForFriends()` — Receive presence only for friends. -For every activity or fragment where you wish to receive user events, you need to register the `UserListener` using the `addUserListener()` method. +If none are set, no presence events are sent. -We suggest adding the listener in the `onResume()` method of the activity or fragment where you wish to receive these events. +Register `UserListener` in `onResume()` and remove it in `onPause()`. @@ -121,9 +111,7 @@ CometChat.addUserListener(listenerID,object :CometChat.UserListener(){ | ------------ | ----------------------------------------------------------------------------------------------- | | `listenerID` | An ID that uniquely identifies that listener. We recommend using the activity or fragment name. | -You will receive an object of the `User` class in the listener methods. - -We recommend removing the listener once the activity or fragment is not in use. We suggest adding this method in the `onPause()` method of the activity or fragment where you wish to receive these events. +Remove the listener in `onPause()` when the activity or fragment is no longer in use. @@ -152,16 +140,10 @@ Always remove listeners when they're no longer needed (e.g., in `onPause()` or ` ## User List Presence -*As a logged-in user, when I retrieve the user list, how do I know if a user is online/offline?* - -When you [retrieve the list of users](/sdk/android/retrieve-users), in the [User](/sdk/android/user-management#user-class) object, you will receive 2 keys: - -1. `status` - This holds either of the two values: - -* `online` - Indicates that the user is currently online and available to chat. -* `offline` - Indicates that the user is currently offline and not available to chat. +When you [retrieve the list of users](/sdk/android/retrieve-users), each `User` object includes: -2. `lastActiveAt` - If the user is offline, this field holds the timestamp of when the user was last online. This can be used to display a **Last seen** indicator for that user. +* `status` — `"online"` or `"offline"` +* `lastActiveAt` — Unix timestamp of when the user was last online (useful for "Last seen" indicators) ---