diff --git a/docs.json b/docs.json index 0c4b83427..db0bcd8cd 100644 --- a/docs.json +++ b/docs.json @@ -3222,35 +3222,20 @@ { "group": " ", "pages": [ - { - "group": "Overview", - "pages": [ - "sdk/react-native/overview", - "sdk/react-native/key-concepts", - "sdk/react-native/message-structure-and-hierarchy", - "sdk/react-native/rate-limits" - ] - }, + "sdk/react-native/overview", "sdk/react-native/setup-sdk", - { - "group": "Authentication", - "pages": [ - "sdk/react-native/authentication-overview", - "sdk/react-native/login-listener" - ] - }, + "sdk/react-native/authentication-overview", { "group": "Messaging", "pages": [ - "sdk/react-native/messaging-overview", "sdk/react-native/send-message", "sdk/react-native/receive-messages", "sdk/react-native/additional-message-filtering", "sdk/react-native/retrieve-conversations", "sdk/react-native/threaded-messages", "sdk/react-native/edit-message", - "sdk/react-native/flag-message", "sdk/react-native/delete-message", + "sdk/react-native/flag-message", "sdk/react-native/delete-conversation", "sdk/react-native/typing-indicators", "sdk/react-native/transient-messages", @@ -3307,8 +3292,12 @@ { "group": "Resources", "pages": [ - "sdk/react-native/resources-overview", + "sdk/react-native/key-concepts", + "sdk/react-native/message-structure-and-hierarchy", "sdk/react-native/real-time-listeners", + "sdk/react-native/rate-limits", + "sdk/react-native/connection-status", + "sdk/react-native/managing-web-sockets-connections-manually", { "group": "Push Notifications", "pages": [ @@ -3316,18 +3305,10 @@ "notifications/react-native-push-notifications-ios" ] }, - "sdk/react-native/push-notification-html-stripping", - "sdk/react-native/upgrading-from-v3" - ] - }, - { - "group": "Advanced", - "pages": [ - "sdk/react-native/advanced-overview", - "sdk/react-native/connection-status", - "sdk/react-native/managing-web-sockets-connections-manually" + "sdk/react-native/push-notification-html-stripping" ] }, + "sdk/react-native/upgrading-from-v3", "sdk/react-native/extensions-overview", "sdk/react-native/ai-user-copilot-overview", "sdk/react-native/ai-chatbots-overview", @@ -3560,27 +3541,12 @@ { "group": " ", "pages": [ - { - "group": "Overview", - "pages": [ - "sdk/ios/overview", - "sdk/ios/key-concepts", - "sdk/ios/message-structure-and-hierarchy", - "sdk/ios/rate-limits" - ] - }, + "sdk/ios/overview", "sdk/ios/setup", - { - "group": "Authentication", - "pages": [ - "sdk/ios/authentication-overview", - "sdk/ios/login-listeners" - ] - }, + "sdk/ios/authentication-overview", { "group": "Messaging", "pages": [ - "sdk/ios/messaging-overview", "sdk/ios/send-message", "sdk/ios/receive-message", "sdk/ios/additional-message-filtering", @@ -3591,9 +3557,9 @@ "sdk/ios/delete-conversation", "sdk/ios/flag-message", "sdk/ios/typing-indicators", - "sdk/ios/delivery-read-receipts", "sdk/ios/interactive-messages", "sdk/ios/transient-messages", + "sdk/ios/delivery-read-receipts", "sdk/ios/mentions", "sdk/ios/reactions" ] @@ -3643,30 +3609,25 @@ "sdk/ios/ai-moderation", "sdk/ios/ai-agents", { - "group": "Advanced", + "group": "Resources", "pages": [ - "sdk/ios/advanced", + "sdk/ios/key-concepts", + "sdk/ios/message-structure-and-hierarchy", + "sdk/ios/all-real-time-delegates-listeners", + "sdk/ios/rate-limits", "sdk/ios/connection-status", - "sdk/ios/web-socket-connection-behaviour", "sdk/ios/managing-web-socket-connections-manually", + "sdk/ios/web-socket-connection-behaviour", "sdk/ios/marking-delivered-with-push-notification", - "sdk/ios/publishing-app-on-appstore" - ] - }, - { - "group": "Resources", - "pages": [ - "sdk/ios/resources-overview", - "sdk/ios/all-real-time-delegates-listeners", "sdk/ios/increment-app-icon-badge-count", "sdk/ios/remove-delivered-notifications", "sdk/ios/launch-call-screen-on-tap-of-push-notification", "sdk/ios/launch-chat-window-on-tap-of-push-notification", "sdk/ios/prepare-your-app-for-background-updates", - "sdk/ios/upgrading-from-v3-to-v4", - "sdk/ios/upgrading-from-v2" + "sdk/ios/publishing-app-on-appstore" ] }, + "sdk/ios/upgrading-from-v3-to-v4", "sdk/ios/extensions-overview", "sdk/ios/ai-user-copilot-overview", "sdk/ios/ai-chatbots-overview", @@ -4023,27 +3984,12 @@ { "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": [ - "sdk/android/messaging-overview", "sdk/android/send-message", "sdk/android/receive-messages", "sdk/android/additional-message-filtering", @@ -4108,25 +4054,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" ] } @@ -4361,27 +4315,12 @@ { "group": " ", "pages": [ - { - "group": "Overview", - "pages": [ - "sdk/flutter/overview", - "sdk/flutter/key-concepts", - "sdk/flutter/message-structure-and-hierarchy", - "sdk/flutter/rate-limits" - ] - }, + "sdk/flutter/overview", "sdk/flutter/setup", - { - "group": "Authentication", - "pages": [ - "sdk/flutter/authentication-overview", - "sdk/flutter/login-listeners" - ] - }, + "sdk/flutter/authentication-overview", { "group": "Messaging", "pages": [ - "sdk/flutter/messaging-overview", "sdk/flutter/send-message", "sdk/flutter/receive-messages", "sdk/flutter/additional-message-filtering", @@ -4436,7 +4375,7 @@ "sdk/flutter/delete-group", "sdk/flutter/retrieve-group-members", "sdk/flutter/group-add-members", - "sdk/flutter/group-kick-member", + "sdk/flutter/group-kick-ban-members", "sdk/flutter/group-change-member-scope", "sdk/flutter/transfer-group-ownership" ] @@ -4446,24 +4385,31 @@ { "group": "Resources", "pages": [ - "sdk/flutter/resources-overview", + "sdk/flutter/key-concepts", + "sdk/flutter/message-structure-and-hierarchy", "sdk/flutter/real-time-listeners", - "sdk/flutter/upgrading-from-v3-guide" + "sdk/flutter/rate-limits", + "sdk/flutter/connection-status", + "sdk/flutter/connection-behaviour" ] }, { - "group": "Advanced", + "group": "Reference", "pages": [ - "sdk/flutter/advanced-overview", - "sdk/flutter/connection-status", - "sdk/flutter/connection-behaviour" + "sdk/reference/messages", + "sdk/reference/entities", + "sdk/reference/auxiliary", + "sdk/reference/calls" ] }, + "sdk/flutter/upgrading-from-v3-guide", + "sdk/flutter/best-practices", + "sdk/flutter/error-codes", + "sdk/flutter/troubleshooting", "sdk/flutter/extensions-overview", "sdk/flutter/ai-user-copilot-overview", "sdk/flutter/ai-chatbots-overview", "sdk/flutter/webhooks-overview", - "sdk/flutter/flutter-overview", "sdk/flutter/changelog" ] } @@ -6384,6 +6330,14 @@ } }, "redirects": [ + { + "source": "/sdk/flutter/group-kick-member", + "destination": "/sdk/flutter/group-kick-ban-members" + }, + { + "source": "/sdk/flutter/login-listeners", + "destination": "/sdk/flutter/authentication-overview#login-listener" + }, { "source": "/react-native/getting-started", "destination": "/react-native/react-native-cli-integration" diff --git a/flutter-sdk-changes-review.md b/flutter-sdk-changes-review.md new file mode 100644 index 000000000..709c967ec --- /dev/null +++ b/flutter-sdk-changes-review.md @@ -0,0 +1,134 @@ +# Flutter SDK (`sdk/flutter/`) Changes Review + +> **Base:** commit `5e4976de` (state before the improvements branch) +> **Target:** commit `9feb900b` (tip of `docs/flutter-sdk-improvments`) +> **Scope:** `sdk/flutter/*.mdx` only, `sdk/flutter/3.0/` excluded +> **Total:** 62 files modified (+8,176 lines, −16 lines) +> **Commits:** +> - `659f8839` — "feat: made docs more agentic and developer friendly" (added Quick Reference `` blocks, `description` frontmatter, `` blocks, `` blocks, and Next Steps `` navigation to all files) +> - `beb0cc1c` — "docs(flutter): add response and error accordions to SDK docs" (added `` and `` sections after every SDK method call across all files except presenter-mode) +> - `9feb900b` — "docs(flutter): add response and error accordions to presenter mode" (added response/error accordions to the final remaining file) + +--- + +## What Changed Across All Files — Pattern Summary + +Every file received some combination of these five additions: + +### 1. `description` frontmatter (all 62 files) +A one-line SEO description was added to the YAML frontmatter of every file. Example: +```yaml +description: "Get started with the CometChat Flutter SDK to add real-time chat and calling features to your Flutter application." +``` + +### 2. AI Agent Quick Reference `` blocks (all 62 files) +A hidden comment `{/* TL;DR for Agents and Quick Reference */}` followed by an `` block containing copy-paste-ready Dart/YAML code snippets was added at the top of every page, right after the frontmatter. These blocks are designed for both AI agents and developers to quickly understand the page's core functionality without reading the full content. Example from `overview.mdx`: +```dart +// Initialize (run once at app start) +AppSettings appSettings = (AppSettingsBuilder() + ..subscriptionType = CometChatSubscriptionType.allUsers + ..region = "REGION" + ..autoEstablishSocketConnection = true +).build(); + +CometChat.init("APP_ID", appSettings, + onSuccess: (msg) => debugPrint("Init success"), + onError: (e) => debugPrint("Init failed: ${e.message}"), +); +``` + +### 3. Response/Error Accordions (most files — wherever SDK methods exist) +After every SDK method call on the page, two expandable `` sections were added: +- **``** — Documents the success callback return type with a table of fields including Parameter, Type, Description, and Sample Value. For complex objects (User, Group, BaseMessage, Call), every field is listed with realistic sample values. +- **``** — Documents the error callback with `code`, `message`, and `details` fields and sample error values. + +Example Response table fields for `sendMessage()`: +`id`, `metadata`, `receiver`, `editedBy`, `conversationId`, `sentAt`, `receiverUid`, `type`, `readAt`, `deletedBy`, `deliveredAt`, `deletedAt`, `replyCount`, `sender`, `receiverType`, `editedAt`, `parentMessageId`, `readByMeAt`, `category`, `deliveredToMeAt`, `updatedAt`, `text`, `tags`, `unreadRepliesCount`, `mentionedUsers`, `hasMentionedMe`, `reactions`, `moderationStatus`, `quotedMessageId` — plus nested Sender and Receiver User object tables. + +Example Error table: +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"SDK initialization failed."` | +| `details` | string | Additional technical details | `"Please verify your App ID and region, then try again."` | + +### 4. `` blocks (select files — where common pitfalls exist) +Warning callouts were added for critical developer pitfalls. Examples: +- `overview.mdx` / `setup.mdx`: *"`CometChat.init()` must be called before any other SDK method. Calling `login()`, `sendMessage()`, or registering listeners before `init()` will fail."* +- `authentication-overview.mdx`: *"Auth Key is for development/testing only. In production, generate Auth Tokens server-side."* +- `delete-message.mdx` / `delete-conversation.mdx` / `delete-group.mdx`: Warnings about permanent/irreversible deletion +- `default-call.mdx`: *"Generate a call token before starting a session"* +- `ai-agents.mdx`: *"Always remove AI Assistant listeners when they're no longer needed (e.g., on widget dispose or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling."* +- `receive-messages.mdx`: Warning about removing message listeners on dispose + +### 5. Next Steps `` navigation (all 62 files) +A `---` horizontal rule followed by a `## Next Steps` heading and a `` with 2–4 `` links was added at the bottom of every page. Each card has a title, icon, href, and description pointing to logically related pages. + +--- + +## Detailed File-by-File Changes + +| File Name | Changes List | Description | +|-----------|-------------|-------------| +| `overview.mdx` | 1. Added `description: "Get started with the CometChat Flutter SDK to add real-time chat and calling features to your Flutter application."`
2. Added Quick Reference `` block containing: `cometchat_sdk: ^4.0.33` install yaml, `CometChat.init()` with `AppSettingsBuilder` code, `CometChat.login()` with Auth Key code, commented `loginWithAuthToken()` alternative, credential source note pointing to Dashboard
3. Added ``: "CometChat.init() must be called before any other SDK method. Calling login(), sendMessage(), or registering listeners before init() will fail."
4. Added Response accordion after `CometChat.init()` — success returns a `String` message: `"Initialization completed successfully"`
5. Added Error accordion after `CometChat.init()` — error fields: `code` (`"ERR_CHAT_API_FAILURE"`), `message` (`"SDK initialization failed."`), `details` (`"Please verify your App ID and region, then try again."`)
6. Added Response accordion after `CometChat.createUser()` — returns a `User` object with 12 fields: `uid`, `name`, `link`, `avatar`, `metadata`, `status` (`"offline"`), `role` (`"default"`), `statusMessage`, `tags`, `hasBlockedMe`, `blockedByMe`, `lastActiveAt`
7. Added Error accordion after `CometChat.createUser()` — error fields: `code` (`"ERR_UID_NOT_FOUND"`), `message`, `details`
8. Added Response accordion after `CometChat.login()` — returns a `User` object with same 12 fields, sample `status` is `"online"`, sample `lastActiveAt` is `1745554700`
9. Added Error accordion after `CometChat.login()` — same error structure
10. Added Next Steps CardGroup with 4 cards: "Setup SDK" (icon: gear, href: `/sdk/flutter/setup`), "Key Concepts" (icon: lightbulb, href: `/sdk/flutter/key-concepts`), "Authentication" (icon: key, href: `/sdk/flutter/authentication-overview`), "Send Messages" (icon: paper-plane, href: `/sdk/flutter/send-message`) | This is the main entry point for the Flutter SDK docs. The Quick Reference block gives developers the complete install → init → login flow in one glance. The `` prevents the #1 integration mistake (calling SDK methods before init). Response accordions document the exact shape of `User` objects returned by `createUser()` and `login()`, including all 12 fields with realistic sample values. Error accordions show the standard `CometChatException` structure (`code`/`message`/`details`) that is consistent across all SDK methods. The Next Steps cards create a guided learning path from overview → setup → auth → messaging. | +| `setup.mdx` | 1. Added `description: "Install and initialize the CometChat Flutter SDK in your application"`
2. Added Quick Reference `` block — same install + init + login code as overview, plus credential source note
3. Added ``: same init-before-other-methods warning
4. Added Response accordion after `CometChat.init()` — `String` success message
5. Added Error accordion after `CometChat.init()` — `code`/`message`/`details`
6. Added Next Steps CardGroup with 2 cards: "Authentication" (icon: key), "Send Messages" (icon: paper-plane) | The setup page is the detailed installation guide (pubspec.yaml, podfile, minSdkVersion, etc.). The Quick Reference duplicates the overview's code block intentionally — developers may land on either page first. Response/Error accordions document what `init()` returns on success/failure so developers know what to expect in their callbacks. | +| `authentication-overview.mdx` | 1. Added `description: "Learn how to authenticate users in your Flutter app using CometChat SDK with Auth Key for development or Auth Token for production."`
2. Added Quick Reference `` block with: `CometChat.login(UID, authKey)` code, `CometChat.loginWithAuthToken(authToken)` code, `CometChat.logout()` code, note about `getLoggedInUser()` to check existing session
3. Added ``: "Auth Key is intended for development/testing only. For production, generate Auth Tokens server-side via the REST API and use loginWithAuthToken()."
4. Added Response accordion after `login()` with Auth Key — `User` object with 12 fields (uid, name, avatar, status=`"online"`, role=`"default"`, lastActiveAt, etc.)
5. Added Error accordion after `login()` with Auth Key — `code` (`"ERR_UID_NOT_FOUND"`), `message`, `details`
6. Added Response accordion after `loginWithAuthToken()` — same `User` object structure
7. Added Error accordion after `loginWithAuthToken()` — same error structure
8. Added Response accordion after `logout()` — `String` success message: `"User logged out successfully"`
9. Added Error accordion after `logout()` — `code`/`message`/`details`
10. Added Next Steps CardGroup with 4 cards: "Send Messages", "Receive Messages", "Key Concepts", "Users" | The auth page now clearly distinguishes between Auth Key (dev) and Auth Token (prod) flows. The `` is a critical security note — shipping Auth Keys in production client code is a common mistake. Each of the three auth methods (login with key, login with token, logout) has its own response/error accordion so developers can see exactly what each returns. | +| `key-concepts.mdx` | 1. Added `description: "Understand the core concepts of CometChat including Dashboard, API keys, users, groups, messages, and conversations."`
2. Added Quick Reference `` block summarizing: CometChat Dashboard purpose, Auth Key vs REST API Key differences (Auth Key = client-side dev, REST API Key = server-side), Users/UID/Auth Token concepts, Groups (GUID, public/private/password types), Messages (text/media/custom/interactive), Conversations (user/group)
3. Added Next Steps CardGroup with 4 cards: "Setup", "Authentication", "Send Messages", "Groups" | The Quick Reference block condenses the entire key-concepts page into a scannable summary. This is especially useful for AI agents that need to understand CometChat's data model quickly. No response/error accordions here since this is a conceptual page with no SDK method calls. | +| `send-message.mdx` | 1. Added `description: "Learn how to send text, media, and custom messages to users and groups using the CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `CometChat.sendMessage(textMessage)` code, `CometChat.sendMediaMessage(mediaMessage)` code, `CometChat.sendCustomMessage(customMessage)` code
3. Added ``: "Available via: SDK \| REST API \| UI Kits \| Dashboard"
4. Added ``: "CometChat.init() and CometChat.login() must complete before sending messages."
5. Added Response accordion after `sendMessage()` for text — `BaseMessage` object with 28 fields: `id` (401), `metadata`, `receiver` (nested User object), `editedBy`, `conversationId` (`"cometchat-uid-1_user_cometchat-uid-2"`), `sentAt` (epoch), `receiverUid`, `type` (`"text"`), `readAt`, `deletedBy`, `deliveredAt`, `deletedAt`, `replyCount`, `sender` (nested User object with uid/name/avatar/status/role/tags/etc.), `receiverType` (`"user"`), `editedAt`, `parentMessageId`, `readByMeAt`, `category` (`"message"`), `deliveredToMeAt`, `updatedAt`, `text` (`"messageText"`), `tags`, `unreadRepliesCount`, `mentionedUsers`, `hasMentionedMe`, `reactions`, `moderationStatus`, `quotedMessageId` — plus full nested Sender User object (12 fields) and Receiver User object (12 fields)
6. Added Error accordion after `sendMessage()` for text
7. Added Response accordion after `sendMediaMessage()` — similar `BaseMessage` structure with additional `attachment` field containing `url`, `extension`, `size`, `mimeType`
8. Added Error accordion after `sendMediaMessage()`
9. Added Response accordion after `sendCustomMessage()` — `BaseMessage` with `customData` map field
10. Added Error accordion after `sendCustomMessage()`
11. Added Next Steps CardGroup with 4 cards: "Receive Messages", "Edit Message", "Delete Message", "Threaded Messages" | This is one of the most heavily documented files (+559 lines). The `BaseMessage` response table is the most comprehensive object documentation in the entire SDK docs — 28 top-level fields plus two nested User objects (Sender and Receiver) each with 12 fields. This gives developers complete visibility into what the `onSuccess` callback returns. The nested object tables use anchor links (`#send-text-sender-object`, `#send-text-receiver-object`) for easy navigation. Media message response adds attachment metadata. Custom message response shows the `customData` map structure. | +| `receive-messages.mdx` | 1. Added `description: "Learn how to receive real-time messages and fetch message history using the CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `CometChat.addMessageListener()` code showing `onTextMessageReceived`, `onMediaMessageReceived`, `onCustomMessageReceived` callbacks; `MessagesRequestBuilder` with `fetchPrevious()`/`fetchNext()` code; `CometChat.removeMessageListener()` cleanup code
3. Added ``: "Always remove message listeners when they're no longer needed (e.g., on widget dispose). Failing to remove listeners can cause memory leaks and duplicate event handling."
4. Added Response accordion after `fetchPrevious()` — `List` with full BaseMessage object table (28 fields per message, same structure as send-message)
5. Added Error accordion after `fetchPrevious()`
6. Added Response accordion after `fetchNext()` — same `List` structure
7. Added Error accordion after `fetchNext()`
8. Added Response accordions for each real-time listener callback: `onTextMessageReceived` (TextMessage object), `onMediaMessageReceived` (MediaMessage with attachment), `onCustomMessageReceived` (CustomMessage with customData), `onTypingStarted`, `onTypingEnded`, `onMessagesDelivered`, `onMessagesRead`, `onMessageEdited`, `onMessageDeleted`
9. Added Error accordions for listener callbacks
10. Added Next Steps CardGroup with 4 cards: "Send Messages", "Threaded Messages", "Message Filtering", "Delivery Receipts" | The largest change after `default-call.mdx` (+767 lines). Every real-time listener callback now has its own Response accordion documenting the exact object shape that arrives in the callback. This is critical for developers building custom UIs — they need to know exactly which fields are available on `TextMessage` vs `MediaMessage` vs `CustomMessage`. The memory leak warning about removing listeners is a common Flutter pitfall. | +| `edit-message.mdx` | 1. Added `description: "Learn how to edit sent messages in your Flutter app using the CometChat SDK."`
2. Added Quick Reference `` block with: `CometChat.editMessage(textMessage)` code for text, `CometChat.editMessage(mediaMessage)` code for media
3. Added Response accordion after `editMessage()` for text — `BaseMessage` object with `editedAt` populated (non-zero epoch), `editedBy` populated with editor's UID
4. Added Error accordion after `editMessage()` for text
5. Added Response accordion after `editMessage()` for media — same structure with attachment metadata
6. Added Error accordion after `editMessage()` for media
7. Added Next Steps CardGroup with 3 cards: "Delete Message", "Send Messages", "Threaded Messages" | The response accordions specifically highlight the `editedAt` and `editedBy` fields that change when a message is edited — this helps developers understand which fields to check in their UI to show "edited" indicators. | +| `delete-message.mdx` | 1. Added `description: "Learn how to delete messages and handle real-time deletion events in your Flutter app using CometChat SDK."`
2. Added Quick Reference `` block with: `CometChat.deleteMessage(messageId)` code, `onMessageDeleted` listener callback code
3. Added ``: "Deleting a message is permanent and cannot be undone. The message will be removed for all participants in the conversation."
4. Added Response accordion after `deleteMessage()` — `BaseMessage` object with `deletedAt` populated (non-zero epoch), `deletedBy` populated with deleter's UID
5. Added Error accordion after `deleteMessage()`
6. Added Next Steps CardGroup with 3 cards: "Edit Message", "Send Messages", "Receive Messages" | The permanence warning is important — unlike some chat platforms, CometChat's delete is not soft-delete by default. Response accordion highlights `deletedAt` and `deletedBy` fields. | +| `delivery-read-receipts.mdx` | 1. Added `description: "Learn how to implement message delivery and read receipts in your Flutter app using CometChat SDK."`
2. Added Quick Reference `` block with: `CometChat.markAsDelivered(message)` code, `CometChat.markAsRead(message)` code, `CometChat.markAsUnread(message)` code, listener callbacks for `onMessagesDelivered`/`onMessagesRead`
3. Added Response accordion after `markAsDelivered()` — void success (no return value)
4. Added Error accordion after `markAsDelivered()`
5. Added Response accordion after `markAsRead()` — void success
6. Added Error accordion after `markAsRead()`
7. Added Response accordion after `markAsUnread()` — void success
8. Added Error accordion after `markAsUnread()`
9. Added Next Steps CardGroup with 3 cards: "Receive Messages", "Send Messages", "Typing Indicators" | Receipt methods return void on success (no object), so the Response accordions simply confirm "void — no return value". The Error accordions still document the `CometChatException` structure. | +| `typing-indicators.mdx` | 1. Added `description: "Learn how to send and receive typing indicators in your Flutter app using CometChat SDK."`
2. Added Quick Reference `` block with: `CometChat.startTyping(typingIndicator)` code, `CometChat.endTyping(typingIndicator)` code, `onTypingStarted`/`onTypingEnded` listener callbacks
3. Added Next Steps CardGroup with 3 cards: "Send Messages", "Receive Messages", "Delivery Receipts" | No response/error accordions — typing indicator methods are fire-and-forget with no success/error callbacks. Quick reference shows both sending and receiving sides. | +| `threaded-messages.mdx` | 1. Added `description: "Learn how to send, receive, and fetch messages within a thread attached to a parent message in CometChat Flutter SDK."`
2. Added Quick Reference `` block with: send-in-thread code (`textMessage.parentMessageId = 103`), fetch-thread code (`MessagesRequestBuilder()..parentMessageId = 103`), hide-replies code (`..hideReplies = true`)
3. Added Response accordion after `sendMessage()` in thread — `BaseMessage` with `parentMessageId` populated (103)
4. Added Error accordion after `sendMessage()` in thread
5. Added Response accordion after `fetchPrevious()` for thread — `List` with `parentMessageId` on each message
6. Added Error accordion after `fetchPrevious()`
7. Added Response accordion after `fetchNext()` for thread — same structure
8. Added Error accordion after `fetchNext()`
9. Added Next Steps CardGroup with 3 cards: "Send Messages", "Receive Messages", "Message Filtering" | The Quick Reference block shows the three key thread operations in one place: sending into a thread, fetching a thread's messages, and excluding thread replies from the main conversation. Response accordions highlight the `parentMessageId` field that links messages to their thread. | +| `mentions.mdx` | 1. Added `description: "Learn how to mention users in messages and fetch mentioned messages using the CometChat Flutter SDK."`
2. Added Quick Reference `` block with: mention in text message code (setting `mentionedUsers` on `TextMessage`), fetch mentioned messages code (`MessagesRequestBuilder()..mentionsWithType`)
3. Added Response accordion after sending message with mentions — `BaseMessage` with `mentionedUsers` array populated, `hasMentionedMe` boolean
4. Added Error accordion
5. Added Response accordion after fetching mentioned messages — `List` with mention metadata
6. Added Error accordion
7. Added Next Steps CardGroup with 3 cards: "Send Messages", "Receive Messages", "Message Filtering" | Response accordions specifically show how `mentionedUsers` array and `hasMentionedMe` boolean appear in the response — developers need this to render @mention UI elements. | +| `reactions.mdx` | 1. Added `description: "Learn how to add, remove, and fetch reactions on messages using the CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `CometChat.addReaction(messageId, emoji)` code, `CometChat.removeReaction(messageId, emoji)` code, `CometChat.fetchMessageReactions(messageId)` code
3. Added Response accordion after `addReaction()` — `BaseMessage` with `reactions` array populated
4. Added Error accordion after `addReaction()`
5. Added Response accordion after `removeReaction()` — `BaseMessage` with updated `reactions` array
6. Added Error accordion after `removeReaction()`
7. Added Response accordion after `fetchMessageReactions()` — `List` with fields: `reaction` (emoji string), `count` (number), `reactedByMe` (boolean)
8. Added Error accordion after `fetchMessageReactions()`
9. Added Next Steps CardGroup with 3 cards: "Send Messages", "Receive Messages", "Interactive Messages" | The `fetchMessageReactions()` response introduces a new object type (`ReactionCount`) not seen in other pages — it has `reaction`, `count`, and `reactedByMe` fields. | +| `interactive-messages.mdx` | 1. Added `description: "Learn how to send interactive messages (Form, Card, Scheduler) using the CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `FormMessage` construction code, `CardMessage` construction code, `SchedulerMessage` construction code
3. Added Response accordion after sending `FormMessage` — `BaseMessage` with `interactiveData` map containing form fields
4. Added Error accordion
5. Added Response accordion after sending `CardMessage` — `BaseMessage` with `interactiveData` containing card layout
6. Added Error accordion
7. Added Next Steps CardGroup with 3 cards: "Send Messages", "Reactions", "Message Filtering" | Interactive messages have a unique `interactiveData` field in the response that contains the form/card/scheduler structure. | +| `transient-messages.mdx` | 1. Added `description: "Learn how to send and receive transient (ephemeral) messages that are not stored in CometChat's database."`
2. Added Quick Reference `` block with: `CometChat.sendTransientMessage(transientMessage)` code, `onTransientMessageReceived` listener callback
3. Added Next Steps CardGroup with 3 cards: "Send Messages", "Typing Indicators", "Real-Time Listeners" | No response/error accordions — transient messages are fire-and-forget. The Quick Reference clarifies that these messages are not persisted. | +| `flag-message.mdx` | 1. Added `description: "Learn how to flag or report messages for moderation in your Flutter app using CometChat SDK."`
2. Added Quick Reference `` block with: `CometChat.flagMessage(message)` code
3. Added Response accordion after `flagMessage()` — success confirmation
4. Added Error accordion after `flagMessage()`
5. Added Next Steps CardGroup with 3 cards: "Delete Message", "AI Moderation", "Extensions" | Flag message is a simple method with a straightforward response. | +| `additional-message-filtering.mdx` | 1. Added `description: "Learn how to use MessagesRequestBuilder to filter and fetch messages with various parameters including pagination, categories, types, tags, and advanced search options in Flutter."`
2. Added Quick Reference `` block with: `MessagesRequestBuilder` examples showing filters by `..categories`, `..types`, `..tags`, `..uid`, `..guid`, `..limit`, `..searchKeyword`, `..hideReplies`, `..hideDeletedMessages`
3. Added Next Steps CardGroup with 4 cards: "Receive Messages", "Send Messages", "Threaded Messages", "Message Structure" | No response/error accordions — this page documents the request builder configuration, not the fetch methods themselves (those are on `receive-messages.mdx`). The Quick Reference is a comprehensive filter cheat sheet. | +| `message-structure-and-hierarchy.mdx` | 1. Added `description: "Understand the message class hierarchy in CometChat Flutter SDK — BaseMessage, TextMessage, MediaMessage, CustomMessage, and InteractiveMessage."`
2. Added Quick Reference `` block summarizing the class hierarchy: `BaseMessage` (parent) → `TextMessage`, `MediaMessage`, `CustomMessage`, `InteractiveMessage` (children), with key fields for each
3. Added Next Steps CardGroup with 4 cards: "Send Messages", "Receive Messages", "Interactive Messages", "Message Filtering" | Conceptual page — no SDK method calls, so no response/error accordions. The Quick Reference gives a class hierarchy overview. | +| `messaging-overview.mdx` | 1. Added `description: "Overview of CometChat's messaging capabilities for Flutter including text, media, custom, and interactive messages."`
2. Added Quick Reference `` block listing all messaging features with links: Send Messages, Receive Messages, Edit/Delete, Threaded Messages, Typing Indicators, Delivery/Read Receipts, Mentions, Reactions, Interactive Messages, Transient Messages, Flag Message
3. Added Next Steps CardGroup with 4 cards: "Send Messages", "Receive Messages", "Threaded Messages", "Reactions" | Index page — the Quick Reference serves as a complete table of contents for the messaging section. | +| `retrieve-conversations.mdx` | 1. Added `description: "Learn how to fetch and paginate through conversations using the CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `ConversationsRequestBuilder` code showing `..limit`, `..conversationType`, `..withTags`, `..tags` filters; `fetchNext()`/`fetchPrevious()` pagination code
3. Added Response accordion after `fetchNext()` — `List` with fields: `conversationId`, `conversationType` (`"user"`/`"group"`), `lastMessage` (nested BaseMessage), `conversationWith` (nested User or Group object), `unreadMessageCount`, `updatedAt`, `tags`, `lastReadMessageId`
4. Added Error accordion after `fetchNext()`
5. Added Response accordion after `fetchPrevious()` — same structure
6. Added Error accordion after `fetchPrevious()`
7. Added Next Steps CardGroup with 4 cards: "Delete Conversation", "Send Messages", "Retrieve Users", "Retrieve Groups" | The `Conversation` object is a complex nested type — it contains a `lastMessage` (full BaseMessage) and a `conversationWith` (User or Group depending on type). The response tables document all these nested structures. | +| `delete-conversation.mdx` | 1. Added `description: "Learn how to delete user and group conversations from the logged-in user's conversation list using the CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `CometChat.deleteConversation(conversationWith, conversationType)` code
3. Added ``: "Deleting a conversation removes it only from the logged-in user's list. The other participant's conversation is not affected. This action cannot be undone."
4. Added Response accordion after `deleteConversation()` — `String` success message
5. Added Error accordion after `deleteConversation()`
6. Added Next Steps CardGroup with 2 cards: "Retrieve Conversations", "Send Messages" | The warning clarifies that conversation deletion is one-sided (only affects the current user) and irreversible. | +| `retrieve-users.mdx` | 1. Added `description: "Learn how to fetch and paginate through users using the CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `UsersRequestBuilder` code showing `..limit`, `..searchKeyword`, `..status`, `..hideBlockedUsers`, `..roles`, `..tags`, `..uids` filters; `fetchNext()` pagination code
3. Added Response accordion after `fetchNext()` — `List` with 12 fields per user: `uid`, `name`, `link`, `avatar`, `metadata`, `status`, `role`, `statusMessage`, `tags`, `hasBlockedMe`, `blockedByMe`, `lastActiveAt`
4. Added Error accordion after `fetchNext()`
5. Added Next Steps CardGroup with 3 cards: "Block Users", "User Presence", "User Management" | The User object table is reused across many pages (login, send-message, etc.) but this is the canonical reference for the full User object shape. | +| `user-management.mdx` | 1. Added `description: "Learn how to create and update users using the CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `CometChat.createUser(user, authKey)` code, `CometChat.updateUser(user)` code
3. Added Response accordion after `createUser()` — `User` object (12 fields)
4. Added Error accordion after `createUser()`
5. Added Response accordion after `updateUser()` — `User` object (12 fields)
6. Added Error accordion after `updateUser()`
7. Added Next Steps CardGroup with 3 cards: "Retrieve Users", "Block Users", "User Presence" | Both user management methods return the full User object on success. | +| `user-presence.mdx` | 1. Added `description: "Learn how to track user online/offline status in real-time using CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `CometChat.addUserListener()` code showing `onUserOnline`/`onUserOffline` callbacks
3. Added Next Steps CardGroup with 3 cards: "Retrieve Users", "User Management", "Real-Time Listeners" | No response/error accordions — presence is received via listeners, not method calls. | +| `users-overview.mdx` | 1. Added `description: "Overview of CometChat's user management capabilities for Flutter."`
2. Added Quick Reference `` block listing: Retrieve Users, User Management, Block Users, User Presence with links
3. Added Next Steps CardGroup with 4 cards | Index page for the Users section. | +| `block-users.mdx` | 1. Added `description: "Learn how to block and unblock users in your Flutter app using the CometChat SDK to manage user interactions and privacy."`
2. Added Quick Reference `` block with: `CometChat.blockUsers(uids)` code, `CometChat.unblockUsers(uids)` code, `BlockedUsersRequestBuilder` with `fetchNext()` code
3. Added Response accordion after `blockUsers()` — `Map` showing success/failure per UID
4. Added Error accordion after `blockUsers()`
5. Added Response accordion after `unblockUsers()` — same Map structure
6. Added Error accordion after `unblockUsers()`
7. Added Response accordion after `fetchNext()` for blocked users — `List` (12 fields per user)
8. Added Error accordion after `fetchNext()`
9. Added Next Steps CardGroup with 3 cards: "Retrieve Users", "User Management", "User Presence" | The `blockUsers()`/`unblockUsers()` methods return a `Map` (not a simple success string) — the response accordion documents this unique return type. | +| `create-group.mdx` | 1. Added `description: "Learn how to create public, private, and password-protected groups using CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `Group` constructor code for public/private/password types, `CometChat.createGroup(group)` code
3. Added Response accordion after `createGroup()` — `Group` object with 15+ fields: `guid`, `name`, `type` (`"public"`/`"private"`/`"password"`), `icon`, `description`, `owner`, `metadata`, `tags`, `membersCount`, `createdAt`, `updatedAt`, `hasJoined`, `scope`, `joinedAt`, `conversationId`
4. Added Error accordion after `createGroup()`
5. Added Next Steps CardGroup with 3 cards: "Join Group", "Retrieve Groups", "Group Members" | The Group object table is the canonical reference for group data — 15+ fields including `membersCount`, `hasJoined`, `scope`, and `conversationId`. | +| `join-group.mdx` | 1. Added `description: "Learn how to join public and password-protected groups using CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `CometChat.joinGroup(guid, groupType, password)` code
3. Added Response accordion after `joinGroup()` — `Group` object (same 15+ fields)
4. Added Error accordion after `joinGroup()`
5. Added Next Steps CardGroup with 3 cards: "Leave Group", "Retrieve Group Members", "Create Group" | Response shows the Group object with `hasJoined` now `true` and `scope` set to `"participant"`. | +| `leave-group.mdx` | 1. Added `description: "Learn how to leave a group using CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `CometChat.leaveGroup(guid)` code
3. Added Response accordion after `leaveGroup()` — `String` success message
4. Added Error accordion after `leaveGroup()`
5. Added Next Steps CardGroup with 3 cards: "Join Group", "Delete Group", "Retrieve Groups" | Simple method — returns success string on leave. | +| `delete-group.mdx` | 1. Added `description: "Learn how to permanently delete a group in CometChat using the Flutter SDK. Only group admins can delete groups."`
2. Added Quick Reference `` block with: `CometChat.deleteGroup(guid)` code
3. Added ``: "Only the group admin can delete a group. Deleting a group is permanent and removes all messages and members."
4. Added Response accordion after `deleteGroup()` — `String` success message
5. Added Error accordion after `deleteGroup()`
6. Added Next Steps CardGroup with 3 cards: "Create Group", "Retrieve Groups", "Leave Group" | The admin-only + permanent deletion warning is critical context for developers. | +| `update-group.mdx` | 1. Added `description: "Learn how to update group details using CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `CometChat.updateGroup(group)` code
3. Added Response accordion after `updateGroup()` — `Group` object (15+ fields) with updated values
4. Added Error accordion after `updateGroup()`
5. Added Next Steps CardGroup with 3 cards: "Create Group", "Retrieve Groups", "Group Members" | Response shows the updated Group object. | +| `transfer-group-ownership.mdx` | 1. Added `description: "Learn how to transfer group ownership to another member using CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `CometChat.transferOwnership(guid, uid)` code
3. Added Response accordion after `transferOwnership()` — `String` success message
4. Added Error accordion after `transferOwnership()`
5. Added Next Steps CardGroup with 3 cards: "Group Members", "Update Group", "Change Member Scope" | Simple method — returns success string. | +| `retrieve-groups.mdx` | 1. Added `description: "Learn how to fetch and paginate through groups using the CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `GroupsRequestBuilder` code showing `..limit`, `..searchKeyword`, `..joinedOnly`, `..tags`, `..withTags` filters; `fetchNext()` code
3. Added Response accordion after `fetchNext()` — `List` (15+ fields per group)
4. Added Error accordion after `fetchNext()`
5. Added Next Steps CardGroup with 3 cards: "Create Group", "Join Group", "Group Members" | Group retrieval response documents the full Group object for each item in the list. | +| `retrieve-group-members.mdx` | 1. Added `description: "Learn how to fetch and paginate through group members using the CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `GroupMembersRequestBuilder("GROUP_ID")` code showing `..limit`, `..scopes` (admin/moderator/participant) filters; `fetchNext()` code
3. Added ``: "Available via: SDK \| REST API \| UI Kits"
4. Simplified intro paragraph — removed redundant sentence about `GroupMembersRequestBuilder`
5. Added Response accordion after `fetchNext()` — `List` with 14 fields: all 12 User fields plus `scope` (`"admin"`/`"moderator"`/`"participant"`) and `joinedAt` (epoch timestamp)
6. Added Error accordion after `fetchNext()`
7. Added Next Steps CardGroup with 3 cards: "Add Members", "Kick Member", "Change Scope" | `GroupMember` extends `User` with two additional fields (`scope` and `joinedAt`) — the response table documents all 14 fields. | +| `group-add-members.mdx` | 1. Added `description: "Learn how to add members to a group using CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `CometChat.addMembersToGroup(guid, members, bannedMembers)` code
3. Added Response accordion after `addMembersToGroup()` — `Map` showing success/failure per member UID
4. Added Error accordion
5. Added Next Steps CardGroup with 3 cards: "Retrieve Group Members", "Kick Member", "Change Scope" | The Map response type is unique — it maps each member UID to a success/failure status string. | +| `group-change-member-scope.mdx` | 1. Added `description: "Learn how to change a group member's scope (role) using CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `CometChat.changeMemberScope(guid, uid, scope)` code showing scope values: `CometChatMemberScope.admin`, `.moderator`, `.participant`
3. Added Response accordion — `String` success message
4. Added Error accordion
5. Added Next Steps CardGroup with 3 cards: "Retrieve Group Members", "Add Members", "Transfer Ownership" | Quick Reference shows all three scope enum values. | +| `group-kick-member.mdx` | 1. Added `description: "Learn how to kick, ban, and unban group members using CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `CometChat.kickGroupMember(guid, uid)` code, `CometChat.banGroupMember(guid, uid)` code, `CometChat.unbanGroupMember(guid, uid)` code
3. Added Response accordion after `kickGroupMember()` — `String` success message
4. Added Error accordion after `kickGroupMember()`
5. Added Response accordion after `banGroupMember()` — `String` success message
6. Added Error accordion after `banGroupMember()`
7. Added Response accordion after `unbanGroupMember()` — `String` success message
8. Added Error accordion after `unbanGroupMember()`
9. Added Next Steps CardGroup with 3 cards: "Retrieve Group Members", "Add Members", "Change Scope" | All three member moderation methods documented with response/error. | +| `groups-overview.mdx` | 1. Added `description: "Overview of CometChat's group management capabilities for Flutter."`
2. Added Quick Reference `` block listing: Create Group, Join Group, Leave Group, Delete Group, Update Group, Transfer Ownership, Retrieve Groups, Retrieve Group Members, Add Members, Change Scope, Kick/Ban Members with links
3. Added Next Steps CardGroup with 4 cards | Index page for the Groups section. | +| `default-call.mdx` | 1. Added `description: "Implement complete calling workflow with ringing functionality including incoming/outgoing call UI, call acceptance, rejection, and cancellation in your Flutter app."`
2. Added Quick Reference `` block with: `CometChat.initiateCall(call)` code, `CometChat.acceptCall(sessionId)` code, `CometChat.rejectCall(sessionId, status)` code with `CometChatCallStatus.rejected`/`.cancelled`/`.busy`, `CometChat.endCall(sessionId)` code
3. Added ``: "You must generate a call token using `CometChatCalls.generateToken()` before starting a call session with `CometChatCalls.startSession()`."
4. Added Response accordion after `initiateCall()` — `Call` object with 28+ fields: all BaseMessage fields (id, metadata, receiver, sender, conversationId, sentAt, type, category, etc.) PLUS call-specific fields: `sessionId` (`"v1.us.1.xxxxxxxx"`), `callStatus` (`"initiated"`), `action` (`"initiated"`), `callInitiator` (nested User object), `callReceiver` (nested User object), `initiatedAt` (epoch), `joinedAt` (epoch) — plus nested Sender, Receiver, CallInitiator, and CallReceiver User object tables (12 fields each)
5. Added Error accordion after `initiateCall()`
6. Added Response accordion after `acceptCall()` — `Call` object with `callStatus` = `"ongoing"`, `action` = `"accepted"`
7. Added Error accordion after `acceptCall()`
8. Added Response accordion after `rejectCall()` (rejected) — `Call` object with `callStatus` = `"rejected"`, `action` = `"rejected"`
9. Added Error accordion after `rejectCall()` (rejected)
10. Added Response accordion after `rejectCall()` (cancelled by initiator) — `Call` object with `callStatus` = `"cancelled"`, `action` = `"cancelled"`
11. Added Error accordion after `rejectCall()` (cancelled)
12. Added Response accordion after `endCall()` — `Call` object with `callStatus` = `"ended"`, `action` = `"ended"`
13. Added Error accordion after `endCall()`
14. Added Response accordion after `CometChatCalls.startSession()` — `Widget?` representing the call UI to embed in your screen
15. Added Error accordion after `startSession()`
16. Added Next Steps CardGroup with 3 cards: "Direct Call", "Standalone Calling", "Call Logs" | This is the single largest file change (+876 lines). The `Call` object extends `BaseMessage` with 7 additional call-specific fields (`sessionId`, `callStatus`, `action`, `callInitiator`, `callReceiver`, `initiatedAt`, `joinedAt`). Each call lifecycle state (initiated, ongoing, rejected, cancelled, ended) has its own Response accordion showing the exact `callStatus` and `action` values for that state — this is critical for developers building custom call UIs who need to know which status values to check. The `startSession()` response is unique — it returns a Flutter `Widget?` that developers embed in their screen to show the call interface. | +| `direct-call.mdx` | 1. Added `description: "Implement direct calling without ringing functionality — generate a token and start a call session directly."`
2. Added Quick Reference `` block with: `CometChatCalls.generateToken(sessionId, userAuthToken)` code, `CometChatCalls.startSession(callToken, callSettings)` code with `CallSettingsBuilder` showing `..enableDefaultLayout`, `..listener`
3. Added Response accordion after `generateToken()` — `String` call token
4. Added Error accordion after `generateToken()`
5. Added Response accordion after `startSession()` — `Widget?` call UI widget
6. Added Error accordion after `startSession()`
7. Added Next Steps CardGroup with 3 cards: "Default Call", "Standalone Calling", "Recording" | Direct calling skips the ringing flow — the Quick Reference shows the simplified two-step process (generate token → start session). | +| `standalone-calling.mdx` | 1. Added `description: "Implement standalone calling that works independently of CometChat's messaging infrastructure."`
2. Added Quick Reference `` block with: standalone `CometChatCalls.init()` code, `generateToken()` code, `startSession()` code
3. Added Response accordion after `generateToken()` — `String` call token
4. Added Error accordion
5. Added Response accordion after `startSession()` — `Widget?` call UI widget
6. Added Error accordion
7. Added Next Steps CardGroup with 3 cards: "Default Call", "Direct Call", "Call Logs" | Standalone calling is for apps that only need calling (no chat). The Quick Reference shows the independent init flow. | +| `calling-setup.mdx` | 1. Added `description: "Learn how to install and initialize the CometChat Calls SDK for Flutter to enable voice and video calling in your application."`
2. Added Quick Reference `` block with: `cometchat_calls_sdk: ^4.0.x` install yaml, `CometChatCalls.init(callAppSettings)` code with `CallAppSettingsBuilder` showing `..appId`, `..region`
3. Added Response accordion after `CometChatCalls.init()` — `String` success message: `"CometChat Calls SDK initialized successfully"`
4. Added Error accordion after `CometChatCalls.init()`
5. Added Next Steps CardGroup with 3 cards: "Default Call", "Direct Call", "Standalone Calling" | The Calls SDK has its own separate init method (`CometChatCalls.init()`) distinct from the main SDK's `CometChat.init()`. | +| `calling-overview.mdx` | 1. Added `description: "Implement voice and video calling in your Flutter application with CometChat's calling SDK, supporting ringing calls, direct calls, and standalone calling."`
2. Added Quick Reference `` block summarizing three calling modes: Default Calling (with ringing, requires chat SDK), Direct Calling (no ringing, requires chat SDK), Standalone Calling (independent, no chat SDK needed) — with use-case guidance for each
3. Added Next Steps CardGroup with 4 cards: "Calling Setup", "Default Call", "Direct Call", "Standalone Calling" | The Quick Reference is a decision guide — helps developers choose between the three calling modes based on their use case. | +| `call-logs.mdx` | 1. Added `description: "Learn how to fetch and manage call logs in your Flutter application using CometChat's Call SDK, including filtering by call type, status, and direction."`
2. Added Quick Reference `` block with: `CallLogRequestBuilder` code showing `..limit`, `..callType`, `..callStatus`, `..callDirection` filters; `fetchNext()`/`fetchPrevious()` code; `CometChatCalls.getCallDetails(sessionId)` code
3. Added Response accordion after `fetchNext()` — `List` with 10+ fields: `sessionId`, `callType` (`"audio"`/`"video"`), `callStatus` (`"initiated"`/`"ongoing"`/`"ended"`/`"cancelled"`/`"rejected"`/`"busy"`/`"unanswered"`), `callDirection` (`"incoming"`/`"outgoing"`), `initiator` (User object), `receiver` (User object), `initiatedAt`, `endedAt`, `duration`, `participants`
4. Added Error accordion after `fetchNext()`
5. Added Response accordion after `fetchPrevious()` — same structure
6. Added Error accordion after `fetchPrevious()`
7. Added Response accordion after `getCallDetails()` — `List` for a specific session
8. Added Error accordion after `getCallDetails()`
9. Added Next Steps CardGroup with 3 cards: "Default Call", "Recording", "Presenter Mode" | The `CallLog` object is distinct from the `Call` object — it's a historical record with `duration`, `endedAt`, and `participants` fields not present on the real-time `Call` object. | +| `recording.mdx` | 1. Added `description: "Learn how to enable and manage call recording in your Flutter app using CometChat's Calls SDK."`
2. Added Quick Reference `` block with: recording configuration in `CallSettingsBuilder` (`..enableRecording`), fetch recordings code
3. Added Response accordion after fetching recordings — recording object with `recordingUrl`, `recordingDuration`, `startedAt`, `endedAt`
4. Added Error accordion
5. Added Next Steps CardGroup with 3 cards: "Call Logs", "Default Call", "Presenter Mode" | Recording response includes the `recordingUrl` for playback/download. | +| `presenter-mode.mdx` | 1. Added `description: "Learn how to implement presenter mode in your Flutter app for webinars, online classes, and broadcast-style calling experiences with CometChat."`
2. Added Quick Reference `` block with: `PresentationSettingsBuilder` code showing `..enableDefaultLayout`, `..isPresenter = true` (presenter) and `..isPresenter = false` (viewer); `CometChatCalls.joinPresentation(callToken, settings)` code for both roles
3. Added Response accordion after `joinPresentation()` — `Widget?` representing the presentation UI, documented as: "A Flutter widget containing the presentation UI. Display this widget in your screen to show the presentation interface."
4. Added Error accordion after `joinPresentation()` — `code` (`"ERR_CHAT_API_FAILURE"`), `message` (`"Failed to start the presentation session."`), `details` (`"The call token provided is invalid or expired."`)
5. Added Next Steps CardGroup with 3 cards: "Default Call", "Recording", "Video View Customisation" | This was the final file updated (commit `9feb900b`). The Quick Reference shows both presenter and viewer code side-by-side so developers can see the `isPresenter` flag difference. | +| `video-view-customisation.mdx` | 1. Added `description: "Learn how to customize the video view in CometChat calls for Flutter."`
2. Added Quick Reference `` block with: video view customization code
3. Added Next Steps CardGroup with 3 cards: "Presenter Mode", "Default Call", "Recording" | No response/error accordions — this page covers UI customization, not SDK method calls. | +| `real-time-listeners.mdx` | 1. Added `description: "Complete reference for all real-time event listeners in the CometChat Flutter SDK."`
2. Added Quick Reference `` block listing all 5 listener types with their key callbacks: `MessageListener` (onTextMessageReceived, onMediaMessageReceived, onCustomMessageReceived, onMessageEdited, onMessageDeleted, onMessagesDelivered, onMessagesRead, onTypingStarted, onTypingEnded, onTransientMessageReceived), `UserListener` (onUserOnline, onUserOffline), `GroupListener` (onGroupMemberJoined, onGroupMemberLeft, onGroupMemberKicked, onGroupMemberBanned, onGroupMemberUnbanned, onGroupMemberScopeChanged, onMemberAddedToGroup), `CallListener` (onIncomingCallReceived, onOutgoingCallAccepted, onOutgoingCallRejected, onIncomingCallCancelled), `ConnectionListener` (onConnected, onConnecting, onDisconnected, onFeatureThrottled)
3. Added Next Steps CardGroup with 3 cards: "Receive Messages", "Connection Status", "Login Listeners" | The Quick Reference is a comprehensive callback catalog — developers can scan all available listener callbacks in one place without reading the full page. | +| `login-listeners.mdx` | 1. Added `description: "Learn how to handle login and logout state changes using LoginListener in CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `CometChat.addLoginListener()` code showing `onLoginSuccess`, `onLoginFailure`, `onLogoutSuccess`, `onLogoutFailure` callbacks
3. Added Next Steps CardGroup with 3 cards: "Authentication", "Real-Time Listeners", "Connection Status" | Login listeners help developers react to auth state changes (e.g., auto-redirect on logout). | +| `connection-status.mdx` | 1. Added `description: "Monitor real-time WebSocket connection status with CometChat SDK using ConnectionListener callbacks and getConnectionStatus method."`
2. Added Quick Reference `` block with: `CometChat.addConnectionListener()` code showing `onConnected`, `onConnecting`, `onDisconnected`, `onFeatureThrottled` callbacks; `CometChat.getConnectionStatus()` code returning `CometChatConnectionStatus.connected`/`.connecting`/`.disconnected`
3. Added Next Steps CardGroup with 3 cards: "Connection Behaviour", "Real-Time Listeners", "Login Listeners" | The Quick Reference shows both the listener approach (reactive) and the `getConnectionStatus()` approach (polling) for monitoring connection state. | +| `connection-behaviour.mdx` | 1. Added `description: "Understand how CometChat SDK manages WebSocket connections in auto and manual modes, including background behavior and reconnection handling."`
2. Added Quick Reference `` block comparing Auto Mode (default — SDK manages connections automatically) vs Manual Mode (`autoEstablishSocketConnection = false` — developer controls `connect()`/`disconnect()`/`ping()`)
3. Added Response accordion after `CometChat.connect()` — `String` success message
4. Added Error accordion after `CometChat.connect()`
5. Added Response accordion after `CometChat.disconnect()` — `String` success message
6. Added Error accordion after `CometChat.disconnect()`
7. Added Response accordion after `CometChat.ping()` — `String` success message
8. Added Error accordion after `CometChat.ping()`
9. Added Next Steps CardGroup with 3 cards: "Connection Status", "Real-Time Listeners", "Setup" | The auto vs manual mode comparison in the Quick Reference is a key decision point for developers — most should use auto mode, but apps with specific background requirements may need manual mode. | +| `session-timeout.mdx` | 1. Added `description: "Learn how to configure session timeout behavior in CometChat Flutter SDK."`
2. Added Quick Reference `` block with: session timeout configuration code
3. Added Next Steps CardGroup with 3 cards: "Authentication", "Connection Behaviour", "Login Listeners" | No response/error accordions — session timeout is a configuration, not a method call. | +| `rate-limits.mdx` | 1. Added `description: "Understand the API rate limits for CometChat Flutter SDK operations."`
2. Added Quick Reference `` block summarizing rate limit categories and their values (messages per second, API calls per minute, etc.)
3. Added Next Steps CardGroup with 3 cards: "Send Messages", "Retrieve Conversations", "Setup" | The Quick Reference gives developers a quick view of rate limits without reading the full table. | +| `advanced-overview.mdx` | 1. Added `description: "Advanced SDK features including connection management, real-time listeners, and login state handling for Flutter applications."`
2. Added Quick Reference `` block listing 4 advanced features with one-line descriptions and links: Connection Status (monitor SDK connection state), Connection Behaviour (understand connection lifecycle), Login Listeners (handle login state changes), Real-Time Listeners (all event listeners reference)
3. Added Next Steps CardGroup with 4 cards: "Connection Status", "Real-Time Listeners", "Login Listeners", "Connection Behaviour" | Index page for the Advanced section. | +| `resources-overview.mdx` | 1. Added `description` frontmatter
2. Added Quick Reference `` block listing resource topics
3. Added Next Steps CardGroup | Index page for the Resources section. | +| `flutter-overview.mdx` | 1. Added `description` frontmatter
2. Added Quick Reference `` block with high-level SDK capabilities: real-time messaging, voice/video calling, user/group management, typing indicators, read receipts, file sharing, reactions, mentions, interactive messages, AI features
3. Added Next Steps CardGroup with 4 cards: "Overview/Setup", "Key Concepts", "Authentication", "Send Messages" | Top-level Flutter SDK overview — the Quick Reference gives a feature checklist. | +| `upgrading-from-v3-guide.mdx` | 1. Added `description: "Guide for migrating your Flutter app from CometChat SDK v3 to v4."`
2. Added Quick Reference `` block summarizing key v3→v4 breaking changes and migration steps
3. Added Next Steps CardGroup with 3 cards: "Setup", "Authentication", "Key Concepts" | The Quick Reference gives a scannable migration checklist. | +| `ai-agents.mdx` | 1. Added `description: "Learn how to integrate AI Agents in your Flutter app to enable intelligent, automated interactions that process user messages, trigger tools, and respond with contextually relevant information."`
2. Added Quick Reference `` block with: `CometChat.addAIAssistantListener("LISTENER_ID", AIAssistantListener(onAIAssistantEventReceived: (event) {}))` code, `CometChat.addMessageListener("LISTENER_ID", MessageListener(onAIAssistantMessageReceived: (msg) {}, onAIToolResultReceived: (result) {}))` code, `CometChat.removeAIAssistantListener("LISTENER_ID")` cleanup code
3. Added ``: "Available via: SDK \| REST API \| UI Kits \| Dashboard"
4. Added ``: "Always remove AI Assistant listeners when they're no longer needed (e.g., on widget dispose or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling."
5. Added Next Steps CardGroup with 3 cards: "AI Moderation", "AI Chatbots", "Extensions" | The Quick Reference shows both the AI-specific listener (`AIAssistantListener`) and the message listener callbacks for AI events (`onAIAssistantMessageReceived`, `onAIToolResultReceived`). The memory leak warning is especially important for AI listeners since they may be added in multiple screens. | +| `ai-moderation.mdx` | 1. Added `description: "Learn how to implement AI-powered content moderation in your Flutter app using CometChat SDK to automatically review messages for inappropriate content."`
2. Added Quick Reference `` block with: moderation check code showing `message.metadata["@injected"]["extensions"]["ai-moderation"]` path, status values (`"approved"`, `"pending"`, `"rejected"`), real-time listener for moderation status updates
3. Added Response accordion after sending a moderated message — `BaseMessage` with `metadata` containing nested `@injected.extensions.ai-moderation` object with fields: `status` (`"pending"`), `confidence` (number), `categories` (array of flagged categories)
4. Added Error accordion
5. Added Response accordion for real-time moderation status update — same metadata structure with `status` changed to `"approved"` or `"rejected"`
6. Added Error accordion
7. Added Next Steps CardGroup with 4 cards: "AI Agents", "AI Chatbots", "Send Messages", "Extensions" | The moderation metadata path (`@injected.extensions.ai-moderation`) is deeply nested — the Response accordion documents the exact path developers need to access moderation results. The two Response accordions show the initial "pending" state and the final "approved"/"rejected" state. | +| `ai-chatbots-overview.mdx` | 1. Added `description: "Configure AI-powered chatbots to provide automated assistance and maintain conversational momentum in your Flutter app."`
2. Added Quick Reference `` block summarizing: chatbot configuration via Dashboard, chatbot types (rule-based, AI-powered), integration with messaging flow
3. Added Next Steps CardGroup with 4 cards: "AI Agents", "AI Moderation", "AI User Copilot", "Extensions" | Index page for AI chatbots — no SDK method calls, so no response/error accordions. | +| `extensions-overview.mdx` | 1. Added `description: "Explore CometChat extensions that add enhanced functionality to your Flutter chat application"`
2. Added Quick Reference `` block listing all extension categories: User Experience (Pin message, Link preview, Thumbnails, Voice transcription), User Engagement (Polls, Reactions, Mentions, Message translation, Stickers), Collaboration (Whiteboard, Collaborative documents), Notifications (Push, Email, SMS), Moderation (Content filtering, Profanity detection), Security (Disappearing messages, End-to-end encryption) — with link to full Extensions Overview
3. Added ``: "Available via: SDK \| REST API \| UI Kits"
4. Added Next Steps CardGroup with 3 cards: "AI Features", "Webhooks", "Setup" | The Quick Reference is a comprehensive extension catalog organized by category — developers can quickly find which extension they need. | +| `webhooks-overview.mdx` | 1. Added `description: "Configure server-side webhooks to receive real-time notifications for messages, users, groups, calls, and moderation events in your Flutter application."`
2. Added Quick Reference `` block with: setup requirements (HTTPS endpoint, publicly accessible URL, POST method with `application/json`, return HTTP 200 OK), event categories (Messages: `message_sent`/`message_edited`/`message_deleted`/`message_read_receipt`; Users: `user_blocked`/`user_unblocked`/`user_connection_status_changed`; Groups: `group_created`/`group_member_added`/`group_member_left`; Calls: `call_initiated`/`call_started`/`call_ended`/`recording_generated`; Moderation: `moderation_engine_approved`/`moderation_engine_blocked`), configuration link to Dashboard
3. Added ``: "Webhooks are configured at the application level through the CometChat Dashboard, not within the Flutter SDK. The SDK handles real-time events via listeners, while webhooks deliver events to your backend server."
4. Added Next Steps CardGroup with 3 cards: "Extensions", "Real-Time Listeners", "AI Agents" | The Quick Reference lists all webhook event names — this is valuable for backend developers who need to know which events to listen for. The `` clarifies the SDK vs webhook distinction (SDK = client-side listeners, webhooks = server-side HTTP callbacks). | diff --git a/notifications/react-native-push-notifications-android.mdx b/notifications/react-native-push-notifications-android.mdx index 36615b443..a51e7a886 100644 --- a/notifications/react-native-push-notifications-android.mdx +++ b/notifications/react-native-push-notifications-android.mdx @@ -3,6 +3,18 @@ title: "React Native Push Notification (Android)" description: "Bring the SampleAppWithPushNotifications experience—FCM + VoIP calls—into any React Native project using CometChat UI Kit." --- + + +| Field | Value | +| --- | --- | +| Platform | Android (FCM) | +| Key Classes | `CometChatNotifications`, `VoipNotificationHandler`, `PendingCallManager` | +| Key Methods | `registerPushToken()`, `unregisterPushToken()`, `messaging().getToken()` | +| Push Platform | `CometChatNotifications.PushPlatforms.FCM_REACT_NATIVE_ANDROID` | +| Prerequisites | CometChat SDK initialized, user logged in, FCM configured, `google-services.json` in `android/app` | + + + { {/* | Notification taps do nothing | Keep Notifee foreground/background handlers and ensure the navigation ref is ready before routing. | */} {/* | Call UI not showing | Verify CallKeep setup, telecom permissions, and that `VoipNotificationHandler.initialize()` runs post-login. | */} {/* | Inline reply needed | Extend Notifee action buttons; CometChat expects you to send the message manually after reading `remoteMessage.data`. | */} + +--- + +## Next Steps + + + +Set up APNs push notifications for iOS + + +Strip HTML tags and customize notification content + + +Learn how to send different types of messages + + +Handle incoming messages in real time + + diff --git a/notifications/react-native-push-notifications-ios.mdx b/notifications/react-native-push-notifications-ios.mdx index e92eec374..9409502a6 100644 --- a/notifications/react-native-push-notifications-ios.mdx +++ b/notifications/react-native-push-notifications-ios.mdx @@ -3,6 +3,18 @@ title: "React Native Push Notifications (iOS)" description: "Bring the SampleAppWithPushNotifications experience—APNs + VoIP—into any React Native project using CometChat UI Kit." --- + + +| Field | Value | +| --- | --- | +| Platform | iOS (APNs + PushKit/CallKit) | +| Key Classes | `CometChatNotifications`, `VoipNotificationHandler`, `PendingCallManager` | +| Key Methods | `registerPushToken()`, `unregisterPushToken()`, `PushNotificationIOS.requestPermissions()` | +| Push Platforms | `APNS_REACT_NATIVE_DEVICE`, `APNS_REACT_NATIVE_VOIP` | +| Prerequisites | CometChat SDK initialized, user logged in, APNs `.p8` key uploaded, physical iOS device | + + + { {/* | Notification taps do nothing | Keep foreground/background handlers and ensure navigation ref is ready before routing. | */} {/* | Call UI not showing | Verify PushKit VoIP capability, CallKeep entitlements/permissions, and that `voipHandler.initialize()` runs after login. | */} {/* | Inline reply needed | Extend Notifee action buttons; CometChat expects you to send the message manually after reading `remoteMessage.data`. | */} + +--- + +## Next Steps + + + +Set up FCM push notifications for Android + + +Strip HTML tags and customize notification content + + +Learn how to send different types of messages + + +Handle incoming messages in real time + + diff --git a/sdk/android/additional-message-filtering.mdx b/sdk/android/additional-message-filtering.mdx index a215f75c7..9aa168b17 100644 --- a/sdk/android/additional-message-filtering.mdx +++ b/sdk/android/additional-message-filtering.mdx @@ -1,35 +1,75 @@ --- title: "Additional Message Filtering" +sidebarTitle: "Message Filtering" +description: "Filter messages by category, type, timestamp, tags, and other parameters using MessagesRequest in the CometChat Android SDK." --- + +```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() -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: +// Fetch messages +messagesRequest.fetchNext(callback) +messagesRequest.fetchPrevious(callback) +``` + + +The [`MessagesRequest`](/sdk/reference/messages#basemessage) 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 -*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. @@ -84,9 +124,7 @@ val messagesRequest = MessagesRequestBuilder() ## 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,11 +151,7 @@ val messagesRequest = MessagesRequestBuilder() ## Messages for a group conversation -*In other words, 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. - -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. @@ -144,9 +178,7 @@ val messagesRequest = MessagesRequestBuilder() ## 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. @@ -203,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 -*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. @@ -266,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 -*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. @@ -333,9 +361,7 @@ 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* - -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`. @@ -392,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 -*In other words, 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. +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. @@ -455,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 -*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()`. @@ -524,11 +546,7 @@ val messagesRequest = MessagesRequestBuilder() ## Messages for multiple categories -*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/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. +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. @@ -597,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 -*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/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. @@ -694,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 -*In other words, how do I fetch messages that are a part of a thread and not directly a user/group conversations* - -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. @@ -760,9 +772,7 @@ 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* - -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`. @@ -821,9 +831,7 @@ val messagesRequest = MessagesRequestBuilder() ## 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`. @@ -882,9 +890,7 @@ val messagesRequest = MessagesRequestBuilder() ## 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`. @@ -943,9 +949,7 @@ val messagesRequest = MessagesRequestBuilder() ## Messages by tags -*In other words, 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. +Use `setTags()` with a list of tag names to fetch only messages with those tags. @@ -982,9 +986,13 @@ val messagesRequest = MessagesRequestBuilder() ## Messages with tags -*In other words, 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()`. -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` . +| Additional Field | Getter | Return Type | Description | +| --- | --- | --- | --- | +| tags | `getTags()` | `List` | Tags associated with the message | @@ -1017,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`. @@ -1058,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`. @@ -1099,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`. @@ -1140,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`. @@ -1181,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. @@ -1226,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. @@ -1263,10 +1259,30 @@ val UID = "cometchat-uid-1" val messagesRequest = MessagesRequestBuilder() .setLimit(50) .setUID(UID) - .setAttachmemnt(attachmentTypes) + .setAttachmentTypes(attachmentTypes) .build() ``` + + +--- + +## 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 deleted file mode 100644 index 18501a4d5..000000000 --- a/sdk/android/advanced-overview.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: "Advanced" -sidebarTitle: "Overview" ---- - - diff --git a/sdk/android/ai-agents.mdx b/sdk/android/ai-agents.mdx index 853da43a7..505579aa8 100644 --- a/sdk/android/ai-agents.mdx +++ b/sdk/android/ai-agents.mdx @@ -1,13 +1,33 @@ --- title: "AI Agents" +sidebarTitle: "AI Agents" +description: "Integrate AI-powered agents for intelligent, automated interactions in the Android SDK" --- -# AI Agents Overview + + +```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) { } +}) +``` + 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 @@ -17,7 +37,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): @@ -130,4 +150,321 @@ These events are received via the **`MessageListener`** after the run completes. ``` - \ No newline at end of file + + + +## 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](/sdk/reference/entities#user) | User who sent the message | +| `receiver` | AppEntity | Message receiver ([User](/sdk/reference/entities#user) or [Group](/sdk/reference/entities#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](/sdk/reference/entities#user) | User who sent the message | +| `receiver` | AppEntity | Message receiver ([User](/sdk/reference/entities#user) or [Group](/sdk/reference/entities#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](/sdk/reference/entities#user) | User who sent the message | +| `receiver` | AppEntity | Message receiver ([User](/sdk/reference/entities#user) or [Group](/sdk/reference/entities#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 +} +``` + + + +--- + +## 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..d77b05e36 100644 --- a/sdk/android/ai-chatbots-overview.mdx +++ b/sdk/android/ai-chatbots-overview.mdx @@ -1,4 +1,10 @@ --- -title: "AI" +title: "AI Chatbots" +sidebarTitle: "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 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). + +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/ai-moderation.mdx b/sdk/android/ai-moderation.mdx index 3c3a0214c..be622f014 100644 --- a/sdk/android/ai-moderation.mdx +++ b/sdk/android/ai-moderation.mdx @@ -1,10 +1,33 @@ --- title: "AI Moderation" +sidebarTitle: "AI Moderation" +description: "Automatically review messages for inappropriate content using AI moderation in the Android SDK" --- -## 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. +```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 + } +}) +``` + + +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). @@ -62,6 +85,7 @@ The `getModerationStatus()` method returns one of the following values: | Status | Enum Value | Description | |--------|------------|-------------| +| Unmoderated | `ModerationStatus.UNMODERATED` | Message has not been submitted for moderation | | Pending | `ModerationStatus.PENDING` | Message is being processed by moderation | | Approved | `ModerationStatus.APPROVED` | Message passed moderation and is visible | | Disapproved | `ModerationStatus.DISAPPROVED` | Message violated rules and was blocked | @@ -117,7 +141,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 provides a [`BaseMessage`](/sdk/reference/messages#basemessage) with the final moderation status: @@ -234,4 +258,18 @@ 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 + + diff --git a/sdk/android/ai-user-copilot-overview.mdx b/sdk/android/ai-user-copilot-overview.mdx index 3e798a3fb..c68785914 100644 --- a/sdk/android/ai-user-copilot-overview.mdx +++ b/sdk/android/ai-user-copilot-overview.mdx @@ -1,4 +1,210 @@ --- -title: "AI" -url: "/fundamentals/ai-user-copilot/overview" ---- \ No newline at end of file +title: "AI User Copilot" +sidebarTitle: "AI User Copilot" +description: "AI-powered smart replies, conversation starters, and summaries using the CometChat Android SDK" +--- + + + +```kotlin +// Smart Replies +CometChat.getSmartReplies("UID", CometChatConstants.RECEIVER_TYPE_USER, + object : CometChat.CallbackListener>() { + override fun onSuccess(replies: HashMap) { } + override fun onError(e: CometChatException) { } + }) + +// Conversation Starter +CometChat.getConversationStarter("UID", CometChatConstants.RECEIVER_TYPE_USER, + object : CometChat.CallbackListener>() { + override fun onSuccess(starters: List) { } + override fun onError(e: CometChatException) { } + }) + +// Conversation Summary +CometChat.getConversationSummary("UID", CometChatConstants.RECEIVER_TYPE_USER, + object : CometChat.CallbackListener() { + override fun onSuccess(summary: String) { } + override fun onError(e: CometChatException) { } + }) +``` + +**Requires:** AI features enabled in [CometChat Dashboard](https://app.cometchat.com) + + +AI User Copilot provides AI-powered assistance to users during conversations. For a broader introduction and Dashboard configuration, see the [AI User Copilot Overview](/fundamentals/ai-user-copilot/overview). + +## Smart Replies + +Use `getSmartReplies()` to get AI-suggested replies for the current conversation context. + + + +```kotlin +val receiverId = "UID" +val receiverType = CometChatConstants.RECEIVER_TYPE_USER + +CometChat.getSmartReplies(receiverId, receiverType, + object : CometChat.CallbackListener>() { + override fun onSuccess(replies: HashMap) { + Log.d(TAG, "Smart replies: $replies") + // Display reply suggestions to the user + } + + override fun onError(e: CometChatException) { + Log.e(TAG, "Error: ${e.message}") + } + }) +``` + + +```java +String receiverId = "UID"; +String receiverType = CometChatConstants.RECEIVER_TYPE_USER; + +CometChat.getSmartReplies(receiverId, receiverType, + new CometChat.CallbackListener>() { + @Override + public void onSuccess(HashMap replies) { + Log.d(TAG, "Smart replies: " + replies); + // Display reply suggestions to the user + } + + @Override + public void onError(CometChatException e) { + Log.e(TAG, "Error: " + e.getMessage()); + } + }); +``` + + + +| Parameter | Description | +| --- | --- | +| `receiverId` | UID of the user or GUID of the group | +| `receiverType` | `CometChatConstants.RECEIVER_TYPE_USER` or `RECEIVER_TYPE_GROUP` | + +Returns a `HashMap` of suggested reply options. + +## Conversation Starter + +Use `getConversationStarter()` to get AI-suggested opening messages for a new conversation. + + + +```kotlin +val receiverId = "UID" +val receiverType = CometChatConstants.RECEIVER_TYPE_USER + +CometChat.getConversationStarter(receiverId, receiverType, + object : CometChat.CallbackListener>() { + override fun onSuccess(starters: List) { + Log.d(TAG, "Conversation starters: $starters") + // Display starter suggestions to the user + } + + override fun onError(e: CometChatException) { + Log.e(TAG, "Error: ${e.message}") + } + }) +``` + + +```java +String receiverId = "UID"; +String receiverType = CometChatConstants.RECEIVER_TYPE_USER; + +CometChat.getConversationStarter(receiverId, receiverType, + new CometChat.CallbackListener>() { + @Override + public void onSuccess(List starters) { + Log.d(TAG, "Conversation starters: " + starters); + // Display starter suggestions to the user + } + + @Override + public void onError(CometChatException e) { + Log.e(TAG, "Error: " + e.getMessage()); + } + }); +``` + + + +| Parameter | Description | +| --- | --- | +| `receiverId` | UID of the user or GUID of the group | +| `receiverType` | `CometChatConstants.RECEIVER_TYPE_USER` or `RECEIVER_TYPE_GROUP` | + +Returns a `List` of suggested conversation openers. + +## Conversation Summary + +Use `getConversationSummary()` to get an AI-generated summary of the conversation history. + + + +```kotlin +val receiverId = "UID" +val receiverType = CometChatConstants.RECEIVER_TYPE_USER + +CometChat.getConversationSummary(receiverId, receiverType, + object : CometChat.CallbackListener() { + override fun onSuccess(summary: String) { + Log.d(TAG, "Summary: $summary") + // Display summary to the user + } + + override fun onError(e: CometChatException) { + Log.e(TAG, "Error: ${e.message}") + } + }) +``` + + +```java +String receiverId = "UID"; +String receiverType = CometChatConstants.RECEIVER_TYPE_USER; + +CometChat.getConversationSummary(receiverId, receiverType, + new CometChat.CallbackListener() { + @Override + public void onSuccess(String summary) { + Log.d(TAG, "Summary: " + summary); + // Display summary to the user + } + + @Override + public void onError(CometChatException e) { + Log.e(TAG, "Error: " + e.getMessage()); + } + }); +``` + + + +| Parameter | Description | +| --- | --- | +| `receiverId` | UID of the user or GUID of the group | +| `receiverType` | `CometChatConstants.RECEIVER_TYPE_USER` or `RECEIVER_TYPE_GROUP` | + +Returns a `String` containing the AI-generated conversation summary. + +--- + +## Next Steps + + + + Integrate AI-powered agents for automated interactions + + + Automatically review messages for inappropriate content + + + Configure AI Copilot features in the Dashboard + + + Send messages in conversations + + diff --git a/sdk/android/android-overview.mdx b/sdk/android/android-overview.mdx deleted file mode 100644 index c85f2beb4..000000000 --- a/sdk/android/android-overview.mdx +++ /dev/null @@ -1,4 +0,0 @@ ---- -title: "Java UI Kit" -url: "/ui-kit/android/overview" ---- \ No newline at end of file diff --git a/sdk/android/authentication-overview.mdx b/sdk/android/authentication-overview.mdx index 7e3f45b6b..226fb99c9 100644 --- a/sdk/android/authentication-overview.mdx +++ b/sdk/android/authentication-overview.mdx @@ -1,37 +1,91 @@ --- title: "Authentication" -sidebarTitle: "Overview" +sidebarTitle: "Authentication" +description: "Log users into CometChat using Auth Key for development or Auth Token for production" --- + +```kotlin +// Check if user is already logged in +val loggedInUser = CometChat.getLoggedInUser() -### Create User +// Login with Auth Key (development only) +CometChat.login("UID", "AUTH_KEY", object : CometChat.CallbackListener() { + override fun onSuccess(user: User?) { } + override fun onError(e: CometChatException?) { } +}) -Before you log in a user, you must add the user to CometChat. +// Login with Auth Token (production) +CometChat.login("AUTH_TOKEN", object : CometChat.CallbackListener() { + override fun onSuccess(user: User?) { } + override fun onError(e: CometChatException?) { } +}) -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. +// Logout +CometChat.logout(object : CometChat.CallbackListener() { + override fun onSuccess(p0: String?) { } + override fun onError(p0: CometChatException?) { } +}) +``` - -Sample Users +**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 + + +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 + +### Create a User + +A user must exist in CometChat before they can log 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`. +- **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 will need to log the user into CometChat using the `login()` method. +### Check for an Existing Session -We recommend you call the CometChat `login()` method once your user logs into your app. The `login()` method needs to be called only once. +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 +} +``` + + -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. +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 `CometChat.getLoggedInUser()` to check for an existing session first. ## 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 +140,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. @@ -97,7 +151,7 @@ This advanced authentication procedure does not use the Auth Key directly in you ```java private String authToken = "AUTH_TOKEN"; -CometChat.login(authToken, new CometChat.CallbackListener() +CometChat.login(authToken, new CometChat.CallbackListener() { @Override public void onSuccess(User user) { Log.d(TAG, "Login Successful : " + user.toString()); @@ -175,3 +229,105 @@ 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 + + + + Start sending text, media, and custom messages to users and groups + + + Retrieve and manage users in your application + + + Monitor the SDK connection state in real time + + + Understand core CometChat concepts and terminology + + 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 d48752d66..406ad7bb3 100644 --- a/sdk/android/block-users.mdx +++ b/sdk/android/block-users.mdx @@ -1,14 +1,80 @@ --- title: "Block Users" +sidebarTitle: "Block Users" +description: "Block and unblock users to control communication in your Android app" --- + + + +```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) { } +}) -## Block Users +// Unblock users +CometChat.unblockUsers(uids, object : CometChat.CallbackListener>() { + override fun onSuccess(resultMap: HashMap) { } + override fun onError(e: CometChatException) { } +}) -*In other words, as a logged-in user, how do I block a user from sending me messages?* +// 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) { } +}); -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. +// 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) { } +}); +``` + + + + +## Block Users + +Use `blockUsers()` to block one or more users. All communication to and from blocked users is stopped. Pass a `List` of UIDs to block. @@ -54,13 +120,11 @@ 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?* - -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. +Use `unblockUsers()` to unblock previously blocked users. Pass a `List` of UIDs to unblock. @@ -106,19 +170,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?* +--- -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. +## Get List of Blocked Users -The `BlockedUsersRequestBuilder` class allows you to set the below 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. @@ -143,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. @@ -168,9 +230,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. +* `BlockedUsersRequest.DIRECTION_BLOCKED_BY_ME` - Ensures that the list of blocked users only contains users blocked by the logged-in user. +* `BlockedUsersRequest.DIRECTION_HAS_BLOCKED_ME` - Ensures that the list of blocked users only contains users that have blocked the logged-in user. +* `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. @@ -193,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. @@ -239,3 +301,24 @@ override fun onError(e: CometChatException) { + + + +--- + +## 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..3d30c77a1 100644 --- a/sdk/android/call-logs.mdx +++ b/sdk/android/call-logs.mdx @@ -1,20 +1,35 @@ --- title: "Call Logs" +sidebarTitle: "Call Logs" +description: "Retrieve and display call history for users and groups using the Android SDK" --- + +```kotlin +// Build call log request +val callLogRequest = CallLogRequest.CallLogRequestBuilder() + .setAuthToken(CometChat.getUserAuthToken()) + .setLimit(50) + .setCallCategory(CometChatCallsConstants.CALL_CATEGORY_CALL) + .build() -## 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. +// Fetch call logs +callLogRequest.fetchNext(object : CometChatCalls.CallbackListener>() { + override fun onSuccess(callLogs: List) { /* Display logs */ } + override fun onError(e: CometChatException) { } +}) -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. +// Get specific call details +CometChatCalls.getCallDetails(sessionID, callback) +``` + -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. +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. -## Fetching Call Logs +## Fetch 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 +55,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 +100,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 +151,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 +192,145 @@ CometChatCalls.getCallDetails(sessionID, new CometChatCalls.CallbackListener + + + +Returns a list of [`CallLog`](/sdk/reference/calls#calllog) objects for the specified session. + +--- + + + +## Call Payload Structure + + + +The [`Call`](/sdk/reference/messages#call) object extends [`BaseMessage`](/sdk/reference/messages#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](/sdk/reference/entities#user) | User who sent the call message | +| `receiver` | AppEntity | Call receiver ([User](/sdk/reference/entities#user) or [Group](/sdk/reference/entities#group)) | +| `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](/sdk/reference/entities#user) | 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 + + + + 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..d8ccf2b1d 100644 --- a/sdk/android/calling-overview.mdx +++ b/sdk/android/calling-overview.mdx @@ -1,11 +1,21 @@ --- title: "Calling" sidebarTitle: "Overview" +description: "Implement voice and video calling in your Android application with CometChat" --- -## 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. +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 + + +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 @@ -20,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 @@ -36,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 @@ -89,3 +63,138 @@ Use this when you want: Configure automatic call termination when participants are inactive.
+ +--- + +## 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 + + + + 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..d7a1553ed 100644 --- a/sdk/android/calling-setup.mdx +++ b/sdk/android/calling-setup.mdx @@ -1,23 +1,19 @@ --- title: "Setup" +sidebarTitle: "Setup" +description: "Install and initialize the CometChat Calls SDK for Android applications" --- -## Get your Application Keys +## Prerequisites -[Signup 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 @@ -58,11 +54,19 @@ dependencies { ## Initialize CometChatCalls -The `init()` method initialises the settings required for CometChatCalls. The`init()`method takes the below parameters: +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`. + +### CallAppSettings Options -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: +| 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. | -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. + +`CometChatCalls.init()` must be called before any other Calls SDK method. + @@ -126,3 +130,22 @@ CometChatCalls.init( | ----------------- | -------------------------------------- | | `context` | Android context for your application | | `callAppSettings` | An object of the CallAppSettings class | + +--- + +## 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/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 02a960181..259c66f7e 100644 --- a/sdk/android/connection-behaviour.mdx +++ b/sdk/android/connection-behaviour.mdx @@ -1,28 +1,43 @@ --- title: "Connection Behaviour" +sidebarTitle: "Connection Behaviour" +description: "Understand and configure WebSocket connection management in the CometChat Android SDK" --- + +```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 SDK behaviour on login - -When the login method of the SDK is called, the SDK performs the below operations: +**Default:** Auto mode - SDK handles connection automatically +**Manual mode:** Requires explicit connect/disconnect calls + -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. -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 the app is reopened, and the init() method is called, the web-socket connection to the server is established automatically. +## Default SDK Behaviour on Login -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. +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 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. - -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. +The default mode. The SDK automatically establishes and maintains the WebSocket connection. Set `autoEstablishSocketConnection(true)` (or omit it — auto mode is the default). @@ -39,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 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. - -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. +Set `autoEstablishSocketConnection(false)` to take control of the WebSocket connection. Call `CometChat.connect()` to establish and `CometChat.disconnect()` to break it. -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. - -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. +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. @@ -56,13 +67,9 @@ If you do not call the `CometChat.ping()` method within 30 seconds, the SDK will | 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 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: - ## 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: +Set `autoEstablishSocketConnection(false)` during `init()` to take control of the WebSocket connection. Error callbacks receive a [`CometChatException`](/sdk/reference/auxiliary#cometchatexception): @@ -92,36 +99,34 @@ 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) } -}); +}) ``` -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 +Call `connect()` to establish the connection. Ensure the user is logged in first (`CometChat.getLoggedInUser()`). @@ -158,9 +163,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. +Call `disconnect()` to break the connection. Real-time events stop until reconnected. @@ -197,15 +202,9 @@ 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. - - - -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. +Call `CometChat.ping()` within 30 seconds of the app entering the background to keep the connection alive. @@ -242,4 +241,25 @@ 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. + +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. + + +--- + +## 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..040bcab56 100644 --- a/sdk/android/connection-status.mdx +++ b/sdk/android/connection-status.mdx @@ -1,23 +1,40 @@ --- title: "Connection Status" +sidebarTitle: "Connection Status" +description: "Monitor real-time connection status to CometChat web-socket servers in the Android SDK" --- + +```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 - -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 | +Use `ConnectionListener` to monitor real-time WebSocket connection state. The SDK automatically attempts to reconnect when disconnected. -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. +| 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 | -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. +Error callbacks receive a [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) with details about the connection failure. @@ -81,7 +98,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: @@ -100,18 +119,37 @@ val connectionStatus = CometChat.getConnectionStatus() -The above method will return either of the below 3 values: - -1. `CometChatConstants.WS_STATE_CONNECTED` (connected); +Returns one of: -2. `CometChatConstants.WS_STATE_CONNECTING`(connecting) - -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 | Know more about CometChat SDK connection behaviour [click here](/sdk/android/connection-behaviour) + + +--- + +## 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..63ae636e0 100644 --- a/sdk/android/create-group.mdx +++ b/sdk/android/create-group.mdx @@ -1,27 +1,35 @@ --- -title: "Create A Group" +title: "Create Group" +sidebarTitle: "Create Group" +description: "Create public, private, and password-protected groups using the Android SDK" --- + +```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 a Group - -*In other words, 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. - -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: +// Create with members +val groupMembers = listOf( + GroupMember("uid1", CometChatConstants.SCOPE_ADMIN), + GroupMember("uid2", CometChatConstants.SCOPE_PARTICIPANT) +) +CometChat.createGroupWithMembers(group, groupMembers, emptyList(), callback) +``` + -1.`CometChatConstants.GROUP_TYPE_PUBLIC` (public) +## Create a Group -2.`CometChatConstants.GROUP_TYPE_PASSWORD` (password) +Use `createGroup()` with a [`Group`](/sdk/reference/entities#group) object. The `groupType` must be one of: -3.`CometChatConstants.GROUP_TYPE_PRIVATE` (private) +1. `CometChatConstants.GROUP_TYPE_PUBLIC` +2. `CometChatConstants.GROUP_TYPE_PASSWORD` +3. `CometChatConstants.GROUP_TYPE_PRIVATE` @@ -76,30 +84,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`](/sdk/reference/entities#group) object, an array of [`GroupMember`](/sdk/reference/entities#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`](/sdk/reference/entities#groupmember) class, you can use the following constructor: * `new GroupMember(String UID, String scope)` @@ -164,10 +172,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 +196,77 @@ 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. | + +## 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 +} +``` + + + + + +--- + +## 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..5ba82b1f4 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" --- -## 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. @@ -123,7 +123,7 @@ CometChat.initiateCall(call, object : CometChat.CallbackListener() { | `receiverType` | The type of the receiver: `CometChatConstants.RECEIVER_TYPE_USER` or `CometChatConstants.RECEIVER_TYPE_GROUP` | | `callType` | The type of the call: `CometChatConstants.CALL_TYPE_AUDIO` or `CometChatConstants.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/calls#calllog) object is returned containing the call details including a unique `sessionId` required for starting the call session. ## Call Listeners @@ -203,6 +203,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 +565,23 @@ CometChat.rejectCall(sessionID, status, object : CometChat.CallbackListener + + +--- + +## 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..6b6538be3 100644 --- a/sdk/android/delete-conversation.mdx +++ b/sdk/android/delete-conversation.mdx @@ -1,12 +1,32 @@ --- -title: "Delete A Conversation" +title: "Delete Conversation" +sidebarTitle: "Delete Conversation" +description: "Delete user or group conversations using the CometChat Android SDK." --- + +```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. +Use `deleteConversation()` to delete a conversation for the logged-in user. -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. +| 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 | @@ -75,11 +95,23 @@ 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). +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). -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 | +## 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..c926f50d5 100644 --- a/sdk/android/delete-group.mdx +++ b/sdk/android/delete-group.mdx @@ -1,12 +1,25 @@ --- -title: "Delete A Group" +title: "Delete Group" +sidebarTitle: "Delete Group" +description: "Permanently delete groups as an admin using the Android SDK" --- + +```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. + ## 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. +Use `deleteGroup()` to permanently delete a group. Only group **Admins** can delete groups. @@ -49,6 +62,26 @@ 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 | + + +--- + +## 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..f0a330cb8 100644 --- a/sdk/android/delete-message.mdx +++ b/sdk/android/delete-message.mdx @@ -1,19 +1,37 @@ --- -title: "Delete A Message" +title: "Delete Message" +sidebarTitle: "Delete Message" +description: "Delete messages using the CometChat Android SDK." --- + +```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) { } +}) -While [deleting a message](/sdk/android/delete-message#delete-a-message) is straightforward, receiving events for deleted messages with CometChat has two parts: +// Listen for delete events +CometChat.addMessageListener("LISTENER_ID", object : CometChat.MessageListener() { + override fun onMessageDeleted(message: BaseMessage?) { } +}) +``` + -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. +Deleting a message is straightforward. Receiving delete events has two parts: -## Delete a Message +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 -*In other words, as a sender, how do I delete a message?* +## 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. @@ -54,7 +72,12 @@ CometChat.deleteMessage(messageId,object : CometChat.CallbackListener -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. +| 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`](/sdk/reference/messages#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. @@ -67,9 +90,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. @@ -97,13 +118,24 @@ CometChat.addMessageListener(listenerID, object : CometChat.MessageListener() { -## Missed Message Delete Events +| 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 | -*In other words, as a recipient, how do I know if someone deleted a message when my app was not running?* + +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. -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. +```kotlin +CometChat.removeMessageListener("LISTENER_ID") +``` + + +## Missed Message Delete Events -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`](/sdk/reference/messages#action) message is created when a message is deleted. + +For the message deleted event, in the [`Action`](/sdk/reference/messages#action) object received, the following fields can help you get the relevant information- 1. `action` - `deleted` 2. `actionOn` - Updated message object which was deleted. @@ -115,3 +147,24 @@ 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.
+ +--- + +--- + +## 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..7abf0a19d 100644 --- a/sdk/android/delivery-read-receipts.mdx +++ b/sdk/android/delivery-read-receipts.mdx @@ -1,14 +1,12 @@ --- title: "Delivery & Read Receipts" +sidebarTitle: "Delivery & Read Receipts" +description: "Mark messages as delivered, read, or unread and receive real-time receipt events using the CometChat Android SDK." --- - - ## 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: +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 | | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | @@ -126,19 +124,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) ``` @@ -190,9 +188,7 @@ 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?* - -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 | | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | @@ -263,7 +259,7 @@ CometChat.markAsRead(message.getId(), message.getSender().getUid(),CometChatCons ```java -CometChat.markAsRead(message.getId(), message.getRecieverUID(), CometChatConstants.RECEIVER_TYPE_USER, message.getSender().getUid(), new CometChat.CallbackListener() { +CometChat.markAsRead(message.getId(), message.getReceiverUid(), CometChatConstants.RECEIVER_TYPE_GROUP, message.getSender().getUid(), new CometChat.CallbackListener() { @Override public void onSuccess(Void unused) { Log.e(TAG, "markAsRead : " + "Success"); @@ -296,7 +292,7 @@ CometChat.markAsRead(message.id, message.sender.uid, CometChatConstants.RECEIVER ```kotlin -CometChat.markAsRead(message.id, message.receiverUID, CometChatConstants.RECEIVER_TYPE_GROUP, message.sender.uid, object : CallbackListener() { +CometChat.markAsRead(message.id, message.receiverUid, CometChatConstants.RECEIVER_TYPE_GROUP, message.sender.uid, object : CallbackListener() { override fun onSuccess(unused: Void?) { Log.e(TAG, "markAsRead : " + "Success") } @@ -376,33 +372,27 @@ Starting v3, the `markAsRead()` method working with v2.x is deprecated and will ## Mark Messages as Unread -The Mark 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? - -You can mark the messages for a particular conversation as unread using the `markAsUnread()` method. This method takes the below parameters as input: +Use `markMessageAsUnread()` to mark a message as unread. All messages below that message in the conversation will contribute to the unread count. On success, returns an updated [`Conversation`](/sdk/reference/entities#conversation) object. -| Parameter | Information | -| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| message | To mark a message as unread, pass a non-null BaseMessage instance to the markAsUnread() 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 markAsUnread() 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. | -| listener | The callback listener that will be called on success or error. This should be a non-null `CallbackListener` instance. | +| Parameter | Information | +| --------- | ----------- | +| `message` | A non-null [`BaseMessage`](/sdk/reference/messages#basemessage) instance. All messages below this message in the conversation will be marked as unread. | +| `listener` | A non-null `CallbackListener` instance. | ```java BaseMessage message = messageInstance; -CometChat.markAsUnread(message, new CometChat.CallbackListener() { +CometChat.markMessageAsUnread(message, new CometChat.CallbackListener() { @Override - public void onSuccess(Void unused) { - Log.e("TAG", "markAsUnread: onSuccess"); + public void onSuccess(Conversation conversation) { + Log.e("TAG", "markMessageAsUnread: onSuccess"); } @Override public void onError(CometChatException e) { - Log.e("TAG", "markAsUnread: onError: " + e); + Log.e("TAG", "markMessageAsUnread: onError: " + e); } }); ``` @@ -413,13 +403,13 @@ CometChat.markAsUnread(message, new CometChat.CallbackListener() { ```kotlin val message: BaseMessage = messageInstance -CometChat.markAsUnread(message, object : CometChat.CallbackListener() { - override fun onSuccess(unused: Void) { - Log.e("TAG", "markAsUnread: onSuccess") +CometChat.markMessageAsUnread(message, object : CometChat.CallbackListener() { + override fun onSuccess(conversation: Conversation) { + Log.e("TAG", "markMessageAsUnread: onSuccess") } override fun onError(e: CometChatException) { - Log.e("TAG", "markAsUnread: onError: $e") + Log.e("TAG", "markMessageAsUnread: onError: $e") } }) ``` @@ -430,15 +420,15 @@ CometChat.markAsUnread(message, object : CometChat.CallbackListener() { ```java BaseMessage message = messageInstance; -CometChat.markAsUnread(message, new CometChat.CallbackListener() { +CometChat.markMessageAsUnread(message, new CometChat.CallbackListener() { @Override - public void onSuccess(Void unused) { - Log.e("TAG", "markAsUnread: onSuccess"); + public void onSuccess(Conversation conversation) { + Log.e("TAG", "markMessageAsUnread: onSuccess"); } @Override public void onError(CometChatException e) { - Log.e("TAG", "markAsUnread: onError: " + e); + Log.e("TAG", "markMessageAsUnread: onError: " + e); } }); ``` @@ -449,13 +439,13 @@ CometChat.markAsUnread(message, new CometChat.CallbackListener() { ```kotlin val message: BaseMessage = messageInstance -CometChat.markAsUnread(message, object : CometChat.CallbackListener() { - override fun onSuccess(unused: Void) { - Log.e("TAG", "markAsUnread: onSuccess") +CometChat.markMessageAsUnread(message, object : CometChat.CallbackListener() { + override fun onSuccess(conversation: Conversation) { + Log.e("TAG", "markMessageAsUnread: onSuccess") } override fun onError(e: CometChatException) { - Log.e("TAG", "markAsUnread: onError: $e") + Log.e("TAG", "markMessageAsUnread: onError: $e") } }) ``` @@ -466,10 +456,15 @@ 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?* - ### 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. @@ -528,7 +523,7 @@ CometChat.addMessageListener("Listener 1", object : MessageListener() { -You will receive events in the form of `MessageReceipt` objects. The message receipt contains the following parameters: +You will receive events in the form of [`MessageReceipt`](/sdk/reference/auxiliary#messagereceipt) objects. The message receipt contains the following parameters: | Parameter | Information | | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | @@ -589,7 +584,7 @@ CometChat.getMessageReceipts(messageId, object : CallbackListener -You will receive a list of `MessageReceipt` objects in the `onSuccess()` method. +You will receive a list of [`MessageReceipt`](/sdk/reference/auxiliary#messagereceipt) objects in the `onSuccess()` method. @@ -599,6 +594,93 @@ The following features will be available only if the **Enhanced Messaging Status * `onMessagesReadByAll` event, * `deliveredAt` field in a group message, * `readAt` field in a group message. -* `markAsUnread` method. +* `markMessageAsUnread` 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. + + +## 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) | + + + +--- + +## 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..93208e67c 100644 --- a/sdk/android/direct-calling.mdx +++ b/sdk/android/direct-calling.mdx @@ -1,18 +1,12 @@ --- title: "Call Session" +sidebarTitle: "Call Session" +description: "Start and manage call sessions with video and audio controls in the Android SDK" --- -## Overview +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**. -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). - - - -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 @@ -298,7 +292,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 @@ -538,7 +534,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. @@ -663,3 +658,23 @@ CometChatCalls.endSession() + + +--- + +## 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..a57adbbc8 100644 --- a/sdk/android/edit-message.mdx +++ b/sdk/android/edit-message.mdx @@ -1,19 +1,35 @@ --- -title: "Edit A Message" +title: "Edit Message" +sidebarTitle: "Edit Message" +description: "Edit text and custom messages using the CometChat Android SDK." --- + +```kotlin +// Edit a text message +val updatedMessage = TextMessage( + message.receiverUid, + "Updated text", + message.receiverType +) +updatedMessage.id = message.id -While [editing a message](/sdk/android/edit-message#edit-a-message) is straightforward, receiving events for edited messages with CometChat has two parts: +CometChat.editMessage(updatedMessage, object: CometChat.CallbackListener() { + override fun onSuccess(message: BaseMessage) { } + override fun onError(e: CometChatException) { } +}) -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 +// Listen for edit events +CometChat.addMessageListener("LISTENER_ID", object : CometChat.MessageListener() { + override fun onMessageEdited(message: BaseMessage) { } +}) +``` + ## 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`](/sdk/reference/messages#textmessage) or [`CustomMessage`](/sdk/reference/messages#custommessage) object. Set the message ID using `setId()`. ### Add/Update Tags @@ -40,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()`. @@ -89,6 +103,11 @@ CometChat.editMessage(updatedMessage, object: CometChat.CallbackListener @@ -130,13 +147,24 @@ CometChat.addMessageListener(listenerID, object : CometChat.MessageListener() { -## Missed Message Edit Events + +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. -*In other words, as a recipient, how do I know when someone edited their message when my app was not running?* +```kotlin +CometChat.removeMessageListener("LISTENER_ID") +``` + + +| 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 | + +## 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. 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 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. -For the message edited event, in the `Action` object received, the following fields can help you get the relevant information- +For the message edited event, in the [`Action`](/sdk/reference/messages#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. @@ -148,3 +176,24 @@ 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 + + + Handle real-time message events with listeners + + + Understand message types and properties + + 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/extensions-overview.mdx b/sdk/android/extensions-overview.mdx index 29c1774bd..b9b79ce04 100644 --- a/sdk/android/extensions-overview.mdx +++ b/sdk/android/extensions-overview.mdx @@ -1,4 +1,43 @@ --- title: "Extensions" +sidebarTitle: "Extensions" +description: "Enhance your Android app with CometChat extensions for moderation, translation, and more" url: "/fundamentals/extensions-overview" ---- \ No newline at end of file +--- + + + +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..dbbc3fc6f 100644 --- a/sdk/android/flag-message.mdx +++ b/sdk/android/flag-message.mdx @@ -1,7 +1,32 @@ --- title: "Flag Message" +sidebarTitle: "Flag Message" +description: "Report inappropriate messages to moderators using the Android SDK flagging system" --- + + +```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. @@ -225,3 +250,22 @@ Here's a complete implementation showing how to build a report message flow: ``` + +--- + +## 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..91c38574a 100644 --- a/sdk/android/group-add-members.mdx +++ b/sdk/android/group-add-members.mdx @@ -1,17 +1,31 @@ --- -title: "Add Members To A Group" +title: "Add Members" +sidebarTitle: "Add Members" +description: "Add members to groups with specific roles using the Android SDK" --- + +```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) { } + }) +``` -## Add Members to Group +**Note:** Only admins and moderators can add members. The result HashMap contains UID as key and "success" or error message as value. + -You can add members to the group using the `addMembersToGroup()` method. This method takes the below parameters: +## Add Members to Group -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`](/sdk/reference/entities#groupmember) objects, and an optional list of UIDs to ban. @@ -60,18 +74,12 @@ 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?* +When a member is added to a group, existing members receive a real-time event in `onMemberAddedToGroup()` of the `GroupListener` class. The callback provides an [`Action`](/sdk/reference/messages#action) object, the adding [`User`](/sdk/reference/entities#user), the added [`User`](/sdk/reference/entities#user), and the [`Group`](/sdk/reference/entities#group). - -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, 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. - ```java @@ -100,13 +108,83 @@ 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?* +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`](/sdk/reference/messages#action) message with these fields: + +1. `action` - `added` +2. `actionOn` - [`User`](/sdk/reference/entities#user) object containing the details of the user who was added to the group +3. `actionBy` - [`User`](/sdk/reference/entities#user) object containing the details of the user who added the member to the group +4. `actionFor` - [`Group`](/sdk/reference/entities#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. + + +## GroupMember Payload Structure + + + +The [`GroupMember`](/sdk/reference/entities#groupmember) object extends [`User`](/sdk/reference/entities#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 +} +``` -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- +--- -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 +## 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..fd5ac4e66 100644 --- a/sdk/android/group-change-member-scope.mdx +++ b/sdk/android/group-change-member-scope.mdx @@ -1,12 +1,34 @@ --- title: "Change Member Scope" +sidebarTitle: "Change Scope" +description: "Update group member roles and permissions using the Android SDK" --- + +```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. + ## 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. Only group **Admins** can change scopes. @@ -63,9 +85,7 @@ 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?* - -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 +When a member's scope changes, group members receive a real-time event in `onGroupMemberScopeChanged()` of the `GroupListener` class. The callback provides an [`Action`](/sdk/reference/messages#action) object, the updating [`User`](/sdk/reference/entities#user), the updated [`User`](/sdk/reference/entities#user), and the [`Group`](/sdk/reference/entities#group). @@ -95,15 +115,34 @@ 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?* - -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 message history, scope changes appear as [`Action`](/sdk/reference/messages#action) messages with these fields: 1. `action` - `scopeChanged` -2. `actionOn` - User object containing the details of the user whos 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 +2. `actionOn` - [`User`](/sdk/reference/entities#user) object containing the details of the user whos scope has been changed +3. `actionBy` - [`User`](/sdk/reference/entities#user) object containing the details of the user who changed the scope of the member +4. `actionFor` - [`Group`](/sdk/reference/entities#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. + + +--- + +## 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..ac7f64174 100644 --- a/sdk/android/group-kick-member.mdx +++ b/sdk/android/group-kick-member.mdx @@ -1,17 +1,29 @@ --- -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" --- + +```kotlin +// Kick a member (can rejoin) +CometChat.kickGroupMember("UID", "GUID", object : CallbackListener() { + override fun onSuccess(message: String) { } + override fun onError(e: CometChatException) { } +}) -There are certain actions that can be performed on the group members: +// Ban a member (cannot rejoin without unban) +CometChat.banGroupMember("UID", "GUID", callback) + +// Unban a member +CometChat.unbanGroupMember("UID", "GUID", callback) +``` -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 +**Note:** Only admins and moderators can kick, ban, or unban members. + -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 @@ -171,15 +183,11 @@ 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. - -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 `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. @@ -204,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. @@ -227,9 +235,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. +### Fetch Banned Members -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. +After configuring the builder, call `build()` then `fetchNext()` to retrieve banned members. @@ -278,13 +286,7 @@ bannedGroupMembersRequest?.fetchNext(object :CometChat.CallbackListener @@ -327,27 +329,46 @@ CometChat.addGroupListener(MainActivity::class.java.simpleName, object : GroupLi ## 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. - -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`](/sdk/reference/messages#action) messages with these fields: 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 +2. `actionBy` - [`User`](/sdk/reference/entities#user) object containing the details of the user who has kicked the member +3. `actionOn` - [`User`](/sdk/reference/entities#user) object containing the details of the member that has been kicked +4. `actionFor` - [`Group`](/sdk/reference/entities#group) object containing the details of the Group from which the member was kicked -For group member banned event, the details can be obtained using the below fields of the `Action` class- +For group member banned event, the details can be obtained using the below fields of the [`Action`](/sdk/reference/messages#action) class- 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 +2. `actionBy` - [`User`](/sdk/reference/entities#user) object containing the details of the user who has banned the member +3. `actionOn` - [`User`](/sdk/reference/entities#user) object containing the details of the member that has been banned +4. `actionFor` - [`Group`](/sdk/reference/entities#group) object containing the details of the Group from which the member was banned -For group member unbanned event, the details can be obtained using the below fields of the `Action` class- +For group member unbanned event, the details can be obtained using the below fields of the [`Action`](/sdk/reference/messages#action) class- 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 +2. `actionBy` - [`User`](/sdk/reference/entities#user) object containing the details of the user who has unbanned the member +3. `actionOn` - [`User`](/sdk/reference/entities#user) object containing the details of the member that has been unbanned +4. `actionFor` - [`Group`](/sdk/reference/entities#group) object containing the details of the Group from which the member was unbanned + + +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. + + +--- + +## 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..ff74d1727 100644 --- a/sdk/android/groups-overview.mdx +++ b/sdk/android/groups-overview.mdx @@ -1,10 +1,52 @@ --- title: "Groups" sidebarTitle: "Overview" +description: "Manage group creation, membership, and permissions in the Android SDK" --- + +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 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. -Each group includes three kinds of users- admin, moderator, member. +## 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) | + + +--- + +## 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..61e9bd497 100644 --- a/sdk/android/interactive-messages.mdx +++ b/sdk/android/interactive-messages.mdx @@ -1,12 +1,12 @@ --- title: "Interactive Messages" +sidebarTitle: "Interactive Messages" +description: "Send and receive interactive messages with embedded forms, buttons, and other UI elements using the CometChat Android SDK." --- - - 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: @@ -19,37 +19,18 @@ 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. - -```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,12 +46,27 @@ 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 +## Goal Completion A key feature of `InteractiveMessage` is checking whether a user's interactions with the message meet the defined `InteractionGoal` @@ -83,20 +79,63 @@ 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. +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 +178,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 +## Real-time Events -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,30 +210,30 @@ 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. - } -}) -``` - - - -### On Interaction Goal Completed + +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. 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,25 +244,189 @@ 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. + +## 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 +} ``` - + - + -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. +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"] +} +``` + + -## Usage + + +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 +} +``` + + + +--- -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 + + + + 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..c8e52b921 100644 --- a/sdk/android/join-group.mdx +++ b/sdk/android/join-group.mdx @@ -1,12 +1,27 @@ --- -title: "Join A Group" +title: "Join Group" +sidebarTitle: "Join Group" +description: "Join public, private, and password-protected groups using the Android SDK" --- + +```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) +``` + ## 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 start participating in a group conversation. @@ -50,25 +65,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. +You can identify if a group is joined using the `hasJoined` parameter in the [`Group`](/sdk/reference/entities#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?* - -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. The callback provides an [`Action`](/sdk/reference/messages#action) object, the joined [`User`](/sdk/reference/entities#user), and the [`Group`](/sdk/reference/entities#group). @@ -98,12 +111,31 @@ 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?* +When fetching message history, if a member joined a group the logged-in user is part of, the list will contain an [`Action`](/sdk/reference/messages#action) message with these fields: -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. +1. `action` - `joined` +2. `actionBy` - [`User`](/sdk/reference/entities#user) object containing the details of the user who joined the group +3. `actionFor` - [`Group`](/sdk/reference/entities#group) object containing the details of the group the user has joined -For the group member joined event, in the `Action` object received, the following fields can help you get the relevant information- + +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. + -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 + + + + 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..740a3a871 100644 --- a/sdk/android/key-concepts.mdx +++ b/sdk/android/key-concepts.mdx @@ -1,25 +1,49 @@ --- title: "Key Concepts" +sidebarTitle: "Key Concepts" +description: "Understand core CometChat concepts including users, groups, authentication, and messaging" --- + +**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") -### CometChat Dashboard +**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 The CometChat Dashboard enables you to create new apps (projects) and manage your existing apps. 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 +## Auth & Rest API Keys You can generate two types of keys from the dashboard. @@ -28,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. @@ -43,21 +67,21 @@ UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and othe
-### Auth Token +## 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 +## 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 +## Typical Workflow | Your App | Your Server | CometChat | | ----------------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | @@ -66,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. @@ -90,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: @@ -100,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 | @@ -112,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. -| 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 | +## Message Categories -### Auto Mode Connection +| 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 @@ -136,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 @@ -148,3 +176,42 @@ 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 + + + + 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..e9e1509b3 100644 --- a/sdk/android/leave-group.mdx +++ b/sdk/android/leave-group.mdx @@ -1,12 +1,28 @@ --- -title: "Leave A Group" +title: "Leave Group" +sidebarTitle: "Leave Group" +description: "Leave groups to stop receiving messages and updates using the Android SDK" --- + +```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?) { } +}) +``` + ## 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 stop receiving updates and messages for a group. @@ -53,11 +69,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?* - -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. The callback provides an [`Action`](/sdk/reference/messages#action) object, the left [`User`](/sdk/reference/entities#user), and the [`Group`](/sdk/reference/entities#group). @@ -87,12 +101,31 @@ 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?* +When fetching message history, if a member left a group the logged-in user is part of, the list will contain an [`Action`](/sdk/reference/messages#action) message with these fields: -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. +1. `action` - `left` +2. `actionBy` - [`User`](/sdk/reference/entities#user) object containing the details of the user who left the group +3. `actionFor` - [`Group`](/sdk/reference/entities#group) object containing the details of the group the user has left -For the group member left event, in the `Action` object received, the following fields can help you get the relevant information- + +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. + -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 + + + + 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..5dfd4fe39 100644 --- a/sdk/android/login-listeners.mdx +++ b/sdk/android/login-listeners.mdx @@ -1,88 +1,131 @@ --- title: "Login Listeners" +sidebarTitle: "Login Listeners" +description: "Android Activity and Fragment lifecycle patterns for CometChat login and logout event handling" --- + - -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: - -| 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 ") - } +// 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") ``` + - +This page covers Android-specific lifecycle patterns for `LoginListener`. For the basic add/remove API, see [Authentication](/sdk/android/authentication-overview#login-listener). - +## Android Activity/Fragment Example -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. +Register the listener in `onCreate()` and remove it in `onDestroy()` to follow the Android lifecycle. Callbacks provide [`User`](/sdk/reference/entities#user) objects on success and [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) on failure: ```java -CometChat.removeLoginListener("UNIQUE_ID"); +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 -CometChat.removeLoginListener("UNIQUE_ID") +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) + } +} ``` - - + + +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. + + +--- + +## Next Steps + + + + Login methods, Auth Key vs Auth Token, and logout + + + Register listeners for messages, users, groups, and calls + + + Monitor connection status to CometChat servers + + + Initialize the SDK before logging in users + + diff --git a/sdk/android/mentions.mdx b/sdk/android/mentions.mdx index ce0320209..d2df93dd5 100644 --- a/sdk/android/mentions.mdx +++ b/sdk/android/mentions.mdx @@ -1,21 +1,37 @@ --- title: "Mentions" +sidebarTitle: "Mentions" +description: "Send messages with user mentions, retrieve mentioned users, and filter messages by mention metadata using the CometChat Android SDK." --- - - -## 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>"` +To mention a user, embed `<@uid:UID>` in your message text. For example: `"Hello <@uid:cometchat-uid-1>"`. The `sendMessage()` method returns a [`TextMessage`](/sdk/reference/messages#textmessage) object on success. - + + + +```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 +51,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 +74,8 @@ CometChat.sendMessage(textMessage, object : CallbackListener() { } }) ``` - - - + ```java private String receiverID = "GUID"; private String messageText = "Hello <@uid:cometchat-uid-1>"; @@ -78,27 +95,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 +109,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 +121,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 +174,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 +204,8 @@ messagesRequest.fetchPrevious(object : CometChat.CallbackListener - - + ```java String GUID = "cometchat-guid-1"; @@ -205,24 +231,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 +269,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 +297,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 +328,8 @@ messagesRequest.fetchPrevious(object : CometChat.CallbackListener - - + ```java String GUID = "cometchat-guid-1"; @@ -327,42 +356,15 @@ 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) - } -}) -``` - + -## 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 [`User`](/sdk/reference/entities#user) objects mentioned in it. Returns an empty list if no users were mentioned. @@ -383,21 +385,36 @@ message.mentionedUsers ## Check if Logged-in user has been mentioned -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`. +To check if the logged-in user has been mentioned in a particular message we can use the `hasMentionedMe()` method on any [`BaseMessage`](/sdk/reference/messages#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 -``` - - +--- - +## 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..0b8cbbc69 100644 --- a/sdk/android/message-structure-and-hierarchy.mdx +++ b/sdk/android/message-structure-and-hierarchy.mdx @@ -1,87 +1,166 @@ --- -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" --- + +**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.) -The below diagram helps you better understand the various message categories and types that a CometChat message can belong to. +**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 */ } +} +``` + + +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()` on a [`BaseMessage`](/sdk/reference/messages#basemessage) 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: - -1. groupMember - action performed on a group member. -2. message - action performed on a message. +System-generated messages triggered by actions on group members or messages. Represented as [`Action`](/sdk/reference/messages#action) objects. -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: +Types: `groupMember`, `message`. -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. +The `action` property specifies what happened: -For the type `message`, the action can be either one of the below: +**For `groupMember`:** `joined`, `left`, `kicked`, `banned`, `unbanned`, `added`, `scopeChanged` -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 +Call-related messages. Types: `audio`, `video`. Represented as [`Call`](/sdk/reference/messages#call) objects. -1. audio -2. video +The `status` property indicates the call state: `initiated`, `ongoing`, `canceled`, `rejected`, `unanswered`, `busy`, `ended`. -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 -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. +--- + +## 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..4923d2c82 100644 --- a/sdk/android/messaging-overview.mdx +++ b/sdk/android/messaging-overview.mdx @@ -1,12 +1,93 @@ --- title: "Messaging" sidebarTitle: "Overview" +description: "Send, receive, and manage messages with CometChat's Android SDK messaging features" --- + +```kotlin +// Send a text message +val textMessage = TextMessage("UID", "Hello!", CometChatConstants.RECEIVER_TYPE_USER) +CometChat.sendMessage(textMessage, callback) -Messaging is one of the core features of CometChat. We've thoughtfully created methods to help you send, receive and fetch message history. +// 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) { } +}) -At the minimum, you must add code for [sending messages](/sdk/android/send-message) and [receiving messages](/sdk/android/receive-messages). +// Remove listener +CometChat.removeMessageListener("LISTENER_ID") +``` -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). +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 + +CometChat supports three message types out of the box: + +| Type | Class | Use Case | +| --- | --- | --- | +| Text | `TextMessage` | Plain text chat | +| Media | `MediaMessage` | Images, videos, audio, files | +| Custom | `CustomMessage` | Location, polls, or any JSON data | + +For a full breakdown of message categories and hierarchy, see [Message Structure](/sdk/android/message-structure-and-hierarchy). + +--- + +## Next Steps + + + + Send text, media, and custom messages to users and groups + + + Handle real-time incoming messages with listeners + + + Understand message categories, types, and hierarchy + + + Show real-time typing status in 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 1957a9830..3536e19bf 100644 --- a/sdk/android/overview.mdx +++ b/sdk/android/overview.mdx @@ -1,303 +1,139 @@ --- title: "Overview" +sidebarTitle: "Overview" +description: "Get started with the CometChat Android SDK - install, initialize, and add real-time chat to your Android application" --- 🚀 **CometChat Android SDK v5 is now available!** It removes the Gson dependency, adds Parcelable support, and introduces structural equality. [Try the v5 →](/sdk/android/v5/overview) -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. + -#### **I want to integrate with my app** - -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) - -#### **I want to explore a sample app (includes UI)** - -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 - -[Signup 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 (in case you are using the calls SDKS) -* 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" -} -``` - - - - - - - -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. - - - -Finally, add the below lines `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. 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 three 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. - - - -```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") +// 1. Add dependency to build.gradle +implementation "com.cometchat:chat-sdk-android:4.2.0" +// 2. Initialize (run once at app start) 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 the `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. - -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. - - - -```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 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/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()) - } + .subscribePresenceForAllUsers() + .setRegion("REGION") + .build() +CometChat.init(context, "APP_ID", appSettings, callback) - override fun onError(p0: CometChatException?) { - Log.d(TAG, "Login failed with exception: " + p0?.message) - } - } - ) -} else { - // User already logged in -} +// 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 + -Make sure you replace the `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. + +`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. + -UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. +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 + + + + [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: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. + + + +## Sample Apps - +Import the app into Android Studio and follow the steps mentioned in the `README.md` file. -### Integrate our UI Kits + + + Java sample app + + + Kotlin sample app + + + +## UI Kits + +Refer to the [Android UI Kit](/ui-kit/android/overview) for pre-built, customizable components. + +## Resources + + + + UIDs, GUIDs, auth tokens, and core SDK concepts + + + Message categories, types, and hierarchy + + + Latest SDK version and release notes + + + Migration guide for V3 users + + + Steps to publish your Android app + + + +--- -* Please refer [Android Java UI Kit](/ui-kit/android/overview) section to integrate Android Java UI Kit inside 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..7056fa2b2 100644 --- a/sdk/android/presenter-mode.mdx +++ b/sdk/android/presenter-mode.mdx @@ -1,44 +1,43 @@ --- title: "Presenter Mode" +sidebarTitle: "Presenter Mode" +description: "Create webinar-style calling experiences with presenters and viewers using the Android SDK" --- + +```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) { } +}) +``` -## 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. - -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 into an Android application. Before you begin, we strongly recommend you read the calling setup guide. +**Use Cases:** Webinars, online classes, keynote speeches, all-hands meetings +**Capacity:** Up to 5 presenters + 95 viewers (100 total) + -Before starting a call session you have to generate a call token. You need to call this method for the 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. +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. -`PresentationSettingsBuilder` class takes the 1 mandatory parameter as a part of the constructor: +| 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. Context of the application. +Before starting a presentation, generate a call token using `generateToken()` as described in [Call Session](/sdk/android/direct-calling#generate-call-token). -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)` +## Start Presentation Session -A basic example of how to start a Presentation: +Configure the presentation using `PresentationSettingsBuilder`. Set `setIsPresenter(true)` for presenters or `setIsPresenter(false)` for viewers. @@ -188,11 +187,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 +212,32 @@ 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. + + +--- + + + +## Next Steps -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: + + + 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..3a423b0b1 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" +sidebarTitle: "Publishing to Play Store" +description: "Guide to preparing and publishing your CometChat Android app on Google Play Store" --- + + +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,47 @@ 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) + +--- + +## 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..50114ec89 100644 --- a/sdk/android/rate-limits.mdx +++ b/sdk/android/rate-limits.mdx @@ -1,34 +1,130 @@ --- title: "Rate Limits" +sidebarTitle: "Rate Limits" +description: "Understand CometChat REST API rate limits and how to handle rate limit responses" --- + +**Rate Limits:** +- **Core Operations:** 10,000 requests/minute (login, create/delete user, create/join group) +- **Standard Operations:** 20,000 requests/minute (all other operations) -### CometChat REST API Rate Limits +**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 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 either login a user, add user to a group, remove a user from a group, etc for total 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, 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 ? +## 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}") + } + } +} +``` + + + +--- + +## 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..ca4ff4501 100644 --- a/sdk/android/reactions.mdx +++ b/sdk/android/reactions.mdx @@ -1,14 +1,14 @@ --- title: "Reactions" +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." --- - - -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 -Users can add a reaction to a message by calling `addReaction` with the message ID and the reaction emoji. +Users can add a reaction to a message by calling `addReaction` with the message ID and the reaction emoji. On success, returns a [`BaseMessage`](/sdk/reference/messages#basemessage) object with updated reactions. @@ -53,7 +53,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).
@@ -104,14 +104,14 @@ CometChat.removeReaction(messageId, emoji, object : CometChat.CallbackListener>() { +reactionRequest.fetchNext(new CometChat.CallbackListener>() { @Override - public void onSuccess(List reactions) { + public void onSuccess(List reactions) { Log.e(TAG, "Total Reactions: " + reactions.size()); - for (MessageReaction reaction : reactions) { + for (Reaction reaction : reactions) { Log.e(TAG, "Reaction: " + reaction.getReaction()); } } @@ -149,13 +149,13 @@ reactionRequest.fetchNext(new CometChat.CallbackListener>( val limit = 30 val messageId = 1 -val reactionRequest = ReactionRequest.ReactionRequestBuilder() +val reactionRequest = ReactionsRequest.ReactionsRequestBuilder() .setLimit(limit) .setMessageId(messageId) .build() -reactionRequest.fetchNext(object : CometChat.CallbackListener>() { - override fun onSuccess(reactions: List?) { +reactionRequest.fetchNext(object : CometChat.CallbackListener>() { + override fun onSuccess(reactions: List?) { Log.e(TAG, "Total Reactions: ${reactions?.size}") reactions?.forEach { reaction -> Log.e(TAG, "Reaction: ${reaction.reaction}") @@ -182,16 +182,16 @@ The `fetchPrevious()` method fetches the previous set of reactions for the messa int limit = 30; int messageId = 1; -ReactionRequest reactionRequest = new ReactionRequest.ReactionRequestBuilder() +ReactionsRequest reactionRequest = new ReactionsRequest.ReactionsRequestBuilder() .setLimit(30) .setMessageId(1) .build(); -reactionRequest.fetchPrevious(new CometChat.CallbackListener>() { +reactionRequest.fetchPrevious(new CometChat.CallbackListener>() { @Override - public void onSuccess(List reactions) { + public void onSuccess(List reactions) { Log.e(TAG, "Total Reactions: " + reactions.size()); - for (MessageReaction reaction : reactions) { + for (Reaction reaction : reactions) { Log.e(TAG, "Reaction: " + reaction.getReaction()); } } @@ -210,13 +210,13 @@ reactionRequest.fetchPrevious(new CometChat.CallbackListener>() { - override fun onSuccess(reactions: List?) { +reactionRequest.fetchPrevious(object : CometChat.CallbackListener>() { + override fun onSuccess(reactions: List?) { Log.e(TAG, "Total Reactions: ${reactions?.size}") reactions?.forEach { reaction -> Log.e(TAG, "Reaction: ${reaction.reaction}") @@ -235,21 +235,21 @@ reactionRequest.fetchPrevious(object : CometChat.CallbackListener ```java private String listenerID = "UNIQUE_LISTENER_ID"; -CometChat.addMessageListener(listenerID, new CometChat.MessageReactionListener() { +CometChat.addMessageListener(listenerID, new CometChat.MessageListener() { @Override - public void onMessageReactionAdded(MessageReaction reaction) { + public void onMessageReactionAdded(ReactionEvent reactionEvent) { Log.e(TAG, "Reaction added"); } @Override - public void onMessageReactionRemoved(MessageReaction reaction) { + public void onMessageReactionRemoved(ReactionEvent reactionEvent) { Log.e(TAG, "Reaction removed"); } }); @@ -261,12 +261,12 @@ CometChat.addMessageListener(listenerID, new CometChat.MessageReactionListener() ```kotlin val listenerID = "UNIQUE_LISTENER_ID" -CometChat.addMessageListener(listenerID, object : CometChat.MessageReactionListener { - override fun onMessageReactionAdded(reaction: MessageReaction?) { +CometChat.addMessageListener(listenerID, object : CometChat.MessageListener() { + override fun onMessageReactionAdded(reactionEvent: ReactionEvent?) { Log.e(TAG, "Reaction added") } - override fun onMessageReactionRemoved(reaction: MessageReaction?) { + override fun onMessageReactionRemoved(reactionEvent: ReactionEvent?) { Log.e(TAG, "Reaction removed") } }) @@ -285,7 +285,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 +294,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. @@ -324,7 +328,7 @@ message.reactions ## 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`. @@ -351,9 +355,9 @@ for (reactionCount in message.reactions) { 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 (`CometChatConstants.REACTION_ADDED` or `CometChatConstants.REACTION_REMOVED`) that corresponds to the message being reacted to. +When you receive a real-time reaction event (`ReactionEvent`), call the `updateMessageWithReactionInfo()` method, passing the `BaseMessage` instance (message), the inner `Reaction` from the event (for example `reactionEvent.getReaction()`), and the reaction event action type (`CometChatConstants.REACTION_ADDED` or `CometChatConstants.REACTION_REMOVED`) that corresponds to the message being reacted to. @@ -362,9 +366,9 @@ When you receive a real-time reaction event (`MessageReaction`), call the `updat BaseMessage message = ...; // The reaction event data received in real-time -MessageReaction messageReaction = ...; +Reaction 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 String action = CometChatConstants.REACTION_ADDED; BaseMessage modifiedBaseMessage = CometChatHelper.updateMessageWithReactionInfo( @@ -382,9 +386,9 @@ action val message: BaseMessage = ... // The reaction event data received in real-time -val messageReaction: MessageReaction = ... +val messageReaction: Reaction = ... -// 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 val action = CometChatConstants.REACTION_ADDED // Update the BaseMessage instance with the new reaction information @@ -400,3 +404,103 @@ 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 +} +``` + + + +--- + +## 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..0d672f4e7 100644 --- a/sdk/android/real-time-listeners.mdx +++ b/sdk/android/real-time-listeners.mdx @@ -1,8 +1,29 @@ --- -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" --- + +```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. @@ -17,10 +38,10 @@ The `UserListener` class provides you with live events related to users. Below a | Method | Information | | -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `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. | +| `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`](/sdk/reference/entities#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`](/sdk/reference/entities#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()`. @@ -40,22 +61,27 @@ CometChat.addUserListener(UNIQUE_LISTENER_ID, new CometChat.UserListener() { - + +```kotlin +CometChat.addUserListener(UNIQUE_LISTENER_ID, object : CometChat.UserListener() { + override fun onUserOnline(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. + } -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. + override fun onUserOffline(user: User) { - - -```java -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. @@ -70,7 +96,9 @@ 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. +These callbacks use [`Action`](/sdk/reference/messages#action), [`User`](/sdk/reference/entities#user), and [`Group`](/sdk/reference/entities#group) objects. + +Use `addGroupListener()` to register and `removeGroupListener()` to unregister. Call remove in `onPause()`. @@ -138,27 +166,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. @@ -172,7 +179,7 @@ The `MessageListener` class provides you with live events related to messages. B | `onTypingEnded(TypingIndicator typingIndicator)` | This event is triggered when a user stops typing in a user/group conversation. | | `onMessagesDelivered(MessageReceipt messageReceipt)` | This event is triggered when a set of messages are marked as delivered for any particular conversation. | | `onMessagesRead(MessageReceipt messageReceipt)` | This event is triggered when a set of messages are marked as read for any particular conversation. | -| `onMessageEdited(BaseMessage message)` | This method is triggered when a particular message has been edited in a user/group conversation. | +| `onMessageEdited(BaseMessage message)` | This method is triggered when a particular message has been edited in a user/group conversation. See [`BaseMessage`](/sdk/reference/messages#basemessage). | | `onMessageDeleted(BaseMessage message)` | This event is triggered when a particular message is deleted in a user/group conversation. | | `onInteractiveMessageReceived(InteractiveMessage message)` | This event is triggered when an Interactive Message is received. | | `onInteractionGoalCompleted(InteractionReceipt receipt)` | This event is triggered when an interaction Goal is achieved. | @@ -180,7 +187,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()`. @@ -312,22 +319,18 @@ 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. | Method | Information | | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `onIncomingCallReceived(Call call)` | This event is triggered when the logged-in user receives an incoming call. The details of the call can be obtained from the Call object received as the method parameter. | -| `onOutgoingCallAccepted(Call 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 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 | +| `onIncomingCallReceived(Call call)` | This event is triggered when the logged-in user receives an incoming call. The details of the call can be obtained from the [`Call`](/sdk/reference/messages#call) object received as the method parameter. | +| `onOutgoingCallAccepted(Call 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`](/sdk/reference/messages#call) object received as the method parameter. | +| `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`](/sdk/reference/messages#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`](/sdk/reference/messages#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()`. @@ -382,6 +385,21 @@ 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. +## 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..a42dacdae 100644 --- a/sdk/android/receive-messages.mdx +++ b/sdk/android/receive-messages.mdx @@ -1,21 +1,28 @@ --- 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." --- + +| 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: -*In other words, as a recipient, 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, you need to register the `MessageListener` using the `addMessageListener()` method. +## Real-Time Messages -We suggest adding the listener in the `onResume()` method of the activity or the fragment where you wish to receive these events in. +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. @@ -39,9 +46,7 @@ CometChat.addMessageListener(listenerID, new CometChat.MessageListener() { } }); ``` - - ```kotlin val listenerID:String = "UNIQUE_LISTENER_ID" @@ -60,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. @@ -78,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 -*In other words, as a recipient, 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 @@ -143,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 @@ -183,13 +174,10 @@ messagesRequest.fetchNext(object : CallbackListener>() { } }) ``` - - - -### Fetch Missed Messages of a particular group conversation - + + ```java @@ -221,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" @@ -257,21 +243,20 @@ messagesRequest.fetchNext(object : CallbackListener>() { override fun onError(e: CometChatException) { Log.d(TAG, "Message fetching failed with exception: " + e.message) } -}) +}) ``` - - + + -## 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. +## 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 @@ -301,9 +286,7 @@ messagesRequest.fetchPrevious(new CometChat.CallbackListener>( } }); ``` - - ```kotlin val UID:String = "cometchat-uid-1" @@ -330,13 +313,10 @@ messagesRequest.fetchPrevious(object : CallbackListener>() { } }) ``` - - - -### Fetch Unread Messages of a particular group conversation - + + ```java @@ -366,9 +346,7 @@ messagesRequest.fetchPrevious(new CometChat.CallbackListener>( } }); ``` - - ```kotlin val GUID:String = "cometchat-guid-1" @@ -395,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. - +The list of messages received is in the form of objects of [`BaseMessage`](/sdk/reference/messages#basemessage) class. 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`](/sdk/reference/messages#action) or [`Call`](/sdk/reference/messages#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 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 @@ -442,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 @@ -471,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 @@ -513,9 +478,7 @@ messagesRequest.fetchPrevious(new CometChat.CallbackListener>( } }); ``` - - ```kotlin val limit: Int = 30 @@ -542,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 -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`. - - - -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 @@ -598,9 +543,7 @@ messagesRequest.fetchPrevious(new CometChat.CallbackListener>( } }); ``` - - ```kotlin val limit: Int = 30 @@ -624,13 +567,10 @@ messagesRequest.fetchPrevious(object : CallbackListener>() { } }) ``` - - - -### Search Messages in a particular group conversation - + + ```java @@ -657,9 +597,7 @@ messagesRequest.fetchPrevious(new CometChat.CallbackListener>( } }); ``` - - ```kotlin val limit = 30 @@ -683,65 +621,65 @@ 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?* - -### Fetch Unread Message Count of a particular one-on-one conversation +### Search Capabilities -*In other words, 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. -In order to get the unread message count for a particular user (with respect to the logged-in user), you can use the `getUnreadMessageCountForUser()`. +| 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 @@ -753,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 @@ -769,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 - -*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 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 } @@ -837,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 - -*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 counts, you can 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 @@ -934,175 +780,267 @@ 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 - -*In other words, 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. -This method, just like others, has two variants: +// All user conversations only +CometChat.getUnreadMessageCountForAllUsers(object : CometChat.CallbackListener>() { + override fun onSuccess(stringIntegerHashMap: HashMap) { + Log.d(TAG,"onSuccess: ${stringIntegerHashMap.size}") + } - - -```java -CometChat.getUnreadMessageCountForAllUsers(Callbacks); -``` + override fun onError(e: CometChatException) { + Log.d(TAG,"onError: ${e.message}") + } +}) - +// All group conversations only +CometChat.getUnreadMessageCountForAllGroups(object : CometChat.CallbackListener>() { + override fun onSuccess(stringIntegerHashMap: HashMap) { + Log.d(TAG,"onSuccess: ${stringIntegerHashMap.size}") + } - -```kotlin -CometChat.getUnreadMessageCountForAllUsers(Callbacks) + override fun onError(e: CometChatException) { + Log.e(TAG,"onError: ${e.message}") + } +}) ``` - - -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) -``` - - +### Excluding Blocked Users - +Pass `true` as the second argument to any of the methods above to ignore messages from blocked users: ```java -CometChat.getUnreadMessageCountForAllUsers(new CometChat.CallbackListener>() { -@Override - public void onSuccess(HashMap stringIntegerHashMap) { - // Handle Success -} - -@Override - public void onError(CometChatException e) { - // Handle Error -} -}); +CometChat.getUnreadMessageCountForUser(UID, true, Callbacks); +CometChat.getUnreadMessageCountForGroup(GUID, true, Callbacks); +CometChat.getUnreadMessageCount(true, Callbacks); +CometChat.getUnreadMessageCountForAllUsers(true, Callbacks); +CometChat.getUnreadMessageCountForAllGroups(true, Callbacks); ``` - - ```kotlin -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}") -} -}) +CometChat.getUnreadMessageCountForUser(UID, true, Callbacks) +CometChat.getUnreadMessageCountForGroup(GUID, true, Callbacks) +CometChat.getUnreadMessageCount(true, Callbacks) +CometChat.getUnreadMessageCountForAllUsers(true, Callbacks) +CometChat.getUnreadMessageCountForAllGroups(true, Callbacks) ``` - - -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 -*In other words, how do I find out the number of unread messages for every group?* +## Get Message Details -In order to fetch the unread message counts for all groups, you can use the `getUnreadMessageCountForAllGroups()` method. - -This method has two variants: +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 other [`BaseMessage`](/sdk/reference/messages#basemessage) subclass). ```java -CometChat.getUnreadMessageCountForAllGroups(Callbacks); -``` - - - - -```kotlin -CometChat.getUnreadMessageCountForAllGroups(Callbacks) -``` +int messageId = MESSAGE_ID; - - - - -If you wish to ignore the messages from blocked users you can use the below syntax setting the boolean parameter to `true`: +CometChat.getMessageDetails(messageId, new CometChat.CallbackListener() { + @Override + public void onSuccess(BaseMessage message) { + Log.d(TAG, "Message details fetched: " + message.toString()); + } - - -```java -CometChat.getUnreadMessageCountForAllGroups(boolean hideMessagesFromBlockedUsers, Callbacks); + @Override + public void onError(CometChatException e) { + Log.d(TAG, "Error fetching message details: " + e.getMessage()); + } +}); ``` - - ```kotlin -CometChat.getUnreadMessageCountForAllGroups(hideMessagesFromBlockedUsers: Boolean, Callbacks) -``` - - +val messageId: Int = MESSAGE_ID - - - - -```java -CometChat.getUnreadMessageCountForAllGroups(new CometChat.CallbackListener>() { -@Override - public void onSuccess(HashMap stringIntegerHashMap) { - // Handle success -} +CometChat.getMessageDetails(messageId, object : CometChat.CallbackListener() { + override fun onSuccess(message: BaseMessage) { + Log.d(TAG, "Message details fetched: $message") + } -@Override - public void onError(CometChatException e) { - // Handle Error -} -}); + override fun onError(e: CometChatException) { + Log.d(TAG, "Error fetching message details: ${e.message}") + } +}) ``` - + - -```kotlin -CometChat.getUnreadMessageCountForAllGroups(object : CometChat.CallbackListener>() { -override fun onSuccess(stringIntegerHashMap: HashMap) { - Log.d(TAG,"onSuccess: ${stringIntegerHashMap.size}") -} +| Parameter | Type | Description | +| ----------- | ----- | -------------------------------- | +| `messageId` | `int` | The ID of the message to fetch | + +--- -override fun onError(e: CometChatException) { - Log.e(TAG,"onError: ${e.message}") +## 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 + + + +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 } -}) ``` - - - - -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. + + + + +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/recording.mdx b/sdk/android/recording.mdx index 8f497bb70..e2fda0ab3 100644 --- a/sdk/android/recording.mdx +++ b/sdk/android/recording.mdx @@ -1,18 +1,14 @@ --- title: "Recording" +sidebarTitle: "Recording" +description: "Record calls and access recordings from the Dashboard using the Android SDK" --- - - -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. 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) calling and followed the steps to implement them. Just 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). - -A basic example of how to make changes 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. The callbacks receive a [`User`](/sdk/reference/entities#user) object identifying who toggled recording. @@ -56,9 +52,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 | | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | @@ -67,8 +63,6 @@ The options available for recording of calls are: ### Start Recording -You can use the startRecording() method to start call recording. - ```java @@ -88,8 +82,6 @@ CallManager.getInstance().startRecording() ### Stop Recording -You can use the stopRecording() method to stop call recording. - ```java @@ -106,3 +98,23 @@ CallManager.getInstance().stopRecording() + + +--- + +## 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 deleted file mode 100644 index 59e91dad5..000000000 --- a/sdk/android/resources-overview.mdx +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: "Resources" ---- - - - -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. diff --git a/sdk/android/retrieve-conversations.mdx b/sdk/android/retrieve-conversations.mdx index 62aa4de7a..119cfa58c 100644 --- a/sdk/android/retrieve-conversations.mdx +++ b/sdk/android/retrieve-conversations.mdx @@ -1,22 +1,37 @@ --- title: "Retrieve Conversations" +sidebarTitle: "Retrieve Conversations" +description: "Fetch, filter, tag, and search conversations using the CometChat Android SDK." --- + +```kotlin +// Fetch conversations with filters +val conversationsRequest = ConversationsRequestBuilder() + .setLimit(50) + .setConversationType(CometChatConstants.CONVERSATION_TYPE_USER) + .build() -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. +conversationsRequest.fetchNext(object : CallbackListener>() { + override fun onSuccess(conversations: List) { } + override fun onError(e: CometChatException) { } +}) -## Retrieve List of Conversations +// Get specific conversation +CometChat.getConversation("UID_or_GUID", "user", callback) +``` + -*In other words, as a logged-in user, how do I retrieve the latest conversations that I've been a part of?* +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. -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. +## Retrieve List of Conversations -The `ConversationsRequestBuilder` class allows you to set the below 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. @@ -41,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. @@ -73,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`. @@ -100,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. @@ -131,6 +141,8 @@ conversationsRequest = ConversationsRequestBuilder() ### Set Group Tags +Fetch group conversations where the group has specific tags. + ```java @@ -162,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 | @@ -189,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. @@ -220,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. @@ -247,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. @@ -274,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. @@ -307,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. @@ -338,11 +356,67 @@ 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. +### Hide Agentic Conversations + +Use `hideAgentic(true)` to exclude AI agent conversations from the list. + + + +```java +ConversationsRequest conversationsRequest = new ConversationsRequest.ConversationsRequestBuilder() + .setLimit(50) + .hideAgentic(true) + .build(); +``` + + + + +```kotlin +val conversationsRequest = ConversationsRequestBuilder() + .setLimit(50) + .hideAgentic(true) + .build() +``` + + + + + +### Only Agentic Conversations + +Use `onlyAgentic(true)` to fetch only AI agent conversations. + + + +```java +ConversationsRequest conversationsRequest = new ConversationsRequest.ConversationsRequestBuilder() + .setLimit(50) + .onlyAgentic(true) + .build(); +``` + + + + +```kotlin +val conversationsRequest = ConversationsRequestBuilder() + .setLimit(50) + .onlyAgentic(true) + .build() +``` + + + + + + +`hideAgentic()` and `onlyAgentic()` are mutually exclusive — use only one per request. + -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. @@ -352,38 +426,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: @@ -393,23 +462,18 @@ The `Conversation` object consists of the following fields: | `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 | +| `conversationWith` | [`User`](/sdk/reference/entities#user) or [`Group`](/sdk/reference/entities#group) object containing the details of the user or group | | `unreadMessageCount` | Unread message count for the conversation | ## 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: +Use `tagConversation()` to add tags to a [`Conversation`](/sdk/reference/entities#conversation). - 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 | @@ -419,7 +483,7 @@ String conversationType = "user"; List tags = new ArrayList<>(); tags.add("archived"); -CometChat.tagConversation(id, conversationWith, tags, new CometChat.CallbackListener() { +CometChat.tagConversation(id, conversationType, tags, new CometChat.CallbackListener() { @Override public void onSuccess(Conversation conversation) { Log.d(TAG, conversation.toString()); @@ -466,15 +530,12 @@ 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?* - -In order to fetch a specific conversation, you can 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`](/sdk/reference/entities#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` | @@ -515,7 +576,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`](/sdk/reference/entities#conversation) object. Useful for updating your Recent Chats list when receiving real-time messages. @@ -536,6 +597,146 @@ 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. +While converting a [`Message`](/sdk/reference/messages#basemessage) object to a [`Conversation`](/sdk/reference/entities#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. + +## 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](/sdk/reference/messages#basemessage) | 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 | + + + +--- + +## 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..ca45bd229 100644 --- a/sdk/android/retrieve-group-members.mdx +++ b/sdk/android/retrieve-group-members.mdx @@ -1,20 +1,33 @@ --- title: "Retrieve Group Members" +sidebarTitle: "Retrieve Members" +description: "Fetch and filter group members list using the Android SDK" --- + +```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) { } +}) +``` + ## 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` with the group's GUID to configure filters, then call `fetchNext()`. Each result is a [`GroupMember`](/sdk/reference/entities#groupmember) object. ### 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. @@ -39,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. @@ -64,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"`). @@ -93,9 +106,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. +### Fetch Members -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. +After configuring the builder, call `build()` then `fetchNext()` to retrieve members. @@ -141,3 +154,74 @@ groupMembersRequest?.fetchNext(object:CometChat.CallbackListener + + +## GroupMember Payload Structure + + + +The [`GroupMember`](/sdk/reference/entities#groupmember) object extends [`User`](/sdk/reference/entities#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 +} +``` + + + +--- + +## 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..afffe7940 100644 --- a/sdk/android/retrieve-groups.mdx +++ b/sdk/android/retrieve-groups.mdx @@ -1,18 +1,36 @@ --- title: "Retrieve Groups" +sidebarTitle: "Retrieve Groups" +description: "Fetch and filter groups list using the Android SDK" --- + +```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) { } +}) -## Retrieve List of Groups +// Get specific group details +CometChat.getGroup("GUID", callback) +``` + -*In other words, as a logged-in user, how do I retrieve the list of groups I've joined and groups that are available?* +## Retrieve List of Groups -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. +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. @@ -37,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. @@ -62,7 +80,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. +Return only groups the logged-in user has joined. @@ -87,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. @@ -120,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`. @@ -145,11 +163,9 @@ 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. - -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. +### Fetch Groups -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. +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. @@ -195,9 +211,7 @@ 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?* - -To get the information of a group, you can use the `getGroup()` method. +Use `getGroup()` to fetch details for a specific group by GUID. @@ -242,11 +256,11 @@ override fun onError(p0: CometChatException?) { | --------- | ------------------------------------------------------------ | | `GUID` | The GUID of the group for whom the details are to be fetched | -On success, the `Group` object containing the details of the group is returned. +On success, the [`Group`](/sdk/reference/entities#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. @@ -292,3 +306,78 @@ 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 +} +``` + + + + + + +--- + +## 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..17b25d9ac 100644 --- a/sdk/android/retrieve-users.mdx +++ b/sdk/android/retrieve-users.mdx @@ -1,12 +1,38 @@ --- title: "Retrieve Users" +sidebarTitle: "Retrieve Users" +description: "Fetch user details, retrieve user lists with filters, and get online user counts using the Android SDK" --- + +```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) { } +}) +``` + ## 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. @@ -25,17 +51,15 @@ val user = CometChat.getLoggedInUser() -This method will return a `User` object containing all the information related to the logged-in user. +This method will return a [`User`](/sdk/reference/entities#user) object containing all the information related to the logged-in 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. - -The `UsersRequestBuilder` class allows you to set the below 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. @@ -60,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. @@ -87,7 +111,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. +Define which user property the `searchKeyword` should be searched in. Works only with `setSearchKeyword()`. By default, searches both UID and Name. @@ -122,12 +146,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 +176,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. +Exclude users blocked by the logged-in user from the results. Default is `false`. @@ -183,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. @@ -216,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`. @@ -243,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. @@ -276,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`. @@ -303,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. @@ -336,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 pass 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`. @@ -363,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. @@ -388,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. @@ -438,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. @@ -484,11 +508,11 @@ The `getUser()` method takes the following parameters: | --------- | ---------------------------------------------------------- | | `UID` | The UID of the user for whom the details are to be fetched | -On success, the `User` object containing the details of the user is returned. +On success, the [`User`](/sdk/reference/entities#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. @@ -524,3 +548,72 @@ 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 +} +``` + + + + + +## 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..6c7063d3f 100644 --- a/sdk/android/send-message.mdx +++ b/sdk/android/send-message.mdx @@ -1,106 +1,62 @@ --- -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." --- + - -Using CometChat, you can send three types of messages: - -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 - -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. - -## Text Message - -*In other words, as a sender, 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. - -### 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) -``` - - - - - -### 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); -``` +// 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) { } +}) - +// 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) { } +}) - -```kotlin -val tags: MutableList = ArrayList() -tags.add("pinned") -textMessage.setTags(tags) +// 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) { } +}) ``` - - - - -### Set Quoted Message +| 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` | + -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. +CometChat supports three types of messages: - - -```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. -``` +| 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 [Interactive Messages](/sdk/android/interactive-messages) for forms, cards, and custom UI elements. - +## 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`](/sdk/reference/messages#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); @@ -117,9 +73,7 @@ CometChat.sendMessage(textMessage, new CometChat.CallbackListener() } }); ``` - - ```kotlin private val receiverID = "UID" @@ -138,9 +92,7 @@ CometChat.sendMessage(textMessage, object : CallbackListener() { } }) ``` - - ```java private String receiverID = "GUID"; @@ -161,9 +113,7 @@ CometChat.sendMessage(textMessage, new CometChat.CallbackListener() } }); ``` - - ```kotlin private val receiverID = "GUID" @@ -181,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`](/sdk/reference/messages#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 -*In other words, as a sender, how do I send a media message like photos, videos & files?* +Send images, videos, audio, or files using `sendMediaMessage()`. -To send a media message to any user or group, you need to 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 @@ -214,9 +223,7 @@ metadata.put("latitude", "50.6192171633316"); metadata.put("longitude", "-72.68182268750002"); mediaMessage.setMetadata(metadata); ``` - - ```kotlin val metadata = JSONObject() @@ -224,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 @@ -261,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. @@ -301,9 +296,7 @@ CometChat.sendMediaMessage(mediaMessage, new CometChat.CallbackListener - ```kotlin private val receiverID = "UID" @@ -322,9 +315,7 @@ CometChat.sendMediaMessage(mediaMessage, object : CallbackListener } }) ``` - - ```java private String receiverID = "GUID"; @@ -346,9 +337,7 @@ CometChat.sendMediaMessage(mediaMessage, new CometChat.CallbackListener - ```kotlin private val receiverID = "GUID" @@ -367,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`](/sdk/reference/auxiliary#attachment) class: @@ -409,9 +398,7 @@ CometChat.sendMediaMessage(mediaMessage, new CometChat.CallbackListener - ```kotlin val receiverId = "recipient_UID" @@ -435,9 +422,7 @@ CometChat.sendMediaMessage(mediaMessage, object : CallbackListener - ```java String receiverId = "recipient_GUID"; @@ -463,9 +448,7 @@ CometChat.sendMediaMessage(mediaMessage, new CometChat.CallbackListener - ```kotlin val receiverId = "recipient_GUID" @@ -489,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`](/sdk/reference/messages#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 @@ -608,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 @@ -746,52 +725,38 @@ 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. +When a media message is sent successfully, the response will include a [`MediaMessage`](/sdk/reference/messages#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. +You can use the `setMetadata()`, `setCaption()` & `setTags()` methods to add metadata, caption and tags in the same way as a single attachment. ## Custom Message -*In other words, as a sender, how do I send a custom message like location co-ordinates?* - -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. - -The `sendCustomMessage()` methods takes an object of the `CustomMessage` which can be obtained using the below constructor. +Send custom data that doesn't fit text or media using `sendCustomMessage()`. ```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 @@ -813,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()`. @@ -916,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, you will receive an object of `CustomMessage` class. - -### Update Conversation +On success, `sendCustomMessage()` returns a [`CustomMessage`](/sdk/reference/messages#custommessage) object. -*How can I decide whether the custom message should update the last message of a conversation?* +### Control Conversation Update -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 updates the conversation's last message. To prevent this: @@ -1033,11 +994,9 @@ CometChat.sendCustomMessage(customMessage, object : CallbackListener -### Custom Notification Body +### Custom Notification Text -*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. +Set custom text for push, email, and SMS notifications: @@ -1148,6 +1107,175 @@ 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 + + + +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/session-timeout.mdx b/sdk/android/session-timeout.mdx index 23470881f..83eb05d64 100644 --- a/sdk/android/session-timeout.mdx +++ b/sdk/android/session-timeout.mdx @@ -1,27 +1,42 @@ --- -title: "Session Timeout Flow" +title: "Session Timeout" +sidebarTitle: "Session Timeout" +description: "Configure idle timeout and auto-termination for inactive call sessions in Android" --- + +```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 +**Available since:** v4.1.0 +**Default timeout:** 180 seconds (3 minutes alone) +**Warning shown:** 60 seconds before auto-termination + -## 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: -1. After 120 seconds of being alone in the session, the participant will see a dialog box +*Available since v4.1.0* -2. This dialog provides options to either: +The Calls SDK automatically terminates call sessions when a participant is alone for too long, preventing abandoned calls from consuming resources. - * Stay in the call - * Leave immediately +When a participant is alone in a session: -3. If no action is taken within the next 60 seconds, the call will automatically end +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 -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. +The default timeout is 180 seconds (3 minutes). -### Session Timeout Flow +## Session Timeout Flow @@ -32,3 +47,25 @@ 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 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..54463e705 100644 --- a/sdk/android/setup.mdx +++ b/sdk/android/setup.mdx @@ -1,31 +1,49 @@ --- title: "Setup" +sidebarTitle: "Setup" +description: "Install and initialize the CometChat Android SDK in your application" --- + +```kotlin +// 1. Add dependency to build.gradle +implementation "com.cometchat:chat-sdk-android:4.2.0" + +// 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 +``` - -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 - - - -### Get your Application Keys - -[Signup for CometChat](https://app.cometchat.com) and then: +**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 + -1. Create a new app -2. Head over to the **API Keys** section and note the **Auth Key**, **App ID** & **Region** +## Prerequisites - -Minimum Requirement +| Requirement | Minimum Version | +| --- | --- | +| Android API Level | 21 | +| Android API Level (with Calls SDK) | 24 | +| Java | 8 | +| AndroidX | Required | -* Android API Level 21 -* Android API level 24 (in case you are using the calls SDKS) -* Androidx Compatibility +Get your credentials from the [CometChat Dashboard](https://app.cometchat.com): +- App ID +- Region +- Auth Key (for development) - + +**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 +## Add the CometChat Dependency ### Gradle @@ -53,7 +71,7 @@ Then, add CometChat to the **app level** `build.gradle` file in the `dependencie ```java dependencies { - implementation "com.cometchat:chat-sdk-android:4.1.8" + implementation "com.cometchat:chat-sdk-android:4.2.0" } ``` @@ -63,11 +81,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 +104,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. + @@ -161,6 +183,18 @@ CometChat.init(this,appID,appSetting, object : CometChat.CallbackListener @@ -186,3 +220,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..3f9297eee 100644 --- a/sdk/android/standalone-calling.mdx +++ b/sdk/android/standalone-calling.mdx @@ -1,5 +1,7 @@ --- title: "Standalone Calling" +sidebarTitle: "Standalone Calling" +description: "Implement calling functionality using only the CometChat Calls SDK without the Chat SDK" --- ## Overview @@ -502,6 +504,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 +591,22 @@ CometChatCalls.endSession() + +--- + +## 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..dd8c8ac14 100644 --- a/sdk/android/threaded-messages.mdx +++ b/sdk/android/threaded-messages.mdx @@ -1,26 +1,70 @@ --- title: "Threaded Messages" +sidebarTitle: "Threaded Messages" +description: "Send, receive, and fetch threaded messages using the CometChat Android SDK." --- + + + +```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) { } +}) -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: +// 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) { } +}); -1. Text Message -2. Media Message -3. Custom Message. +// 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(); +``` + + + -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`. +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. -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. +## Send Message in a Thread -**Example to Send a Text Message in a thread in a user conversation.** +Any message type ([`TextMessage`](/sdk/reference/messages#textmessage), [`MediaMessage`](/sdk/reference/messages#mediamessage), or [`CustomMessage`](/sdk/reference/messages#custommessage)) can be sent in a thread. Set the `parentMessageId` using `setParentMessageId()` to indicate which thread the message belongs to. @@ -63,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()`. @@ -133,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. - -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). @@ -191,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. @@ -241,3 +276,22 @@ 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. + +--- + +## 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..ff81832ef 100644 --- a/sdk/android/transfer-group-ownership.mdx +++ b/sdk/android/transfer-group-ownership.mdx @@ -1,14 +1,28 @@ --- title: "Transfer Group Ownership" +sidebarTitle: "Transfer Ownership" +description: "Transfer group ownership to another member using the Android SDK" --- + +```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) { } + }) +``` -*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?* - -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. +**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 + -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 group member. Only the current owner can do this. The owner must transfer ownership before they can leave the group. @@ -51,3 +65,23 @@ CometChat.transferGroupOwnership(GUID, UID, object : CallbackListener() + + +--- + +## 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..4d6e11059 100644 --- a/sdk/android/transient-messages.mdx +++ b/sdk/android/transient-messages.mdx @@ -1,14 +1,14 @@ --- title: "Transient Messages" +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." --- - - 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. ## 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. @@ -41,9 +41,7 @@ CometChat.sendTransientMessage(transientMessage) ## Real-time Transient Messages -*In other words, as a recipient, 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. @@ -75,7 +73,30 @@ 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. | +| **sender** | An object of the [`User`](/sdk/reference/entities#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` | +| **receiverType** | The type of the receiver - `CometChatConstants.RECEIVER_TYPE_USER` or `CometChatConstants.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. + + +--- + +## 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/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 452fd1f4a..363959b53 100644 --- a/sdk/android/typing-indicators.mdx +++ b/sdk/android/typing-indicators.mdx @@ -1,19 +1,35 @@ --- title: "Typing Indicators" +sidebarTitle: "Typing Indicators" +description: "Send and receive real-time typing indicators using the CometChat Android SDK." --- + +```kotlin +// Start typing indicator +val typingIndicator = TypingIndicator("UID", CometChatConstants.RECEIVER_TYPE_USER) +CometChat.startTyping(typingIndicator) -## Send a Typing Indicator +// 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) { } +}) +``` + -*In other words, as a sender, how do I let the recipient(s) know that I'm typing?* +## Send a Typing Indicator ### 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`](/sdk/reference/auxiliary#typingindicator) object to notify the receiver that you're typing. - + ```java TypingIndicator typingIndicator = new TypingIndicator(UID, CometChatConstants.RECEIVER_TYPE_USER); @@ -22,7 +38,7 @@ CometChat.startTyping(typingIndicator); - + ```kotlin val typingIndicator =TypingIndicator(UID,CometChatConstants.RECEIVER_TYPE_USER) @@ -31,7 +47,7 @@ CometChat.startTyping(typingIndicator) - + ```java TypingIndicator typingIndicator = new TypingIndicator(GUID, CometChatConstants.RECEIVER_TYPE_GROUP); @@ -40,7 +56,7 @@ CometChat.startTyping(typingIndicator); - + ```kotlin val typingIndicator = TypingIndicator(GUID,CometChatConstants.RECEIVER_TYPE_GROUP) @@ -53,19 +69,19 @@ 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); -CometChat.endtyping(typingIndicator); +CometChat.endTyping(typingIndicator); ``` - + ```kotlin val typingIndicator = TypingIndicator(UID,CometChatConstants.RECEIVER_TYPE_USER) @@ -74,7 +90,7 @@ CometChat.endTyping(typingIndicator) - + ```java TypingIndicator typingIndicator = new TypingIndicator(GUID, CometChatConstants.RECEIVER_TYPE_GROUP); @@ -83,7 +99,7 @@ CometChat.endTyping(typingIndicator); - + ```kotlin val typingIndicator = TypingIndicator(GUID,CometChatConstants.RECEIVER_TYPE_GROUP) @@ -95,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 -*In other words, as a recipient, 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. @@ -144,11 +155,92 @@ override fun onTypingStarted(typingIndicator: TypingIndicator?) { -The `TypingIndicator` class consists of the below parameters: +The [`TypingIndicator`](/sdk/reference/auxiliary#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. | +| `sender` | An object of the [`User`](/sdk/reference/entities#user) class holding all the information related to the sender of the typing indicator. | | `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 | + +## 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. + + +--- + +## 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 4fbbba0e3..775c1013a 100644 --- a/sdk/android/update-group.mdx +++ b/sdk/android/update-group.mdx @@ -1,14 +1,29 @@ --- -title: "Update A Group" +title: "Update Group" +sidebarTitle: "Update Group" +description: "Modify group details, settings, and metadata using the Android SDK" --- + +```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) { } +}) +``` -## Update Group +**Note:** Only admins and moderators can update group details. See [Group Class](/sdk/android/create-group#group-class) for editable fields. + -*In other words, as a group owner, how can I update the group details?* +## Update Group -You can update the existing details of the group using the `updateGroup()` method. +Use `updateGroup()` with a [`Group`](/sdk/reference/entities#group) object containing the fields you want to update. @@ -56,13 +71,13 @@ 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. +This method takes an instance of the [`Group`](/sdk/reference/entities#group) class as a parameter, which should contain the data you wish to update. -| Parameter | Description | -| --------- | ---------------------------- | -| `group` | an instance of class `Group` | +| Parameter | Description | +| --------- | ------------------------------ | +| `group` | An instance of the [`Group`](/sdk/reference/entities#group) class | -After the successful update of the group, you will receive an instance of `Group` class containing updated information of the group. +After the successful update of the group, you will receive an instance of the [`Group`](/sdk/reference/entities#group) class containing the updated information of the group. 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. diff --git a/sdk/android/upgrading-from-v3-guide.mdx b/sdk/android/upgrading-from-v3-guide.mdx index 14bccd7a3..060bbd836 100644 --- a/sdk/android/upgrading-from-v3-guide.mdx +++ b/sdk/android/upgrading-from-v3-guide.mdx @@ -1,12 +1,28 @@ --- title: "Upgrading From V3" +sidebarTitle: "Upgrading from V3" +description: "Migration guide for upgrading from CometChat Android SDK v3 to v4" --- + +**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.2.0` (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. The API surface is the same — only the Maven URL, dependency artifact, and import package names changed. ## Maven URL Change @@ -32,7 +48,7 @@ allprojects { ```java dependencies { - implementation 'com.cometchat:chat-sdk-android:4.1.7' + implementation 'com.cometchat:chat-sdk-android:4.2.0' } ``` @@ -40,6 +56,25 @@ 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. + +--- + +## 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..f129296f0 100644 --- a/sdk/android/user-management.mdx +++ b/sdk/android/user-management.mdx @@ -1,30 +1,41 @@ --- title: "User Management" +sidebarTitle: "User Management" +description: "Create, update, and delete user accounts in CometChat using the Android SDK" --- + +```kotlin +// Create user (use API Key - dev/testing only) +val apiKey = "API_KEY" +val user = User() +user.uid = "user1" +user.name = "Kevin" -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. - -Summing up- +CometChat.createUser(user, apiKey, object : CometChat.CallbackListener() { + override fun onSuccess(user: User) { } + override fun onError(e: CometChatException) { } +}) -**When a user registers in your app** +// Update logged-in user (no API Key needed) +val updatedUser = User() +updatedUser.name = "Andrew Joseph" -1. You add the user details in your database -2. You create a user in CometChat +CometChat.updateCurrentUserDetails(updatedUser, object : CallbackListener() { + override fun onSuccess(user: User) { } + override fun onError(e: CometChatException) { } +}) +``` -**When a user logs into your app** +**Note:** User creation/updates should ideally happen on your backend using [REST API](https://api-explorer.cometchat.com). + -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. 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. - -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) +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`](/sdk/reference/entities#user) object and your API Key. @@ -71,6 +82,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 +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, 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. +Use `updateUser()` with a [`User`](/sdk/reference/entities#user) object and API Key. Ideally done on your backend via the [REST API](https://api-explorer.cometchat.com/reference/update-user). @@ -126,11 +141,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`](/sdk/reference/entities#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. +Use `updateCurrentUserDetails()` to update the currently logged-in user's profile. No API Key required. @@ -173,11 +188,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 +210,74 @@ 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 | + +## 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 +} +``` + + + +--- + + + +## 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..321e29fd2 100644 --- a/sdk/android/user-presence.mdx +++ b/sdk/android/user-presence.mdx @@ -1,30 +1,76 @@ --- title: "User Presence" +sidebarTitle: "User Presence" +description: "Track and subscribe to user online/offline status and presence updates in your Android app" --- + + + +```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. - -## Real-time Presence - -*In other words, as a logged-in user, how do I know if a user is online or offline?* +// 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"); +``` + + + -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. +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`. -In the `AppSettings` class, you can set the type of presence you wish to receive. +## Real-time Presence -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()` - 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. +`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 you wish to receive user events in, 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 the fragment where you wish to receive these events in. +Register `UserListener` in `onResume()` and remove it in `onPause()`. @@ -65,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 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. +Remove the listener in `onPause()` when the activity or fragment is no longer in use. @@ -90,15 +134,36 @@ 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?* +When you [retrieve the list of users](/sdk/android/retrieve-users), each [`User`](/sdk/reference/entities#user) object includes: + +* `status` — `"online"` or `"offline"` +* `lastActiveAt` — Unix timestamp of when the user was last online (useful for "Last seen" indicators) -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 : -* `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. -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..a58443988 100644 --- a/sdk/android/users-overview.mdx +++ b/sdk/android/users-overview.mdx @@ -1,10 +1,44 @@ --- title: "Users" sidebarTitle: "Overview" +description: "Manage users, retrieve user lists, and track user presence in your Android application" --- + +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. +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) | + +--- + +## 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..216115d9e 100644 --- a/sdk/android/video-view-customisation.mdx +++ b/sdk/android/video-view-customisation.mdx @@ -1,20 +1,33 @@ --- title: "Video View Customisation" +sidebarTitle: "Video View Customisation" +description: "Customize the main video container appearance, aspect ratio, and UI controls in Android calls" --- + +```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) -This section will guide you to customise the main video container. - -## Implementation +// Apply to call settings +val callSettings = CometChatCalls.CallSettingsBuilder(context, videoContainer) + .setMainVideoContainerSetting(videoSettings) + .build() +``` -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. +**Prerequisites:** [Default Calling](/sdk/android/default-calling) or [Direct Calling](/sdk/android/direct-calling) setup + -Please make sure your callSettings is configured accordingly for [Default Calling](/sdk/android/direct-calling) or [Direct Calling](/sdk/android/default-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 -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 +67,25 @@ videoSettings.setUserListButtonParams(CometChatCallsConstants.POSITION_BOTTOM_RI + + +--- + + + +## 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..59e15a8c5 100644 --- a/sdk/android/webhooks-overview.mdx +++ b/sdk/android/webhooks-overview.mdx @@ -1,4 +1,41 @@ --- title: "Webhooks" +sidebarTitle: "Webhooks" +description: "Configure server-side event notifications with CometChat webhooks" url: "/fundamentals/webhooks-overview" ---- \ No newline at end of file +--- + + + +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 diff --git a/sdk/flutter/additional-message-filtering.mdx b/sdk/flutter/additional-message-filtering.mdx index 01dcd182d..35f03b472 100644 --- a/sdk/flutter/additional-message-filtering.mdx +++ b/sdk/flutter/additional-message-filtering.mdx @@ -1,35 +1,95 @@ --- title: "Additional Message Filtering" +sidebarTitle: "Message Filtering" +description: "Advanced filtering options for fetching messages using MessagesRequestBuilder in the CometChat Flutter SDK." --- + +```dart +// Basic message request for user conversation +MessagesRequest request = (MessagesRequestBuilder() + ..uid = "user_uid" + ..limit = 30 +).build(); + +// Fetch messages for group with filters +MessagesRequest request = (MessagesRequestBuilder() + ..guid = "group_guid" + ..limit = 50 + ..categories = ["message", "custom"] + ..types = ["text", "image"] + ..hideReplies = true +).build(); + +// Unread messages only +MessagesRequest request = (MessagesRequestBuilder() + ..uid = "user_uid" + ..unread = true + ..limit = 50 +).build(); + +// Paginate through messages +List messages = await request.fetchPrevious(); +List moreMessages = await request.fetchPrevious(); // Next page +``` -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: +**Key properties:** `uid`, `guid`, `limit`, `categories`, `types`, `tags`, `unread`, `parentMessageId`, `messageId`, `timestamp`, `hideReplies`, `hideDeleted`, `hideQuotedMessages`, `searchKeyword`, `updatedAfter`, `updatesOnly`, `hideMessagesFromBlockedUsers`, `withTags`, `hasMentions`, `hasLinks`, `hasAttachments`, `hasReactions`, `mentionedUids`, `attachmentTypes`, `withParent` + + +The `MessagesRequest` class helps you fetch messages based on various parameters — returning [`BaseMessage`](/sdk/reference/messages#basemessage) objects that can be [`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). It uses the Builder design pattern via `MessagesRequestBuilder`. + +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. Calling `fetchPrevious()`/`fetchNext()` repeatedly on the same object gets subsequent pages. + +### MessagesRequestBuilder Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| `uid` | `String?` | User ID to fetch conversation messages for | +| `guid` | `String?` | Group ID to fetch conversation messages for | +| `limit` | `int?` | Number of messages per request (max 100, default 30) | +| `messageId` | `int?` | Fetch messages before/after this message ID | +| `timestamp` | `DateTime?` | Fetch messages before/after this timestamp | +| `unread` | `bool?` | Fetch only unread messages | +| `hideMessagesFromBlockedUsers` | `bool?` | Exclude messages from blocked users (default `false`) | +| `searchKeyword` | `String?` | Search keyword to filter messages | +| `updatedAfter` | `DateTime?` | Fetch messages updated/received after this time | +| `updatesOnly` | `bool?` | Fetch only updated messages (use with `updatedAfter`) | +| `category` | `String?` | Single message category filter | +| `type` | `String?` | Single message type filter | +| `parentMessageId` | `int?` | Fetch messages in a specific thread | +| `hideReplies` | `bool?` | Exclude threaded messages (default `false`) | +| `hideDeleted` | `bool?` | Exclude deleted messages (default `false`) | +| `categories` | `List?` | Filter by multiple message categories | +| `types` | `List?` | Filter by multiple message types | +| `withTags` | `bool?` | Include tag information in response (default `false`) | +| `tags` | `List?` | Filter by specific tags | +| `hasMentions` | `bool?` | Fetch only messages with mentions (default `false`) | +| `hasLinks` | `bool?` | Fetch only messages with links (default `false`) | +| `hasAttachments` | `bool?` | Fetch only messages with attachments (default `false`) | +| `hasReactions` | `bool?` | Fetch only messages with reactions (default `false`) | +| `mentionedUids` | `List?` | Fetch messages mentioning specific users | +| `attachmentTypes` | `List?` | Filter by specific attachment types | +| `interactionGoalCompletedOnly` | `bool?` | Fetch only messages with completed interaction goals (default `false`) | +| `withParent` | `bool?` | Include parent message with replies (default `false`) | +| `hideQuotedMessages` | `bool?` | Exclude quoted messages (default `false`) | ## 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`. +To achieve this, you can use the `limit` property. This takes an integer value 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`. @@ -49,7 +109,7 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() *In other words, how do I fetch messages between me and any user* -This can be achieved using the `UID` parameter. 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 the `uid` property to fetch messages between the logged-in user and a specific user. @@ -68,7 +128,7 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() *In other words, how do I fetch messages for any group conversation* -You can achieve this using the `GUID` 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 the `guid` property to fetch messages from a group. The logged-in user must be a member of the group. @@ -83,11 +143,15 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() + +If neither `uid` nor `guid` is set, all messages for the logged-in user across all conversations will be fetched. All parameters below can be combined with `uid` or `guid`. + + ## 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 `messageId` parameter. This method takes the messageId as input and provides messages only after/before the message-id based on if the fetchNext() or fetchPrevious() method is triggered. +Use the `messageId` property. This provides messages only after/before the message-id based on if `fetchNext()` or `fetchPrevious()` is called. @@ -104,13 +168,13 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() -This method can be used along with `UID` or `GUID` parameter to fetch messages after/before any specific message-id for a particular user/group conversation. +This property can be used along with `uid` or `guid` to fetch messages after/before any specific message-id for a particular user/group conversation. ## 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 `timestamp` parameter . This method takes the `DateTime` timestamp as input and provides messages only after/before the timestamp based on if fetchNext() or fetchPrevious() method is triggered. +Use the `timestamp` property. This takes a `DateTime` value and provides messages only after/before the timestamp based on if `fetchNext()` or `fetchPrevious()` is called. @@ -127,13 +191,13 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() -This method can be used along with `UID` or `UID` methods to fetch messages after/before any specific date or time for a particular user/group conversation. +This property can be used along with `uid` or `guid` to fetch messages after/before any specific date or time for a particular user/group conversation. ## 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 unread parameter. This method takes a boolean value as input. If the value is set to true, the SDK will return just the unread messages. +Use the `unread` property set to `true` to return just the unread messages. @@ -150,13 +214,13 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() -This method along with `GUID` or `UID` can be used to fetch unread messages for a particular group or user conversation respectively. +Combine with `guid` or `uid` to fetch unread messages for a specific conversation. ## 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` parameter. 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 the `hideMessagesFromBlockedUsers` property. If set to `true`, messages from users blocked by the logged-in user will be excluded. Default is `false`. @@ -173,13 +237,13 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() -This parameter 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 *In other words, how do I fetch messages that have been received or updated after a particular date or time* -This method accepts a `DateTime` 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 the `updatedAfter` property with a `DateTime` value to return all messages that have been updated and the ones that have been sent/received after the specified time. Updated messages include those marked as read/delivered, edited, or deleted. @@ -196,13 +260,13 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() -This can be useful in finding the messages that have been received or updated after a certain time. It can prove very useful if you are saving the messages locally and would like to know if the messages that have been updated or received after the last message is 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 *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 `updatedAfter` parameter 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 `updatedAfter` parameter. +Use the `updatesOnly` property set to `true` together with `updatedAfter` to get just the updated messages and not the messages sent/received after the specified time. This property must be used with `updatedAfter`. @@ -226,7 +290,7 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() We recommend before trying this, you refer to the [Message structure and hierarchy guide](/sdk/flutter/message-structure-and-hierarchy) to get familiar with the various categories of messages. -For this, you will have to use the `categories` method. This method accepts a list of categories. This tells the SDK to fetch messages only belonging to these categories. +Use the `categories` property with a list of category names to filter by message category. @@ -246,7 +310,7 @@ MessagesRequest messageRequest = (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 `UID` and GUID can help display only the messages you wish to display avoiding the other category of messages. +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 `uid` and `guid` can help display only the messages you wish to display avoiding the other category of messages. ## Messages for multiple types @@ -254,7 +318,7 @@ The above snippet will help you get only the messages belonging to the `message` We recommend you refer to the [Message structure and hierarchy guide](/sdk/flutter/message-structure-and-hierarchy) to get familiar with the various types of messages before trying this out. -This can be easily achieved using the `types` parameter, which accepts a list of types. This tells the SDK to fetch messages only belonging to these types. +Use the `types` property with a list of type names to filter by message type. @@ -274,13 +338,13 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() -Using the above code snippet, you can fetch all the media messages. This along with UID or GUID can be used to fetch media messages for any particular conversation. This can be useful in many other scenarios as well. +Using the above code snippet, you can fetch all the media messages. This along with `uid` or `guid` can be used to fetch media messages for any particular conversation. This can be useful in many other scenarios as well. ## 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* -This can be done using the `parentMessageId` parameter. This parameter 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 the `parentMessageId` property when you have implemented threaded conversations. This will return only messages belonging to the thread with the specified parent ID. @@ -303,7 +367,7 @@ The above code snippet returns the messages that belong to the thread with paren *In other words, how do I exclude threaded messages from the normal user/group conversations* -In order to do this, you can use the `hideReplies` parameter. This parameter 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 the `hideReplies` property set to `true` to exclude messages that belong to threads. Default is `false`. @@ -324,7 +388,7 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() *In other words, how do I exclude deleted messages a user/group conversations* -In order to do this, you can use the hideDeleted parameter. This parameter takes boolean as input. If set to true, it 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 the `hideDeleted` property set to `true` to exclude deleted messages. Default is `false`. @@ -341,11 +405,32 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() +## Hide quoted messages in user/group conversations + +*In other words, how do I exclude quoted messages from user/group conversations* + +Use the `hideQuotedMessages` property set to `true` to exclude quoted messages. Default is `false`. + + + +```dart +String UID = "cometchat-uid-1"; + +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..uid = UID + ..hideQuotedMessages = true + ..limit = 50).build(); +``` + + + + + ## Messages by tags *In other words, how do I fetch messages belonging to specific tags* -In order to do this, you can use the `tags` parameter. This parameter accepts a list of tags. This tells the SDK to fetch messages only belonging to these tags. +Use the `tags` property with a list of tag names to fetch only messages with those tags. @@ -369,7 +454,7 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() *In other words, how do I fetch messages with the tags information* -In order to do this, you can use the `withTags` parameter. This parameter 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` . +Use the `withTags` property set to `true` to include tag information in the response. Default is `false`. @@ -378,7 +463,7 @@ String UID = "cometchat-uid-1"; MessagesRequest messageRequest = (MessagesRequestBuilder() ..uid = UID - ...withTags = true + ..withTags = true ..limit = 50).build(); ``` @@ -386,11 +471,17 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() +When `withTags` is set to `true`, each message's tags field will be populated. + +| Additional Field | Type | Description | +| --- | --- | --- | +| tags | `List` | 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 other words, as a logged-in user, how do I fetch messages that contain links?* -In order to do this, you can use the `hasLinks` parameter. This parameter 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 the `hasLinks` property set to `true` to fetch only messages containing links. Default is `false`. @@ -415,9 +506,9 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() ## Messages with attachments -In other words, as a logged-in user, how do I fetch messages that contains attachments? +*In other words, as a logged-in user, how do I fetch messages that contain attachments?* -In order to do this, you can use the `hasAttachments` parameter. This parameter 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 the `hasAttachments` property set to `true` to fetch only messages with attachments (image, audio, video, or file). Default is `false`. @@ -442,9 +533,9 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() ## Messages with reactions -In other words, as a logged-in user, how do I fetch messages that contains reactions? +*In other words, as a logged-in user, how do I fetch messages that contain reactions?* -In order to do this, you can use the `hasReactions` parameter. This parameter 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 the `hasReactions` property set to `true` to fetch only messages with reactions. Default is `false`. @@ -469,9 +560,9 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() ## Messages with mentions -In other words, as a logged-in user, how do I fetch messages that contains mentions? +*In other words, as a logged-in user, how do I fetch messages that contain mentions?* -In order to do this, you can use the `hasMentions` parameter. This parameter 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 the `hasMentions` property set to `true` to fetch only messages with mentions. Default is `false`. @@ -496,9 +587,9 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() ## Messages with particular user mentions -In other words, as a logged-in user, how do I fetch messages that mentions specific users? +*In other words, as a logged-in user, how do I fetch messages that mention specific users?* -In order to do this, you can use the `mentionedUids` parameter. This parameter accepts a list of UIDs. When set, the SDK will fetch messages which have the mentions of the UIDs passed. +Use the `mentionedUids` property with a list of UIDs to fetch messages that mention specific users. @@ -511,7 +602,7 @@ This feature is only available with `Conversation & Advanced Search`. The `Conve ```dart String UID = "cometchat-uid-1"; List mentionedUIDs = []; -tags.add("cometchat-uid-1"); +mentionedUIDs.add("cometchat-uid-1"); MessagesRequest messageRequest = (MessagesRequestBuilder() ..uid = UID ..mentionedUids = mentionedUIDs @@ -521,3 +612,49 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() + +## Messages with specific attachment types + +*In other words, as a logged-in user, how do I fetch messages with specific types of attachments?* + +Use the `attachmentTypes` property with a list of attachment type values to fetch messages with specific attachment types. + + + +This feature is only available with `Conversation & Advanced Search`. 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) + + + + + +```dart +String UID = "cometchat-uid-1"; + +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..uid = UID + ..attachmentTypes = ["image", "video"] + ..limit = 50).build(); +``` + + + + + +--- + +## Next Steps + + + + Handle incoming messages in real-time with listeners + + + Fetch and display conversation lists with filtering options + + + Understand message categories, types, and hierarchy + + + Work with message threads and replies + + diff --git a/sdk/flutter/advanced-overview.mdx b/sdk/flutter/advanced-overview.mdx index 7a8e791f6..a068113c3 100644 --- a/sdk/flutter/advanced-overview.mdx +++ b/sdk/flutter/advanced-overview.mdx @@ -1,8 +1,51 @@ --- title: "Advanced" sidebarTitle: "Overview" +description: "Advanced SDK features including connection management, real-time listeners, and login state handling for Flutter applications." --- + +```dart +// Check connection status +CometChat.getConnectionStatus(); // "connected" | "connecting" | "disconnected" -This section helps you to know about the Connection Listeners. +// Listen for connection changes +CometChat.addConnectionListener("LISTENER_ID", ConnectionListener( + onConnected: () => debugPrint("Connected"), + onDisconnected: () => debugPrint("Disconnected"), +)); + +// Listen for login events +CometChat.addLoginListener("LISTENER_ID", LoginListener( + loginSuccess: (User user) => debugPrint("Logged in: ${user.name}"), + logoutSuccess: () => debugPrint("Logged out"), +)); +``` + + +This section covers advanced SDK features for managing connections, monitoring real-time events, and handling login state changes in your Flutter application. + +These features help you build robust applications that gracefully handle network changes, maintain real-time synchronization, and respond to authentication events. + +--- + +## Next Steps + + + + Monitor and respond to SDK connection state changes + + + Complete reference for all event listeners + + + Consolidated reference for all 7 listener types + + + Handle login and logout state changes + + + Understand SDK connection lifecycle + + diff --git a/sdk/flutter/ai-agents.mdx b/sdk/flutter/ai-agents.mdx index 1ee853823..173304cf6 100644 --- a/sdk/flutter/ai-agents.mdx +++ b/sdk/flutter/ai-agents.mdx @@ -1,40 +1,98 @@ --- title: "AI Agents" +sidebarTitle: "AI Agents" +description: "Learn how to integrate AI Agents in your Flutter app to enable intelligent, automated interactions that process user messages, trigger tools, and respond with contextually relevant information." --- -# 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**. + + +| Feature | Description | +| --- | --- | +| [AI Agents](#agent-run-lifecycle-and-message-flow) | Intelligent automated conversations with real-time streaming | +| [AI Moderation](/sdk/flutter/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) | + +```dart +// Add AI Assistant listener for real-time events +CometChat.addAIAssistantListener("LISTENER_ID", AIAssistantListener( + onAIAssistantEventReceived: (AIAssistantBaseEvent event) { + debugPrint("AI Event: ${event.type}"); + }, +)); + +// Add Message listener for agentic messages +CometChat.addMessageListener("LISTENER_ID", MessageListener( + onAIAssistantMessageReceived: (AIAssistantMessage msg) { + debugPrint("AI Reply: ${msg.text}"); + }, + onAIToolResultReceived: (AIToolResultMessage result) { + debugPrint("Tool Result: $result"); + }, +)); + +// Remove listeners when done +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 + + +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). + + +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 — 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`](/sdk/reference/messages#aiassistantbaseevent) with these common properties: + +| Getter | Return Type | Description | +|--------|-------------|-------------| +| `type` | `String` | Event type (e.g., `run_started`, `text_message_content`) | +| `conversationId` | `String` | The conversation this event belongs to | +| `messageId` | `String` | The message ID associated with the event | +| `parentMessageId` | `String` | Parent message ID (for threaded messages) | +| `runId` | `String` | The run ID for this agent execution | +| `threadId` | `String` | The thread ID for this agent execution | +| `timestamp` | `int` | Timestamp of the event | +| `data` | `Map` | Full event data payload | + +Some events carry additional data: + +| Event | Extra Property | Description | +|-------|---------------|-------------| +| Text Message Content | `delta` | The streaming text chunk for progressive rendering | +| Tool Call Arguments | `toolCallId`, `delta` | Tool call ID and argument chunk | +| Tool Call Result | `toolCallId`, `content`, `role` | Tool call ID, result content, and role | @@ -68,12 +126,16 @@ class AIAssistantEventHandler with AIAssistantListener { + +Always remove AI Assistant listeners when they're no longer needed (e.g., on widget dispose or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + + #### Event descriptions -- Run Start: A new run has begun for the user’s message. +- 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. +- 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. @@ -81,10 +143,31 @@ class AIAssistantEventHandler with AIAssistantListener { ### 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 | + +Each message type extends `BaseMessage` and has a typed data accessor: + +| Message Type | Data Getter | Data Properties | +|--------------|-------------|-----------------| +| `AIAssistantMessage` | `getAssistantMessageData()` | `runId`, `threadId`, `text` | +| `AIToolResultMessage` | `getToolResultMessageData()` | `runId`, `threadId`, `text`, `toolCallId` | +| `AIToolArgumentMessage` | `getToolArgumentMessageData()` | `runId`, `threadId`, `toolCalls` | + +The `toolCalls` on `AIToolArgumentMessage` returns a list of `AIToolCall` objects, each with: + +| Property | Type | Description | +|----------|------|-------------| +| `id` | `String` | Unique tool call ID | +| `type` | `String` | Tool call type | +| `function` | `AIToolCallFunction` | Function object with `name` and `arguments` | +| `displayName` | `String` | Display name of the tool | +| `executionText` | `String` | Execution description text | @@ -111,4 +194,23 @@ These events are received via the **`MessageListener`** after the run completes. } ``` - \ No newline at end of file + + +--- + +## Next Steps + + + + Configure and deploy AI chatbots for automated conversations + + + Implement AI-powered content moderation for your chat + + + AI-powered features like smart replies and conversation summaries + + + Send text messages that trigger AI Agent responses + + diff --git a/sdk/flutter/ai-chatbots-overview.mdx b/sdk/flutter/ai-chatbots-overview.mdx index 7a460169b..72c785dbd 100644 --- a/sdk/flutter/ai-chatbots-overview.mdx +++ b/sdk/flutter/ai-chatbots-overview.mdx @@ -1,4 +1,51 @@ --- title: "Bots" +sidebarTitle: "AI Bots" +description: "Configure AI-powered chatbots to provide automated assistance and maintain conversational momentum in your Flutter app." url: "/ai-chatbots/overview" --- + + + +```dart +// AI Bots are configured via the CometChat Dashboard +// Navigate to: AI Agents > Custom Bots > AI Bots + +// Configuration options: +// 1. Set GPT Model (e.g., gpt-4, gpt-3.5-turbo) +// 2. Add your OpenAI API Key +// 3. Set Custom Instructions for bot behavior +// 4. Configure Temperature (0-1) for response creativity +// 5. Enable AI toggle + +// Once configured, bots respond automatically to user messages +// No additional SDK code required - bots work via CometChat backend +``` + +**Dashboard Path:** [CometChat Dashboard](https://app.cometchat.com) → Your App → AI Agents → Custom Bots → AI Bots + + +AI Bots provide automated assistance to users seeking guidance or insights. Configure intelligent chatbots through the CometChat Dashboard to maintain conversational momentum in your Flutter application. + + +**Available via:** [Dashboard](https://app.cometchat.com) | [REST API](https://api-explorer.cometchat.com) | UI Kits + + +--- + +## Next Steps + + + + Build custom AI agents that respond to user queries + + + Automatically moderate content using AI + + + Enhance user experience with AI-powered assistance + + + Learn how to send messages that bots can respond to + + diff --git a/sdk/flutter/ai-moderation.mdx b/sdk/flutter/ai-moderation.mdx index e0414eb82..4d8868826 100644 --- a/sdk/flutter/ai-moderation.mdx +++ b/sdk/flutter/ai-moderation.mdx @@ -1,11 +1,42 @@ --- title: "AI Moderation" +sidebarTitle: "AI Moderation" +description: "Learn how to implement AI-powered content moderation in your Flutter app using CometChat SDK to automatically review messages for inappropriate content." --- + + +```dart +// Send message and check moderation status +CometChat.sendMessage(textMessage, onSuccess: (TextMessage message) { + if (message.moderationStatus?.value == ModerationStatusEnum.PENDING.value) { + // Message is under moderation review + } +}, onError: (e) {}); + +// Listen for moderation results +CometChat.addMessageListener("MODERATION_LISTENER", MessageListener( + onMessageModerated: (BaseMessage message) { + // Handle APPROVED or DISAPPROVED status + }, +)); + +// Remove listener when done +CometChat.removeMessageListener("MODERATION_LISTENER"); +``` + +**Moderation Status:** `PENDING` → `APPROVED` or `DISAPPROVED` +**Supported Types:** Text, Image, Video messages + + ## 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. + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) | [Dashboard](https://app.cometchat.com) + + For a broader understanding of moderation features, configuring rules, and managing flagged messages, see the [Moderation Overview](/moderation/overview). @@ -53,6 +84,8 @@ Moderation is triggered **only** for the following message types: | Text Messages | ✅ | Content analyzed for inappropriate text | | Image Messages | ✅ | Images scanned for unsafe content | | Video Messages | ✅ | Videos analyzed for prohibited content | + +Moderation applies to [`TextMessage`](/sdk/reference/messages#textmessage) and [`MediaMessage`](/sdk/reference/messages#mediamessage) types. | Custom Messages | ❌ | Not subject to AI moderation | | Action Messages | ❌ | Not subject to AI moderation | @@ -98,6 +131,99 @@ When you send a text, image, or video message, check the initial moderation stat + +**On Success** — A `TextMessage` object containing all details of the sent message, including the initial moderation status: + + + +**TextMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `501` | +| `metadata` | object | Custom metadata attached to the message | `{}` | +| `receiver` | object | Receiver user object | [See below ↓](#send-moderated-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `null` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `sentAt` | number | Epoch timestamp when the message was sent | `1745554729` | +| `receiverUid` | string | UID of the receiver | `"cometchat-uid-2"` | +| `type` | string | Type of the message | `"text"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `null` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `0` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `0` | +| `replyCount` | number | Number of replies to this message | `0` | +| `sender` | object | Sender user object | [See below ↓](#send-moderated-sender-object) | +| `receiverType` | string | Type of the receiver | `"user"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `0` | +| `parentMessageId` | number | ID of the parent message (for threads) | `-1` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"message"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` | +| `updatedAt` | number | Epoch timestamp when the message was last updated | `1745554729` | +| `text` | string | The text content of the message | `"Hello, how are you?"` | +| `tags` | array | List of tags associated with the message | `[]` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `mentionedUsers` | array | List of mentioned users | `[]` | +| `hasMentionedMe` | boolean | Whether the current user is mentioned | `false` | +| `reactions` | array | List of reactions on the message | `[]` | +| `moderationStatus` | string | Moderation status of the message | `"pending"` | +| `quotedMessageId` | number | ID of the quoted message | `null` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-1"` | +| `name` | string | Display name of the sender | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-2"` | +| `name` | string | Display name of the receiver | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_BLOCKED_BY_EXTENSION"` | +| `message` | string | Human-readable error message | `"Message blocked by moderation."` | +| `details` | string | Additional technical details | `"The message was flagged and blocked by the AI moderation extension."` | + + + ### Step 2: Listen for Moderation Results Implement the `MessageListener` to receive moderation results in real-time: @@ -172,4 +298,20 @@ 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/flutter/flag-message) documentation. + +After implementing AI Moderation, explore these related features: + + + + Build intelligent AI-powered agents for automated conversations + + + Allow users to manually report inappropriate messages + + + Create automated chatbot experiences for your users + + + Handle incoming messages and moderation events + + diff --git a/sdk/flutter/ai-user-copilot-overview.mdx b/sdk/flutter/ai-user-copilot-overview.mdx index 3e798a3fb..12601d050 100644 --- a/sdk/flutter/ai-user-copilot-overview.mdx +++ b/sdk/flutter/ai-user-copilot-overview.mdx @@ -1,4 +1,6 @@ --- title: "AI" +sidebarTitle: "AI User Copilot" +description: "Enhance your Flutter app with AI-powered features like Smart Replies, Conversation Starters, and Conversation Summaries using CometChat." url: "/fundamentals/ai-user-copilot/overview" ---- \ No newline at end of file +--- diff --git a/sdk/flutter/all-real-time-listeners.mdx b/sdk/flutter/all-real-time-listeners.mdx new file mode 100644 index 000000000..e6a5293d8 --- /dev/null +++ b/sdk/flutter/all-real-time-listeners.mdx @@ -0,0 +1,538 @@ +--- +title: "All Real Time Listeners" +sidebarTitle: "All Real Time Listeners" +description: "Complete reference for all CometChat Flutter SDK real-time listeners including User, Group, Message, Call, Connection, Login, and AI Assistant listeners." +--- + + + +```dart +// User Listener — online/offline presence +CometChat.addUserListener("ID", UserListenerImpl()); + +// Message Listener — messages, typing, receipts, reactions +CometChat.addMessageListener("ID", MessageListenerImpl()); + +// Group Listener — member join/leave/kick/ban/scope changes +CometChat.addGroupListener("ID", GroupListenerImpl()); + +// Call Listener — incoming/outgoing call events +CometChat.addCallListener("ID", CallListenerImpl()); + +// Connection Listener — WebSocket connection state +CometChat.addConnectionListener("ID", ConnectionListenerImpl()); + +// Login Listener — authentication state changes +CometChat.addLoginListener("ID", LoginListenerImpl()); + +// Always clean up in dispose() +CometChat.removeUserListener("ID"); +CometChat.removeMessageListener("ID"); +CometChat.removeGroupListener("ID"); +CometChat.removeCallListener("ID"); +CometChat.removeConnectionListener("ID"); +CometChat.removeLoginListener("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 listener types: + +1. Create a class that uses the listener mixin with `with` +2. Register a listener with a unique ID using `addXListener()` +3. Handle events by overriding the callback methods +4. 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 in your widget's `dispose()` method to prevent memory leaks. + + +Always remove listeners when they're no longer needed (e.g., in `dispose()`). Failing to remove listeners can cause memory leaks and duplicate event handling. + + +CometChat provides 7 listener types: + +1. [User Listener](/sdk/flutter/all-real-time-listeners#user-listener) +2. [Group Listener](/sdk/flutter/all-real-time-listeners#group-listener) +3. [Message Listener](/sdk/flutter/all-real-time-listeners#message-listener) +4. [Call Listener](/sdk/flutter/all-real-time-listeners#call-listener) +5. [Connection Listener](/sdk/flutter/all-real-time-listeners#connection-listener) +6. [Login Listener](/sdk/flutter/all-real-time-listeners#login-listener) +7. [AI Assistant Listener](/sdk/flutter/all-real-time-listeners#ai-assistant-listener) + +--- + +## User Listener + +Receive online/offline presence events for users. + +| Method | Description | +|--------|-------------| +| `onUserOnline(User user)` | Triggered when a user comes online and is available to chat. | +| `onUserOffline(User user)` | Triggered when a user goes offline. | + +```dart +class MyUserListener with UserListener { + @override + void onUserOnline(User user) { + debugPrint("User online: ${user.name}"); + } + + @override + void onUserOffline(User user) { + debugPrint("User offline: ${user.name}"); + } +} + +// Register +CometChat.addUserListener("UNIQUE_LISTENER_ID", MyUserListener()); + +// Remove when done +CometChat.removeUserListener("UNIQUE_LISTENER_ID"); +``` + +--- + +## Group Listener + +Receive events when group members join, leave, are kicked/banned, or have their scope changed. + +| Method | Description | +|--------|-------------| +| `onGroupMemberJoined(Action action, User joinedUser, Group joinedGroup)` | A user joined the group. All members receive this event. | +| `onGroupMemberLeft(Action action, User leftUser, Group leftGroup)` | A member left the group. All members receive this event. | +| `onGroupMemberKicked(Action action, User kickedUser, User kickedBy, Group kickedFrom)` | A member was kicked. All members including the kicked user receive this event. | +| `onGroupMemberBanned(Action action, User bannedUser, User bannedBy, Group bannedFrom)` | A member was banned. All members including the banned user receive this event. | +| `onGroupMemberUnbanned(Action action, User unbannedUser, User unbannedBy, Group unbannedFrom)` | A member was unbanned. All group members receive this event. | +| `onGroupMemberScopeChanged(Action action, User updatedBy, User updatedUser, String scopeChangedTo, String scopeChangedFrom, Group group)` | A member's scope was changed. All group members receive this event. | +| `onMemberAddedToGroup(Action action, User addedby, User userAdded, Group addedTo)` | A user was added to the group. All members including the added user receive this event. | + +```dart +class MyGroupListener with GroupListener { + @override + void onGroupMemberJoined(Action action, User joinedUser, Group joinedGroup) { + debugPrint("${joinedUser.name} joined ${joinedGroup.name}"); + } + + @override + void onGroupMemberLeft(Action action, User leftUser, Group leftGroup) { + debugPrint("${leftUser.name} left ${leftGroup.name}"); + } + + @override + void onGroupMemberKicked( + Action action, User kickedUser, User kickedBy, Group kickedFrom) { + debugPrint("${kickedUser.name} was kicked by ${kickedBy.name}"); + } + + @override + void onGroupMemberBanned( + Action action, User bannedUser, User bannedBy, Group bannedFrom) { + debugPrint("${bannedUser.name} was banned by ${bannedBy.name}"); + } + + @override + void onGroupMemberUnbanned( + Action action, User unbannedUser, User unbannedBy, Group unbannedFrom) { + debugPrint("${unbannedUser.name} was unbanned by ${unbannedBy.name}"); + } + + @override + void onGroupMemberScopeChanged(Action action, User updatedBy, + User updatedUser, String scopeChangedTo, String scopeChangedFrom, Group group) { + debugPrint("${updatedUser.name} scope changed to $scopeChangedTo"); + } + + @override + void onMemberAddedToGroup( + Action action, User addedby, User userAdded, Group addedTo) { + debugPrint("${userAdded.name} was added to ${addedTo.name}"); + } +} + +// Register +CometChat.addGroupListener("UNIQUE_LISTENER_ID", MyGroupListener()); + +// Remove when done +CometChat.removeGroupListener("UNIQUE_LISTENER_ID"); +``` + +--- + +## Message Listener + +Receive events for incoming messages, typing indicators, read/delivery receipts, message edits/deletes, reactions, and moderation results. + +| Method | Description | +|--------|-------------| +| `onTextMessageReceived(TextMessage textMessage)` | A text message was received. | +| `onMediaMessageReceived(MediaMessage mediaMessage)` | A media message was received. | +| `onCustomMessageReceived(CustomMessage customMessage)` | A custom message was received. | +| `onTypingStarted(TypingIndicator typingIndicator)` | A user started typing in a conversation. | +| `onTypingEnded(TypingIndicator typingIndicator)` | A user stopped typing in a conversation. | +| `onMessagesDelivered(MessageReceipt messageReceipt)` | Messages were marked as delivered. | +| `onMessagesRead(MessageReceipt messageReceipt)` | Messages were marked as read. | +| `onMessagesDeliveredToAll(MessageReceipt messageReceipt)` | A group message was delivered to all members. | +| `onMessagesReadByAll(MessageReceipt messageReceipt)` | A group message was read by all members. | +| `onMessageEdited(BaseMessage message)` | A message was edited. | +| `onMessageDeleted(BaseMessage message)` | A message was deleted. | +| `onTransientMessageReceived(TransientMessage message)` | A transient (non-persistent) message was received. | +| `onInteractiveMessageReceived(InteractiveMessage message)` | An interactive message was received. | +| `onInteractionGoalCompleted(InteractionReceipt receipt)` | An interaction goal was achieved. | +| `onMessageReactionAdded(ReactionEvent reactionEvent)` | A reaction was added to a message. | +| `onMessageReactionRemoved(ReactionEvent reactionEvent)` | A reaction was removed from a message. | +| `onMessageModerated(BaseMessage message)` | A message was processed by moderation (approved or disapproved). | +| `onAIAssistantMessageReceived(AIAssistantMessage aiAssistantMessage)` | A persisted AI assistant reply was received. | +| `onAIToolResultReceived(AIToolResultMessage aiToolResultMessage)` | A persisted AI tool result message was received. | +| `onAIToolArgumentsReceived(AIToolArgumentMessage aiToolArgumentMessage)` | A persisted AI tool argument message was received. | + +```dart +class MyMessageListener with MessageListener { + @override + void onTextMessageReceived(TextMessage textMessage) { + debugPrint("Text message: ${textMessage.text}"); + } + + @override + void onMediaMessageReceived(MediaMessage mediaMessage) { + debugPrint("Media message received"); + } + + @override + void onCustomMessageReceived(CustomMessage customMessage) { + debugPrint("Custom message received"); + } + + @override + void onTypingStarted(TypingIndicator typingIndicator) { + debugPrint("Typing started"); + } + + @override + void onTypingEnded(TypingIndicator typingIndicator) { + debugPrint("Typing ended"); + } + + @override + void onMessagesDelivered(MessageReceipt messageReceipt) { + debugPrint("Messages delivered"); + } + + @override + void onMessagesRead(MessageReceipt messageReceipt) { + debugPrint("Messages read"); + } + + @override + void onMessagesDeliveredToAll(MessageReceipt messageReceipt) { + debugPrint("Messages delivered to all"); + } + + @override + void onMessagesReadByAll(MessageReceipt messageReceipt) { + debugPrint("Messages read by all"); + } + + @override + void onMessageEdited(BaseMessage message) { + debugPrint("Message edited: ${message.id}"); + } + + @override + void onMessageDeleted(BaseMessage message) { + debugPrint("Message deleted: ${message.id}"); + } + + @override + void onTransientMessageReceived(TransientMessage message) { + debugPrint("Transient message received"); + } + + @override + void onInteractiveMessageReceived(InteractiveMessage message) { + debugPrint("Interactive message received"); + } + + @override + void onInteractionGoalCompleted(InteractionReceipt receipt) { + debugPrint("Interaction goal completed"); + } + + @override + void onMessageReactionAdded(ReactionEvent reactionEvent) { + debugPrint("Reaction added: ${reactionEvent.reaction}"); + } + + @override + void onMessageReactionRemoved(ReactionEvent reactionEvent) { + debugPrint("Reaction removed: ${reactionEvent.reaction}"); + } + + @override + void onMessageModerated(BaseMessage message) { + debugPrint("Message moderated: ${message.id}"); + } + + @override + void onAIAssistantMessageReceived(AIAssistantMessage aiAssistantMessage) { + debugPrint("AI Assistant message received"); + } + + @override + void onAIToolResultReceived(AIToolResultMessage aiToolResultMessage) { + debugPrint("AI Tool result received"); + } + + @override + void onAIToolArgumentsReceived(AIToolArgumentMessage aiToolArgumentMessage) { + debugPrint("AI Tool arguments received"); + } +} + +// Register +CometChat.addMessageListener("UNIQUE_LISTENER_ID", MyMessageListener()); + +// Remove when done +CometChat.removeMessageListener("UNIQUE_LISTENER_ID"); +``` + +--- + +## Call Listener + +Receive events for incoming and outgoing call state changes. + +| Method | Description | +|--------|-------------| +| `onIncomingCallReceived(Call call)` | An incoming call was received. | +| `onOutgoingCallAccepted(Call call)` | The outgoing call initiated by the logged-in user was accepted. | +| `onOutgoingCallRejected(Call call)` | The outgoing call initiated by the logged-in user was rejected. | +| `onIncomingCallCancelled(Call call)` | An incoming call was cancelled by the initiator. | +| `onCallEndedMessageReceived(Call call)` | A call ended. The call object contains the final status and duration. | + +```dart +class MyCallListener with CallListener { + @override + void onIncomingCallReceived(Call call) { + debugPrint("Incoming call from: ${call.sender?.name}"); + } + + @override + void onOutgoingCallAccepted(Call call) { + debugPrint("Outgoing call accepted"); + } + + @override + void onOutgoingCallRejected(Call call) { + debugPrint("Outgoing call rejected"); + } + + @override + void onIncomingCallCancelled(Call call) { + debugPrint("Incoming call cancelled"); + } + + @override + void onCallEndedMessageReceived(Call call) { + debugPrint("Call ended"); + } +} + +// Register +CometChat.addCallListener("UNIQUE_LISTENER_ID", MyCallListener()); + +// Remove when done +CometChat.removeCallListener("UNIQUE_LISTENER_ID"); +``` + +--- + +## Connection Listener + +Receive events when the WebSocket connection state changes. + +| Method | Description | +|--------|-------------| +| `onConnected()` | SDK has an active connection to CometChat servers. | +| `onConnecting()` | 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. | +| `onConnectionError(CometChatException error)` | A connection error occurred. | + +```dart +class MyConnectionListener with ConnectionListener { + @override + void onConnected() { + debugPrint("Connected to CometChat"); + } + + @override + void onConnecting() { + debugPrint("Connecting..."); + } + + @override + void onDisconnected() { + debugPrint("Disconnected from CometChat"); + } + + @override + void onFeatureThrottled() { + debugPrint("Feature throttled"); + } + + @override + void onConnectionError(CometChatException error) { + debugPrint("Connection error: ${error.message}"); + } +} + +// Register +CometChat.addConnectionListener("UNIQUE_LISTENER_ID", MyConnectionListener()); + +// Remove when done +CometChat.removeConnectionListener("UNIQUE_LISTENER_ID"); +``` + +--- + +## Login Listener + +Receive events when the user's authentication state changes. + +| Method | Description | +|--------|-------------| +| `loginSuccess(User user)` | User logged in successfully. Provides the `User` object. | +| `loginFailure(CometChatException e)` | Login failed. Provides a `CometChatException`. | +| `logoutSuccess()` | User logged out successfully. | +| `logoutFailure(CometChatException e)` | Logout failed. Provides a `CometChatException`. | + +```dart +class MyLoginListener with LoginListener { + @override + void loginSuccess(User user) { + debugPrint("Login success: ${user.name}"); + } + + @override + void loginFailure(CometChatException e) { + debugPrint("Login failed: ${e.message}"); + } + + @override + void logoutSuccess() { + debugPrint("Logout success"); + } + + @override + void logoutFailure(CometChatException e) { + debugPrint("Logout failed: ${e.message}"); + } +} + +// Register +CometChat.addLoginListener("UNIQUE_LISTENER_ID", MyLoginListener()); + +// Remove when done +CometChat.removeLoginListener("UNIQUE_LISTENER_ID"); +``` + +--- + +## AI Assistant Listener + +Receive real-time streaming events from AI Agent runs. These events arrive as the agent processes a user's message, before the final persisted messages arrive via the `MessageListener`. + +| Method | Description | +|--------|-------------| +| `onAIAssistantEventReceived(AIAssistantBaseEvent aiAssistantBaseEvent)` | Triggered for each streaming event during an AI Agent run (run start, tool calls, text message streaming, run finished). | + +```dart +class MyAIAssistantListener with AIAssistantListener { + @override + void onAIAssistantEventReceived(AIAssistantBaseEvent aiAssistantBaseEvent) { + debugPrint("AI Assistant event: ${aiAssistantBaseEvent.toString()}"); + } +} + +// Register +CometChat.addAIAssistantListener("UNIQUE_LISTENER_ID", MyAIAssistantListener()); + +// Remove when done +CometChat.removeAIAssistantListener("UNIQUE_LISTENER_ID"); +``` + +--- + +## Using Listeners in a StatefulWidget + +Here's a complete example showing how to register and remove listeners within a Flutter widget lifecycle: + +```dart +class ChatScreen extends StatefulWidget { + const ChatScreen({super.key}); + + @override + State createState() => _ChatScreenState(); +} + +class _ChatScreenState extends State + with MessageListener, ConnectionListener { + static const String _listenerId = "CHAT_SCREEN_LISTENER"; + + @override + void initState() { + super.initState(); + CometChat.addMessageListener(_listenerId, this); + CometChat.addConnectionListener(_listenerId, this); + } + + @override + void dispose() { + CometChat.removeMessageListener(_listenerId); + CometChat.removeConnectionListener(_listenerId); + super.dispose(); + } + + @override + void onTextMessageReceived(TextMessage textMessage) { + setState(() { + // Update your message list + }); + } + + @override + void onConnected() { + debugPrint("Connection restored"); + } + + @override + void onDisconnected() { + debugPrint("Connection lost"); + } + + @override + Widget build(BuildContext context) { + return const Scaffold( + body: Center(child: Text("Chat Screen")), + ); + } +} +``` + +--- + +## 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/flutter/authentication-overview.mdx b/sdk/flutter/authentication-overview.mdx index 5157b3883..07ff5d486 100644 --- a/sdk/flutter/authentication-overview.mdx +++ b/sdk/flutter/authentication-overview.mdx @@ -1,16 +1,69 @@ --- 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 Flutter SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +```dart +// Check existing session +User? user = await CometChat.getLoggedInUser(); + +// Login with Auth Key (development only) +CometChat.login("cometchat-uid-1", "AUTH_KEY", + onSuccess: (User user) { debugPrint("Logged in: $user"); }, + onError: (CometChatException e) { debugPrint("Error: ${e.message}"); } +); + +// Login with Auth Token (production) +CometChat.loginWithAuthToken("AUTH_TOKEN", + onSuccess: (User user) { debugPrint("Logged in: $user"); }, + onError: (CometChatException e) { debugPrint("Error: ${e.message}"); } +); + +// Logout +CometChat.logout( + onSuccess: (String msg) { debugPrint("Logged out"); }, + onError: (CometChatException e) { debugPrint("Error: ${e.message}"); } +); +``` + +**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` + + +After [initializing](/sdk/flutter/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. + +### How It Works + +```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.loginWithAuthToken(authToken) + CometChat-->>YourApp: User object (logged in) +``` + +## Before You Log In -### Create User +### Create a User -Before you login the user, you must add the user to CometChat. +A user must exist in CometChat before they can 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. +- **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. @@ -18,19 +71,31 @@ We have setup 5 users for testing having UIDs: `cometchat-uid-1`, `cometchat-uid -Once initialization is successful, you will need to log the user into CometChat using the `login()` method. +### Check for an Existing Session -We recommend you call the CometChat `login()` method once your user logs into your app. The `login()` method needs to be called only once. +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. - +```dart +User? user = await CometChat.getLoggedInUser(); +if (user != null) { + // User is already logged in — proceed to your app +} +``` -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. +If `getLoggedInUser()` returns `null`, no active session exists and you need to call `login()`. + +| Method | Returns | Description | +| ------ | ------- | ----------- | +| `CometChat.getLoggedInUser()` | `Future` | Returns the currently logged-in user, or `null` if no session exists | - -## 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. +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-with-auth-token) instead of an Auth Key to ensure enhanced security. + + +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. + @@ -53,20 +118,56 @@ await CometChat.login(UID, authKey, -| Parameter | Description | -| --------- | -------------------------------------------------- | -| UID | The `UID` of the user that you would like to login | -| authKey | CometChat App Auth Key | +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `UID` | `String` | The UID of the user to log in | +| `authKey` | `String` | Your CometChat Auth Key | + +On success, the `onSuccess` callback receives a [`User`](/sdk/reference/entities#user) object containing the logged-in user's details. + + +**On Success** — A `User` object representing the logged-in user: + + -After the user logs in, their information is returned in the `User` object. +**User Object:** -## Login using Auth Token +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-1"` | +| `name` | string | Display name of the user | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | -This advanced authentication procedure does not use the Auth Key directly in your client code thus ensuring safety. + -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. -3. Pass the **Auth Token** to your client and use it in the `login()` method. + + +**CometChatException:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_UID_NOT_FOUND"` | +| `message` | string | Human-readable error message | `"The specified UID does not exist."` | +| `details` | string | Additional technical details | `"Please verify the UID and try again."` | + + + +## Login with Auth Token + +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 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 `loginWithAuthToken()`. @@ -89,15 +190,51 @@ if (user == null) { -| Parameter | Description | -| ---------------------------------------------- | ----------- | -| authToken | Auth Token of the user you would like to login | +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `authToken` | `String` | Auth Token generated on your server for the user | + +On success, the `onSuccess` callback receives a [`User`](/sdk/reference/entities#user) object containing the logged-in user's details. + + +**On Success** — A `User` object representing the logged-in user: + + -After the user logs in, their information is returned in the `User` object. +**User Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-1"` | +| `name` | string | Display name of the user | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + + + + + +**CometChatException:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_UID_NOT_FOUND"` | +| `message` | string | Human-readable error message | `"The specified UID does not exist."` | +| `details` | string | Additional technical details | `"Please verify the UID and try again."` | + + ## 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. @@ -113,3 +250,99 @@ CometChat.logout( onSuccess: ( successMessage) { + + +**On Success** — A `String` message confirming the logout: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `message` | string | Success confirmation message | `"Logout successful"` | + + + + + +**CometChatException:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_NOT_LOGGED_IN"` | +| `message` | string | Human-readable error message | `"No active user session."` | +| `details` | string | Additional technical details | `"Please log in before attempting to log out."` | + + + +--- + +## 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 a `CometChatException`. | +| `logoutSuccess()` | User logged out successfully. | +| `logoutFailure(CometChatException e)` | Logout failed. Provides a `CometChatException`. | + +### Add a Listener + + + +```dart +class Class_Name with LoginListener { + + // CometChat.addLoginListener("UNIQUE_LISTENER_ID", this); // call this in initState + + @override + void loginSuccess(User user) { + debugPrint("LoginListener loginSuccess: $user"); + } + + @override + void loginFailure(CometChatException e) { + debugPrint("LoginListener loginFailure: ${e.message}"); + } + + @override + void logoutSuccess() { + debugPrint("LoginListener logoutSuccess"); + } + + @override + void logoutFailure(CometChatException e) { + debugPrint("LoginListener logoutFailure: ${e.message}"); + } +} +``` + + + +### Remove a Listener + +```dart +CometChat.removeLoginListener("UNIQUE_LISTENER_ID"); +``` + + +Always remove login listeners when they're no longer needed (e.g., on widget disposal or when navigating away). Failing to remove listeners can cause memory leaks and duplicate event handling. + + +--- + +## Next Steps + + + + Send your first text, media, or custom message + + + Create, update, and manage users in your app + + + Monitor the SDK connection state in real time + + + Complete reference for all SDK event listeners + + diff --git a/sdk/flutter/best-practices.mdx b/sdk/flutter/best-practices.mdx new file mode 100644 index 000000000..37662f154 --- /dev/null +++ b/sdk/flutter/best-practices.mdx @@ -0,0 +1,158 @@ +--- +title: "Best Practices" +sidebarTitle: "Best Practices" +description: "Recommended patterns and practices for building with the CometChat Flutter SDK." +--- + +Follow these best practices to build reliable, performant, and secure applications with the CometChat Flutter SDK. Organized by topic — jump to what's relevant for your current work. + +## Initialization & Authentication + +| Practice | Description | +|----------|-------------| +| Initialize once at startup | Call `CometChat.init()` in your `main()` or root widget's `initState()`. It only needs to be called once per session. | +| Use environment variables | Store App ID, Region, and Auth Key in a config file or 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/flutter/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 + +| 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 in your widget's `dispose()` method to prevent memory leaks. | +| Keep callbacks lightweight | Avoid heavy processing inside listener callbacks. Use `setState()` or 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 + +| Practice | Description | +|----------|-------------| +| Batch operations | Space out bulk operations using a queue or throttle mechanism. | +| 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 `metadata` to attach location, device info, or other contextual data to messages. | +| 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)` on your `MessagesRequestBuilder` 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 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 using Flutter's `RichText` or `Text.rich`. | + +## Typing Indicators + +| 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 + +| 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 + +| 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 map for success or error messages. | +| 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, 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. | + +## 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 | If you disconnect in background, call `CometChat.connect()` when returning to foreground. | + +## Flutter-Specific Practices + +| Practice | Description | +|----------|-------------| +| iOS Podfile configuration | Run `pod install` in the `ios/` directory after adding the SDK dependency. Set the minimum iOS deployment target as required. | +| Android minimum API level | Ensure `minSdkVersion` in `android/app/build.gradle` meets the SDK requirement. | +| Use `dispose()` for cleanup | Always remove listeners and cancel subscriptions in your widget's `dispose()` method. | +| Use `debugPrint` for logging | Prefer `debugPrint()` over `print()` for SDK-related logging — it handles long strings and is stripped in release builds. | +| Handle platform exceptions | CometChat methods may throw `PlatformException` from native channels. Wrap calls in try/catch blocks. | +| State management integration | Dispatch SDK events to your state management layer (Provider, Bloc, Riverpod) rather than calling `setState()` directly in listener callbacks. | + +## Upgrading from V3 + +| Practice | Description | +|----------|-------------| +| Follow the setup guide first | Complete the v4 [setup instructions](/sdk/flutter/setup) before changing dependencies. | +| Update pubspec.yaml | Replace the v3 `cometchat_pro` dependency with the v4 `cometchat_sdk` package. | +| Test incrementally | Test each feature area (messaging, calling, groups) individually after updating. | +| Remove old packages | Remove v3 packages from `pubspec.yaml` and run `flutter pub get` to avoid conflicts. | + +--- + +## Next Steps + + + + Common issues and solutions + + + Installation and initialization guide + + diff --git a/sdk/flutter/block-users.mdx b/sdk/flutter/block-users.mdx index 8613e6df1..6370279cd 100644 --- a/sdk/flutter/block-users.mdx +++ b/sdk/flutter/block-users.mdx @@ -1,14 +1,54 @@ --- title: "Block Users" +sidebarTitle: "Block Users" +description: "Learn how to block and unblock users in your Flutter app using the CometChat SDK to manage user interactions and privacy." --- + +```dart +// Block users +List uids = ["UID1", "UID2"]; +CometChat.blockUser(uids, onSuccess: (Map map) { + debugPrint("Blocked: $map"); +}, onError: (CometChatException e) { + debugPrint("Error: ${e.message}"); +}); + +// Unblock users +CometChat.unblockUser(uids, onSuccess: (Map map) { + debugPrint("Unblocked: $map"); +}, onError: (CometChatException e) { + debugPrint("Error: ${e.message}"); +}); + +// Get blocked users list +BlockedUsersRequest request = (BlockedUsersRequestBuilder()..limit = 30).build(); +request.fetchNext(onSuccess: (List users) { }, onError: (e) { }); +``` + +**Directions:** `directionBlockedByMe` | `directionHasBlockedMe` | `directionBoth` (default) + + +Block users to prevent them from sending messages to the logged-in user. This feature helps users manage their privacy and control who can communicate with them. + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) + ## 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 `List` as a parameter which holds the list of `UIDs` to be blocked. +You can block users using the `blockUser()` 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 `blockUser()` method takes a `List` as a parameter which holds the list of `UIDs` to be blocked. + +### Parameters + +| Parameter | Type | Description | +|-----------|------|-------------| +| `uids` | `List?` | List of UIDs of users to block | +| `onSuccess` | `Function(Map map)?` | Callback triggered on successful block operation | +| `onError` | `Function(CometChatException excep)?` | Callback triggered on error | @@ -28,13 +68,46 @@ debugPrint("Blocked User Unsuccessful ${e.message} "); + +**On Success** — A `Map` containing UIDs as keys and `"success"` or `"fail"` as values indicating the result of each block operation: + + + +**Map Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `UID1` | string | Block result for UID1 | `"success"` | +| `UID2` | string | Block result for UID2 | `"success"` | +| `UID3` | string | Block result for UID3 | `"success"` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_UID_NOT_FOUND"` | +| `message` | string | Human-readable error message | `"The specified UID does not exist."` | +| `details` | string | Additional technical details | `"Please verify the UID and try again."` | + + + In the `onSuccess()` callback, you receive a Map 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. ## 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 `List` as a parameter which holds the list of `UIDs` to be unblocked. +You can unblock the already blocked users using the `unblockUser()` method. You can unblock multiple users in a single operation. The `unblockUser()` method takes a `List` as a parameter which holds the list of `UIDs` to be unblocked. + +### Parameters + +| Parameter | Type | Description | +|-----------|------|-------------| +| `uids` | `List?` | List of UIDs of users to unblock | +| `onSuccess` | `Function(Map map)?` | Callback triggered on successful unblock operation | +| `onError` | `Function(CometChatException excep)?` | Callback triggered on error | @@ -55,6 +128,31 @@ CometChat.unblockUser(uids, onSuccess: (Map map) { + +**On Success** — A `Map` containing UIDs as keys and `"success"` or `"fail"` as values indicating the result of each unblock operation: + + + +**Map Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `UID1` | string | Unblock result for UID1 | `"success"` | +| `UID2` | string | Unblock result for UID2 | `"success"` | +| `UID3` | string | Unblock result for UID3 | `"success"` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_UID_NOT_FOUND"` | +| `message` | string | Human-readable error message | `"The specified UID does not exist."` | +| `details` | string | Additional technical details | `"Please verify the UID and try again."` | + + + In the `onSuccess()` callback, you receive a Map 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. ## Get list of blocked users @@ -65,6 +163,15 @@ In order to fetch the list of blocked users, you can use the `BlockedUsersReques The `BlockedUsersRequestBuilder` class allows you to set the below parameters: +### BlockedUsersRequestBuilder + +| Parameter | Type | Description | +|-----------|------|-------------| +| `limit` | `int?` | Number of blocked users to fetch per request. Max: 100, Default: 30 | +| `searchKeyword` | `String?` | Keyword to filter blocked users by name | +| `direction` | `String?` | Direction of block — `directionBlockedByMe`, `directionHasBlockedMe`, or `directionBoth` (default) | +| `setPage` | `int?` | Fetch blocked users from a particular page | + ### Set Limit This method sets the limit i.e. the number of blocked users that should be fetched in a single iteration. @@ -109,7 +216,7 @@ BlockedUsersRequest blockedUsersRequest = (BlockedUsersRequestBuilder() ```dart BlockedUsersRequest blockedUsersRequest = (BlockedUsersRequestBuilder() ..limit = 50 - .direction = CometChatBlockedUsersDirection.directionBlockedByMe + ..direction = CometChatBlockedUsersDirection.directionBlockedByMe ).build(); ``` @@ -138,3 +245,63 @@ blockedUsersRequest.fetchNext(onSuccess: (List userList){ + + +**On Success** — A `List` containing the blocked users: + + + +**User Object (per item in list):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-3"` | +| `name` | string | Display name of the user | `"Kevin Hart"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `true` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_UID_NOT_FOUND"` | +| `message` | string | Human-readable error message | `"The specified UID does not exist."` | +| `details` | string | Additional technical details | `"Please verify the UID and try again."` | + + + +Relevant fields to access on returned [`User`](/sdk/reference/entities#user) objects: + +| Field | Type | Description | +|-------|------|-------------| +| `blockedByMe` | `bool` | Whether the logged-in user has blocked this user | +| `hasBlockedMe` | `bool` | Whether this user has blocked the logged-in user | + +--- + +## Next Steps + + + + Fetch and filter users from your CometChat app + + + Create, update, and delete users programmatically + + + Track online/offline status of users in real-time + + + Complete guide to user features in CometChat + + diff --git a/sdk/flutter/call-logs.mdx b/sdk/flutter/call-logs.mdx index 7965eaa21..93188f665 100644 --- a/sdk/flutter/call-logs.mdx +++ b/sdk/flutter/call-logs.mdx @@ -1,20 +1,52 @@ --- title: "Call Logs" +sidebarTitle: "Call Logs" +description: "Learn how to fetch and manage call logs in your Flutter application using CometChat's Call SDK, including filtering by call type, status, and direction." --- + +```dart +// Build call log request +CallLogRequest callLogRequest = (CallLogRequestBuilder() + ..authToken = CometChat.getUserAuthToken() + ..limit = 30 + ..callCategory = CometChatCallsConstants.callCategoryCall +).build(); + +// Fetch call logs +callLogRequest.fetchNext(onSuccess: (List callLogs) { + debugPrint("Call logs fetched: ${callLogs.length}"); +}, onError: (CometChatCallsException e) { + debugPrint("Error: ${e.message}"); +}); + +// Get specific call details +CometChatCalls.getCallDetails(sessionID, userAuthToken, onSuccess: (List callLogs) { + debugPrint("Call details: $callLogs"); +}, onError: (CometChatCallsException e) { + debugPrint("Error: ${e.message}"); +}); +``` + +**Filters:** `callType`, `callStatus`, `callCategory`, `callDirection`, `hasRecording`, `uid`, `guid` + ## Overview CometChat's Flutter 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. + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [Dashboard](https://app.cometchat.com) + + 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 Flutter application. ## Fetching Call Logs -To fetch all call logs in your Flutter application, you should use the `CallLogRequestBuilder`, This builder allows you to customize the call logs fetching process according to your needs. +To fetch all call logs in your Flutter application, you should use the `CallLogRequestBuilder`, This builder allows you to customize the [`CallLog`](/sdk/reference/calls#calllog) fetching process according to your needs. ```dart CallLogRequest callAppSettings = (CallLogRequestBuilder() @@ -56,6 +88,89 @@ callAppSettings.fetchNext(onSuccess: (List callLogs){ }); ``` + +**On Success** — A `List` containing call log entries. Each `CallLog` object includes: + + + +**CallLog Object (per item in list):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sessionId` | string | Unique call session identifier | `"v1.us.1.xxxxxxxx"` | +| `initiator` | object | User who initiated the call | [See below ↓](#fetch-next-initiator-object) | +| `receiver` | object | User or group that received the call | [See below ↓](#fetch-next-receiver-object) | +| `receiverType` | string | Type of the receiver | `"user"` | +| `status` | string | Current status of the call | `"ended"` | +| `type` | string | Type of the call | `"video"` | +| `mode` | string | Mode of the call | `"call"` | +| `startedAt` | number | Epoch timestamp when the call started | `1745554729` | +| `endedAt` | number | Epoch timestamp when the call ended | `1745555329` | +| `initiatedAt` | number | Epoch timestamp when the call was initiated | `1745554700` | +| `totalAudioMinutes` | number | Total audio minutes of the call | `0` | +| `totalVideoMinutes` | number | Total video minutes of the call | `10.0` | +| `totalDurationInMinutes` | number | Total call duration in minutes | `10.0` | +| `totalDuration` | string | Total call duration in timer format | `"00:10:00"` | +| `totalParticipants` | number | Total number of participants | `2` | +| `hasRecording` | boolean | Whether the call has a recording | `false` | +| `participants` | array | List of call participants | [See below ↓](#fetch-next-participants-object) | +| `recordings` | array | List of call recordings | `[]` | + +--- + + + +**`initiator` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the initiator | `"cometchat-uid-1"` | +| `name` | string | Display name of the initiator | `"Andrew Joseph"` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-2"` | +| `name` | string | Display name of the receiver | `"George Alan"` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | + +--- + + + +**`participants` Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the participant | `"cometchat-uid-1"` | +| `name` | string | Display name of the participant | `"Andrew Joseph"` | +| `totalAudioMinutes` | number | Audio minutes for this participant | `0` | +| `totalVideoMinutes` | number | Video minutes for this participant | `10.0` | +| `totalDurationInMinutes` | number | Total duration for this participant | `10.0` | +| `deviceId` | string | Device identifier used to join | `"device-abc-123"` | +| `isJoined` | boolean | Whether the participant joined the call | `true` | +| `joinedAt` | number | Epoch timestamp when the participant joined | `1745554735` | +| `state` | string | Current state of the participant | `"ended"` | +| `leftAt` | number | Epoch timestamp when the participant left | `1745555329` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to fetch the requested data."` | +| `details` | string | Additional technical details | `"An unexpected error occurred while fetching call logs."` | + + + ### Fetch Previous The**`fetchPrevious()`**method retrieves the previous set of call logs. @@ -74,6 +189,89 @@ callAppSettings.fetchPrevious(onSuccess: (List callLogs){ }); ``` + +**On Success** — A `List` containing previous call log entries. Each `CallLog` object includes: + + + +**CallLog Object (per item in list):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sessionId` | string | Unique call session identifier | `"v1.us.1.yyyyyyyy"` | +| `initiator` | object | User who initiated the call | [See below ↓](#fetch-previous-initiator-object) | +| `receiver` | object | User or group that received the call | [See below ↓](#fetch-previous-receiver-object) | +| `receiverType` | string | Type of the receiver | `"user"` | +| `status` | string | Current status of the call | `"ended"` | +| `type` | string | Type of the call | `"audio"` | +| `mode` | string | Mode of the call | `"call"` | +| `startedAt` | number | Epoch timestamp when the call started | `1745550000` | +| `endedAt` | number | Epoch timestamp when the call ended | `1745550600` | +| `initiatedAt` | number | Epoch timestamp when the call was initiated | `1745549980` | +| `totalAudioMinutes` | number | Total audio minutes of the call | `10.0` | +| `totalVideoMinutes` | number | Total video minutes of the call | `0` | +| `totalDurationInMinutes` | number | Total call duration in minutes | `10.0` | +| `totalDuration` | string | Total call duration in timer format | `"00:10:00"` | +| `totalParticipants` | number | Total number of participants | `2` | +| `hasRecording` | boolean | Whether the call has a recording | `false` | +| `participants` | array | List of call participants | [See below ↓](#fetch-previous-participants-object) | +| `recordings` | array | List of call recordings | `[]` | + +--- + + + +**`initiator` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the initiator | `"cometchat-uid-1"` | +| `name` | string | Display name of the initiator | `"Andrew Joseph"` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-2"` | +| `name` | string | Display name of the receiver | `"George Alan"` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | + +--- + + + +**`participants` Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the participant | `"cometchat-uid-1"` | +| `name` | string | Display name of the participant | `"Andrew Joseph"` | +| `totalAudioMinutes` | number | Audio minutes for this participant | `10.0` | +| `totalVideoMinutes` | number | Video minutes for this participant | `0` | +| `totalDurationInMinutes` | number | Total duration for this participant | `10.0` | +| `deviceId` | string | Device identifier used to join | `"device-abc-123"` | +| `isJoined` | boolean | Whether the participant joined the call | `true` | +| `joinedAt` | number | Epoch timestamp when the participant joined | `1745550005` | +| `state` | string | Current state of the participant | `"ended"` | +| `leftAt` | number | Epoch timestamp when the participant left | `1745550600` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to fetch the requested data."` | +| `details` | string | Additional technical details | `"An unexpected error occurred while fetching call logs."` | + + + ## 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. Upon success, this function will return a list of call details, as multiple calls can be initiated for one session ID. @@ -89,4 +287,120 @@ CometChatCalls.getCallDetails(sessionID, userAuthToken, onSuccess: (List +**On Success** — A `List` containing detailed call log entries for the specified session. Each `CallLog` object includes: + + + +**CallLog Object (per item in list):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sessionId` | string | Unique call session identifier | `"v1.us.1.xxxxxxxx"` | +| `initiator` | object | User who initiated the call | [See below ↓](#get-call-details-initiator-object) | +| `receiver` | object | User or group that received the call | [See below ↓](#get-call-details-receiver-object) | +| `receiverType` | string | Type of the receiver | `"user"` | +| `status` | string | Current status of the call | `"ended"` | +| `type` | string | Type of the call | `"video"` | +| `mode` | string | Mode of the call | `"call"` | +| `startedAt` | number | Epoch timestamp when the call started | `1745554729` | +| `endedAt` | number | Epoch timestamp when the call ended | `1745555329` | +| `initiatedAt` | number | Epoch timestamp when the call was initiated | `1745554700` | +| `totalAudioMinutes` | number | Total audio minutes of the call | `0` | +| `totalVideoMinutes` | number | Total video minutes of the call | `10.0` | +| `totalDurationInMinutes` | number | Total call duration in minutes | `10.0` | +| `totalDuration` | string | Total call duration in timer format | `"00:10:00"` | +| `totalParticipants` | number | Total number of participants | `2` | +| `hasRecording` | boolean | Whether the call has a recording | `false` | +| `participants` | array | List of call participants | [See below ↓](#get-call-details-participants-object) | +| `recordings` | array | List of call recordings | [See below ↓](#get-call-details-recordings-object) | + +--- + + + +**`initiator` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the initiator | `"cometchat-uid-1"` | +| `name` | string | Display name of the initiator | `"Andrew Joseph"` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-2"` | +| `name` | string | Display name of the receiver | `"George Alan"` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | + +--- + + + +**`participants` Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the participant | `"cometchat-uid-1"` | +| `name` | string | Display name of the participant | `"Andrew Joseph"` | +| `totalAudioMinutes` | number | Audio minutes for this participant | `0` | +| `totalVideoMinutes` | number | Video minutes for this participant | `10.0` | +| `totalDurationInMinutes` | number | Total duration for this participant | `10.0` | +| `deviceId` | string | Device identifier used to join | `"device-abc-123"` | +| `isJoined` | boolean | Whether the participant joined the call | `true` | +| `joinedAt` | number | Epoch timestamp when the participant joined | `1745554735` | +| `state` | string | Current state of the participant | `"ended"` | +| `leftAt` | number | Epoch timestamp when the participant left | `1745555329` | + +--- + + + +**`recordings` Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `rid` | string | Unique identifier of the recording | `"recording-001"` | +| `duration` | number | Total recording duration in minutes | `10.0` | +| `startTime` | number | Epoch timestamp when the recording started | `1745554729` | +| `endTime` | number | Epoch timestamp when the recording ended | `1745555329` | +| `recording_url` | string | URL of the call recording | `"https://recordings.cometchat.io/recording-001.mp4"` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to fetch the requested data."` | +| `details` | string | Additional technical details | `"Unable to retrieve call details for the specified session."` | + + + Note: Replace**`"SESSION_ID"`**with the ID of the session you are interested in. + +--- + +## Next Steps + + + + Implement voice and video calls with ringing functionality + + + Learn how to record calls and access recordings + + + Start calls without the ringing flow + + + Configure the CometChat Calls SDK + + diff --git a/sdk/flutter/calling-overview.mdx b/sdk/flutter/calling-overview.mdx index 61fbffcfe..9d820d9fa 100644 --- a/sdk/flutter/calling-overview.mdx +++ b/sdk/flutter/calling-overview.mdx @@ -1,11 +1,26 @@ --- title: "Calling" sidebarTitle: "Overview" +description: "Implement voice and video calling in your Flutter application with CometChat's calling SDK, supporting ringing calls, direct calls, and standalone calling." --- -## Overview + -CometChat provides voice and video calling capabilities for your Flutter application. This guide helps you choose the right implementation approach based on your use case. +Choose your calling approach: +- **Ringing** → [Default Call](/sdk/flutter/default-call) — Full call flow with notifications, accept/reject +- **Call Session** → [Direct Call](/sdk/flutter/direct-call) — Session-based calling with custom UI +- **Standalone** → [Standalone Calling](/sdk/flutter/standalone-calling) — Calls SDK only, no Chat SDK needed + +```yaml +# Install Calls SDK +dependencies: + cometchat_calls_sdk: ^4.2.2 +``` + +**Features:** Recording, Presenter Mode, Video View Customization, Call Logs, Session Timeout + + +CometChat provides three ways to add voice and video calling to your Flutter app. Which one you pick depends on how much of the call flow you want CometChat to handle vs. building yourself. ## Prerequisites @@ -19,55 +34,48 @@ dependencies: For detailed setup instructions, see the [Calls SDK Setup](/sdk/flutter/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/flutter/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/flutter/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/flutter/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 @@ -88,3 +96,20 @@ Use this when you want: Configure automatic call termination when participants are inactive. + +## Next Steps + + + + Install and configure the CometChat Calls SDK + + + Implement the complete ringing call flow + + + Start and manage call sessions directly + + + Implement calling without the Chat SDK + + diff --git a/sdk/flutter/calling-setup.mdx b/sdk/flutter/calling-setup.mdx index eb0dc43ea..8a2e38d7e 100644 --- a/sdk/flutter/calling-setup.mdx +++ b/sdk/flutter/calling-setup.mdx @@ -1,8 +1,33 @@ --- title: "Setup" +sidebarTitle: "Calling Setup" +description: "Learn how to install and initialize the CometChat Calls SDK for Flutter to enable voice and video calling in your application." --- + +```yaml +# pubspec.yaml +dependencies: + cometchat_calls_sdk: ^4.2.2 +``` + +```dart +import 'package:cometchat_calls_sdk/cometchat_calls_sdk.dart'; + +CallAppSettings callAppSettings = (CallAppSettingBuilder() + ..appId = "APP_ID" + ..region = "REGION" +).build(); + +CometChatCalls.init(callAppSettings, + onSuccess: (String message) => debugPrint("Calls SDK initialized"), + onError: (CometChatCallsException e) => debugPrint("Error: ${e.message}"), +); +``` + +**Required:** App ID, Region from [CometChat Dashboard](https://app.cometchat.com) + ### Get your Application Keys @@ -45,9 +70,9 @@ import 'package:cometchat_calls_sdk/cometchat_calls_sdk.dart'; -## Initialise CometChatCalls +## 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 below parameters: 1. 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. @@ -81,3 +106,73 @@ debugPrint("Initialization failed with exception: ${e.message}"); | Parameter | Description | | ----------------- | -------------------------------------- | | `callAppSettings` | An object of the CallAppSettings class | + + +**On Success** — A `String` message confirming the Calls SDK initialization: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `message` | string | Success confirmation message | `"Initialization completed successfully"` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Calls SDK initialization failed."` | +| `details` | string | Additional technical details | `"Please verify your App ID and region, then try again."` | + + + + +`CometChatCalls.init()` must be called before any other Calls SDK method. Calling `generateToken()`, `startSession()`, or registering listeners before `init()` will fail. + + +### Initialization Order + +If you're using both the Chat SDK and Calls SDK, initialize them in sequence: + +```dart +// 1. Chat SDK first +CometChat.init(appId, appSettings, onSuccess: (String successMessage) { + debugPrint("Chat SDK initialized"); + + // 2. Then Calls SDK + CallAppSettings callAppSettings = (CallAppSettingBuilder() + ..appId = "APP_ID" + ..region = "REGION" + ).build(); + + CometChatCalls.init(callAppSettings, onSuccess: (String message) { + debugPrint("Calls SDK initialized"); + // 3. Now both SDKs are ready + }, onError: (CometChatCallsException e) { + debugPrint("Calls SDK init failed: ${e.message}"); + }); +}, onError: (CometChatException e) { + debugPrint("Chat SDK init failed: ${e.message}"); +}); +``` + +For [Standalone Calling](/sdk/flutter/standalone-calling), you only need `CometChatCalls.init()` — no Chat SDK required. + +--- + +## Next Steps + + + + Implement the complete ringing call flow + + + Start and manage call sessions + + + Use Calls SDK without the Chat SDK + + + Compare calling approaches and features + + diff --git a/sdk/flutter/changelog.mdx b/sdk/flutter/changelog.mdx index eb92a1622..995dda87f 100644 --- a/sdk/flutter/changelog.mdx +++ b/sdk/flutter/changelog.mdx @@ -1,4 +1,5 @@ --- title: "Changelog" +sidebarTitle: "Changelog" url: "https://github.com/cometchat/chat-sdk-flutter/releases" --- \ No newline at end of file diff --git a/sdk/flutter/connection-behaviour.mdx b/sdk/flutter/connection-behaviour.mdx index ba5b683a9..fb2e027ee 100644 --- a/sdk/flutter/connection-behaviour.mdx +++ b/sdk/flutter/connection-behaviour.mdx @@ -1,8 +1,36 @@ --- title: "Connection Behaviour" +sidebarTitle: "Connection Behaviour" +description: "Understand how CometChat SDK manages WebSocket connections in auto and manual modes, including background behavior and reconnection handling." --- + +```dart +// Auto Mode (default) - SDK manages connection automatically +AppSettings appSettings = (AppSettingsBuilder() + ..subscriptionType = CometChatSubscriptionType.allUsers + ..region = "REGION" + ..autoEstablishSocketConnection = true // Default behavior +).build(); + +// Manual Mode - You control the connection +AppSettings appSettings = (AppSettingsBuilder() + ..subscriptionType = CometChatSubscriptionType.allUsers + ..region = "REGION" + ..autoEstablishSocketConnection = false // Manual control +).build(); + +// Manual mode methods +CometChat.connect(onSuccess: (msg) {}, onError: (e) {}); // Establish connection +CometChat.disconnect(onSuccess: (msg) {}, onError: (e) {}); // Break connection +CometChat.ping(onSuccess: () {}, onError: (e) {}); // Keep alive in background +``` + +**Connection Modes:** +- **Auto Mode:** SDK manages WebSocket automatically (foreground=connected, background=disconnected) +- **Manual Mode:** You control connect/disconnect; call `ping()` every 30s to keep background connection alive + ## Default SDK behaviour on login @@ -18,6 +46,8 @@ When the app is reopened, and the init() method is called, the web-socket connec 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. +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. + ## 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. @@ -90,6 +120,25 @@ CometChat.init(appId, appSettings, onSuccess: (String successMessage) { + +**On Success** — A `String` message confirming SDK initialization: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `message` | string | Success confirmation message | `"Initialization completed successfully"` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"SDK initialization failed."` | +| `details` | string | Additional technical details | `"Please verify your App ID and region, then try again."` | + + + You can manage the connection to the web-socket server using the `connect()` and `disconnect()` methods provided by the SDK. ## Connect to the web-socket server @@ -113,6 +162,25 @@ CometChat.connect( + +**On Success** — A `String` message confirming the WebSocket connection was established: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `message` | string | Success confirmation message | `"Web socket connection successful"` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_NOT_LOGGED_IN"` | +| `message` | string | Human-readable error message | `"No active user session."` | +| `details` | string | Additional technical details | `"Please log in before establishing a WebSocket connection."` | + + + ## Disconnect from the web-socket 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. @@ -134,6 +202,25 @@ CometChat.disconnect( + +**On Success** — A `String` message confirming the WebSocket connection was disconnected: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `message` | string | Success confirmation message | `"Web socket disconnection successful"` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_NOT_LOGGED_IN"` | +| `message` | string | Human-readable error message | `"No active user session."` | +| `details` | string | Additional technical details | `"Please log in before disconnecting the WebSocket connection."` | + + + ## Maintain long-standing background connection @@ -161,6 +248,44 @@ CometChat.ping( + +**On Success** — A confirmation that the ping was sent successfully (no return value): + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `message` | string | Success confirmation | `"ping successful"` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_NOT_LOGGED_IN"` | +| `message` | string | Human-readable error message | `"No active user session."` | +| `details` | string | Additional technical details | `"Please log in before sending a ping to the server."` | + + + ## 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. + +--- + +## Next Steps + + + + Monitor real-time WebSocket connection status with listeners + + + Configure CometChat SDK initialization and settings + + + Learn about all available real-time event listeners + + + Implement user login and logout functionality + + diff --git a/sdk/flutter/connection-status.mdx b/sdk/flutter/connection-status.mdx index a0877d610..890d70074 100644 --- a/sdk/flutter/connection-status.mdx +++ b/sdk/flutter/connection-status.mdx @@ -1,24 +1,89 @@ --- title: "Connection Status" +sidebarTitle: "Connection Status" +description: "Monitor real-time WebSocket connection status with CometChat SDK using ConnectionListener callbacks and getConnectionStatus method." --- + +```dart +// Add connection listener +CometChat.addConnectionListener("connection_listener", ConnectionListenerImpl()); + +// Connection listener implementation +class ConnectionListenerImpl with ConnectionListener { + @override + void onConnected() => debugPrint("Connected"); + + @override + void onConnecting() => debugPrint("Connecting..."); + + @override + void onDisconnected() => debugPrint("Disconnected"); + + @override + void onFeatureThrottled() => debugPrint("Feature throttled"); + + @override + void onConnectionError(CometChatException error) => debugPrint("Error: ${error.message}"); +} + +// Check current connection status +String status = CometChat.getConnectionStatus(); +// Returns: CometChatWSState.connected, connecting, disconnected, or featureThrottled + +// Remove listener when done +CometChat.removeConnectionListener("connection_listener"); +``` + + +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. + +When the connection drops, the SDK automatically attempts to reconnect, cycling through `disconnected` → `connecting` → `connected`. + +## Connection States + +| Value | Callback | Description | +|-------|----------|-------------| +| `CometChatWSState.connected` | `onConnected()` | SDK has an active connection to CometChat servers | +| `CometChatWSState.connecting` | `onConnecting()` | SDK is attempting to establish or re-establish a connection | +| `CometChatWSState.disconnected` | `onDisconnected()` | SDK is disconnected due to network issues or other errors | +| `CometChatWSState.featureThrottled` | `onFeatureThrottled()` | A feature has been throttled to prevent performance loss | +| — | `onConnectionError(CometChatException)` | An error occurred while maintaining the connection | + +## Get Current Status + +Use `getConnectionStatus()` to check the current connection state at any time: + + + +```dart +String connectionStatus = CometChat.getConnectionStatus(); +``` + + + +The method returns one of the following values: -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 +1. `CometChatWSState.connected` (connected) +2. `CometChatWSState.connecting` (connecting) +3. `CometChatWSState.disconnected` (disconnected) +4. `CometChatWSState.featureThrottled` (featureThrottled) -Connection Status provides you with the below 3 methods to get the status of the connection to CometChat web-socket servers: +## Listen for Connection Changes -| 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 | -| onConnectionError | This method is called when the CometChat SDK gets error due to any issue while maintaining the connection like network fluctuations, etc. | +Register a `ConnectionListener` to receive real-time connection state updates. We recommend adding this on app startup after `CometChat.init()` completes. -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. +### ConnectionListener Events + +| Event | Parameter | Description | +|-------|-----------|-------------| +| `onConnected()` | — | Triggered when the SDK successfully establishes a connection to the WebSocket server | +| `onConnecting()` | — | Triggered when the SDK is attempting to establish a connection to the WebSocket server | +| `onDisconnected()` | — | Triggered when the SDK gets disconnected due to network fluctuations or other issues | +| `onFeatureThrottled()` | — | Triggered when CometChat automatically toggles off certain features to prevent performance loss | +| `onConnectionError(CometChatException error)` | `CometChatException` | Triggered when an error occurs while maintaining the WebSocket connection | -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. @@ -60,27 +125,37 @@ void onConnectionError(CometChatException error) { -You can also get the current connection status by using `getConnectionStatus` property provided by CometChat SDK + +Always remove connection listeners when they're no longer needed (e.g., on widget dispose or navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + + +### Remove Connection Listener - - ```dart -String connectionStatus = CometChat.getConnectionStatus(); +CometChat.removeConnectionListener("listenerId"); ``` - - - - -The above method will return either of the below 3 values: - -1. `CometChatWSState.connected` (connected); -2. `CometChatWSState.connecting`(connecting) -3. `CometChatWSState.disconnected`(disconnected) -4. `CometChatWSState.featureThrottled`(featureThrottled) - Know more about CometChat SDK connection behaviour [click here](/sdk/flutter/connection-behaviour) + +--- + +## Next Steps + + + + Understand how CometChat SDK manages WebSocket connections + + + Monitor user login and logout events in real-time + + + Complete reference for all SDK listeners + + + Install and initialize the CometChat SDK + + diff --git a/sdk/flutter/create-group.mdx b/sdk/flutter/create-group.mdx index c5eba5686..0c6157da2 100644 --- a/sdk/flutter/create-group.mdx +++ b/sdk/flutter/create-group.mdx @@ -1,22 +1,59 @@ --- title: "Create A Group" +sidebarTitle: "Create Group" +description: "Create public, private, or password-protected groups and optionally add members during creation using the CometChat Flutter SDK." --- + +```dart +// Create a group +Group group = Group(guid: "GUID", name: "Group Name", type: CometChatGroupType.public); +await CometChat.createGroup( + group: group, + onSuccess: (Group group) => debugPrint("Created: ${group.name}"), + onError: (CometChatException e) => debugPrint("Error: ${e.message}"), +); + +// Create group with members +CometChat.createGroupWithMembers( + group: group, + groupMembers: [GroupMember(uid: "UID", scope: GroupMemberScope.participant)], + bannedUserIds: [], + onSuccess: (Group group) => debugPrint("Created with members: ${group.name}"), + onError: (CometChatException e) => debugPrint("Error: ${e.message}"), +); +``` + +**Group types:** `CometChatGroupType.public` | `CometChatGroupType.password` | `CometChatGroupType.private` +**Member scopes:** `GroupMemberScope.admin` | `GroupMemberScope.moderator` | `GroupMemberScope.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 *In other words, 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. + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) + -The `groupType` needs to be either of the below 3 values: +Use `createGroup()` to create a new group. Pass a `Group` object with the group details. -1.`CometChatGroupType.`*public* (public) +| Group Type | Constant | Description | +| --- | --- | --- | +| Public | `CometChatGroupType.public` | Any user can join | +| Password | `CometChatGroupType.password` | Users must provide the correct password | +| Private | `CometChatGroupType.private` | Users must be added by an admin/moderator | -2.`CometChatGroupType.`*password* (password) +### Parameters -3.`CometChatGroupType.`*private* (private) +| Parameter | Type | Description | +|-----------|------|-------------| +| `group` | `Group` | An instance of the `Group` class containing group details (guid, name, type, password) | +| `onSuccess` | `Function(Group group)?` | Callback triggered on successful group creation | +| `onError` | `Function(CometChatException excep)?` | Callback triggered on error | @@ -40,13 +77,45 @@ String GUID = "GUID"; -The `createGroup()` method takes the following parameters: + +**On Success** — A `Group` object containing all details of the newly created group: + + + +**Group Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Unique identifier for the group | `"cometchat-guid-1"` | +| `name` | string | Display name of the group | `"Hello Group!"` | +| `icon` | string | URL of the group icon | `null` | +| `description` | string | Description of the group | `null` | +| `membersCount` | number | Number of members in the group | `1` | +| `metadata` | object | Custom metadata attached to the group | `{}` | +| `joinedAt` | number | Epoch timestamp when the logged-in user joined the group | `1745554729` | +| `hasJoined` | boolean | Whether the logged-in user has joined the group | `true` | +| `createdAt` | number | Epoch timestamp when the group was created | `1745554729` | +| `owner` | string | UID of the group owner | `"cometchat-uid-1"` | +| `updatedAt` | number | Epoch timestamp when the group was last updated | `1745554729` | +| `tags` | array | List of tags associated with the group | `[]` | +| `type` | string | Type of the group (public, private, password) | `"public"` | +| `scope` | string | Scope of the logged-in user in the group | `"admin"` | +| `password` | string | Password for password-protected groups | `null` | +| `isBannedFromGroup` | boolean | Whether the logged-in user is banned from the group | `false` | + + + + -| Parameter | Description | -| --------- | ---------------------------- | -| `group` | An instance of `Group` class | +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_GUID_NOT_FOUND"` | +| `message` | string | Human-readable error message | `"The specified group does not exist."` | +| `details` | string | Additional technical details | `"Please provide a valid GUID for the group."` | -After the 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. @@ -54,8 +123,94 @@ GUID can be alphanumeric with underscore and hyphen. Spaces, punctuation and oth +## Add Members While Creating a Group + +Use `createGroupWithMembers()` to create a group and add members in one operation. + +### Parameters + +| Parameter | Type | Description | +|-----------|------|-------------| +| `group` | `Group` | The `Group` object with group details (guid, name, type, password) | +| `groupMembers` | `List` | List of `GroupMember` objects to add during creation | +| `bannedUserIds` | `List` | List of UIDs to ban upon creation (defaults to empty) | +| `onSuccess` | `Function(Group group)?` | Callback triggered on successful creation | +| `onError` | `Function(CometChatException excep)?` | Callback triggered on error | + +Create a `GroupMember` with: `GroupMember(uid: "UID", scope: GroupMemberScope.participant)` + + + +```dart +String GUID = "cometchat-guid-11"; +String groupName = "Hello Group!"; +String groupType = CometChatGroupType.public; + +Group group = Group(guid: GUID, name: groupName, type: groupType); +List members = [ + GroupMember(uid: "cometchat-uid-1", scope: GroupMemberScope.participant), +]; +List bannedUserIds = ["cometchat-uid-2"]; + +CometChat.createGroupWithMembers( + group: group, + groupMembers: members, + bannedUserIds: bannedUserIds, + onSuccess: (Group group) { + debugPrint("Group created with members: ${group.name}"); + }, + onError: (CometChatException e) { + debugPrint("Error creating group with members: ${e.message}"); + }, +); +``` + + + + + + +**On Success** — A `Group` object containing all details of the newly created group: + + + +**Group Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Unique identifier for the group | `"cometchat-guid-11"` | +| `name` | string | Display name of the group | `"Hello Group!"` | +| `icon` | string | URL of the group icon | `null` | +| `description` | string | Description of the group | `null` | +| `membersCount` | number | Number of members in the group | `2` | +| `metadata` | object | Custom metadata attached to the group | `{}` | +| `joinedAt` | number | Epoch timestamp when the logged-in user joined the group | `1745554729` | +| `hasJoined` | boolean | Whether the logged-in user has joined the group | `true` | +| `createdAt` | number | Epoch timestamp when the group was created | `1745554729` | +| `owner` | string | UID of the group owner | `"cometchat-uid-1"` | +| `updatedAt` | number | Epoch timestamp when the group was last updated | `1745554729` | +| `tags` | array | List of tags associated with the group | `[]` | +| `type` | string | Type of the group (public, private, password) | `"public"` | +| `scope` | string | Scope of the logged-in user in the group | `"admin"` | +| `password` | string | Password for password-protected groups | `null` | +| `isBannedFromGroup` | boolean | Whether the logged-in user is banned from the group | `false` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_GUID_NOT_FOUND"` | +| `message` | string | Human-readable error message | `"The specified group does not exist."` | +| `details` | string | Additional technical details | `"Please provide a valid GUID for the group."` | + + + ## 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 | @@ -73,3 +228,22 @@ GUID can be alphanumeric with underscore and hyphen. Spaces, punctuation and oth | 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/flutter/default-call.mdx b/sdk/flutter/default-call.mdx index 8370c838e..f7f8c2005 100644 --- a/sdk/flutter/default-call.mdx +++ b/sdk/flutter/default-call.mdx @@ -1,11 +1,41 @@ --- title: "Ringing" +sidebarTitle: "Ringing" +description: "Implement complete calling workflow with ringing functionality including incoming/outgoing call UI, call acceptance, rejection, and cancellation in your Flutter app." --- + + +```dart +// Initiate a call +Call call = Call( + receiverUid: "USER_ID", + receiverType: CometChatReceiverType.user, + type: CometChatCallType.video, +); + +CometChat.initiateCall(call, + onSuccess: (Call call) => debugPrint("Call initiated: ${call.sessionId}"), + onError: (CometChatException e) => debugPrint("Error: ${e.message}"), +); + +// Accept / Reject / Cancel +CometChat.acceptCall(sessionId, onSuccess: (Call call) {}, onError: (e) {}); +CometChat.rejectCall(sessionId, CometChatConstants.CALL_STATUS_REJECTED, onSuccess: (Call call) {}, onError: (e) {}); +CometChat.rejectCall(sessionId, CometChatConstants.CALL_STATUS_CANCELLED, onSuccess: (Call call) {}, onError: (e) {}); +``` + +**Flow:** Initiate → Receiver notified → Accept/Reject → Start session + + ## 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**. + +**Available via:** SDK | [UI Kits](/ui-kit/flutter/overview) + + After the call is accepted, you need to start the call session. See the [Call Session](/sdk/flutter/direct-call#start-call-session) guide for details on starting and managing the actual call. @@ -22,7 +52,7 @@ After the call is accepted, you need to start the call session. See the [Call Se ## Initiate Call -The `initiateCall()` method sends a call request to a user or a group. On success, the receiver gets an `onIncomingCallReceived()` callback. +The `initiateCall()` method sends a [`Call`](/sdk/reference/messages#call) request to a user or a group. On success, the receiver gets an `onIncomingCallReceived()` callback. ```dart // User call @@ -109,10 +139,150 @@ CometChat.initiateCall( 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` object containing all details of the initiated call: + + + +**Call Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `501` | +| `metadata` | object | Custom metadata attached to the call | `{}` | +| `receiver` | object | Receiver user object | [See below ↓](#initiate-call-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `null` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `sentAt` | number | Epoch timestamp when the call was initiated | `1745554729` | +| `receiverUid` | string | UID of the receiver | `"cometchat-uid-2"` | +| `type` | string | Type of the call | `"video"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `null` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `0` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `0` | +| `replyCount` | number | Number of replies | `0` | +| `sender` | object | Sender user object (call initiator) | [See below ↓](#initiate-call-sender-object) | +| `receiverType` | string | Type of the receiver | `"user"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `0` | +| `parentMessageId` | number | ID of the parent message | `0` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"call"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` | +| `updatedAt` | number | Epoch timestamp when the call was last updated | `1745554729` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `quotedMessageId` | number | ID of the quoted message | `null` | +| `sessionId` | string | Unique call session identifier | `"v1.us.1.xxxxxxxx"` | +| `callStatus` | string | Current status of the call | `"initiated"` | +| `action` | string | Call action type | `"initiated"` | +| `callInitiator` | object | User who initiated the call | [See below ↓](#initiate-call-initiator-object) | +| `callReceiver` | object | User who receives the call | [See below ↓](#initiate-call-call-receiver-object) | +| `initiatedAt` | number | Epoch timestamp when the call was initiated | `1745554729` | +| `joinedAt` | number | Epoch timestamp when the user joined the call | `0` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-1"` | +| `name` | string | Display name of the sender | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-2"` | +| `name` | string | Display name of the receiver | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + +--- + + + +**`callInitiator` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the call initiator | `"cometchat-uid-1"` | +| `name` | string | Display name of the call initiator | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`callReceiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the call receiver | `"cometchat-uid-2"` | +| `name` | string | Display name of the call receiver | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"The call operation failed."` | +| `details` | string | Additional technical details | `"Unable to initiate the call. Please try again."` | + + + ## 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. + +Always remove call listeners when they're no longer needed (e.g., on widget dispose). Failing to remove listeners can cause memory leaks and duplicate event handling. + + ```dart String listenerId = "UNIQUE_LISTENER_ID"; @@ -191,6 +361,142 @@ CometChat.acceptCall( ); ``` + +**On Success** — A `Call` object containing all details of the accepted call: + + + +**Call Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `502` | +| `metadata` | object | Custom metadata attached to the call | `{}` | +| `receiver` | object | Receiver user object | [See below ↓](#accept-call-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `null` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `sentAt` | number | Epoch timestamp when the call was initiated | `1745554729` | +| `receiverUid` | string | UID of the receiver | `"cometchat-uid-2"` | +| `type` | string | Type of the call | `"video"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `null` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `0` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `0` | +| `replyCount` | number | Number of replies | `0` | +| `sender` | object | Sender user object (call initiator) | [See below ↓](#accept-call-sender-object) | +| `receiverType` | string | Type of the receiver | `"user"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `0` | +| `parentMessageId` | number | ID of the parent message | `0` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"call"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` | +| `updatedAt` | number | Epoch timestamp when the call was last updated | `1745554800` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `quotedMessageId` | number | ID of the quoted message | `null` | +| `sessionId` | string | Unique call session identifier | `"v1.us.1.xxxxxxxx"` | +| `callStatus` | string | Current status of the call | `"ongoing"` | +| `action` | string | Call action type | `"accepted"` | +| `callInitiator` | object | User who initiated the call | [See below ↓](#accept-call-initiator-object) | +| `callReceiver` | object | User who receives the call | [See below ↓](#accept-call-call-receiver-object) | +| `initiatedAt` | number | Epoch timestamp when the call was initiated | `1745554729` | +| `joinedAt` | number | Epoch timestamp when the user joined the call | `1745554800` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-1"` | +| `name` | string | Display name of the sender | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-2"` | +| `name` | string | Display name of the receiver | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554750` | + +--- + + + +**`callInitiator` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the call initiator | `"cometchat-uid-1"` | +| `name` | string | Display name of the call initiator | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`callReceiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the call receiver | `"cometchat-uid-2"` | +| `name` | string | Display name of the call receiver | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554750` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"The call operation failed."` | +| `details` | string | Additional technical details | `"Unable to accept the call. The session may have expired."` | + + + ## Reject Call Use `rejectCall()` to reject an incoming call. Set the status to `CALL_STATUS_REJECTED`. @@ -212,6 +518,142 @@ CometChat.rejectCall( ); ``` + +**On Success** — A `Call` object containing all details of the rejected call: + + + +**Call Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `503` | +| `metadata` | object | Custom metadata attached to the call | `{}` | +| `receiver` | object | Receiver user object | [See below ↓](#reject-call-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `null` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `sentAt` | number | Epoch timestamp when the call was initiated | `1745554729` | +| `receiverUid` | string | UID of the receiver | `"cometchat-uid-2"` | +| `type` | string | Type of the call | `"video"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `null` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `0` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `0` | +| `replyCount` | number | Number of replies | `0` | +| `sender` | object | Sender user object (call initiator) | [See below ↓](#reject-call-sender-object) | +| `receiverType` | string | Type of the receiver | `"user"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `0` | +| `parentMessageId` | number | ID of the parent message | `0` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"call"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` | +| `updatedAt` | number | Epoch timestamp when the call was last updated | `1745554750` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `quotedMessageId` | number | ID of the quoted message | `null` | +| `sessionId` | string | Unique call session identifier | `"v1.us.1.xxxxxxxx"` | +| `callStatus` | string | Current status of the call | `"rejected"` | +| `action` | string | Call action type | `"rejected"` | +| `callInitiator` | object | User who initiated the call | [See below ↓](#reject-call-initiator-object) | +| `callReceiver` | object | User who receives the call | [See below ↓](#reject-call-call-receiver-object) | +| `initiatedAt` | number | Epoch timestamp when the call was initiated | `1745554729` | +| `joinedAt` | number | Epoch timestamp when the user joined the call | `0` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-1"` | +| `name` | string | Display name of the sender | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-2"` | +| `name` | string | Display name of the receiver | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + +--- + + + +**`callInitiator` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the call initiator | `"cometchat-uid-1"` | +| `name` | string | Display name of the call initiator | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`callReceiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the call receiver | `"cometchat-uid-2"` | +| `name` | string | Display name of the call receiver | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"The call operation failed."` | +| `details` | string | Additional technical details | `"Unable to reject the call. The session may have expired."` | + + + ## Cancel Call The caller can cancel an outgoing call before it's answered using `rejectCall()` with status `CALL_STATUS_CANCELLED`. @@ -233,6 +675,142 @@ CometChat.rejectCall( ); ``` + +**On Success** — A `Call` object containing all details of the cancelled call: + + + +**Call Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `504` | +| `metadata` | object | Custom metadata attached to the call | `{}` | +| `receiver` | object | Receiver user object | [See below ↓](#cancel-call-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `null` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `sentAt` | number | Epoch timestamp when the call was initiated | `1745554729` | +| `receiverUid` | string | UID of the receiver | `"cometchat-uid-2"` | +| `type` | string | Type of the call | `"video"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `null` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `0` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `0` | +| `replyCount` | number | Number of replies | `0` | +| `sender` | object | Sender user object (call initiator) | [See below ↓](#cancel-call-sender-object) | +| `receiverType` | string | Type of the receiver | `"user"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `0` | +| `parentMessageId` | number | ID of the parent message | `0` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"call"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` | +| `updatedAt` | number | Epoch timestamp when the call was last updated | `1745554760` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `quotedMessageId` | number | ID of the quoted message | `null` | +| `sessionId` | string | Unique call session identifier | `"v1.us.1.xxxxxxxx"` | +| `callStatus` | string | Current status of the call | `"cancelled"` | +| `action` | string | Call action type | `"cancelled"` | +| `callInitiator` | object | User who initiated the call | [See below ↓](#cancel-call-initiator-object) | +| `callReceiver` | object | User who receives the call | [See below ↓](#cancel-call-call-receiver-object) | +| `initiatedAt` | number | Epoch timestamp when the call was initiated | `1745554729` | +| `joinedAt` | number | Epoch timestamp when the user joined the call | `0` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-1"` | +| `name` | string | Display name of the sender | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-2"` | +| `name` | string | Display name of the receiver | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + +--- + + + +**`callInitiator` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the call initiator | `"cometchat-uid-1"` | +| `name` | string | Display name of the call initiator | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`callReceiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the call receiver | `"cometchat-uid-2"` | +| `name` | string | Display name of the call receiver | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"The call operation failed."` | +| `details` | string | Additional technical details | `"Unable to cancel the call. The session may have expired."` | + + + ## Start Call Session Once the call is accepted, both participants need to start the call session. @@ -311,6 +889,142 @@ void onCallEndButtonPressed() { } ``` + +**On Success** — A `Call` object containing all details of the ended call: + + + +**Call Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `505` | +| `metadata` | object | Custom metadata attached to the call | `{}` | +| `receiver` | object | Receiver user object | [See below ↓](#end-call-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `null` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `sentAt` | number | Epoch timestamp when the call was initiated | `1745554729` | +| `receiverUid` | string | UID of the receiver | `"cometchat-uid-2"` | +| `type` | string | Type of the call | `"video"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `null` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `0` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `0` | +| `replyCount` | number | Number of replies | `0` | +| `sender` | object | Sender user object (call initiator) | [See below ↓](#end-call-sender-object) | +| `receiverType` | string | Type of the receiver | `"user"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `0` | +| `parentMessageId` | number | ID of the parent message | `0` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"call"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` | +| `updatedAt` | number | Epoch timestamp when the call was last updated | `1745555000` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `quotedMessageId` | number | ID of the quoted message | `null` | +| `sessionId` | string | Unique call session identifier | `"v1.us.1.xxxxxxxx"` | +| `callStatus` | string | Current status of the call | `"ended"` | +| `action` | string | Call action type | `"ended"` | +| `callInitiator` | object | User who initiated the call | [See below ↓](#end-call-initiator-object) | +| `callReceiver` | object | User who receives the call | [See below ↓](#end-call-call-receiver-object) | +| `initiatedAt` | number | Epoch timestamp when the call was initiated | `1745554729` | +| `joinedAt` | number | Epoch timestamp when the user joined the call | `1745554800` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-1"` | +| `name` | string | Display name of the sender | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-2"` | +| `name` | string | Display name of the receiver | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554900` | + +--- + + + +**`callInitiator` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the call initiator | `"cometchat-uid-1"` | +| `name` | string | Display name of the call initiator | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`callReceiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the call receiver | `"cometchat-uid-2"` | +| `name` | string | Display name of the call receiver | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554900` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"The call operation failed."` | +| `details` | string | Additional technical details | `"Unable to end the call. The session may have already ended."` | + + + **Remote participant** (receives `onCallEnded()` callback): ```dart @@ -350,3 +1064,158 @@ CometChat.rejectCall( }, ); ``` + + +**On Success** — A `Call` object containing all details of the busy-rejected call: + + + +**Call Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `506` | +| `metadata` | object | Custom metadata attached to the call | `{}` | +| `receiver` | object | Receiver user object | [See below ↓](#busy-call-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `null` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `sentAt` | number | Epoch timestamp when the call was initiated | `1745554729` | +| `receiverUid` | string | UID of the receiver | `"cometchat-uid-2"` | +| `type` | string | Type of the call | `"video"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `null` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `0` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `0` | +| `replyCount` | number | Number of replies | `0` | +| `sender` | object | Sender user object (call initiator) | [See below ↓](#busy-call-sender-object) | +| `receiverType` | string | Type of the receiver | `"user"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `0` | +| `parentMessageId` | number | ID of the parent message | `0` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"call"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` | +| `updatedAt` | number | Epoch timestamp when the call was last updated | `1745554740` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `quotedMessageId` | number | ID of the quoted message | `null` | +| `sessionId` | string | Unique call session identifier | `"v1.us.1.xxxxxxxx"` | +| `callStatus` | string | Current status of the call | `"busy"` | +| `action` | string | Call action type | `"busy"` | +| `callInitiator` | object | User who initiated the call | [See below ↓](#busy-call-initiator-object) | +| `callReceiver` | object | User who receives the call | [See below ↓](#busy-call-call-receiver-object) | +| `initiatedAt` | number | Epoch timestamp when the call was initiated | `1745554729` | +| `joinedAt` | number | Epoch timestamp when the user joined the call | `0` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-1"` | +| `name` | string | Display name of the sender | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-2"` | +| `name` | string | Display name of the receiver | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`callInitiator` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the call initiator | `"cometchat-uid-1"` | +| `name` | string | Display name of the call initiator | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`callReceiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the call receiver | `"cometchat-uid-2"` | +| `name` | string | Display name of the call receiver | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"The call operation failed."` | +| `details` | string | Additional technical details | `"Unable to send busy status. The session may have expired."` | + + + +--- + +## 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/flutter/delete-conversation.mdx b/sdk/flutter/delete-conversation.mdx index 57473b8ca..7eed0b031 100644 --- a/sdk/flutter/delete-conversation.mdx +++ b/sdk/flutter/delete-conversation.mdx @@ -1,12 +1,44 @@ --- -title: "Delete A Conversation" +title: "Delete Conversation" +sidebarTitle: "Delete Conversation" +description: "Learn how to delete user and group conversations from the logged-in user's conversation list using the CometChat Flutter SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +```dart +// Delete a user conversation +await CometChat.deleteConversation( + "UID", + CometChatConversationType.user, + onSuccess: (String message) => debugPrint("Deleted: $message"), + onError: (CometChatException e) => debugPrint("Error: ${e.message}"), +); + +// Delete a group conversation +await CometChat.deleteConversation( + "GUID", + CometChatConversationType.group, + onSuccess: (String message) => debugPrint("Deleted: $message"), + onError: (CometChatException e) => debugPrint("Error: ${e.message}"), +); +``` -In case you want to delete a conversation, you can use the `deleteConversation()` method. +**Note:** Deletes only for the logged-in user. Use [REST API](https://api-explorer.cometchat.com/reference/deletes-conversation) to delete for all participants. + -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. + +This operation is irreversible. Deleted conversations cannot be recovered. All messages in the conversation will be removed from the user's view. + + +Use `deleteConversation()` to delete a conversation for the logged-in user. + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) + + +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. @@ -43,11 +75,51 @@ await CometChat.deleteConversation(conversationWith, conversationType, -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). +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 the [REST API documentation](https://api-explorer.cometchat.com/reference/deletes-conversation). + +| Parameter | Type | Description | Required | +| --- | --- | --- | --- | +| `conversationWith` | `String` | `UID` of the user or `GUID` of the group whose conversation you want to delete. | Yes | +| `conversationType` | `String` | The type of conversation to delete. Use `CometChatConversationType.user` or `CometChatConversationType.group`. | Yes | + + +**On Success** — A `String` message confirming the conversation was deleted: + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `message` | string | Success confirmation message | `"cometchat-uid-1_user_cometchat-uid-2 deleted successfully"` | + + + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to delete the conversation."` | +| `details` | string | Additional technical details | `"The specified conversation could not be found or deleted."` | + + + +--- -The `deleteConversation()` method takes the following parameters: +## Next Steps -| 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 | + + + Fetch and filter conversation lists + + + Delete individual messages from conversations + + + Listen for incoming messages in real-time + + + Show when users are typing in conversations + + diff --git a/sdk/flutter/delete-group.mdx b/sdk/flutter/delete-group.mdx index 2bc36f2e0..4f48f7e14 100644 --- a/sdk/flutter/delete-group.mdx +++ b/sdk/flutter/delete-group.mdx @@ -1,12 +1,49 @@ --- title: "Delete A Group" +sidebarTitle: "Delete Group" +description: "Delete a group permanently using the CometChat Flutter SDK. Only the group owner can perform this operation." --- + +```dart +// Delete a group (owner only) +String guid = "GROUP_ID"; + +CometChat.deleteGroup(guid, + onSuccess: (String message) { + debugPrint("Deleted: $message"); + }, + onError: (CometChatException e) { + debugPrint("Error: ${e.message}"); + }, +); +``` + +**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. The group is represented by a [`Group`](/sdk/reference/entities#group) object. -## Delete Group + +This operation is irreversible. Deleted groups and their messages cannot be recovered. + -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. +## Delete a Group + +Use `deleteGroup()` with the group's GUID. + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) + + +### Parameters + +| Parameter | Type | Description | +|-----------|------|-------------| +| `guid` | `String` | The GUID of the group you would like to delete | +| `onSuccess` | `Function(String message)?` | Callback triggered on successful deletion | +| `onError` | `Function(CometChatException excep)?` | Callback triggered on error | @@ -24,8 +61,44 @@ debugPrint("Delete Group failed with exception: ${e.message}"); -The `deleteGroup()` method takes the following parameters: + +**On Success** — A `String` message confirming the operation: + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `message` | string | Success confirmation message | `"cometchat-guid-1 deleted successfully"` | + + + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_GUID_NOT_FOUND"` | +| `message` | string | Human-readable error message | `"The specified group does not exist."` | +| `details` | string | Additional technical details | `"Please provide a valid group GUID."` | + + + +--- + +## Next Steps -| Parameter | Description | -| --------- | ---------------------------------------------- | -| `GUID` | The GUID of the group you would like to delete | + + + 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/flutter/delete-message.mdx b/sdk/flutter/delete-message.mdx index ebf63f117..0240e6336 100644 --- a/sdk/flutter/delete-message.mdx +++ b/sdk/flutter/delete-message.mdx @@ -1,19 +1,70 @@ --- title: "Delete A Message" +sidebarTitle: "Delete Message" +description: "Delete messages and handle real-time deletion events using the CometChat Flutter SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +| Field | Value | +| --- | --- | +| Key Classes | `BaseMessage`, `CometChatException` | +| Key Methods | `CometChat.deleteMessage()` | +| Listener Events | `onMessageDeleted` | +| Prerequisites | SDK initialized, user logged in | + +```dart +// Delete a message by ID +int messageId = 1234; +await CometChat.deleteMessage(messageId, + onSuccess: (BaseMessage message) { + debugPrint("Message deleted at: ${message.deletedAt}"); + }, + onError: (CometChatException e) { + debugPrint("Delete failed: ${e.message}"); + }, +); + +// Listen for deleted messages +CometChat.addMessageListener("listener_id", MessageListener( + onMessageDeleted: (BaseMessage message) { + debugPrint("Message ${message.id} was deleted"); + }, +)); + +// Remove listener when done +CometChat.removeMessageListener("listener_id"); +``` + +**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. + While [deleting a message](/sdk/flutter/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/flutter/delete-message#real-time-message-delete-events) when your app is running. -2. Calling a method to retrieve [missed message delete events](/sdk/flutter/delete-message#missed-message-delete-events)-me when your app was not running. +2. Calling a method to retrieve [missed message delete events](/sdk/flutter/delete-message#missed-message-delete-events) when your app was not running. + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) + ## 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 of the message to be deleted. + +| Parameter | Type | Description | +| --- | --- | --- | +| `messageId` | `int` | The ID of the message to delete. | +| `onSuccess` | `Function(BaseMessage)` | Callback triggered on success with the deleted message object. | +| `onError` | `Function(CometChatException)` | Callback triggered on error with exception details. | @@ -33,13 +84,103 @@ await CometChat.deleteMessage(messageId, -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. + +**On Success** — A `BaseMessage` object with `deletedAt` and `deletedBy` fields set: -By default, CometChat allows certain roles to delete a message. + -## Real-time Message Delete Events +**BaseMessage Object:** -*In other words, as a recipient, how do I know when someone deletes a message when my app is running?* +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `1234` | +| `metadata` | object | Custom metadata attached to the message | `{}` | +| `receiver` | object | Receiver user object | [See below ↓](#delete-message-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `null` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `sentAt` | number | Epoch timestamp when the message was sent | `1745554729` | +| `receiverUid` | string | UID of the receiver | `"cometchat-uid-2"` | +| `type` | string | Type of the message | `"text"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `"cometchat-uid-1"` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `1745554750` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `1745554800` | +| `replyCount` | number | Number of replies to this message | `0` | +| `sender` | object | Sender user object | [See below ↓](#delete-message-sender-object) | +| `receiverType` | string | Type of the receiver | `"user"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `0` | +| `parentMessageId` | number | ID of the parent message (for threads) | `0` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"message"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` | +| `updatedAt` | number | Epoch timestamp when the message was last updated | `1745554800` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `quotedMessageId` | number | ID of the quoted message | `null` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-1"` | +| `name` | string | Display name of the sender | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-2"` | +| `name` | string | Display name of the receiver | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"The message could not be deleted."` | +| `details` | string | Additional technical details | `"Ensure the message ID is valid and you have permission to delete this message."` | + + + +The deleted message object is returned with `deletedAt` (timestamp) and `deletedBy` (UID of deleter) fields set. + +Relevant fields to access on the returned message: + +| Field | Property | Return Type | Description | +|-------|----------|-------------|-------------| +| deletedAt | `deletedAt` | `int` | Timestamp when the message was deleted | +| deletedBy | `deletedBy` | `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 | | --------------- | ----------------------- | ------------------------- | @@ -48,7 +189,11 @@ By default, CometChat allows certain roles to delete a message. | Group Admin | Group Conversation | All messages in the group | | Group Moderator | Group Conversation | All messages in the group | -In order to receive real-time events for a message being deleted, you need to override the `onMessageDeleted()` method of the `MessageListener` class. +## 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?* + +Use `onMessageDeleted` in `MessageListener` to receive real-time delete events. @@ -69,6 +214,27 @@ void onMessageDeleted(BaseMessage message) { + +Always remove message listeners when they're no longer needed (e.g., in the `dispose()` method). Failing to remove listeners can cause memory leaks and duplicate event handling. + +```dart +@override +void dispose() { + CometChat.removeMessageListener("listenerId"); + super.dispose(); +} +``` + + +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 | Property | Return Type | Description | +|-------|----------|-------------|-------------| +| deletedAt | `deletedAt` | `int` | Timestamp when the message was deleted | +| deletedBy | `deletedBy` | `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?* @@ -83,7 +249,24 @@ For the message deleted event, in the `Action` object received, the following fi 4. `actionFor` - User/group object having the details of the receiver to which the message was sent. +You must be the message sender or a group admin/moderator to delete a message. + -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. +--- - +## Next Steps + + + + Modify sent messages before deletion + + + Send text, media, and custom messages + + + Handle incoming messages in real-time + + + Report inappropriate messages + + diff --git a/sdk/flutter/delivery-read-receipts.mdx b/sdk/flutter/delivery-read-receipts.mdx index 1d1716d1e..ca2605290 100644 --- a/sdk/flutter/delivery-read-receipts.mdx +++ b/sdk/flutter/delivery-read-receipts.mdx @@ -1,29 +1,81 @@ --- title: "Delivery & Read Receipts" +sidebarTitle: "Delivery & Read Receipts" +description: "Mark messages as delivered, read, or unread and receive real-time receipt events using the CometChat Flutter SDK." --- + +| Field | Value | +| --- | --- | +| Key Classes | `MessageReceipt`, `BaseMessage`, `Conversation` | +| Key Methods | `CometChat.markAsDelivered()`, `CometChat.markAsRead()`, `CometChat.markMessageAsUnread()`, `CometChat.getMessageReceipts()` | +| Listener Events | `onMessagesDelivered`, `onMessagesRead`, `onMessagesDeliveredToAll`, `onMessagesReadByAll` | +| Prerequisites | SDK initialized, user logged in | + +```dart +// Mark message as delivered +CometChat.markAsDelivered(message, onSuccess: (String unused) { + debugPrint("Marked as delivered"); +}, onError: (CometChatException e) { + debugPrint("Error: ${e.message}"); +}); + +// Mark message as read +CometChat.markAsRead(message, onSuccess: (String unused) { + debugPrint("Marked as read"); +}, onError: (CometChatException e) { + debugPrint("Error: ${e.message}"); +}); + +// Mark message as unread +CometChat.markMessageAsUnread(message, onSuccess: (Conversation conversation) { + debugPrint("Marked as unread"); +}, onError: (CometChatException e) { + debugPrint("Error: ${e.message}"); +}); + +// Listen for receipts +CometChat.addMessageListener("receipts_listener", MessageListener( + onMessagesDelivered: (MessageReceipt receipt) { }, + onMessagesRead: (MessageReceipt receipt) { }, + onMessagesDeliveredToAll: (MessageReceipt receipt) { }, + onMessagesReadByAll: (MessageReceipt receipt) { }, +)); + +// Remove listener when done +CometChat.removeMessageListener("receipts_listener"); +``` + + + +Delivery and read receipts allow you to track when messages have been delivered to and read by recipients, providing real-time feedback on message status. + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) + ## 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: +You can mark the messages for a particular conversation as delivered using the `markAsDelivered()` method. This method takes a `BaseMessage` object as input. -| Parameter | Information | -| ------------ | ---------------------------------------------------------------------------------------------------------- | -| id | The ID of the message above which all the messages for a particular conversation are to be marked as read. | -| receiverUid | In case of one to one conversation message's sender UID will be the receipt's receiver Id. | -| receiverType | Type of the receiver. Could be either of the two values( user or group). | -Messages for both user & group conversations can be marked as read using this method. +| Parameter | Type | Description | +| --- | --- | --- | +| `message` | [`BaseMessage`](/sdk/reference/messages#basemessage) | The message object to mark as delivered. All messages before this message in the conversation will be marked as delivered. | +| `onSuccess` | `Function(String)` | Callback triggered on success with a confirmation string. | +| `onError` | `Function(CometChatException)` | Callback triggered on error with exception details. | + +Messages for both user & group conversations can be marked as delivered using this method. 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: -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. +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 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 and pass it to the `markAsDelivered()` method. -This method will mark all the messages before the messageId specified, for the conversation with receiverId and receiverType(user/group) as read. +This method will mark all the messages before the message specified, for the conversation with `receiverId` and `receiverType` (user/group) as delivered. In case you would like to be notified of an error if the receipts fail to go through you can use `markAsDelivered()` method with the callbacks as shown below: @@ -31,9 +83,9 @@ In case you would like to be notified of an error if the receipts fail to go thr ```dart CometChat.markAsDelivered(message, onSuccess: (String unused) { -debugPrint("markAsDelivered : $unused "); + debugPrint("markAsDelivered : $unused "); }, onError: (CometChatException e) { -debugPrint("markAsDelivered unsuccessful : ${e.message} "); + debugPrint("markAsDelivered unsuccessful : ${e.message} "); }); ``` @@ -41,21 +93,40 @@ debugPrint("markAsDelivered unsuccessful : ${e.message} "); -## Mark Messages as Read + +**On Success** — A `String` message confirming the message has been marked as delivered: -*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 | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `message` | `String` | Success confirmation message | `"markAsDelivered success"` | -Messages for both user and group conversations can be marked as read using this method. + + + -The message object takes the below parameters as input: + -| Parameter | Information | -| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| id | The ID of the message above which all the messages for a particular conversation are to be marked as read. | -| receiverUid | In a one-to-one conversation, the message's sender UID will be the receipt's receiver ID. In a group conversation, the 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). | +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | `String` | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | `String` | Human-readable error message | `"Failed to mark the message as delivered."` | +| `details` | `String` | Additional technical details | `"An unexpected error occurred while processing the request."` | + + + +## 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 a `BaseMessage` object as input. + +| Parameter | Type | Description | +| --- | --- | --- | +| `baseMessage` | [`BaseMessage`](/sdk/reference/messages#basemessage) | The message object to mark as read. All messages before this message in the conversation will be marked as read. | +| `onSuccess` | `Function(String)` | Callback triggered on success with a confirmation string. | +| `onError` | `Function(CometChatException)` | Callback triggered on error with exception details. | Messages for both user and group conversations can be marked as read using this method. @@ -95,6 +166,29 @@ CometChat.markAsRead(message, onSuccess: (String unused) { + +**On Success** — A `String` message confirming the message has been marked as read: + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `message` | `String` | Success confirmation message | `"markAsRead success"` | + + + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | `String` | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | `String` | Human-readable error message | `"Failed to mark the message as read."` | +| `details` | `String` | Additional technical details | `"An unexpected error occurred while processing the request."` | + + + ## Mark Messages as Unread The Mark as Unread feature allows users to designate specific messages or conversations as unread, even if they have been previously viewed. @@ -103,40 +197,74 @@ This feature is valuable for users who want to revisit and respond to important *In other words, how I can mark message as unread?* -You can mark the messages for a particular conversation as unread using the `markAsUnread()` method. +You can mark the messages for a particular conversation as unread using the `markMessageAsUnread()` method. -| Parameter | Information | -| --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| message | To mark a message as unread, pass a non-null `BaseMessage` instance to the `markAsUnread()` 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 `markAsUnread()` 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. | +| Parameter | Type | Description | +| --- | --- | --- | +| `baseMessage` | [`BaseMessage`](/sdk/reference/messages#basemessage) | To mark a message as unread, pass a non-null `BaseMessage` instance. All messages below that message in the conversation will contribute to the unread messages count. | +| `onSuccess` | `Function(Conversation)` | Callback triggered on success with the updated `Conversation` object containing the new unread count. | +| `onError` | `Function(CometChatException)` | Callback triggered on error with exception details. | + +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. ```dart -CometChat.markAsUnread( - message, - onSuccess: (success) { - debugPrint("markAsUnread : $success"); - }, - onError: (error) { - debugPrint("markAsUnread unsuccessfull : $error"); - }, - ); +CometChat.markMessageAsUnread( + message, + onSuccess: (Conversation conversation) { + debugPrint("markMessageAsUnread : $conversation"); + }, + onError: (CometChatException error) { + debugPrint("markMessageAsUnread unsuccessful : $error"); + }, +); ``` + +**On Success** — A `Conversation` object with the updated unread message count: + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `conversationId` | `String` | Unique identifier for the conversation | `"user_superhero1"` | +| `conversationType` | `String` | Type of conversation | `"user"` or `"group"` | +| `unreadMessageCount` | `int` | Updated unread message count | `5` | +| `lastMessage` | `BaseMessage` | The last message in the conversation | Message object | + + + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | `String` | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | `String` | Human-readable error message | `"Failed to mark the message as unread."` | +| `details` | `String` | Additional technical details | `"An unexpected error occurred while processing the request."` | + + + ## 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?* -### 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. -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 | @@ -171,17 +299,29 @@ void onMessagesReadByAll(MessageReceipt messageReceipt) { -You will receive events in the form of `MessageReceipt` objects. The message receipt contains the following parameters: + +Always remove listeners when they're no longer needed (e.g., in the `dispose()` method). Failing to remove listeners can cause memory leaks and duplicate event handling. + +```dart +@override +void dispose() { + CometChat.removeMessageListener("listenerId"); + super.dispose(); +} +``` + -| 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. | -| `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. | +You will receive events in the form of [`MessageReceipt`](/sdk/reference/auxiliary#messagereceipt) objects. The message receipt contains the following parameters: + +| Parameter | Type | Description | +| -------------- | ---- | -------------------------------------------------------------------------------------------------------------------- | +| `messageId` | `int` | The ID of the message prior to which all the messages for that particular conversation have been marked as read. | +| `sender` | [`User`](/sdk/reference/entities#user) | User object containing the details of the user who has marked the message as read. | +| `receiverId` | `String` | Id of the receiver whose conversation has been marked as read. | +| `receiverType` | `String` | Type of the receiver (user/group) | +| `receiptType` | `String` | Type of the receipt (read/delivered) | +| `deliveredAt` | `DateTime` | The timestamp of the time when the message was delivered. This will only be present if the receiptType is delivered. | +| `readAt` | `DateTime` | The timestamp of the time when the message was read. This will only be present when the receiptType is read. | ### Missed Receipts @@ -189,25 +329,25 @@ You will receive message receipts when you load offline messages. While fetching 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 +## Receipt History for a Single Message + +To fetch the message receipts, you can use the `getMessageReceipts()` method. This is useful for group messages to see which members have received/read the message. -In order to fetch the message receipts, you can use the `getMessageReceipts()` method. +| Parameter | Type | Description | +| --- | --- | --- | +| `messageId` | `int` | The ID of the message for which receipts are to be fetched. | +| `onSuccess` | `Function(List)` | Callback triggered on success with a list of `MessageReceipt` objects. | +| `onError` | `Function(CometChatException)` | Callback triggered on error with exception details. | ```dart -private int messageId = 10101; +int messageId = 10101; -CometChat.getMessageReceipts(messageId, new CometChat.CallbackListener>() { -@Override - public void onSuccess(List messageReceipts) { - // Handle message receipts -} - -@Override - public void onError(CometChatException e) { - // Handle error -} +CometChat.getMessageReceipts(messageId, onSuccess: (List messageReceipts) { + debugPrint("Message receipts fetched: $messageReceipts"); +}, onError: (CometChatException e) { + debugPrint("Error fetching receipts: ${e.message}"); }); ``` @@ -215,7 +355,36 @@ CometChat.getMessageReceipts(messageId, new CometChat.CallbackListener -You will receive a list of `MessageReceipt` objects in the `onSuccess()` method. + +**On Success** — A `List` containing receipt details for each group member: + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `messageId` | `int` | The ID of the message | `10101` | +| `sender` | `User` | User who triggered the receipt | User object | +| `receiverId` | `String` | ID of the receiver | `"superhero1"` | +| `receiverType` | `String` | Type of receiver | `"user"` or `"group"` | +| `receiptType` | `String` | Type of receipt | `"delivered"` or `"read"` | +| `deliveredAt` | `DateTime` | Timestamp when delivered | `DateTime` object | +| `readAt` | `DateTime` | Timestamp when read | `DateTime` object | + + + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | `String` | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | `String` | Human-readable error message | `"Failed to fetch message receipts."` | +| `details` | `String` | Additional technical details | `"An unexpected error occurred while processing the request."` | + + + +You will receive a list of `MessageReceipt` objects in the `onSuccess()` callback. @@ -225,6 +394,25 @@ The following features will be available only if the **Enhanced Messaging Status * `onMessagesReadByAll` event, * `deliveredAt` field in a group message, * `readAt` field in a group message. -* `markAsUnread` method. +* `markMessageAsUnread` method. + +--- + +## Next Steps + + + + Handle incoming messages in real-time + + + Show when users are typing + + + Fetch conversation list with unread counts + + + Complete reference for all SDK event listeners + + diff --git a/sdk/flutter/direct-call.mdx b/sdk/flutter/direct-call.mdx index 5b55bf4e9..d4b2fcc6e 100644 --- a/sdk/flutter/direct-call.mdx +++ b/sdk/flutter/direct-call.mdx @@ -1,11 +1,48 @@ --- title: "Call Session" +sidebarTitle: "Call Session" +description: "Learn how to start and manage direct call sessions in your Flutter application using the CometChat Calls SDK, including token generation, call settings, and session control." --- + + +```dart +// Generate call token +String sessionId = "SESSION_ID"; +String userAuthToken = await CometChat.getUserAuthToken(); + +CometChatCalls.generateToken(sessionId, userAuthToken, + onSuccess: (GenerateToken token) { + // Start call session + CallSettings callSettings = (CallSettingsBuilder() + ..defaultLayout = true + ..setAudioOnlyCall = false + ).build(); + + CometChatCalls.startSession(token.token!, callSettings, + onSuccess: (Widget? callingWidget) => debugPrint("Session started"), + onError: (CometChatCallsException e) => debugPrint("Error: ${e.message}"), + ); + }, + onError: (CometChatCallsException e) => debugPrint("Error: ${e.message}"), +); + +// End session +CometChatCalls.endSession( + onSuccess: (success) => debugPrint("Session ended"), + onError: (e) => debugPrint("Error: $e"), +); +``` + + ## Overview This section demonstrates how to start a call session in a Flutter application. Previously known as **Direct Calling**. + +**Available via:** SDK | [UI Kits](/ui-kit/flutter/overview) + + Before you begin, we strongly recommend you read the [calling setup guide](/sdk/flutter/calling-setup). @@ -41,9 +78,32 @@ CometChatCalls.generateToken( | 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. | | `userAuthToken` | The user auth token is the logged-in user auth token which you can get by calling `CometChat.getUserAuthToken()` | + +**On Success** — A `GenerateToken` object containing the call token for the session: + + + +**GenerateToken Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `token` | string | The generated call token used to start a session | `"v1.us-west-2.calls.a]..."` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to generate the call token."` | +| `details` | string | Additional technical details | `"The session ID or auth token provided is invalid."` | + + + ## Start Call Session Use the `startSession()` method to join a call session. This method requires a call token (generated in the previous step) and a `CallSettings` object that configures the call UI and behavior. @@ -70,6 +130,29 @@ CometChatCalls.startSession( ); ``` + +**On Success** — A `Widget?` representing the call UI to be displayed in your application: + + + +**Widget Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `callingWidget` | Widget? | A Flutter widget containing the call UI. Display this widget in your screen to show the call interface. | `Widget` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to start the call session."` | +| `details` | string | Additional technical details | `"The call token provided is invalid or expired."` | + + + ### Call Settings Configure the call experience using the following `CallSettingsBuilder` properties: @@ -101,6 +184,10 @@ Configure the call experience using the following `CallSettingsBuilder` properti The `CometChatCallsEventsListener` provides real-time callbacks for call session events, including participant changes, call state updates, and error conditions. + +Always remove call listeners when they're no longer needed (e.g., on widget dispose or screen navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + + 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 @@ -456,3 +543,22 @@ CometChatCalls.endSession( }, ); ``` + +--- + +## 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/flutter/edit-message.mdx b/sdk/flutter/edit-message.mdx index 76ae225c6..f9f54efde 100644 --- a/sdk/flutter/edit-message.mdx +++ b/sdk/flutter/edit-message.mdx @@ -1,26 +1,72 @@ --- -title: "Edit A Message" +title: "Edit Message" +sidebarTitle: "Edit Message" +description: "Edit text and custom messages using the CometChat Flutter SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +| Field | Value | +| --- | --- | +| Key Classes | `TextMessage`, `CustomMessage`, `BaseMessage` | +| Key Methods | `CometChat.editMessage()` | +| Listener Events | `onMessageEdited` | +| Prerequisites | SDK initialized, user logged in | -While editing a message is straightforward, receiving events for edited messages with CometChat has two parts: +```dart +// Edit a text message +TextMessage updatedMessage = TextMessage( + text: "Updated message text", + receiverUid: "receiver_uid", + receiverType: CometChatReceiverType.user, + type: CometChatMessageType.text, +); +updatedMessage.id = originalMessageId; + +await CometChat.editMessage(updatedMessage, + onSuccess: (BaseMessage message) { + debugPrint("Message edited: $message"); + }, + onError: (CometChatException e) { + debugPrint("Error: ${e.message}"); + }, +); + +// Listen for real-time edits +CometChat.addMessageListener("edits_listener", MessageListener( + onMessageEdited: (BaseMessage message) { + debugPrint("Message was edited: ${message.id}"); + }, +)); + +// Remove listener when done +CometChat.removeMessageListener("edits_listener"); +``` + + + +Editing a message is straightforward. Receiving edit events has two parts: -1. Adding a listener to receive [real-time message edit events](/sdk/flutter/edit-message#real-time-message-edit-events) when your app is running -2. Calling a method to retrieve [missed message edit events](/sdk/flutter/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?* +Use `editMessage()` with a [`TextMessage`](/sdk/reference/messages#textmessage) or [`CustomMessage`](/sdk/reference/messages#custommessage) object. Set the message ID using the `id` property. -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. +| Parameter | Type | Description | +| --- | --- | --- | +| `message` | `BaseMessage` | The message object to edit. Must be a `TextMessage` or `CustomMessage`. Set the `id` property to the ID of the message to edit. | +| `onSuccess` | `Function(BaseMessage)` | Callback triggered on success with the edited message object. | +| `onError` | `Function(CometChatException)` | Callback triggered on error with exception details. | ### 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 `tags` to update tags when editing. New tags replace existing ones. - + ```dart List tags = []; tags.add("pinned"); @@ -29,9 +75,18 @@ textMessage.tags = tags; + +```dart +List tags = []; +tags.add("pinned"); +customMessage.tags = 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()`. @@ -57,7 +112,103 @@ await CometChat.editMessage(updatedMessage, -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. + +**On Success** — A `BaseMessage` object containing all details of the edited message: + + + +**BaseMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `401` | +| `metadata` | object | Custom metadata attached to the message | `{}` | +| `receiver` | object | Receiver user object | [See below ↓](#edit-message-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `"cometchat-uid-1"` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `sentAt` | number | Epoch timestamp when the message was sent | `1745554729` | +| `receiverUid` | string | UID of the receiver | `"cometchat-uid-2"` | +| `type` | string | Type of the message | `"text"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `null` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `1745554750` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `0` | +| `replyCount` | number | Number of replies to this message | `0` | +| `sender` | object | Sender user object | [See below ↓](#edit-message-sender-object) | +| `receiverType` | string | Type of the receiver | `"user"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `1745554800` | +| `parentMessageId` | number | ID of the parent message (for threads) | `0` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"message"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` | +| `updatedAt` | number | Epoch timestamp when the message was last updated | `1745554800` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `quotedMessageId` | number | ID of the quoted message | `null` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-1"` | +| `name` | string | Display name of the sender | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-2"` | +| `name` | string | Display name of the receiver | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"The message could not be modified."` | +| `details` | string | Additional technical details | `"An unexpected error occurred while processing the request."` | + + + +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)). + +Relevant fields to access on the returned message: + +| Field | Property | Return Type | Description | +|-------|----------|-------------|-------------| +| editedAt | `editedAt` | `int` | Timestamp when the message was edited | +| editedBy | `editedBy` | `String` | UID of the user who edited the message | By default, CometChat allows certain roles to edit a message. @@ -70,9 +221,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. @@ -92,21 +241,56 @@ void onMessageEdited(BaseMessage message) { -## Missed Message Edit Events + +Always remove message listeners when they're no longer needed (e.g., in the `dispose()` method). Failing to remove listeners can cause memory leaks and duplicate event handling. -*In other words, as a recipient, how do I know when someone edited their message when my app was not running?* +```dart +@override +void dispose() { + CometChat.removeMessageListener("listenerId"); + super.dispose(); +} +``` + -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.. +The `onMessageEdited` callback receives a [`BaseMessage`](/sdk/reference/messages#basemessage) object with the `editedAt` and `editedBy` fields set. -For the message edited event, in the `Action` object received, the following fields can help you get the relevant information- +Relevant fields to access on the returned message: -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. +| Field | Property | Return Type | Description | +|-------|----------|-------------|-------------| +| editedAt | `editedAt` | `int` | Timestamp when the message was edited | +| editedBy | `editedBy` | `String` | UID of the user who edited the message | - +## Missed Message Edit Events -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. +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`](/sdk/reference/messages#action) object contains: +- `action` — `edited` +- `actionOn` — Updated message object with the edited details +- `actionBy` — User object containing the details of the user who has edited the message +- `actionFor` — User/group object having the details of the receiver to which the message was sent + + +You must be the message sender or a group admin/moderator to edit a message. + +--- + +## Next Steps + + + + Learn how to delete messages from conversations + + + Send text, media, and custom messages + + + Handle incoming messages in real-time + + + Create and manage message threads + + diff --git a/sdk/flutter/error-codes.mdx b/sdk/flutter/error-codes.mdx new file mode 100644 index 000000000..06e093208 --- /dev/null +++ b/sdk/flutter/error-codes.mdx @@ -0,0 +1,234 @@ +--- +title: "Error Codes" +sidebarTitle: "Error Codes" +description: "Complete reference for CometChat Flutter SDK error codes, including client-side validation errors, server-side API errors, and how to handle them." +--- + + + +```dart +String uid = "UID"; +String authKey = "AUTH_KEY"; + +// All errors are CometChatException objects +try { + User? user = await CometChat.login(uid, authKey: authKey); +} on CometChatException catch (e) { + debugPrint(e.code); // e.g., "AUTH_ERR_AUTH_TOKEN_NOT_FOUND" + debugPrint(e.message); // Human-readable description + debugPrint(e.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 three properties: + +| Property | Type | Description | +|----------|------|-------------| +| `code` | `String` | Machine-readable error code | +| `message` | `String?` | Human-readable description | +| `details` | `String?` | Additional context or troubleshooting info | + +```dart +try { + User? user = await CometChat.login(authToken); +} on CometChatException catch (e) { + switch (e.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: + debugPrint("Unexpected error: ${e.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. | + +## Notification Errors + +| Code | Message | +|------|---------| +| `INVALID_PUSH_PLATFORM` | An invalid Push Platform was detected. Please submit a valid push platform to proceed. | +| `INVALID_FCM_TOKEN` | An invalid FCM token was detected. Please submit a valid token to proceed. | +| `INVALID_APNS_DEVICE_TOKEN` | An invalid APNs Device token was detected. Please submit a valid token to proceed. | +| `INVALID_APNS_VOIP_TOKEN` | An invalid APNs VoIP token was detected. Please submit a valid token to proceed. | + +## 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/flutter/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/flutter/extensions-overview.mdx b/sdk/flutter/extensions-overview.mdx index 29c1774bd..5dcf22fb9 100644 --- a/sdk/flutter/extensions-overview.mdx +++ b/sdk/flutter/extensions-overview.mdx @@ -1,4 +1,144 @@ --- title: "Extensions" +sidebarTitle: "Extensions" +description: "Explore CometChat extensions that add enhanced functionality to your Flutter chat application" url: "/fundamentals/extensions-overview" ---- \ No newline at end of file +--- + + +**What are Extensions?** +Extensions are add-on features that extend CometChat's core functionality beyond basic messaging. + +**How to Enable:** +1. Go to [CometChat Dashboard](https://app.cometchat.com) +2. Navigate to your App → Extensions +3. Enable desired extensions +4. Extensions activate automatically on SDK initialization + +**Extension Categories:** +- **User Experience** → Pin message, Link preview, Thumbnails, Voice transcription +- **User Engagement** → Polls, Reactions, Mentions, Message translation, Stickers +- **Collaboration** → Whiteboard, Collaborative documents +- **Notifications** → Push, Email, SMS notifications +- **Moderation** → Content filtering, Profanity detection +- **Security** → Disappearing messages, End-to-end encryption + +**Full Extension List:** [Extensions Overview](/fundamentals/extensions-overview) + + +Extensions extend CometChat's core functionality, adding enhanced features to your chat application. They help you build a complete chat experience beyond basic voice, video, and text messaging. + +## How Extensions Work + +Extensions are enabled through the CometChat Dashboard and automatically integrate with your Flutter application upon SDK initialization and successful login. Once enabled, extension features become available without additional SDK configuration. + +## Enabling Extensions + + + + Log in to the [CometChat Dashboard](https://app.cometchat.com) and select your application. + + + Go to the Extensions section in your app settings. + + + Toggle on the extensions you want to use in your application. + + + Extensions activate automatically when your Flutter app initializes the CometChat SDK. + + + +## Available Extension Categories + +### User Experience + +Extensions that improve the messaging experience: + +| Extension | Description | +| --- | --- | +| Pin Message | Allow users to pin important messages | +| Link Preview | Automatically generate previews for shared links | +| Rich Media Preview | Enhanced media previews for images and videos | +| Thumbnail Generation | Auto-generate thumbnails for media files | +| Voice Transcription | Convert voice messages to text | +| Save Message | Let users bookmark messages for later | + +### User Engagement + +Extensions that increase user interaction: + +| Extension | Description | +| --- | --- | +| Polls | Create and vote on polls within chats | +| Reactions | Add emoji reactions to messages | +| Mentions | Tag users in messages with @mentions | +| Message Translation | Translate messages to different languages | +| Smart Reply | AI-powered reply suggestions | +| Stickers | Send stickers in conversations | +| Giphy/Tenor | Search and share GIFs | + +### Collaboration + +Extensions for team collaboration: + +| Extension | Description | +| --- | --- | +| Collaborative Whiteboard | Real-time whiteboard for visual collaboration | +| Collaborative Document | Edit documents together in real-time | + +### Notifications + +Extensions for alerting users: + +| Extension | Description | +| --- | --- | +| Push Notifications | Mobile and web push alerts | +| Email Notifications | Email alerts for missed messages | +| SMS Notifications | Text message alerts | + +### Moderation + +Extensions for content safety: + +| Extension | Description | +| --- | --- | +| Profanity Filter | Automatically filter inappropriate content | +| Image Moderation | Detect and filter inappropriate images | +| Data Masking | Mask sensitive information in messages | + +### Security + +Extensions for enhanced security: + +| Extension | Description | +| --- | --- | +| Disappearing Messages | Messages that auto-delete after a set time | +| End-to-End Encryption | Secure message encryption | + +## Extension Support in UI Kit + +If you're using CometChat UI Kit for Flutter, many extensions are automatically supported and rendered in the UI. Extension features will only be available if they are supported by the CometChat UI Kit. + + +For detailed information on each extension, including configuration options and usage, visit the [Extensions Overview](/fundamentals/extensions-overview) in the fundamentals documentation. + + +--- + +## Next Steps + + + + Explore all available SDK resources and documentation + + + Configure webhooks for real-time event notifications + + + Understand API rate limits and quotas + + + Handle real-time events in your application + + diff --git a/sdk/flutter/flag-message.mdx b/sdk/flutter/flag-message.mdx index 02b71550c..a2f8d6530 100644 --- a/sdk/flutter/flag-message.mdx +++ b/sdk/flutter/flag-message.mdx @@ -1,11 +1,48 @@ --- title: "Flag Message" +sidebarTitle: "Flag Message" +description: "Learn how to flag and report inappropriate messages for moderation review in your Flutter application using CometChat SDK." --- +{/* TL;DR for Agents and Quick Reference */} + + +```dart +// Get available flag reasons +CometChat.getFlagReasons( + onSuccess: (List reasons) { + debugPrint("Flag reasons: $reasons"); + }, + onError: (CometChatException e) { + debugPrint("Error: ${e.message}"); + }, +); + +// Flag a message +FlagDetail flagDetail = FlagDetail( + reasonId: "spam", + remark: "Optional additional context", +); + +CometChat.flagMessage(messageId, flagDetail, + onSuccess: (String response) { + debugPrint("Message flagged: $response"); + }, + onError: (CometChatException e) { + debugPrint("Error: ${e.message}"); + }, +); +``` + + ## 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. @@ -51,7 +88,7 @@ Before flagging a message, retrieve the list of available flag reasons configure print("Flag reasons fetched: $reasons"); // Use reasons to populate your report dialog UI for (var reason in reasons) { - print("Reason ID: ${reason.id}, Title: ${reason.title}"); + print("Reason ID: ${reason.id}, Name: ${reason.name}"); } }, onError: (CometChatException e) { @@ -68,8 +105,21 @@ The response is a list of `FlagReason` objects containing: | Property | Type | Description | |----------|------|-------------| -| id | String | Unique identifier for the reason | -| title | String | Display text for the reason | +| `id` | `String` | Unique identifier for the reason | +| `name` | `String` | Display name for the reason | +| `description` | `String?` | Optional description of the reason | +| `createdAt` | `DateTime?` | Timestamp when the reason was created | +| `updatedAt` | `DateTime?` | Timestamp when the reason was last updated | + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | `String` | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | `String` | Human-readable error message | `"Failed to fetch flag reasons."` | +| `details` | `String` | Additional technical details | `"An unexpected error occurred while processing the request."` | + + ## Flag a Message @@ -80,9 +130,10 @@ To flag a message, use the `flagMessage()` method with the message ID and a `Fla ```dart int messageId = 123; // ID of the message to flag - FlagDetail flagDetail = FlagDetail() - ..reasonId = "spam" // Required: ID from getFlagReasons() - ..remark = "This message contains promotional content"; // Optional + FlagDetail flagDetail = FlagDetail( + reasonId: "spam", // Required: ID from getFlagReasons() + remark: "This message contains promotional content", // Optional + ); CometChat.flagMessage( messageId, @@ -102,18 +153,29 @@ To flag a message, use the `flagMessage()` method with the message ID and a `Fla | Parameter | Type | Required | Description | |-----------|------|----------|-------------| -| messageId | int | Yes | The ID of the message to flag | -| flagDetail | FlagDetail | Yes | Contains flagging details | -| flagDetail.reasonId | String | Yes | ID of the flag reason (from `getFlagReasons()`) | -| flagDetail.remark | String | No | Additional context or explanation from the user | +| `messageId` | `int` | Yes | The ID of the message to flag | +| `flagDetail` | `FlagDetail` | Yes | Contains flagging details | +| `flagDetail.reasonId` | `String` | Yes | ID of the flag reason (from `getFlagReasons()`) | +| `flagDetail.remark` | `String?` | No | Additional context or explanation from the user | -### Response + +**On Success** — A `String` message confirming the message has been flagged: -```json -{ - "message": "Message {id} has been flagged successfully." -} -``` +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `message` | `String` | Success confirmation message | `"Message 123 has been flagged successfully."` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | `String` | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | `String` | Human-readable error message | `"Failed to flag the message."` | +| `details` | `String` | Additional technical details | `"An unexpected error occurred while processing the request."` | + + ## Complete Example @@ -154,12 +216,10 @@ Here's a complete implementation showing how to build a report message flow: }) async { final completer = Completer(); - FlagDetail flagDetail = FlagDetail() - ..reasonId = reasonId; - - if (remark != null) { - flagDetail.remark = remark; - } + FlagDetail flagDetail = FlagDetail( + reasonId: reasonId, + remark: remark, + ); CometChat.flagMessage( messageId, @@ -197,3 +257,22 @@ Here's a complete implementation showing how to build a report message flow: ``` + +--- + +## Next Steps + + + + Handle incoming messages and real-time events + + + Remove messages from conversations + + + Automate content moderation with AI + + + Track message delivery and read status + + diff --git a/sdk/flutter/flutter-overview.mdx b/sdk/flutter/flutter-overview.mdx index acc4dc70c..fd2f6eb35 100644 --- a/sdk/flutter/flutter-overview.mdx +++ b/sdk/flutter/flutter-overview.mdx @@ -1,4 +1,118 @@ --- title: "Flutter Chat UI Kit" +sidebarTitle: "Flutter Overview" +description: "Complete guide to integrating CometChat's Flutter SDK for real-time messaging, voice/video calling, and AI features in your Flutter applications." url: "/ui-kit/flutter/overview" ---- \ No newline at end of file +--- + +{/* TL;DR for Agents and Quick Reference */} + + +The CometChat Flutter SDK provides a complete set of tools for building real-time chat, voice, and video calling into Flutter apps (iOS, Android, Web, Desktop). + +**Key Capabilities:** +- **Messaging** — 1:1 and group chat, threads, reactions, typing indicators, read receipts, file sharing, interactive messages +- **Calling** — Voice and video calls, ringing flows, direct calls, recording, screen sharing +- **Users & Groups** — User management, presence tracking, group creation, member management, roles +- **AI Features** — AI agents, moderation, chatbots, user copilot +- **Real-time** — WebSocket-based listeners for messages, users, groups, calls, and connection status + +**Quick Links:** +- [Setup](/sdk/flutter/setup) — Install and initialize the SDK +- [Authentication](/sdk/flutter/authentication-overview) — Login and user management +- [Messaging](/sdk/flutter/messaging-overview) — Send, receive, edit messages +- [Users](/sdk/flutter/users-overview) — User presence, retrieval, blocking +- [Groups](/sdk/flutter/groups-overview) — Create, join, manage groups +- [Calling](/sdk/flutter/calling-overview) — Voice and video calls +- [AI Features](/sdk/flutter/ai-agents) — AI-powered chat capabilities +- [Key Concepts](/sdk/flutter/key-concepts) — Core SDK concepts and terminology + +**Credentials:** App ID, Region, Auth Key from [CometChat Dashboard](https://app.cometchat.com) + + +The CometChat Flutter SDK lets you add real-time messaging, voice, and video calling to any Flutter application — iOS, Android, Web, or Desktop. For pre-built, customizable UI widgets, see the [Flutter UI Kit](/ui-kit/flutter/overview). + +## Quick Navigation + +Choose your path: + + + + Install and initialize the CometChat Flutter SDK + + + Learn core concepts before building + + + Start sending text and media messages + + + Add real-time calling to your app + + + +## Flutter UI Kit + +Skip the UI work — use pre-built, customizable Flutter widgets for chat, voice, and video calling: + + + + Pre-built widgets for chat, calling, and more + + + Install, initialize, and build your first chat screen + + + +## Sample Apps + +Explore working examples with full source code: + + + + Flutter SDK sample app + + + Flutter UI Kit sample project + + + +## Resources + + + + Manage your app, API keys, and settings + + + UIDs, GUIDs, auth tokens, and core SDK concepts + + + Latest SDK version and release notes + + + Migration guide for V3 users + + + +## Next Steps + + + + Add the CometChat SDK to your Flutter project + + + Detailed initialization and configuration options + + + Learn about Auth Keys vs Auth Tokens for production + + + Start sending text, media, and custom messages + + + Add voice and video calling to your app + + + Pre-built UI widgets for rapid integration + + diff --git a/sdk/flutter/group-add-members.mdx b/sdk/flutter/group-add-members.mdx index e125be98b..36b38943c 100644 --- a/sdk/flutter/group-add-members.mdx +++ b/sdk/flutter/group-add-members.mdx @@ -1,16 +1,57 @@ --- 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 Flutter SDK." --- + +```dart +// Add members to a group +List members = [ + GroupMember.fromUid(uid: "UID", scope: CometChatMemberScope.participant, name: "User 1"), +]; + +CometChat.addMembersToGroup( + guid: "GUID", + groupMembers: members, + onSuccess: (Map result) { + debugPrint("Members added: $result"); + }, + onError: (CometChatException e) { + debugPrint("Error: ${e.message}"); + }, +); + +// Listen for member added events +class MyGroupListener with GroupListener { + @override + void onMemberAddedToGroup(Action action, User addedby, User userAdded, Group addedTo) { + debugPrint("Member added: ${userAdded.name}"); + } +} +CometChat.addGroupListener("listenerId", MyGroupListener()); +``` + + +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 -You can add members to the group using the `addMembersToGroup()` method. This method takes the below parameters: + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) + + +Use `addMembersToGroup()` to add members to a [Group](/sdk/flutter/retrieve-groups). -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. +| Parameter | Type | Description | +|-----------|------|-------------| +| `guid` | `String` | The GUID of the group to add members to | +| `groupMembers` | `List` | List of [GroupMember](/sdk/reference/entities#groupmember) objects (UID and scope required) | +| `onSuccess` | `Function(Map)` | Callback with a map of UIDs to result status | +| `onError` | `Function(CometChatException)` | Callback triggered on failure | + +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. @@ -38,21 +79,39 @@ CometChat.addMembersToGroup( guid: conversationWith, -In the `onSuccess()` method , you will receive a Map 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 or ban the user failed. + +**On Success** — A `Map` where each key is the UID of the user 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?* +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `cometchat-uid-3` | string | Result for the first member added | `"success"` | +| `cometchat-uid-4` | string | Result for the second member added | `"success"` | - + -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. + - + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_GUID_NOT_FOUND"` | +| `message` | string | Human-readable error message | `"The specified group does not exist."` | +| `details` | string | Additional technical details | `"Please provide a valid group GUID."` | -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. +In the `onSuccess()` callback, you will receive a `Map` 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 failed. + +## Real-Time Group Member Added Events + + +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. + + +Implement `onMemberAddedToGroup()` in `GroupListener` to receive real-time notifications when members are added. @@ -71,15 +130,49 @@ void onMemberAddedToGroup(Action action, User addedby, User userAdded, Group add -## Member Added to Group event in Message History +| Callback Parameter | Type | Description | +|--------------------|------|-------------| +| `action` | `Action` | The action object containing details of the event | +| `addedby` | `User` | The user who added the member | +| `userAdded` | `User` | The user who was added to the group | +| `addedTo` | `Group` | The group the member was added to | -*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?* + +Always remove group listeners when they're no longer needed (e.g., in `dispose()`). Failing to remove listeners can cause memory leaks and duplicate event handling. -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. +```dart +CometChat.removeGroupListener("group_Listener_id"); +``` + + +## Missed Member Added Events + +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- +For the group member added event, in the `Action` object received, the following fields can help you get the relevant information: + +| 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 | + +--- -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 +## 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/flutter/group-change-member-scope.mdx b/sdk/flutter/group-change-member-scope.mdx index 412b54b93..0420f4fdb 100644 --- a/sdk/flutter/group-change-member-scope.mdx +++ b/sdk/flutter/group-change-member-scope.mdx @@ -1,12 +1,37 @@ --- 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 Flutter SDK." --- + +```dart +// Change member scope to admin +CometChat.updateGroupMemberScope( + guid: "GROUP_ID", + uid: "USER_ID", + scope: CometChatMemberScope.admin, + onSuccess: (String message) => debugPrint("Scope updated: $message"), + onError: (CometChatException e) => debugPrint("Error: ${e.message}"), +); + +// Listen for scope change events +CometChat.addGroupListener("listener_id", GroupListenerImpl()); + +// Scopes: CometChatMemberScope.admin, .moderator, .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 -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). + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) + @@ -15,12 +40,12 @@ String UID = "UID"; String GUID = "GUID"; String scope = CometChatMemberScope.admin; -CometChat.updateGroupMemberScope(guid: GUID, uid: UID,scope: scope, +CometChat.updateGroupMemberScope(guid: GUID, uid: UID, scope: scope, onSuccess: (String message) { - debugPrint("Group Member Scope Changed Successfully : $message"); + debugPrint("Group Member Scope Changed Successfully : $message"); }, onError: (CometChatException e) { - debugPrint("Group Member Scope Change failed : ${e.message}"); + debugPrint("Group Member Scope Change failed : ${e.message}"); }); ``` @@ -30,19 +55,42 @@ CometChat.updateGroupMemberScope(guid: GUID, uid: UID,scope: scope, 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.`CometChatMemberScope.`*admin* (admin) 2.`CometChatMemberScope.`*moderator* (moderator) 3.`CometChatMemberScope.`*participant* (participant) | +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `guid` | `String` | The GUID of the group for which the member's scope needs to be changed | +| `uid` | `String` | The UID of the member whose scope you would like to change | +| `scope` | `String` | The updated scope: `CometChatMemberScope.admin`, `CometChatMemberScope.moderator`, or `CometChatMemberScope.participant` | +| `onSuccess` | `Function(String)` | Callback triggered on successful scope change | +| `onError` | `Function(CometChatException)` | Callback triggered on error | The default scope of any member is `participant`. Only the **Admin** of the group can change the scope of any participant in the group. -## Real-Time Group Member Scope Changed Events + +**On Success** — A `String` message confirming the scope change: + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `message` | string | Success confirmation message | `"cometchat-guid-1 scope changed successfully"` | + + + + -*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 whenever a group member's scope changes, you will need to override the `onGroupMemberScopeChanged()` method of the `GroupListener` class +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_NOT_A_MEMBER"` | +| `message` | string | Human-readable error message | `"The user is not a member of this group."` | +| `details` | string | Additional technical details | `"Cannot change scope for a user who is not a member of the group."` | + + + +## Real-Time Group Member Scope Changed Events + +Implement `onGroupMemberScopeChanged()` in `GroupListener` to receive real-time notifications when a member's scope changes. @@ -62,17 +110,42 @@ void onGroupMemberScopeChanged(Action action, User updatedBy, User updatedUser, + +Always remove group listeners when they're no longer needed (e.g., in the `dispose()` method). Failing to remove listeners can cause memory leaks and duplicate event handling. + +```dart +CometChat.removeGroupListener("group_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 fetching previous messages, scope changes appear as [Action](/sdk/reference/messages#action) messages (a subclass of `BaseMessage`). -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. +| 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 | -For the group member scope changed event, in the `Action` object received, the following fields can help you get the relevant information- +--- -1. `action` - `scopeChanged` -2. `actionOn` - User object containing the details of the user whos 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 +## 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/flutter/group-kick-ban-members.mdx b/sdk/flutter/group-kick-ban-members.mdx new file mode 100644 index 000000000..af6112843 --- /dev/null +++ b/sdk/flutter/group-kick-ban-members.mdx @@ -0,0 +1,413 @@ +--- +title: "Ban Or Kick Member From A Group" +sidebarTitle: "Kick & Ban Members" +description: "Learn how to kick, ban, and unban members from groups using the CometChat Flutter SDK, including real-time event handling." +--- + + + +```dart +// Kick a member from group +CometChat.kickGroupMember( + guid: "GROUP_ID", + uid: "USER_ID", + onSuccess: (String message) => debugPrint("Kicked: $message"), + onError: (CometChatException e) => debugPrint("Error: ${e.message}"), +); + +// Ban a member from group +CometChat.banGroupMember( + guid: "GROUP_ID", + uid: "USER_ID", + onSuccess: (String message) => debugPrint("Banned: $message"), + onError: (CometChatException e) => debugPrint("Error: ${e.message}"), +); + +// Unban a member +CometChat.unbanGroupMember( + guid: "GROUP_ID", + uid: "USER_ID", + onSuccess: (String message) => debugPrint("Unbanned: $message"), + onError: (CometChatException e) => debugPrint("Error: ${e.message}"), +); + +// Fetch banned members +BannedGroupMembersRequest request = (BannedGroupMembersRequestBuilder(guid: "GUID") + ..limit = 30 +).build(); +request.fetchNext( + onSuccess: (List members) => debugPrint("Banned: $members"), + onError: (CometChatException e) => debugPrint("Error: ${e.message}"), +); +``` + + +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. + +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. + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) + + +## Kick a Group Member + +The Admin or Moderator of a group can kick a member out of the group using the `kickGroupMember()` method. + + + +```dart +String uid= "cometchat-uid-3"; +String guid = "GUID"; +CometChat.kickGroupMember(guid: guid,uid: uid, + onSuccess: (String message) { + debugPrint("Group Member Kicked Successfully : $message"); + }, onError: (CometChatException e) { + debugPrint("Group Member Kicked failed : ${e.message}"); + }); +``` + + + + + +The `kickGroupMember()` takes following parameters: + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `guid` | `String` | The GUID of the group from which user is to be kicked | +| `uid` | `String` | The UID of the user to be kicked | +| `onSuccess` | `Function(String)` | Callback triggered on successful kick | +| `onError` | `Function(CometChatException)` | Callback triggered on error | + +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** — A `String` message confirming the member was kicked: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `message` | string | Success confirmation message | `"cometchat-uid-3 kicked successfully"` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_NOT_A_MEMBER"` | +| `message` | string | Human-readable error message | `"The user is not a member of this group."` | +| `details` | string | Additional technical details | `"Please verify the user ID and group ID and try again."` | + + + +## Ban a Group Member + +The Admin or Moderator of the group can ban a member from the group using the `banGroupMember()` method. Unlike kicked users, banned users cannot rejoin until unbanned. + + + +```dart +String uid= "cometchat-uid-3"; +String guid = "GUID"; +CometChat.banGroupMember(guid: guid,uid: uid, + onSuccess: (String message) { + debugPrint("Group Member Banned Successfully : $message"); + },onError: (CometChatException e) { + debugPrint("Group Member Ban failed : ${e.message}"); + }); +``` + + + + + +The `banGroupMember()` method takes the following parameters: + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `guid` | `String` | The GUID of the group from which user is to be banned | +| `uid` | `String` | The UID of the user to be banned | +| `onSuccess` | `Function(String)` | Callback triggered on successful ban | +| `onError` | `Function(CometChatException)` | Callback triggered on error | + +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** — A `String` message confirming the member was banned: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `message` | string | Success confirmation message | `"cometchat-uid-3 banned successfully"` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_NOT_A_MEMBER"` | +| `message` | string | Human-readable error message | `"The user is not a member of this group."` | +| `details` | string | Additional technical details | `"Please verify the user ID and group ID and try again."` | + + + +## 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. + + + +```dart +String uid= "cometchat-uid-3"; +String guid = "GUID"; +CometChat.unbanGroupMember(guid: guid,uid: uid, + onSuccess: (String message) { + debugPrint("Group Member Unbanned Successfully : $message"); + }, + onError: (CometChatException e) { + debugPrint("Group Member Unban failed : ${e.message}"); + }); +``` + + + + + +The `unbanGroupMember()` method takes the following parameters + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `guid` | `String` | The GUID of the group from which user is to be unbanned | +| `uid` | `String` | The UID of the user to be unbanned | +| `onSuccess` | `Function(String)` | Callback triggered on successful unban | +| `onError` | `Function(CometChatException)` | Callback triggered on error | + +The unbanned user can now rejoin the group. + + +**On Success** — A `String` message confirming the member was unbanned: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `message` | string | Success confirmation message | `"cometchat-uid-3 unbanned successfully"` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_NOT_A_MEMBER"` | +| `message` | string | Human-readable error message | `"The user is not a member of this group."` | +| `details` | string | Additional technical details | `"Please verify the user ID and group ID and try again."` | + + + +## 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. + +### Set Limit + +This method sets the limit i.e. the number of banned members that should be fetched in a single iteration. + + + +```dart +BannedGroupMembersRequestBuilder builder = BannedGroupMembersRequestBuilder(guid: conversationWith); +BannedGroupMembersRequest bannedGroupMembersRequest = (builder + ..limit = 50 + ).build(); +``` + + + + + +### Set Search Keyword + +This method allows you to set the search string based on which the banned group members are to be fetched. + + + +```dart +BannedGroupMembersRequestBuilder builder = BannedGroupMembersRequestBuilder(guid: conversationWith); +BannedGroupMembersRequest bannedGroupMembersRequest = (builder + ..limit = 50 + ..searchKeyword = "abc" + ).build(); +``` + + + + + +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`](/sdk/reference/entities#groupmember) objects containing n number of banned members where n is the limit set in the builder class. + + + +```dart +BannedGroupMembersRequestBuilder builder = BannedGroupMembersRequestBuilder(guid: conversationWith); +BannedGroupMembersRequest bannedGroupMembersRequest = (builder + ..limit = 50 + ).build(); + +bannedGroupMembersRequest.fetchNext( onSuccess: (List groupMembers) { + debugPrint("Banned Group Members Fetched Successfully : $groupMembers"); + },onError: (CometChatException e) { + debugPrint("Banned Group Members Fetch failed with exception: ${e.message}"); + }); +``` + + + + + + +**On Success** — A `List` containing the banned group members for the specified group (each item is a `GroupMember` object): + + + +**GroupMember Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-3"` | +| `name` | string | Display name of the user | `"Kevin Hart"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | +| `scope` | string | Member scope in the group | `"participant"` | +| `joinedAt` | number | Epoch timestamp when the member joined the group | `1745550000` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_NOT_A_MEMBER"` | +| `message` | string | Human-readable error message | `"The user is not a member of this group."` | +| `details` | string | Additional technical details | `"Please verify the group ID and try again."` | + + + +## 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?* + +Implement these `GroupListener` methods to receive real-time notifications: + +| Method | Triggered When | +|--------|----------------| +| `onGroupMemberKicked()` | A member is kicked | +| `onGroupMemberBanned()` | A member is banned | +| `onGroupMemberUnbanned()` | A member is unbanned | + + + +```dart +class Class_Name with GroupListener { + +//CometChat.addGroupListener("group_Listener_id", this); + +@override +void onGroupMemberKicked(Action action, User kickedUser, User kickedBy, Group kickedFrom) { + print("onGroupMemberKicked "); +} +void onGroupMemberBanned(Action action, User bannedUser, User bannedBy, Group bannedFrom) { + + print("onGroupMemberBanned "); +} + +@override +void onGroupMemberUnbanned(Action action, User unbannedUser, User unbannedBy, Group unbannedFrom) { + print("onGroupMemberUnbanned "); +} +} +``` + + + + + + +Always remove group listeners when they're no longer needed (e.g., in the `dispose()` method). Failing to remove listeners can cause memory leaks and duplicate event handling. + +```dart +CometChat.removeGroupListener("group_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`](/sdk/reference/messages#action) message. An `Action` message is a sub-class of [`BaseMessage`](/sdk/reference/messages#basemessage) class. + +**Kicked event:** + +| Field | Value/Type | Description | +|-------|------------|-------------| +| `action` | `"kicked"` | The action type | +| `actionBy` | User | The user who kicked the member | +| `actionOn` | User | The member who was kicked | +| `actionFor` | Group | The group from which the member was kicked | + +**Banned event:** + +| Field | Value/Type | Description | +|-------|------------|-------------| +| `action` | `"banned"` | The action type | +| `actionBy` | User | The user who banned the member | +| `actionOn` | User | The member who was banned | +| `actionFor` | Group | The group from which the member was banned | + +**Unbanned event:** + +| Field | Value/Type | Description | +|-------|------------|-------------| +| `action` | `"unbanned"` | The action type | +| `actionBy` | User | The user who unbanned the member | +| `actionOn` | User | The member who was unbanned | +| `actionFor` | Group | The group from which the member was unbanned | + +--- + +## Next Steps + + + + Add new members to your groups + + + Update member roles and permissions + + + Fetch the list of members in a group + + + Allow members to leave a group + + diff --git a/sdk/flutter/group-kick-member.mdx b/sdk/flutter/group-kick-member.mdx deleted file mode 100644 index adaa4c841..000000000 --- a/sdk/flutter/group-kick-member.mdx +++ /dev/null @@ -1,235 +0,0 @@ ---- -title: "Ban/Kick Member From A Group" ---- - - - -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. - -## Kick a Group Member - -The Admin or Moderator of a group can kick a member out of the group using the `kickGroupMember()` method. - - - -```dart -String uid= "cometchat-uid-3"; -String guid = "GUID"; -CometChat.kickGroupMember(guid: guid,uid: uid, - onSuccess: (String message) { - debugPrint("Group Member Kicked Successfully : $message"); - }, onError: (CometChatException e) { - debugPrint("Group Member Kicked failed : ${e.message}"); - }); -``` - - - - - -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. - -## Ban a Group Member - -The Admin or Moderator of the group can ban a member from the group using the `banGroupMember()` method. - - - -```dart -String uid= "cometchat-uid-3"; -String guid = "GUID"; -CometChat.banGroupMember(guid: guid,uid: uid, - onSuccess: (String message) { - debugPrint("Group Member Banned Successfully : $message"); - },onError: (CometChatException e) { - debugPrint("Group Member Ban failed : ${e.message}"); - }); -``` - - - - - -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 group same group without being unbanned. - -## 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. - - - -```dart -String uid= "cometchat-uid-3"; -String guid = "GUID"; -CometChat.unbanGroupMember(guid: guid,uid: uid, - onSuccess: (String message) { - debugPrint("Group Member Unbanned Successfully : $message"); - }, - onError: (CometChatException e) { - debugPrint("Group Member Unban failed : ${e.message}"); - }); -``` - - - - - -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 | - -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. - -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. - -### Set Limit - -This method sets the limit i.e. the number of banned members that should be fetched in a single iteration. - - - -```dart -BannedGroupMembersRequestBuilder builder = BannedGroupMembersRequestBuilder(guid: conversationWith); -BannedGroupMembersRequest bannedGroupMembersRequest = (builder - ..limit = 50 - ).build(); -``` - - - - - -### Set Search Keyword - -This method allows you to set the search string based on which the banned group members are to be fetched. - - - -```dart -BannedGroupMembersRequestBuilder builder = BannedGroupMembersRequestBuilder(guid: conversationWith); -BannedGroupMembersRequest bannedGroupMembersRequest = (builder - ..limit = 50 - ..searchKeyword = "abc" - ).build(); -``` - - - - - -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. - - - -```dart -BannedGroupMembersRequestBuilder builder = BannedGroupMembersRequestBuilder(guid: conversationWith); -BannedGroupMembersRequest bannedGroupMembersRequest = (builder - ..limit = 50 - ).build(); - -bannedGroupMembersRequest.fetchNext( onSuccess: (List groupMembers) { - debugPrint("Banned Group Members Fetched Successfully : $groupMembers"); - },onError: (CometChatException e) { - debugPrint("Banned Group Members Fetch failed with exception: ${e.message}"); - }); -``` - - - - - -## 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. - - - -```dart -class Class_Name with GroupListener { - -//CometChat.addGroupListener("group_Listener_id", this); - -@override -void onGroupMemberKicked(Action action, User kickedUser, User kickedBy, Group kickedFrom) { - print("onGroupMemberKicked "); -} -void onGroupMemberBanned(Action action, User bannedUser, User bannedBy, Group bannedFrom) { - - print("onGroupMemberBanned "); -} - -@override -void onGroupMemberUnbanned(Action action, User unbannedUser, User unbannedBy, Group unbannedFrom) { - print("onGroupMemberUnbanned "); -} -} -``` - - - - - -## 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. - -For group member kicked event, the details can be obtained using the below fields of the `Action` class- - -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 - -For group member banned event, the details can be obtained using the below fields of the `Action` class- - -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 - -For group member unbanned event, the details can be obtained using the below fields of the `Action` class- - -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 diff --git a/sdk/flutter/groups-overview.mdx b/sdk/flutter/groups-overview.mdx index 99e877026..3e27ebc8c 100644 --- a/sdk/flutter/groups-overview.mdx +++ b/sdk/flutter/groups-overview.mdx @@ -1,10 +1,75 @@ --- title: "Groups" sidebarTitle: "Overview" +description: "Overview of group management in the CometChat Flutter SDK including group types, member roles, and available operations." --- + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Key Classes | `CometChat`, `Group`, `GroupMember` | +| 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/flutter/create-group), [Join Group](/sdk/flutter/join-group), [Retrieve Groups](/sdk/flutter/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. + -Each group includes three kinds of users- admin, 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. + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/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 | + +## Available Operations + +- [Create a Group](/sdk/flutter/create-group) — Create public, private, or password-protected groups +- [Join a Group](/sdk/flutter/join-group) — Join existing groups as a participant +- [Leave a Group](/sdk/flutter/leave-group) — Leave a group you're a member of +- [Update a Group](/sdk/flutter/update-group) — Update group name, description, icon, and settings +- [Delete a Group](/sdk/flutter/delete-group) — Permanently delete a group (owner only) +- [Transfer Ownership](/sdk/flutter/transfer-group-ownership) — Transfer group ownership to another member +- [Retrieve Groups](/sdk/flutter/retrieve-groups) — Fetch and filter the list of groups +- [Retrieve Group Members](/sdk/flutter/retrieve-group-members) — Get the member list for a group +- [Add Members](/sdk/flutter/group-add-members) — Add users to a group +- [Kick & Ban Members](/sdk/flutter/group-kick-ban-members) — Remove or ban members from a group +- [Change Member Scope](/sdk/flutter/group-change-member-scope) — Promote or demote members + +--- + +## 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/flutter/installation.mdx b/sdk/flutter/installation.mdx new file mode 100644 index 000000000..4e688be89 --- /dev/null +++ b/sdk/flutter/installation.mdx @@ -0,0 +1,110 @@ +--- +title: "Installation" +sidebarTitle: "Installation" +description: "Add the CometChat Flutter SDK to your project and configure platform-specific requirements for iOS and Android." +--- + + + +```yaml +# pubspec.yaml +dependencies: + cometchat_sdk: ^4.0.33 +``` + +```dart +import 'package:cometchat_sdk/cometchat_sdk.dart'; +``` + +**Key Points:** +- Add `cometchat_sdk` to your `pubspec.yaml` and run `flutter pub get` +- iOS: Update Podfile with simulator architecture exclusions, set deployment target to 11+, disable Bitcode +- Android: Requires API Level 21+, AndroidX compatibility +- Import `package:cometchat_sdk/cometchat_sdk.dart` wherever you need the SDK + + + +## Add the CometChat Dependency + +Add the CometChat SDK to your `pubspec.yaml` file: + +```yaml +dependencies: + cometchat_sdk: ^4.0.33 +``` + +Then run: + +```bash +flutter pub get +``` + +## Platform Configuration + +### iOS + +1. Add the following to your Podfile inside the iOS section of your app: + +```ruby +post_install do |installer| + installer.pods_project.targets.each do |target| + flutter_additional_ios_build_settings(target) + target.build_configurations.each do |build_configuration| + build_configuration.build_settings['EXCLUDED_ARCHS[sdk=iphonesimulator*]'] = 'arm64 i386' + end + end +end +``` + +2. Set the deployment target to `11` or higher. + +3. Navigate to your iOS folder in terminal and run `pod install`. For Apple Silicon systems, use a Rosetta terminal. + +4. In Xcode, set **Enable Bitcode** to **No** in your project's Build Settings. + + + + + +### Android + +- Minimum API Level: **21** +- AndroidX compatibility is required + +No additional configuration is needed for Android beyond ensuring these requirements are met. + +## Import the SDK + +Import the CometChat SDK in your Dart files: + +```dart +import 'package:cometchat_sdk/cometchat_sdk.dart'; +``` + +## 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 and 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 in your Flutter app + + + Learn how to authenticate users with Auth Keys and Auth Tokens + + diff --git a/sdk/flutter/interactive-messages.mdx b/sdk/flutter/interactive-messages.mdx index ce85974c3..e13d96a3e 100644 --- a/sdk/flutter/interactive-messages.mdx +++ b/sdk/flutter/interactive-messages.mdx @@ -1,81 +1,77 @@ --- title: "Interactive Messages" +sidebarTitle: "Interactive Messages" +description: "Send and receive interactive messages with embedded forms, buttons, and other UI elements using the CometChat Flutter SDK." --- + +| Field | Value | +| --- | --- | +| Key Classes | `InteractiveMessage`, `InteractionGoal`, `Interaction`, `InteractionReceipt` | +| Key Methods | `CometChat.sendInteractiveMessage()`, `CometChat.markAsInteracted()` | +| Key Constants | `InteractionGoalType.anyAction`, `InteractionGoalType.anyOf`, `InteractionGoalType.allOf`, `InteractionGoalType.none` | +| Listener Events | `onInteractiveMessageReceived`, `onInteractionGoalCompleted` | +| Prerequisites | SDK initialized, user logged in | -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` is a chat message with embedded interactive content. It can contain various properties: - -| Parameter | Description | -| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| receiverId | The UID or GUID of the recipient | -| 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) | -| messageType | The type of the message that needs to be sent | -| interactiveData | A JSONObject holding structured data for the interactive element | -| allowSenderInteraction | A boolean determining whether the message sender can interact with the message, by default, it is set to false | -| interactionGoal | An InteractionGoal object encapsulating the intended outcome of interacting with the InteractiveMessage, by default, it is set to none | - -### 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 - -This method marks a message as interacted by identifying it with the provided Id. it also logs the interactive element associated with the interaction. - - - ```dart -await CometChat.markAsInteracted(messageId, interactedElementId, - onSuccess: (String message ){ - //write code here for after success - - }, onError: - (CometChatException excep){ - //write code here for after err - - }); +// Create and send an interactive form message +InteractiveMessage interactiveMessage = InteractiveMessage( + interactiveData: interactiveData, // Map with form fields + receiverUid: "UID", + type: "form", + receiverType: CometChatReceiverType.user, + allowSenderInteraction: true, + interactionGoal: InteractionGoal(type: InteractionGoalType.none), +); +CometChat.sendInteractiveMessage(interactiveMessage, + onSuccess: (InteractiveMessage message) {}, + onError: (CometChatException e) {}, +); + +// Mark as interacted +CometChat.markAsInteracted(messageId, elementId, + onSuccess: (String message) {}, + onError: (CometChatException e) {}, +); + +// Listen for interactive messages +CometChat.addMessageListener("LISTENER_ID", this); +// onInteractiveMessageReceived(InteractiveMessage message) { } +// onInteractionGoalCompleted(InteractionReceipt receipt) { } ``` - - - - -### Goal Completion - -A key feature of `InteractiveMessage` is checking whether a user's interactions with the message meet the defined `InteractionGoal` - -| | | | -| -------------------------------- | ---------------------------------------------------------------------- | ----------------------------- | -| **Any Interaction** | The goal is considered completed if there is at least one interaction. | InteractionGoalType.anyAction | -| **Any of Specific Interactions** | The goal is achieved if any of the specified interactions occurred. | InteractionGoalType.anyOf | -| **All of Specific Interactions** | The goal is completed when all specified interactions occur. | InteractionGoalType.allOf | -| **None** | The goal is never completed | InteractionGoalType.none | - -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: + -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. +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. -### InteractionGoal + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) + -The `InteractionGoal` represents the desired outcome of an interaction with an InteractiveMessage. It includes: +## InteractiveMessage -* `elementIds`: A list of identifiers for the interactive elements. -* `type`: The type of interaction goal from the `CometChatConstants`. +The `InteractiveMessage` class extends `BaseMessage` and represents a message with embedded interactive content. -### Sending InteractiveMessages +| Parameter | Type | Description | Required | +| --- | --- | --- | --- | +| `receiverUid` | `String` | The UID of the user or GUID of the group | Yes | +| `receiverType` | `String` | `CometChatReceiverType.user` or `CometChatReceiverType.group` | Yes | +| `type` | `String` | Type identifier (e.g., `"form"`, `"card"`) | Yes | +| `interactiveData` | `Map` | JSON structure defining the interactive elements | Yes | +| `allowSenderInteraction` | `bool` | Whether sender can interact with the message | No (default: `false`) | +| `interactionGoal` | `InteractionGoal` | Defines when the interaction is considered complete | No (default: `none`) | +| `tags` | `List` | Tags associated with the message | No | +| `muid` | `String` | Unique message identifier for deduplication | No | +| `parentMessageId` | `int` | ID of the parent message (for threads) | No | +| `metadata` | `Map` | Custom metadata attached to the message | No | -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. +## Send an Interactive Message -Here is an example of how to use it: +Use `CometChat.sendInteractiveMessage()` to send an interactive message. - + ```dart final Map interactiveData = { "title": "Survey", @@ -173,18 +169,296 @@ print(excep); ``` + + +The `sendInteractiveMessage()` method returns an `InteractiveMessage` object on success. + + +**On Success** — An `InteractiveMessage` object containing all details of the sent interactive message: + + + +**InteractiveMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `501` | +| `metadata` | object | Custom metadata attached to the message | `{}` | +| `receiver` | object | Receiver user object | [See below ↓](#send-interactive-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `null` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-3"` | +| `sentAt` | number | Epoch timestamp when the message was sent | `1745554729` | +| `receiverUid` | string | UID of the receiver | `"cometchat-uid-3"` | +| `type` | string | Type of the message | `"form"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `null` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `0` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `0` | +| `replyCount` | number | Number of replies to this message | `0` | +| `sender` | object | Sender user object | [See below ↓](#send-interactive-sender-object) | +| `receiverType` | string | Type of the receiver | `"user"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `0` | +| `parentMessageId` | number | ID of the parent message (for threads) | `0` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"interactive"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` | +| `updatedAt` | number | Epoch timestamp when the message was last updated | `1745554729` | +| `interactiveData` | object | Structured data for the interactive element | `{"title": "Survey", "formFields": [...]}` | +| `interactions` | array | List of user interactions with the message | `[]` | +| `interactionGoal` | object | Intended outcome of interacting with the message | `{"type": "none", "elementIds": []}` | +| `tags` | array | List of tags associated with the message | `[]` | +| `allowSenderInteraction` | boolean | Whether the sender can interact with the message | `true` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `quotedMessageId` | number | ID of the quoted message | `null` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-1"` | +| `name` | string | Display name of the sender | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-3"` | +| `name` | string | Display name of the receiver | `"Kevin Hart"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to send the interactive message."` | +| `details` | string | Additional technical details | `"An unexpected error occurred while processing the request."` | + + + +## Interactive Elements + +The `interactiveData` map defines the UI elements. Common element types: + +| 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 | + +### Text Input + +```dart +{ + "elementType": "textInput", + "elementId": "name", + "optional": false, + "label": "Name", + "maxLines": 1, // Optional: limit to single line + "placeholder": {"text": "Enter text here"} +} +``` + +### Dropdown (Single Select) + +```dart +{ + "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) + +```dart +{ + "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 + +```dart +{ + "elementType": "button", + "elementId": "submitBtn", + "buttonText": "Submit", + "disableAfterInteracted": true, + "action": { + "actionType": "urlNavigation", + "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. +`InteractionGoal` Parameters: + +| Parameter | Type | Description | Required | +| --- | --- | --- | --- | +| `type` | `String` | The type of interaction goal (see goal types below) | Yes | +| `elementIds` | `List` | List of element IDs associated with this goal | No (default: `[]`) | + +| Goal Type | Constant | Description | +| --- | --- | --- | +| Any Interaction | `InteractionGoalType.anyAction` | Complete when any element is interacted with | +| Any of Specific | `InteractionGoalType.anyOf` | Complete when any of the specified elements is interacted with | +| All of Specific | `InteractionGoalType.allOf` | Complete when all specified elements are interacted with | +| None | `InteractionGoalType.none` | Never considered complete (default) | + +### Set an Interaction Goal + + + +```dart +List elementIds = ["name", "gender", "submitButton"]; +InteractionGoal interactionGoal = InteractionGoal( + type: InteractionGoalType.allOf, + elementIds: elementIds, +); + +InteractiveMessage interactiveMessage = InteractiveMessage( + interactiveData: interactiveData, + receiverUid: "cometchat-uid-3", + type: "form", + receiverType: "user", + interactionGoal: interactionGoal, +); + +CometChat.sendInteractiveMessage(interactiveMessage, + onSuccess: (InteractiveMessage message) { + debugPrint("Interactive message sent successfully: $message"); + }, + onError: (CometChatException excep) { + debugPrint("Interactive message sending failed with error: ${excep.message}"); + }, +); +``` + + -### Event Listeners +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. -CometChat SDK provides event listeners to handle real-time events related to `InteractiveMessage`. +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 InteractiveMessage Received +## Interactions -The `onInteractiveMessageReceived` event listener is triggered when an `InteractiveMessage` is received. +An `Interaction` represents a single user action on an interactive element. + +| Property | Type | Description | +| --- | --- | --- | +| `elementId` | `String` | Identifier of the interacted element | +| `interactedAt` | `DateTime` | Timestamp indicating when the interaction occurred | -Here is an example: +## Mark as Interacted + +Use `CometChat.markAsInteracted()` to record when a user interacts with an element. This method marks a message as interacted by identifying it with the provided ID and logs the interactive element associated with the interaction. + + + +```dart +Future recordInteraction() async { + int messageId = 0; // set to your interactive message id + String interactedElementId = ""; // set to the element id + + await CometChat.markAsInteracted( + messageId, + interactedElementId, + onSuccess: (String message) { + // after success + }, + onError: (CometChatException excep) { + // after error + }, + ); +} +``` + + + + +| Parameter | Type | Description | Required | +| --- | --- | --- | --- | +| `messageId` | `int` | The ID of the interactive message | Yes | +| `interactedElementId` | `String` | The element ID that was interacted with | Yes | + + +**On Success** — A `String` message confirming the interaction was recorded: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `message` | string | Success confirmation message | `"Message marked as interacted successfully."` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to mark the message as interacted."` | +| `details` | string | Additional technical details | `"An unexpected error occurred while processing the request."` | + + + +## Real-Time Events + +Register a `MessageListener` to receive interactive message events. + +### Receive Interactive Messages + +The `onInteractiveMessageReceived` event listener is triggered when an `InteractiveMessage` is received. @@ -208,14 +482,21 @@ void onInteractiveMessageReceived(InteractiveMessage message){ ``` - -### On Interaction Goal Completed +### Interaction Goal Completed The `onInteractionGoalCompleted` event listener is invoked when an interaction goal is achieved. -Here is an exampl +`InteractionReceipt` Properties: + +| Property | Type | Description | +| --- | --- | --- | +| `messageId` | `int` | The ID of the interactive message | +| `sender` | `User` | The user who completed the interaction | +| `receiverType` | `String` | Type of the receiver (`"user"` or `"group"`) | +| `receiverId` | `String` | UID or GUID of the receiver | +| `interactions` | `List` | List of interactions that satisfied the goal | @@ -238,11 +519,61 @@ void onInteractionGoalCompleted(InteractionReceipt receipt) { ``` - 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 + +Always remove listeners when they're no longer needed to prevent memory leaks. + +```dart +CometChat.removeMessageListener("UNIQUE_LISTENER_ID"); +``` + + +## Allow Sender Interaction + +By default, the sender cannot interact with their own interactive message. Set `allowSenderInteraction` to `true` to enable sender interaction: + + + +```dart +InteractiveMessage interactiveMessage = InteractiveMessage( + interactiveData: interactiveData, + receiverUid: "cometchat-uid-3", + type: "form", + receiverType: "user", + allowSenderInteraction: true, +); + +CometChat.sendInteractiveMessage(interactiveMessage, + onSuccess: (InteractiveMessage message) { + debugPrint("Interactive message sent successfully: $message"); + }, + onError: (CometChatException excep) { + debugPrint("Interactive message sending failed with error: ${excep.message}"); + }, +); +``` + + + + +--- -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/flutter/join-group.mdx b/sdk/flutter/join-group.mdx index 41e6b00da..bc2595378 100644 --- a/sdk/flutter/join-group.mdx +++ b/sdk/flutter/join-group.mdx @@ -1,12 +1,48 @@ --- title: "Join A Group" +sidebarTitle: "Join Group" +description: "Learn how to join public and password-protected groups using the CometChat Flutter SDK." --- + +```dart +// Join a public group +CometChat.joinGroup("GROUP_GUID", CometChatGroupType.public, + onSuccess: (Group group) => debugPrint("Joined: ${group.name}"), + onError: (CometChatException e) => debugPrint("Error: ${e.message}"), +); + +// Join a password-protected group +CometChat.joinGroup("GROUP_GUID", CometChatGroupType.password, + password: "group_password", + onSuccess: (Group group) => debugPrint("Joined: ${group.name}"), + onError: (CometChatException e) => debugPrint("Error: ${e.message}"), +); +``` + +**Group types:** `CometChatGroupType.public` | `CometChatGroupType.password` | `CometChatGroupType.private` + + +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 -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. + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) + + +### Parameters + +| Parameter | Type | Description | +|-----------|------|-------------| +| `guid` | `String` | The GUID of the group to join | +| `groupType` | `String` | `CometChatGroupType.public`, `CometChatGroupType.password`, or `CometChatGroupType.private` | +| `password` | `String` | Required for password-protected groups (defaults to empty string) | +| `onSuccess` | `Function(Group group)?` | Callback triggered on successful join | +| `onError` | `Function(CometChatException excep)?` | Callback triggered on error | @@ -27,19 +63,45 @@ CometChat.joinGroup(GUID, groupType, password: password, -The `joinGroup()` method takes the below parameters + +**On Success** — A `Group` object containing all details of the joined group: + + + +**Group Object:** -| 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.CometChatGroupType.*public* (public). 2.CometChatGroupType.*password* (password) 3.CometChatGroupType.*private* (private) | -| `password` | Password is mandatory in case of a password protected group. | +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Unique identifier for the group | `"cometchat-guid-1"` | +| `name` | string | Display name of the group | `"Hello Group!"` | +| `icon` | string | URL of the group icon | `null` | +| `description` | string | Description of the group | `null` | +| `membersCount` | number | Number of members in the group | `5` | +| `metadata` | object | Custom metadata attached to the group | `{}` | +| `joinedAt` | number | Epoch timestamp when the logged-in user joined the group | `1745554729` | +| `hasJoined` | boolean | Whether the logged-in user has joined the group | `true` | +| `createdAt` | number | Epoch timestamp when the group was created | `1745551200` | +| `owner` | string | UID of the group owner | `"cometchat-uid-1"` | +| `updatedAt` | number | Epoch timestamp when the group was last updated | `1745554729` | +| `tags` | array | List of tags associated with the group | `[]` | +| `type` | string | Type of the group (public, private, password) | `"public"` | +| `scope` | string | Scope of the logged-in user in the group | `"participant"` | +| `password` | string | Password for password-protected groups | `null` | +| `isBannedFromGroup` | boolean | Whether the logged-in user is banned from the group | `false` | -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. + -You can identify if a group is joined using the `hasJoined` parameter in the `Group` object. +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_GUID_NOT_FOUND"` | +| `message` | string | Human-readable error message | `"The specified group does not exist."` | +| `details` | string | Additional technical details | `"Please provide a valid GUID for the group."` | + + + +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. ## Real-time Group Member Joined Events @@ -50,12 +112,13 @@ If a user joins any group, the members of the group receive a real-time event in ```dart -class Class_Name with GroupListener { +class ClassName with GroupListener { + // CometChat.addGroupListener("group_Listener_id", this); -//CometChat.addGroupListener("group_Listener_id", this); -@override -void onGroupMemberJoined(Action action, User joinedUser, Group joinedGroup) { - debugPrint("onGroupMemberJoined"); + @override + void onGroupMemberJoined(Action action, User joinedUser, Group joinedGroup) { + debugPrint("onGroupMemberJoined"); + } } ``` @@ -63,6 +126,14 @@ void onGroupMemberJoined(Action action, User joinedUser, Group joinedGroup) { + +Always remove group listeners when they're no longer needed (e.g., in `dispose()`). Failing to remove listeners can cause memory leaks and duplicate event handling. + +```dart +CometChat.removeGroupListener("group_Listener_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?* @@ -74,3 +145,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/flutter/key-concepts.mdx b/sdk/flutter/key-concepts.mdx index c0c79ebbb..4e2d9e640 100644 --- a/sdk/flutter/key-concepts.mdx +++ b/sdk/flutter/key-concepts.mdx @@ -1,152 +1,203 @@ --- title: "Key Concepts" +sidebarTitle: "Key Concepts" +description: "Understand the core concepts of CometChat including users, groups, messaging categories, authentication, and member roles." --- + +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 -### CometChat Dashboard - -The CometChat Dashboard enables you to create new apps (projects) and manage your existing apps. - - -How many apps to create? +```dart +// Receiver types +CometChatReceiverType.user // For 1-on-1 messages +CometChatReceiverType.group // For group messages -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! +// Group types +CometChatGroupType.public // Anyone can join +CometChatGroupType.password // Requires password to join +CometChatGroupType.private // Invite-only - +// Member scopes +CometChatMemberScope.admin // Full privileges +CometChatMemberScope.moderator // Moderate members +CometChatMemberScope.participant // Send/receive messages -* 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. +// Message categories +CometChatMessageCategory.message // text, image, video, audio, file +CometChatMessageCategory.custom // Custom data messages +CometChatMessageCategory.action // System-generated messages +CometChatMessageCategory.call // Call-related messages +``` + -### Auth & Rest API Keys +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. -You can generate two types of keys from the dashboard. +### CometChat 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 | +The CometChat Dashboard enables you to create new apps (projects) and manage your existing apps. -### Users + +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. + -A user is anyone who uses CometChat. +- 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. -### UID +## Users -* Each user is uniquely identified using UID. -* The UID is typically the primary ID of the user from your database. +A user is anyone who uses CometChat. Each user is uniquely identified by 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 -UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. +### 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. -### Auth Token +### User List -* 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. +- 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. -### Authentication +## Authentication -To allow a user to use CometChat, the user must log in to CometChat. +CometChat does not handle user registration or friends management — you handle that in your app, then log users into 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**. So the user does not ever directly login to CometChat. +### API Keys -**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. +You can generate two types of keys from the [CometChat Dashboard](https://app.cometchat.com): -### Typical Workflow +| 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 | -| 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 | + +Never expose your REST API Key in client-side code. Use Auth Tokens for production authentication. + -### User Roles +### Auth Tokens -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. +Auth Tokens are secure, per-user credentials for production use: -### User List +- 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 -* 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. +### Authentication Flow -### Groups +| 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, login the user and retrieve the 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 | -A group can be used for multiple users to communicate with each other on a particular topic/interest. +## Groups -### GUID +A group enables multiple users to communicate on a particular topic or interest. Each group is uniquely identified using a GUID (Group Unique Identifier). -* 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. +- The GUID is typically the primary ID of the group from your database +- GUID can be alphanumeric with underscore and hyphen only - GUID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. - -### Types - -CometChat supports three different types of groups: +## Group Types -| 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 | +| 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) | -### Members +## Member Scopes -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. +Once a user joins a group, they become a member with one of three scopes: -CometChat supports three different types of member scopes in a group: +| 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 | -| 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 | +## Message Categories -### Messaging +Every message belongs to one of these categories: -Any message in CometChat can belong to either one of the below categories +| 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 | -| 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 | - -For more information, you can refer to the [Message structure and hierarchy](/sdk/flutter/message-structure-and-hierarchy) guide. +For more details, see the [Message Structure and Hierarchy](/sdk/flutter/message-structure-and-hierarchy) guide. ## Auto Mode Connection - Know more about auto mode connection [click here](/sdk/flutter/connection-behaviour) - -| App State | Behaviour | -| ----------------- | --------------------------------------- | -| App in foreground | Connected with WebSocket | +| App State | Behaviour | +| --- | --- | +| App in foreground | Connected with WebSocket | | App in background | Immediately disconnected with WebSocket | ## Manual Mode Connection - Know more about manual mode connection [click here](/sdk/flutter/connection-behaviour) - -| App State | Behaviour | -| ----------------- | ------------------------------------------------------------------------------------------------------------------ | -| App in foreground | Call `CometChat.connect()` to create the WebSocket connection | +| App State | Behaviour | +| --- | --- | +| 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/flutter/users-overview) | +| GUID | Group Unique Identifier — alphanumeric string you assign to each group | [Groups Overview](/sdk/flutter/groups-overview) | +| Auth Key | Development-only credential for quick testing. Never use in production | [Authentication](/sdk/flutter/authentication-overview) | +| Auth Token | Secure, per-user token generated via REST API. Use in production | [Authentication](/sdk/flutter/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/flutter/send-message) | +| Scope | Group member scope: `admin`, `moderator`, or `participant` | [Change Member Scope](/sdk/flutter/group-change-member-scope) | +| Listener | Callback handler for real-time events (messages, presence, calls, groups) | [Real-Time Listeners](/sdk/flutter/real-time-listeners) | +| Conversation | A chat thread between two users or within a group | [Retrieve Conversations](/sdk/flutter/retrieve-conversations) | +| Metadata | Custom JSON data attached to users, groups, or messages | [Send Message](/sdk/flutter/send-message) | +| Tags | String labels for categorizing users, groups, conversations, or messages | [Additional Message Filtering](/sdk/flutter/additional-message-filtering) | +| RequestBuilder | Builder pattern class for constructing filtered/paginated queries | [Additional Message Filtering](/sdk/flutter/additional-message-filtering) | +| AppSettings | Configuration object for initializing the SDK (App ID, Region, presence) | [Setup SDK](/sdk/flutter/setup) | +| Transient Message | Ephemeral message not stored on server (typing indicators, live reactions) | [Transient Messages](/sdk/flutter/transient-messages) | +| Interactive Message | Message with actionable UI elements (forms, cards, buttons) | [Interactive Messages](/sdk/flutter/interactive-messages) | + +--- + +## Next Steps + + + + Install and initialize the CometChat Flutter SDK + + + Log users in and manage auth tokens + + + Send your first text or media message + + + Create and manage group conversations + + diff --git a/sdk/flutter/leave-group.mdx b/sdk/flutter/leave-group.mdx index f73638b8d..3d57928d7 100644 --- a/sdk/flutter/leave-group.mdx +++ b/sdk/flutter/leave-group.mdx @@ -1,12 +1,48 @@ --- 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 Flutter SDK." --- + +```dart +// Leave a group +CometChat.leaveGroup("GROUP_GUID", + onSuccess: (String message) => debugPrint("Left group: $message"), + onError: (CometChatException e) => debugPrint("Error: ${e.message}"), +); + +// Listen for group member left events +CometChat.addGroupListener("listener_id", GroupListener( + onGroupMemberLeft: (Action action, User leftUser, Group leftGroup) { + debugPrint("${leftUser.name} left ${leftGroup.name}"); + }, +)); +``` + + +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/flutter/transfer-group-ownership). + ## 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. + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) + + +### Parameters + +| Parameter | Type | Description | +|-----------|------|-------------| +| `guid` | `String` | The GUID of the group you would like to leave | +| `onSuccess` | `Function(String returnResponse)?` | Callback triggered on successful leave | +| `onError` | `Function(CometChatException excep)?` | Callback triggered on error | @@ -24,9 +60,28 @@ CometChat.leaveGroup(GUID, onSuccess: ( String message) { -| Parameter | Description | -| --------- | --------------------------------------------- | -| `GUID` | The GUID of the group you would like to leave | + +**On Success** — A `String` message confirming the operation: + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `message` | string | Success confirmation message | `"cometchat-guid-1 left successfully"` | + + + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_NOT_A_MEMBER"` | +| `message` | string | Human-readable error message | `"The user is not a member of this group."` | +| `details` | string | Additional technical details | `"Cannot leave a group that you are not a member of."` | + + Once a group is left, the user will no longer receive any updates or messages pertaining to the group. @@ -54,14 +109,41 @@ void onGroupMemberLeft(Action action, User leftUser, Group leftGroup) { + +Always remove group listeners when they're no longer needed (e.g., in `dispose()`). Failing to remove listeners can cause memory leaks and duplicate event handling. + +```dart +CometChat.removeGroupListener("group_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. +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`](/sdk/reference/messages#action) message. An `Action` message is a sub-class of [`BaseMessage`](/sdk/reference/messages#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 + +--- + +## Next Steps + + + + Join public or password-protected groups + + + Permanently delete a group (admin only) + + + Remove or ban members from a group + + + Fetch and filter the list of groups + + diff --git a/sdk/flutter/login-listeners.mdx b/sdk/flutter/login-listeners.mdx deleted file mode 100644 index 7d720a796..000000000 --- a/sdk/flutter/login-listeners.mdx +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: "Login Listeners" ---- - - - -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: - -| 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 object of the `LoginListener` class itself. - -We suggest adding the listener in the `init` method of the Stateful class or at the initialization of class where you wish to receive these events in. - - - -```dart -class Class_Name with LoginListener { - -// String loginListenerId = "UNIQUE_LISTENER_ID"; -// CometChat.addLoginListener(loginListenerId, Class_Name()); // add this in init -@override -void loginSuccess(User user) { - debugPrint("LoginListener loginSuccess $user"); -} - -@override -void logoutFailure(CometChatException e) { - debugPrint("logoutFailure ${e.message}"); -} - -@override -void logoutSuccess() { - debugPrint("LoginListener logout Success"); -} - -@override -void loginFailure(CometChatException e) { - debugPrint("LoginListener loginFailure ${e.message}"); -} -} -``` - - - - - -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. - - - -```dart -CometChat.removeLoginListener("UNIQUE_LISTENER_ID"); -``` - - - - diff --git a/sdk/flutter/mentions.mdx b/sdk/flutter/mentions.mdx index 2a0ad288e..d837732e7 100644 --- a/sdk/flutter/mentions.mdx +++ b/sdk/flutter/mentions.mdx @@ -1,12 +1,55 @@ --- title: "Mentions" +sidebarTitle: "Mentions" +description: "Send messages with user mentions, retrieve mentioned users, and filter messages by mention metadata using the CometChat Flutter SDK." --- + +| Field | Value | +| --- | --- | +| Key Classes | `TextMessage`, `BaseMessage`, `User`, `MessagesRequest`, `MessagesRequestBuilder` | +| Key Properties | `mentionedUsers`, `hasMentionedMe` | +| Builder Methods | `mentionsWithTagInfo()`, `mentionsWithBlockedInfo()` | +| Mention Format | `<@uid:UID>` | +| Prerequisites | SDK initialized, user logged in | + +```dart +// Send a message with a mention (use <@uid:UID> format) +TextMessage textMessage = TextMessage( + text: "Hello <@uid:cometchat-uid-1>", + receiverUid: "UID", + receiverType: CometChatReceiverType.user, + type: CometChatMessageType.text, +); +CometChat.sendMessage(textMessage, onSuccess: (msg) { + debugPrint("Mentioned users: ${msg.mentionedUsers}"); +}, onError: (e) {}); + +// Get mentioned users from a message +List mentionedUsers = message.mentionedUsers; + +// Check if logged-in user was mentioned +bool wasMentioned = message.hasMentionedMe ?? false; + +// Fetch messages with mention tag info +MessagesRequest request = (MessagesRequestBuilder() + ..uid = "UID" + ..limit = 30 + ..mentionsWithTagInfo(true) +).build(); +request.fetchPrevious(onSuccess: (messages) {}, onError: (e) {}); +``` + + + +Mentions in messages enable users to refer to specific individuals 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. -Mentions in messages enable users to refer to specific individuals within a conversation. + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) + ## Send Mentioned Messages @@ -67,6 +110,120 @@ CometChat.sendMessage(textMessage, onSuccess:(TextMessage textMessage) { + +**On Success** — A `TextMessage` object containing all details of the sent message with mentions: + + + +**TextMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `501` | +| `metadata` | object | Custom metadata attached to the message | `{}` | +| `receiver` | object | Receiver user object | [See below ↓](#fetch-mentions-send-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `null` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `sentAt` | number | Epoch timestamp when the message was sent | `1745554729` | +| `receiverUid` | string | UID of the receiver | `"cometchat-uid-2"` | +| `type` | string | Type of the message | `"text"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `null` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `0` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `0` | +| `replyCount` | number | Number of replies to this message | `0` | +| `sender` | object | Sender user object | [See below ↓](#fetch-mentions-send-sender-object) | +| `receiverType` | string | Type of the receiver | `"user"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `0` | +| `parentMessageId` | number | ID of the parent message (for threads) | `-1` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"message"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` | +| `updatedAt` | number | Epoch timestamp when the message was last updated | `1745554729` | +| `text` | string | The text content of the message | `"Hello, <@uid:cometchat-uid-1>"` | +| `tags` | array | List of tags associated with the message | `[]` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `mentionedUsers` | array | List of mentioned users | [See below ↓](#fetch-mentions-send-mentionedusers-object) | +| `hasMentionedMe` | boolean | Whether the current user is mentioned | `false` | +| `reactions` | array | List of reactions on the message | `[]` | +| `moderationStatus` | string | Moderation status of the message | `null` | +| `quotedMessageId` | number | ID of the quoted message | `null` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-1"` | +| `name` | string | Display name of the sender | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-2"` | +| `name` | string | Display name of the receiver | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + +--- + + + +**`mentionedUsers` Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the mentioned user | `"cometchat-uid-1"` | +| `name` | string | Display name of the mentioned user | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to send the message."` | +| `details` | string | Additional technical details | `"An unexpected error occurred while processing the request."` | + + + You can mention user in text message and media messages captions @@ -86,6 +243,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 tags of the mentioned users. +Relevant fields to access on returned messages and their mentioned users: + +| Field | Property | Return Type | Description | +|-------|----------|-------------|-------------| +| mentionedUsers | `mentionedUsers` | [`List`](/sdk/reference/entities#user) | Array of users mentioned in the message | +| tags (on each mentioned user) | `tags` | `List` | Tags associated with the mentioned user | + ```dart @@ -139,10 +303,106 @@ messagesRequest.fetchPrevious(onSuccess:(List messages) { + +**On Success** — A `List` containing messages with mentioned users and their tag info (each item is a BaseMessage object): + + + +**BaseMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `502` | +| `metadata` | object | Custom metadata attached to the message | `{}` | +| `receiver` | object | Receiver user object | [See below ↓](#fetch-mentions-taginfo-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `null` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `sentAt` | number | Epoch timestamp when the message was sent | `1745554729` | +| `receiverUid` | string | UID of the receiver | `"cometchat-uid-1"` | +| `type` | string | Type of the message | `"text"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `null` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `0` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `0` | +| `replyCount` | number | Number of replies to this message | `0` | +| `sender` | object | Sender user object | [See below ↓](#fetch-mentions-taginfo-sender-object) | +| `receiverType` | string | Type of the receiver | `"user"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `0` | +| `parentMessageId` | number | ID of the parent message (for threads) | `0` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"message"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` | +| `updatedAt` | number | Epoch timestamp when the message was last updated | `1745554729` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `quotedMessageId` | number | ID of the quoted message | `null` | +| `quotedMessage` | object | The quoted message object | `null` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-2"` | +| `name` | string | Display name of the sender | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-1"` | +| `name` | string | Display name of the receiver | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to fetch the requested data."` | +| `details` | string | Additional technical details | `"An unexpected error occurred while processing the request."` | + + + ## 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. +Relevant fields to access on returned messages and their mentioned users: + +| Field | Property | Return Type | Description | +|-------|----------|-------------|-------------| +| mentionedUsers | `mentionedUsers` | [`List`](/sdk/reference/entities#user) | Array of users mentioned in the message | +| blockedByMe (on each mentioned user) | `blockedByMe` | `bool` | Whether the logged-in user has blocked this mentioned user | +| hasBlockedMe (on each mentioned user) | `hasBlockedMe` | `bool` | Whether this mentioned user has blocked the logged-in user | + ```dart @@ -198,12 +458,100 @@ messagesRequest.fetchPrevious(onSuccess:(List messages) { + +**On Success** — A `List` containing messages with mentioned users and their blocked relationship info (each item is a BaseMessage object): + + + +**BaseMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `503` | +| `metadata` | object | Custom metadata attached to the message | `{}` | +| `receiver` | object | Receiver user object | [See below ↓](#fetch-mentions-blockedinfo-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `null` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `sentAt` | number | Epoch timestamp when the message was sent | `1745554729` | +| `receiverUid` | string | UID of the receiver | `"cometchat-uid-1"` | +| `type` | string | Type of the message | `"text"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `null` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `0` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `0` | +| `replyCount` | number | Number of replies to this message | `0` | +| `sender` | object | Sender user object | [See below ↓](#fetch-mentions-blockedinfo-sender-object) | +| `receiverType` | string | Type of the receiver | `"user"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `0` | +| `parentMessageId` | number | ID of the parent message (for threads) | `0` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"message"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` | +| `updatedAt` | number | Epoch timestamp when the message was last updated | `1745554729` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `quotedMessageId` | number | ID of the quoted message | `null` | +| `quotedMessage` | object | The quoted message object | `null` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-2"` | +| `name` | string | Display name of the sender | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-1"` | +| `name` | string | Display name of the receiver | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to fetch the requested data."` | +| `details` | string | Additional technical details | `"An unexpected error occurred while processing the request."` | + + + ## Get Users Mentioned In a Particular Message To retrieve the list of users mentioned in the particular message, you can use the `mentionedUsers` property on any `BaseMessage`. This property will return an array containing User objects of the mentioned users, or an empty array if no users were mentioned in the message. - + ```dart message.mentionedUsers ``` @@ -212,6 +560,8 @@ message.mentionedUsers +The `mentionedUsers` property returns a `List<`[`User`](/sdk/reference/entities#user)`>` objects. + ## Check if Logged-in user has been mentioned To check if the logged-in user has been mentioned in a particular message we can use the `hasMentionedMe` property on any `BaseMessage`. This property will return a boolean value, true if the logged-in user has been mentioned, otherwise `false`. @@ -225,3 +575,22 @@ message.hasMentionedMe
+ +--- + +## 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/flutter/message-structure-and-hierarchy.mdx b/sdk/flutter/message-structure-and-hierarchy.mdx index 97385b653..7f6284d3e 100644 --- a/sdk/flutter/message-structure-and-hierarchy.mdx +++ b/sdk/flutter/message-structure-and-hierarchy.mdx @@ -1,8 +1,55 @@ --- -title: "Message Structure And Hierarchy" +title: "Message Structure and Hierarchy" +sidebarTitle: "Message Structure" +description: "Understand the message categories, types, and class hierarchy in CometChat Flutter SDK including TextMessage, MediaMessage, CustomMessage, InteractiveMessage, and Action." --- - + + +Message class hierarchy: +``` +BaseMessage (extends AppEntity) +├── TextMessage → category: message, type: text +├── MediaMessage → category: message, type: image/video/audio/file +├── CustomMessage → category: custom, type: developer-defined +├── InteractiveMessage → category: interactive, type: form/card/scheduler/customInteractive +├── Action → category: action, type: groupMember/message +├── Call → category: call, type: audio/video +└── AIAssistantMessage → category: agentic, type: assistant +``` + +Message categories and types: +- **message** → `text`, `image`, `video`, `audio`, `file` +- **custom** → Developer-defined types (e.g., `location`, `poll`) +- **interactive** → `form`, `card`, `scheduler`, `customInteractive` +- **action** → `groupMember` (joined/left/kicked/banned), `message` (edited/deleted) +- **call** → `audio`, `video` +- **agentic** → `assistant`, `tool-result`, `tool-arguments` + +```dart +// Common BaseMessage Properties +message.id; // int - Unique message ID +message.sender; // User? - Message sender +message.receiverUid; // String - Receiver UID or GUID +message.receiverType; // String - "user" or "group" +message.category; // String - message/custom/action/interactive/call/agentic +message.type; // String - text/image/video/audio/file/custom +message.sentAt; // DateTime? - When message was sent +message.deliveredAt; // DateTime? - When message was delivered +message.readAt; // DateTime? - When message was read +message.metadata; // Map? - Custom data + +// Type-specific Properties +textMessage.text; // String - Text content +mediaMessage.attachment; // Attachment? - File details +customMessage.customData; // Map? - Custom payload +interactiveMessage.interactiveData; // Map - Interactive element data +``` + + +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/flutter/key-concepts), with subclasses like `TextMessage`, `MediaMessage`, `CustomMessage`, `InteractiveMessage`, `Action`, and `Call`. Understanding this hierarchy helps you handle different message types correctly. + +## Message Hierarchy The below diagram helps you better understand the various message categories and types that a CometChat message can belong to. @@ -11,19 +58,54 @@ The below diagram helps you better understand the various message categories and - -The calling feature is not currently supported by the CometChat flutter SDK - +The calling feature is not currently supported by the CometChat Flutter SDK. -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. Interactive +## Categories Overview + +| Category | Types | SDK Class | Description | +| --- | --- | --- | --- | +| `message` | `text`, `image`, `video`, `audio`, `file` | `TextMessage`, `MediaMessage` | Standard user messages | +| `custom` | Developer-defined | `CustomMessage` | Custom data (location, polls, etc.) | +| `interactive` | `form`, `card`, `scheduler`, `customInteractive` | `InteractiveMessage` | Messages with actionable UI elements | +| `action` | `groupMember`, `message` | `Action` | System-generated events | +| `call` | `audio`, `video` | `Call` | Call-related messages | + +## BaseMessage Properties + +All message types extend `BaseMessage`, which provides these common properties: + +| Property | Type | Description | +| --- | --- | --- | +| `id` | `int` | Unique message identifier | +| `muid` | `String` | Message unique identifier (client-side) | +| `sender` | `User?` | The user who sent the message | +| `receiver` | `AppEntity?` | The receiver (User or Group) | +| `receiverUid` | `String` | UID of the receiver (user UID or group GUID) | +| `type` | `String` | Message type (e.g., `text`, `image`, `custom`) | +| `receiverType` | `String` | `"user"` or `"group"` | +| `category` | `String` | Message category (`message`, `custom`, `action`, `interactive`, `call`) | +| `sentAt` | `DateTime?` | Timestamp when the message was sent | +| `deliveredAt` | `DateTime?` | Timestamp when the message was delivered | +| `readAt` | `DateTime?` | Timestamp when the message was read | +| `metadata` | `Map?` | Custom key-value data attached to the message | +| `readByMeAt` | `DateTime?` | Timestamp when the current user read the message | +| `deliveredToMeAt` | `DateTime?` | Timestamp when the message was delivered to the current user | +| `deletedAt` | `DateTime?` | Timestamp when the message was deleted | +| `editedAt` | `DateTime?` | Timestamp when the message was last edited | +| `deletedBy` | `String?` | UID of the user who deleted the message | +| `editedBy` | `String?` | UID of the user who edited the message | +| `updatedAt` | `DateTime?` | Timestamp of the last update | +| `conversationId` | `String?` | ID of the conversation this message belongs to | +| `parentMessageId` | `int` | ID of the parent message (for threaded messages) | +| `replyCount` | `int` | Number of replies to this message | +| `unreadRepliesCount` | `int` | Number of unread replies | +| `mentionedUsers` | `List` | Users mentioned in this message | +| `hasMentionedMe` | `bool?` | Whether the current user is mentioned | +| `reactions` | `List` | Reactions on this message | +| `quotedMessage` | `BaseMessage?` | The message being quoted/replied to | +| `quotedMessageId` | `int?` | ID of the quoted message | -Each category can be further be classified into types. ## Message @@ -35,24 +117,81 @@ A message belonging to the category `message` can be classified into either 1 of 4. audio- An audio message 5. file- A file message +### TextMessage Properties + +| Property | Type | Description | +| --- | --- | --- | +| `text` | `String` | The text content of the message | +| `tags` | `List?` | Tags associated with the message | +| `moderationStatus` | `ModerationStatusEnum?` | Content moderation status | + +*Inherits all [BaseMessage](#basemessage-properties) properties.* + +### MediaMessage Properties + +| Property | Type | Description | +| --- | --- | --- | +| `caption` | `String?` | Caption for the media file | +| `attachment` | `Attachment?` | Primary file attachment details | +| `file` | `String?` | Local file path | +| `files` | `List?` | Multiple local file paths | +| `attachments` | `List?` | Multiple file attachments | +| `tags` | `List?` | Tags associated with the message | +| `moderationStatus` | `ModerationStatusEnum?` | Content moderation status | + +*Inherits all [BaseMessage](#basemessage-properties) properties.* + +### Attachment Properties + +| Property | Type | Description | +| --- | --- | --- | +| `fileUrl` | `String` | URL of the uploaded file | +| `fileName` | `String` | Name of the file | +| `fileExtension` | `String` | File extension (e.g., `jpg`, `mp4`) | +| `fileMimeType` | `String` | MIME type (e.g., `image/jpeg`) | +| `fileSize` | `int?` | File size in bytes | + ## 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`. +### CustomMessage Properties + +| Property | Type | Description | +| --- | --- | --- | +| `subType` | `String?` | Sub-type for further classification | +| `customData` | `Map?` | Custom key-value payload | +| `tags` | `List?` | Tags associated with the message | +| `conversationText` | `String?` | Text shown in conversation list | +| `updateConversation` | `bool?` | Whether to update the conversation list | +| `sendNotification` | `bool?` | Whether to send a push notification | + +*Inherits all [BaseMessage](#basemessage-properties) properties.* + ## 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. scheduler- for schduler message +3. scheduler- for scheduler message 4. customInteractive- for custom interaction messages +To know about Interactive messages please [click here](/sdk/flutter/interactive-messages). + -to know about Interactive messages please [click here](/sdk/flutter/interactive-messages) +### InteractiveMessage Properties - +| Property | Type | Description | +| --- | --- | --- | +| `interactiveData` | `Map` | Data defining the interactive element (form fields, card content, etc.) | +| `interactions` | `List?` | List of user interactions with this message | +| `interactionGoal` | `InteractionGoal?` | Goal criteria for the interactive element | +| `tags` | `List?` | Tags associated with the message | +| `allowSenderInteraction` | `bool` | Whether the sender can interact with the element | + +*Inherits all [BaseMessage](#basemessage-properties) properties.* ## Action @@ -62,6 +201,21 @@ Action messages are system-generated messages. Messages belonging to the `action 2. message - action performed on a message. +### Action Properties + +| Property | Type | Description | +| --- | --- | --- | +| `message` | `String?` | Human-readable action description | +| `rawData` | `String?` | Raw action data | +| `action` | `String?` | The action performed (e.g., `joined`, `kicked`, `edited`) | +| `oldScope` | `String?` | Previous member scope (for scope changes) | +| `newScope` | `String?` | New member scope (for scope changes) | +| `actionBy` | `AppEntity?` | Entity that performed the action | +| `actionFor` | `AppEntity?` | Entity the action was performed for | +| `actionOn` | `AppEntity?` | Entity the action was performed on | + +*Inherits all [BaseMessage](#basemessage-properties) properties.* + 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: 1. joined - when a group member joins a group @@ -84,12 +238,48 @@ Messages with the category call are Calling related messages. These can belong t 1. audio 2. video +### Call Properties + +| Property | Type | Description | +| --- | --- | --- | +| `sessionId` | `String?` | Unique call session identifier | +| `callStatus` | `String?` | Current status of the call | +| `action` | `String?` | Call action type | +| `rawData` | `String?` | Raw call data | +| `initiatedAt` | `DateTime?` | When the call was initiated | +| `joinedAt` | `DateTime?` | When the receiver joined the call | +| `callInitiator` | `AppEntity?` | The user who initiated the call | +| `callReceiver` | `AppEntity?` | The user/group receiving the call | + +*Inherits all [BaseMessage](#basemessage-properties) properties.* + 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 -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. +| Status | Description | +| --- | --- | +| `initiated` | Call started to a user/group | +| `ongoing` | Receiver accepted the call | +| `cancelled` | Initiator canceled the call | +| `rejected` | Receiver rejected the call | +| `unanswered` | Call was not answered | +| `busy` | Receiver was on another call | +| `ended` | Call completed successfully | + +--- + +## Next Steps + + + + Learn how to send text, media, and custom messages + + + Handle incoming messages with real-time listeners + + + Create forms, cards, and interactive elements + + + Modify or remove sent messages + + diff --git a/sdk/flutter/messaging-overview.mdx b/sdk/flutter/messaging-overview.mdx index 49e55d1d6..2e666df59 100644 --- a/sdk/flutter/messaging-overview.mdx +++ b/sdk/flutter/messaging-overview.mdx @@ -1,12 +1,50 @@ --- title: "Messaging" sidebarTitle: "Overview" +description: "Overview of CometChat messaging features for Flutter including sending, receiving, editing, and deleting messages, plus advanced features like typing indicators and read receipts." --- +{/* TL;DR for Agents and Quick Reference */} + +Choose your path: +- **Send Messages** → [Send Message](/sdk/flutter/send-message) - Text, media, custom +- **Receive Messages** → [Receive Messages](/sdk/flutter/receive-messages) - Real-time listeners +- **Edit/Delete** → [Edit](/sdk/flutter/edit-message) | [Delete](/sdk/flutter/delete-message) +- **Advanced** → [Threads](/sdk/flutter/threaded-messages) | [Reactions](/sdk/flutter/reactions) | [Mentions](/sdk/flutter/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/flutter/send-message) message and [receiving messages](/sdk/flutter/receive-messages). +At the minimum, you must add code for [sending messages](/sdk/flutter/send-message) and [receiving messages](/sdk/flutter/receive-messages). -Once you've implemented that, you can proceed to more advanced features like [typing indicators](/sdk/flutter/typing-indicators) and [Delivery & Read Receipts](/sdk/flutter/delivery-read-receipts). +Once you've implemented that, you can proceed to more advanced features like [typing indicators](/sdk/flutter/typing-indicators) and [delivery & read receipts](/sdk/flutter/delivery-read-receipts). + +## Message Types + +| 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 | + +--- + +## 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/flutter/notifications.mdx b/sdk/flutter/notifications.mdx new file mode 100644 index 000000000..55f0ff0ef --- /dev/null +++ b/sdk/flutter/notifications.mdx @@ -0,0 +1,412 @@ +--- +title: "Notifications" +sidebarTitle: "Notifications" +description: "Manage push notification preferences, token registration, conversation muting, and timezone settings with the CometChat Flutter SDK." +--- + + + +```dart +// Register push token (FCM on Android) +await CometChatNotifications.registerPushToken( + PushPlatforms.FCM_FLUTTER_ANDROID, + fcmToken: "YOUR_FCM_TOKEN", + onSuccess: (response) => debugPrint("Token registered: $response"), + onError: (e) => debugPrint("Error: ${e.message}"), +); + +// Fetch notification preferences +NotificationPreferences? prefs = await CometChatNotifications.fetchPreferences( + onSuccess: (prefs) => debugPrint("Preferences: $prefs"), + onError: (e) => debugPrint("Error: ${e.message}"), +); + +// Mute a conversation +await CometChatNotifications.muteConversations( + [MutedConversation(id: "UID", type: MutedConversationType.ONE_ON_ONE)], + onSuccess: (response) => debugPrint("Muted: $response"), + onError: (e) => debugPrint("Error: ${e.message}"), +); +``` + +**Key classes:** `CometChatNotifications`, `NotificationPreferences`, `MutedConversation`, `PushPlatforms` + + +The `CometChatNotifications` class provides methods to manage push notification preferences, register/unregister push tokens, mute/unmute conversations, and manage timezone settings. + +--- + +## Register Push Token + +Register a push notification token with CometChat for the current user. The token type depends on your platform and push provider. + +```dart +await CometChatNotifications.registerPushToken( + PushPlatforms.FCM_FLUTTER_ANDROID, + fcmToken: "YOUR_FCM_TOKEN", + providerId: "YOUR_PROVIDER_ID", // optional + onSuccess: (String response) { + debugPrint("Token registered: $response"); + }, + onError: (CometChatException e) { + debugPrint("Error: ${e.code} - ${e.message}"); + }, +); +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `pushPlatforms` | `PushPlatforms` | The push platform to register for (required) | +| `fcmToken` | `String?` | FCM token (required for `FCM_FLUTTER_ANDROID` and `FCM_FLUTTER_IOS`) | +| `deviceToken` | `String?` | APNs device token (required for `APNS_FLUTTER_DEVICE`) | +| `voipToken` | `String?` | APNs VoIP token (required for `APNS_FLUTTER_VOIP`) | +| `providerId` | `String?` | Optional provider ID | +| `onSuccess` | `Function(String)?` | Called with success response | +| `onError` | `Function(CometChatException)?` | Called on error | + +### PushPlatforms Enum + +| Value | Description | +|-------|-------------| +| `FCM_FLUTTER_ANDROID` | Firebase Cloud Messaging on Android | +| `FCM_FLUTTER_IOS` | Firebase Cloud Messaging on iOS | +| `APNS_FLUTTER_DEVICE` | Apple Push Notification service (device) | +| `APNS_FLUTTER_VOIP` | Apple Push Notification service (VoIP) | + +## Unregister Push Token + +Remove the push notification token for the current user. + +```dart +await CometChatNotifications.unregisterPushToken( + onSuccess: (String response) { + debugPrint("Token unregistered: $response"); + }, + onError: (CometChatException e) { + debugPrint("Error: ${e.message}"); + }, +); +``` + +--- + +## Notification Preferences + +### Fetch Preferences + +Retrieve the current notification preferences for the logged-in user. + +```dart +NotificationPreferences? prefs = await CometChatNotifications.fetchPreferences( + onSuccess: (NotificationPreferences prefs) { + debugPrint("1:1 messages: ${prefs.oneOnOnePreferences?.messages}"); + debugPrint("Group messages: ${prefs.groupPreferences?.messages}"); + debugPrint("DND: ${prefs.mutePreferences?.dnd}"); + }, + onError: (CometChatException e) { + debugPrint("Error: ${e.message}"); + }, +); +``` + +### Update Preferences + +Update notification preferences for the logged-in user. + +```dart +NotificationPreferences prefs = NotificationPreferences( + usePrivacyTemplate: true, + oneOnOnePreferences: OneOnOnePreferences( + messages: MessagesOptions.SUBSCRIBE_TO_ALL, + replies: RepliesOptions.SUBSCRIBE_TO_ALL, + reactions: ReactionsOptions.SUBSCRIBE_TO_REACTIONS_ON_OWN_MESSAGES, + ), + groupPreferences: GroupPreferences( + messages: MessagesOptions.SUBSCRIBE_TO_MENTIONS, + replies: RepliesOptions.SUBSCRIBE_TO_MENTIONS, + reactions: ReactionsOptions.DONT_SUBSCRIBE, + memberJoined: MemberActionsOptions.SUBSCRIBE, + memberLeft: MemberActionsOptions.DONT_SUBSCRIBE, + memberKicked: MemberActionsOptions.SUBSCRIBE, + memberBanned: MemberActionsOptions.SUBSCRIBE, + memberUnbanned: MemberActionsOptions.DONT_SUBSCRIBE, + memberScopeChanged: MemberActionsOptions.SUBSCRIBE, + memberAdded: MemberActionsOptions.SUBSCRIBE, + ), + mutePreferences: MutePreferences( + dnd: DNDOptions.DISABLED, + ), +); + +await CometChatNotifications.updatePreferences(prefs, + onSuccess: (NotificationPreferences updated) { + debugPrint("Preferences updated"); + }, + onError: (CometChatException e) { + debugPrint("Error: ${e.message}"); + }, +); +``` + +### Reset Preferences + +Reset notification preferences to their default values. + +```dart +await CometChatNotifications.resetPreferences( + onSuccess: (NotificationPreferences prefs) { + debugPrint("Preferences reset to defaults"); + }, + onError: (CometChatException e) { + debugPrint("Error: ${e.message}"); + }, +); +``` + +--- + +## Mute & Unmute Conversations + +### Get Muted Conversations + +Retrieve all conversations muted by the logged-in user. + +```dart +List muted = await CometChatNotifications.getMutedConversations( + onSuccess: (List conversations) { + for (var conv in conversations) { + debugPrint("Muted: ${conv.id} (${conv.type}) until ${conv.until}"); + } + }, + onError: (CometChatException e) { + debugPrint("Error: ${e.message}"); + }, +); +``` + +### Mute Conversations + +Mute one or more conversations. + +```dart +await CometChatNotifications.muteConversations( + [ + MutedConversation( + id: "user_uid", + type: MutedConversationType.ONE_ON_ONE, + until: 1700000000, // Unix timestamp, or null for indefinite + ), + MutedConversation( + id: "group_guid", + type: MutedConversationType.GROUP, + ), + ], + onSuccess: (String response) { + debugPrint("Conversations muted: $response"); + }, + onError: (CometChatException e) { + debugPrint("Error: ${e.message}"); + }, +); +``` + +### Unmute Conversations + +Unmute one or more conversations. + +```dart +await CometChatNotifications.unmuteConversations( + [ + UnmutedConversation( + id: "user_uid", + type: MutedConversationType.ONE_ON_ONE, + ), + ], + onSuccess: (String response) { + debugPrint("Conversations unmuted: $response"); + }, + onError: (CometChatException e) { + debugPrint("Error: ${e.message}"); + }, +); +``` + +--- + +## Timezone + +### Update Timezone + +Update the timezone preference for the logged-in user. This affects DND schedule evaluation. + +```dart +await CometChatNotifications.updateTimezone("America/New_York", + onSuccess: (String response) { + debugPrint("Timezone updated: $response"); + }, + onError: (CometChatException e) { + debugPrint("Error: ${e.message}"); + }, +); +``` + +### Get Timezone + +Retrieve the current timezone preference. + +```dart +String? timezone = await CometChatNotifications.getTimezone( + onSuccess: (String tz) { + debugPrint("Current timezone: $tz"); + }, + onError: (CometChatException e) { + debugPrint("Error: ${e.message}"); + }, +); +``` + +--- + +## Models Reference + +### NotificationPreferences + +| Property | Type | Description | +|----------|------|-------------| +| `usePrivacyTemplate` | `bool?` | Whether to use privacy templates for notifications | +| `oneOnOnePreferences` | `OneOnOnePreferences?` | Preferences for 1:1 conversations | +| `groupPreferences` | `GroupPreferences?` | Preferences for group conversations | +| `mutePreferences` | `MutePreferences?` | Do Not Disturb and schedule settings | + +### OneOnOnePreferences + +| Property | Type | Description | +|----------|------|-------------| +| `messages` | `MessagesOptions?` | Notification preference for messages | +| `replies` | `RepliesOptions?` | Notification preference for replies | +| `reactions` | `ReactionsOptions?` | Notification preference for reactions | + +### GroupPreferences + +| Property | Type | Description | +|----------|------|-------------| +| `messages` | `MessagesOptions?` | Notification preference for group messages | +| `replies` | `RepliesOptions?` | Notification preference for group replies | +| `reactions` | `ReactionsOptions?` | Notification preference for group reactions | +| `memberJoined` | `MemberActionsOptions?` | Notify when a member joins | +| `memberLeft` | `MemberActionsOptions?` | Notify when a member leaves | +| `memberAdded` | `MemberActionsOptions?` | Notify when a member is added | +| `memberKicked` | `MemberActionsOptions?` | Notify when a member is kicked | +| `memberBanned` | `MemberActionsOptions?` | Notify when a member is banned | +| `memberUnbanned` | `MemberActionsOptions?` | Notify when a member is unbanned | +| `memberScopeChanged` | `MemberActionsOptions?` | Notify when a member's scope changes | + +### MutePreferences + +| Property | Type | Description | +|----------|------|-------------| +| `dnd` | `DNDOptions?` | Do Not Disturb mode | +| `schedule` | `Map?` | Per-day mute schedule | + +### DaySchedule + +| Property | Type | Description | +|----------|------|-------------| +| `from` | `int?` | Start hour (0–23) | +| `to` | `int?` | End hour (0–23) | +| `dnd` | `bool?` | Whether DND is active for this day | + +### MutedConversation + +| Property | Type | Description | +|----------|------|-------------| +| `id` | `String?` | UID (for 1:1) or GUID (for group) | +| `type` | `MutedConversationType?` | Conversation type | +| `until` | `num?` | Unix timestamp when mute expires (null = indefinite) | + +### UnmutedConversation + +| Property | Type | Description | +|----------|------|-------------| +| `id` | `String?` | UID (for 1:1) or GUID (for group) | +| `type` | `MutedConversationType?` | Conversation type | + +--- + +## Enums Reference + +### MessagesOptions + +| Value | Int | Description | +|-------|-----|-------------| +| `DONT_SUBSCRIBE` | 1 | Don't receive message notifications | +| `SUBSCRIBE_TO_ALL` | 2 | Receive notifications for all messages | +| `SUBSCRIBE_TO_MENTIONS` | 3 | Only receive notifications for messages that mention you | + +### RepliesOptions + +| Value | Int | Description | +|-------|-----|-------------| +| `DONT_SUBSCRIBE` | 1 | Don't receive reply notifications | +| `SUBSCRIBE_TO_ALL` | 2 | Receive notifications for all replies | +| `SUBSCRIBE_TO_MENTIONS` | 3 | Only receive notifications for replies that mention you | + +### ReactionsOptions + +| Value | Int | Description | +|-------|-----|-------------| +| `DONT_SUBSCRIBE` | 1 | Don't receive reaction notifications | +| `SUBSCRIBE_TO_REACTIONS_ON_OWN_MESSAGES` | 2 | Receive notifications for reactions on your messages | +| `SUBSCRIBE_TO_REACTIONS_ON_ALL_MESSAGES` | 3 | Receive notifications for reactions on all messages | + +### MemberActionsOptions + +| Value | Int | Description | +|-------|-----|-------------| +| `DONT_SUBSCRIBE` | 1 | Don't receive member action notifications | +| `SUBSCRIBE` | 2 | Receive member action notifications | + +### DNDOptions + +| Value | Int | Description | +|-------|-----|-------------| +| `DISABLED` | 1 | Do Not Disturb is disabled | +| `ENABLED` | 2 | Do Not Disturb is enabled | + +### MutedConversationType + +| Value | String | Description | +|-------|--------|-------------| +| `ONE_ON_ONE` | `"oneOnOne"` | 1:1 conversation | +| `GROUP` | `"group"` | Group conversation | + +### DayOfWeek + +| Value | String | +|-------|--------| +| `MONDAY` | `"monday"` | +| `TUESDAY` | `"tuesday"` | +| `WEDNESDAY` | `"wednesday"` | +| `THURSDAY` | `"thursday"` | +| `FRIDAY` | `"friday"` | +| `SATURDAY` | `"saturday"` | +| `SUNDAY` | `"sunday"` | + +--- + +## Next Steps + + + + Installation and initialization guide + + + Monitor SDK connection state changes + + + Recommended patterns and practices + + + Complete SDK error code reference + + diff --git a/sdk/flutter/overview.mdx b/sdk/flutter/overview.mdx index fea57ac6b..6789301ed 100644 --- a/sdk/flutter/overview.mdx +++ b/sdk/flutter/overview.mdx @@ -1,200 +1,149 @@ --- -title: "Overview" +title: "Flutter SDK" +sidebarTitle: "Overview" +description: "Add real-time chat, voice, and video to your Flutter application with the CometChat SDK." --- - -🚀 **v5 Beta Available** — The Flutter Chat SDK v5 is now available in beta with significant improvements. [Check out the v5 Overview →](/sdk/flutter/v5/overview) - +{/* TL;DR for Agents and Quick Reference */} + -This guide demonstrates how to add chat to a Flutter application. Before you begin, we strongly recommend you read the [Key Concepts](/sdk/flutter/key-concepts) guide. - -#### I want to integrate with my app - -1. [Get your application keys](overview#get-your-application-keys) -2. [Add the CometChat dependency](overview#add-the-cometchat-dependency) -3. [Initialise CometChat](overview#initialise-cometchat) -4. [Register and Login your user](overview#register-and-login-your-user) - -#### I want to explore a sample app - -Follow the steps mentioned in the `README.md` file to run the sample app - -[Flutter Chat App](https://github.com/cometchat-pro/flutter-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 Keys** section and note the **Auth Key**, **App ID** & **Region** - - -Minimum Requirements - -* Android API Level 21 -* AndroidX Compatibility -* iOS 11 or higher -* Flutter SDK 1.2 or higher - - - -### Add the CometChat Dependency - -1. Add the following code in your `pubspec.yaml` file and run `pub get` command. - - - -```dart -cometchat_sdk: ^4.1.1 +```yaml +# Install (pubspec.yaml) +cometchat_sdk: ^4.0.33 ``` - - - - -2. For iOS change iOS deployment target to 11 or higher. -3. Add the following code to podfile inside iOS section of your app. - - - -``` -post_install do |installer| - -installer.pods_project.targets.each do |target| - -flutter_additional_ios_build_settings(target) - -//Copy from here-------> - -target.build_configurations.each do |build_configuration| - -build_configuration.build_settings['EXCLUDED_ARCHS[sdk=iphonesimulator*]'] = 'arm64 i386' - -end - -//Copy TILL here-------> - -end - -end -``` - - - - - -4. For iOS navigate to your iOS folder in terminal or CMD and do `pod install` . For apple chip system use rosetta terminal. -5. import CometChat SDK using the following code in dart. - - - ```dart import 'package:cometchat_sdk/cometchat_sdk.dart'; -``` - - - - - -### Initialise CometChat - -The `init()` method initializes 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 three settings: - -* **Region**: The region where your app was created. -* [User Presence](/sdk/flutter/user-presence) Presence Subscription: 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 [Connection Behaviour](/sdk/flutter/connection-behaviour) section. The default value for this property is **true.** -* **adminHost(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. -* **clientHost(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. - - - -```dart -String region = "REGION"; -String appId = "APP_ID"; - -AppSettings appSettings= (AppSettingsBuilder() - ..subscriptionType = CometChatSubscriptionType.allUsers - ..region= region - ..adminHost = "" //optional - ..clientHost = "" //optional - ..autoEstablishSocketConnection = true +// 1. Initialize (once at app startup) +AppSettings appSettings = (AppSettingsBuilder() + ..subscriptionType = CometChatSubscriptionType.allUsers + ..region = "APP_REGION" // e.g. "us", "eu", "in" + ..autoEstablishSocketConnection = true ).build(); -CometChat.init(appId, appSettings, - onSuccess: (String successMessage) { - debugPrint("Initialization completed successfully $successMessage"); - }, onError: (CometChatException excep) { - debugPrint("Initialization failed with exception: ${excep.message}"); - } +CometChat.init("APP_ID", appSettings, + onSuccess: (msg) => debugPrint("Init success"), + onError: (e) => debugPrint("Init failed: ${e.message}"), ); -``` - - - - - -Make sure you replace the `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. - -To create users on the fly, you can use the `createUser()` method. This method takes an `User` object and the `Auth Key` as input parameters and returns the created `User` object if the request is successful. - - - -```dart -String authKey = "AUTH_KEY";//Replace with the auth key of app -User user = User( uid: "usr1", name: "Kevin" );//Replace with name and uid of user - -CometChat.createUser(user, authKey, - onSuccess: (User user){ - debugPrint("Create User succesful ${user}"); - }, onError: (CometChatException e){ - debugPrint("Create User Failed with exception ${e.message}"); - } +// 2. Login (check session first) +CometChat.getLoggedInUser( + onSuccess: (user) { + if (user == null) { + CometChat.login("cometchat-uid-1", "AUTH_KEY", // dev only — use Auth Token in production + onSuccess: (user) => debugPrint("Login success"), + onError: (e) => debugPrint("Login failed"), + ); + } + }, + onError: (e) => debugPrint("Error: ${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 will need to log the user into CometChat using the `login()` method. - - - -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/flutter/authentication-overview#login-using-auth-token) instead of an Auth Key to ensure enhanced security. - - - - - -```dart -String UID = "user_id"; // Replace with the UID of the user to login -String authKey = "AUTH_KEY"; // Replace with your App Auth Key - -final user = await CometChat.getLoggedInUser(); -if (user == null) { -await CometChat.login(UID, authKey, - onSuccess: (User user) { - debugPrint("Login Successful : $user" ); - }, onError: (CometChatException e) { - debugPrint("Login failed with exception: ${e.message}"); - } - ); -} -``` - - - - - -We recommend you call the CometChat `login()` method once your user logs into your app. The `login()` method needs to be called only once. +**Credentials:** App ID, Region, Auth Key from [CometChat Dashboard](https://app.cometchat.com) +**Test UIDs:** `cometchat-uid-1` through `cometchat-uid-5` + + +The CometChat Flutter SDK lets you add real-time messaging, voice, and video calling to any Flutter application — iOS, Android, Web, or Desktop. + +## Requirements + +| Requirement | Minimum Version | +|-------------|-----------------| +| Flutter SDK | 1.2 | +| Android API Level | 21 | +| iOS | 11 | + +Requires AndroidX compatibility. For iOS platform setup, see [Setup](/sdk/flutter/setup#ios-setup). + +## 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/flutter/setup). + + + Log in users with Auth Key (development) or Auth Token (production). See [Authentication](/sdk/flutter/authentication-overview). + + + 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, 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: + + + + Flutter sample app + + + +## UI Kits + +Skip the UI work — use pre-built, customizable components: + + + + Flutter UI Kit + + + +## Resources + + + + UIDs, GUIDs, auth tokens, and core SDK concepts + + + Message categories, types, and hierarchy + + + Latest SDK version and release notes + + + Migration guide for V3 users + + + Common issues and solutions + + + +## Next Steps + + + + Install and initialize the CometChat Flutter SDK + + + Log in users with Auth Key or Auth Token + + + Send your first text, media, or custom message + + + UIDs, GUIDs, auth tokens, and core SDK concepts + + diff --git a/sdk/flutter/presenter-mode.mdx b/sdk/flutter/presenter-mode.mdx index 88887cb43..0c3f0369c 100644 --- a/sdk/flutter/presenter-mode.mdx +++ b/sdk/flutter/presenter-mode.mdx @@ -1,35 +1,45 @@ --- title: "Presenter Mode" +sidebarTitle: "Presenter Mode" +description: "Learn how to implement presenter mode in your Flutter app for webinars, online classes, and broadcast-style calling experiences with CometChat." --- + +```dart +// Join as presenter +String callToken = "GENERATED_TOKEN"; -## Overview +PresentationSettings settings = (PresentationSettingsBuilder() + ..enableDefaultLayout = true + ..isPresenter = true // true = presenter, false = viewer + ..listener = this +).build(); -The Presenter Mode feature allows developers to create a calling service experience in which: +CometChatCalls.joinPresentation(callToken, settings, + onSuccess: (Widget? widget) => debugPrint("Joined"), + onError: (e) => debugPrint("Error: $e") +); +``` -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. +- **Presenter** (max 5): Can share video, audio, and screen +- **Viewer** (up to 100 total): Passive consumers, no outgoing streams + -Using this feature developers can create experiences such as: +## Overview -1. All hands calls -2. Keynote speeches -3. Webinars -4. Talk shows -5. Online classes -6. and many more... +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. -About this guide +| 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 | -This guide demonstrates how to start a presentation into an Android application. Before you begin, we strongly recommend you read the calling setup guide. +Using this feature developers can create experiences such as webinars, keynote speeches, talk shows, online classes, and more. -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 presentation, generate a call token using `generateToken()` as described in [Call Session](/sdk/flutter/direct-call#generate-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. @@ -59,6 +69,29 @@ CometChatCalls.joinPresentation(generatedToken, presentationSettings, onSuccess:
+ +**On Success** — A `Widget?` representing the presentation UI to be displayed in your application: + + + +**Widget Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `callingWidget` | Widget? | A Flutter widget containing the presentation UI. Display this widget in your screen to show the presentation interface. | `Widget` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to start the presentation session."` | +| `details` | string | Additional technical details | `"The call token provided is invalid or expired."` | + + + The `CometChatCallsEventsListener` listener provides you with the below callback methods: | Callback Method | Description | @@ -104,3 +137,23 @@ 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: + + +--- + +## Next Steps + + + + Start standard call sessions without presenter mode + + + Record call and presentation sessions + + + Customize the video layout and containers + + + Configure session timeout settings for calls + + diff --git a/sdk/flutter/rate-limits.mdx b/sdk/flutter/rate-limits.mdx index 17581b144..32a79fc78 100644 --- a/sdk/flutter/rate-limits.mdx +++ b/sdk/flutter/rate-limits.mdx @@ -1,34 +1,103 @@ --- title: "Rate Limits" +sidebarTitle: "Rate Limits" +description: "Understand CometChat REST API rate limits, response headers, and how to handle rate-limited requests in your Flutter application." --- + +- 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 +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 -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` +## Response Headers + +CometChat includes rate limit information in response headers: + +| 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) | + +## Handling Rate Limits + +When you exceed the rate limit, CometChat returns HTTP `429 Too Many Requests`. Implement exponential backoff to handle this gracefully: + + + +```dart +Future callWithRetry( + Future Function() apiCall, { + int maxRetries = 3, +}) async { + for (int attempt = 0; attempt < maxRetries; attempt++) { + try { + return await apiCall(); + } catch (e) { + if (e is CometChatException && + e.code == "TOO_MANY_REQUEST" && + attempt < maxRetries - 1) { + final waitTime = Duration(seconds: (1 << attempt)); // 1s, 2s, 4s + debugPrint('Rate limited. Retrying in ${waitTime.inSeconds}s...'); + await Future.delayed(waitTime); + } else { + rethrow; + } + } + } + throw Exception('Max retries exceeded'); +} + +// Usage +UsersRequest usersRequest = (UsersRequestBuilder() + ..limit = 30 +).build(); + +List users = await callWithRetry(() => usersRequest.fetchNext( + onSuccess: (List userList) => userList, + onError: (CometChatException e) => throw e, +)); +``` + + + +## 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 -`X-Rate-Limit-Reset: 1625143246` - -## Is there any endpoint that returns rate limit of all resources ? - -No, we don't provide a rate-limit endpoint. + +Rate limits can be adjusted based on your use case and plan. Contact CometChat support if you need higher limits. + -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: +--- -`X-Rate-Limit: 700` +## Next Steps -`X-Rate-Limit-Remaining: 699` + + + Install and configure the CometChat Flutter SDK + + + Learn the core concepts behind CometChat + + diff --git a/sdk/flutter/reactions.mdx b/sdk/flutter/reactions.mdx index 86824cf6c..7f0c3e057 100644 --- a/sdk/flutter/reactions.mdx +++ b/sdk/flutter/reactions.mdx @@ -1,79 +1,333 @@ --- title: "Reactions" +sidebarTitle: "Reactions" +description: "Add, remove, and fetch emoji reactions on messages in your Flutter chat application using CometChat SDK." --- + +| Field | Value | +| --- | --- | +| Key Classes | `BaseMessage`, `Reaction`, `ReactionCount`, `ReactionEvent`, `ReactionsRequest`, `ReactionsRequestBuilder` | +| Key Methods | `CometChat.addReaction()`, `CometChat.removeReaction()`, `ReactionsRequest.fetchNext()`, `ReactionsRequest.fetchPrevious()`, `CometChatHelper.updateMessageWithReactionInfo()` | +| Listener Events | `onMessageReactionAdded`, `onMessageReactionRemoved` | +| Prerequisites | SDK initialized, user logged in | -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 Flutter SDK. +```dart +// Add a reaction to a message +CometChat.addReaction(messageId, "\U0001f600", onSuccess: (message) { + debugPrint("Reaction added: ${message.getReactions().last}"); +}, onError: (e) {}); + +// Remove a reaction from a message +CometChat.removeReaction(messageId, "\U0001f600", onSuccess: (message) { + debugPrint("Reaction removed"); +}, onError: (e) {}); + +// Fetch reactions for a message +ReactionsRequest request = (ReactionsRequestBuilder() + ..messageId = messageId + ..limit = 30 +).build(); +request.fetchNext(onSuccess: (reactions) {}, onError: (e) {}); + +// Listen for reaction events +CometChat.addMessageListener("LISTENER_ID", MessageListener( + onMessageReactionAdded: (ReactionEvent event) {}, + onMessageReactionRemoved: (ReactionEvent event) {}, +)); +``` + + + +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. + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) + ## 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. + +| Parameter | Type | Description | +| --- | --- | --- | +| `messageId` | `int` | The ID of the message to react to. | +| `reaction` | `String` | The reaction emoji (e.g., `"\U0001f600"`, `"\U0001f44d"`). | ```dart int messageId = 1; -CometChat.addReaction(messageId, "😴", onSuccess: (message) { +CometChat.addReaction(messageId, "\U0001f634", onSuccess: (message) { debugPrint("Success : ${message.getReactions().last}"); }, onError: (e) { debugPrint("Error: ${e.message}"); }); ``` - - -You can react on Text, Media and Custom messages. - + +**On Success** — A `BaseMessage` object representing the message with the reaction added: + + + +**BaseMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `401` | +| `metadata` | object | Custom metadata attached to the message | `{}` | +| `receiver` | object | Receiver user object | [See below \u2193](#add-reaction-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `null` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `sentAt` | number | Epoch timestamp when the message was sent | `1745554729` | +| `receiverUid` | string | UID of the receiver | `"cometchat-uid-2"` | +| `type` | string | Type of the message | `"text"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `null` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `1745554750` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `0` | +| `replyCount` | number | Number of replies to this message | `0` | +| `sender` | object | Sender user object | [See below \u2193](#add-reaction-sender-object) | +| `receiverType` | string | Type of the receiver | `"user"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `0` | +| `parentMessageId` | number | ID of the parent message (for threads) | `0` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"message"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` | +| `updatedAt` | number | Epoch timestamp when the message was last updated | `1745554729` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `quotedMessageId` | number | ID of the quoted message | `null` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-1"` | +| `name` | string | Display name of the sender | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-2"` | +| `name` | string | Display name of the receiver | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to process the reaction."` | +| `details` | string | Additional technical details | `"An unexpected error occurred while processing the request."` | + + ## 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. + +| Parameter | Type | Description | +| --- | --- | --- | +| `messageId` | `int` | The ID of the message to remove the reaction from. | +| `reaction` | `String` | The reaction emoji to remove (e.g., `"\U0001f600"`, `"\U0001f44d"`). | ```dart - int messageId = 1; -CometChat.removeReaction(messageId, "😴", onSuccess: (message) { +CometChat.removeReaction(messageId, "\U0001f634", onSuccess: (message) { debugPrint("Success : ${message.getReactions().last}"); }, onError: (e) { debugPrint("Error: ${e.message}"); }); ``` + + + + +**On Success** — A `BaseMessage` object representing the message with the reaction removed: + + + +**BaseMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `401` | +| `metadata` | object | Custom metadata attached to the message | `{}` | +| `receiver` | object | Receiver user object | [See below \u2193](#remove-reaction-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `null` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `sentAt` | number | Epoch timestamp when the message was sent | `1745554729` | +| `receiverUid` | string | UID of the receiver | `"cometchat-uid-2"` | +| `type` | string | Type of the message | `"text"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `null` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `1745554750` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `0` | +| `replyCount` | number | Number of replies to this message | `0` | +| `sender` | object | Sender user object | [See below \u2193](#remove-reaction-sender-object) | +| `receiverType` | string | Type of the receiver | `"user"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `0` | +| `parentMessageId` | number | ID of the parent message (for threads) | `0` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"message"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` | +| `updatedAt` | number | Epoch timestamp when the message was last updated | `1745554729` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `quotedMessageId` | number | ID of the quoted message | `null` | + +--- + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-1"` | +| `name` | string | Display name of the sender | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-2"` | +| `name` | string | Display name of the receiver | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to process the reaction."` | +| `details` | string | Additional technical details | `"An unexpected error occurred while processing the request."` | + + + +Both `addReaction()` and `removeReaction()` return a [`BaseMessage`](/sdk/reference/messages#basemessage) object with the updated reactions. + +## Read Reaction Data from a Message + +Any `BaseMessage` exposes reaction data through its `reactions` property: + +### Get All Reactions + +Use the `reactions` property to retrieve the list of reactions on a message. Returns a `List<`[`ReactionCount`](/sdk/reference/auxiliary#reactioncount)`>` containing the reactions, or an empty list if no one has reacted. + + + +```dart +message.reactions +``` +### Check if the Logged-in User Has Reacted -## 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 `limit` with max limit 100. For this, you will require the ID of the message. This ID needs to be passed to the `messageId` property of the builder class. The `reaction` property will allow you to fetch details for specific reaction or emoji. +Use the `reactedByMe` property on any `ReactionCount` object to check whether the logged-in user has reacted with that particular emoji. Returns `true` if they have, `false` otherwise. + + +```dart +for (ReactionCount reactionCount in message.reactions) { + debugPrint("isReactedByMe ${reactionCount.reactedByMe}"); //Return true is logged-in user reacted on that message, otherwise false +} +``` + + -| Setting | Description | -|-----------------------------------|------------------------------------------------------------------------------------------------------------------| -| `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 Reactions for a Message +To get the full list of who reacted with what on a specific message, use `ReactionsRequestBuilder`. You can paginate through results with `fetchNext()` and `fetchPrevious()` (max 100 per request). -## Fetch Next -The fetchNext() method fetches the next set of reactions for the message. +| Builder Property | Type | Description | +| --- | --- | --- | +| `messageId` | `int?` | The message ID to fetch reactions for. Required. | +| `reaction` | `String?` | Filter to a specific emoji (e.g., `"\U0001f60a"`). When set, only reactions matching this emoji are returned. | +| `limit` | `int` | Number of reactions to fetch per request. Default is `10`. | +### Fetch Next +The `fetchNext()` method fetches the next set of reactions for the message. ```dart int messageId = 1; -ReactionRequest reactionRequest = (ReactionRequestBuilder()..limit = 30..messageId = messageId).build(); +ReactionsRequest reactionsRequest = (ReactionsRequestBuilder() + ..limit = 30 + ..messageId = messageId +).build(); -reactionRequest.fetchNext( - onSuccess: (messageReactions) { - for (MessageReaction messageReaction in messageReactions) { - debugPrint("Success: ${messageReaction.getReactions()}"); +reactionsRequest.fetchNext( + onSuccess: (reactions) { + for (Reaction reaction in reactions) { + debugPrint("Success: $reaction"); } }, onError: (e) { @@ -81,11 +335,62 @@ reactionRequest.fetchNext( }, ); ``` - -## Fetch Previous +The `fetchNext()` method returns a `List` representing individual user reactions on the message. + + +**On Success** — A list of `Reaction` objects for the message: + + + +**Reaction Object (per item in list):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique reaction identifier | `"r1"` | +| `messageId` | number | ID of the message this reaction belongs to | `1` | +| `reaction` | string | The reaction emoji | `"\U0001f634"` | +| `uid` | string | UID of the user who reacted | `"cometchat-uid-1"` | +| `reactedAt` | number | Epoch timestamp when the reaction was added | `1745554729` | +| `reactedBy` | object | User who added the reaction | [See below \u2193](#fetch-next-reaction-reactedby-object) | + +--- + + + +**`reactedBy` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-1"` | +| `name` | string | Display name of the user | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to fetch the requested data."` | +| `details` | string | Additional technical details | `"An unexpected error occurred while processing the request."` | + + + +### Fetch Previous + The `fetchPrevious()` method fetches the previous set of reactions for the message. @@ -93,12 +398,15 @@ The `fetchPrevious()` method fetches the previous set of reactions for the messa ```dart int messageId = 1; -ReactionRequest reactionRequest = (ReactionRequestBuilder()..limit = 30..messageId = messageId).build(); +ReactionsRequest reactionsRequest = (ReactionsRequestBuilder() + ..limit = 30 + ..messageId = messageId +).build(); -reactionRequest.fetchPrevious( - onSuccess: (messageReactions) { - for (MessageReaction messageReaction in messageReactions) { - debugPrint("Success: ${messageReaction.getReactions()}"); +reactionsRequest.fetchPrevious( + onSuccess: (reactions) { + for (Reaction reaction in reactions) { + debugPrint("Success: $reaction"); } }, onError: (e) { @@ -106,13 +414,61 @@ reactionRequest.fetchPrevious( }, ); ``` -
-## 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. + +**On Success** — A list of `Reaction` objects for the message: + + + +**Reaction Object (per item in list):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique reaction identifier | `"r1"` | +| `messageId` | number | ID of the message this reaction belongs to | `1` | +| `reaction` | string | The reaction emoji | `"\U0001f634"` | +| `uid` | string | UID of the user who reacted | `"cometchat-uid-1"` | +| `reactedAt` | number | Epoch timestamp when the reaction was added | `1745554729` | +| `reactedBy` | object | User who added the reaction | [See below \u2193](#fetch-previous-reaction-reactedby-object) | + +--- + + + +**`reactedBy` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-1"` | +| `name` | string | Display name of the user | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to fetch the requested data."` | +| `details` | string | Additional technical details | `"An unexpected error occurred while processing the request."` | + + + +## Real-Time Reaction Events + +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. @@ -136,78 +492,85 @@ class MyClass with MessageListener { } } ``` - +Each reaction listener callback receives a `ReactionEvent` object containing: +| Parameter | Type | Description | +| --- | --- | --- | +| `reaction` | `Reaction?` | The reaction that was added or removed. | +| `receiverId` | `String?` | The UID or GUID of the receiver. | +| `receiverType` | `String?` | The type of the receiver (`"user"` or `"group"`). | +| `conversationId` | `String?` | The unique conversation identifier. | +| `parentMessageId` | `int?` | The 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 ```dart String listenerID = "UNIQUE_LISTENER_ID"; -CometChat.removeMessageReactionListener(listenerID); +CometChat.removeMessageListener(listenerID); ``` - -## Get Reactions List -To retrieve the list of reactions reacted on particular message, you can use the `reactions` property on `TextMessage`, `MediaMessage` and `CustomMessage`. This property will return a List of `ReactionCount` containing the reactions, or an empty list if no one reacted on the message. - - - -```dart -message.reactions -``` + +Always remove listeners when they're no longer needed (e.g., in the `dispose()` method). Failing to remove listeners can cause memory leaks and duplicate event handling. + - - +## Update a Message with Reaction Info +When you receive a real-time reaction event, you'll want to update the corresponding message object so your UI reflects the change. `CometChatHelper.updateMessageWithReactionInfo()` does this — it takes the `BaseMessage` instance, the `Reaction` event data, and the action type, then returns the updated message. -## 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 `reactedByMe` property on any `ReactionCount` object. This method will return a boolean value, `true` if the logged-in user has reacted on that message, otherwise `false`. +| Parameter | Type | Description | +|-----------|------|-------------| +| `baseMessage` | `BaseMessage` | The message object to update. | +| `messageReaction` | `Reaction` | The reaction event received from the listener. | +| `action` | `String` | `ReactionAction.reactionAdded` or `ReactionAction.reactionRemoved` | ```dart -for (ReactionCount reactionCount in message.reactions) { - debugPrint("isReactedByMe ${reactionCount.reactedByMe}"); //Return true is logged-in user reacted on that message, otherwise false +// Pass the message and Reaction from your listener (e.g. onMessageReactionAdded) +Future refreshMessageWithReaction( + BaseMessage message, + Reaction messageReaction, +) async { + // The received reaction event action type: reactionAdded or reactionRemoved + var action = ReactionAction.reactionAdded; + + BaseMessage? modifiedBaseMessage = + await CometChatHelper.updateMessageWithReactionInfo( + message, + messageReaction, + action, + ); + // Use modifiedBaseMessage?.reactions to refresh your UI } ``` - -## Updated 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. - -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 (`ReactionAction.REACTION_ADDED` or `ReactionAction.REACTION_REMOVED`) that corresponds to the message being reacted to. - - - -```dart -// The message to which the reaction is related -BaseMessage message = ...; - -// The reaction event data received in real-time -MessageReaction messageReaction = ...; +After calling this method, use `modifiedBaseMessage?.reactions` to get the latest reactions and refresh your UI. -// The recieved reaction event real-time action type. Can be CometChatConstants.REACTION_ADDED or CometChatConstants.REACTION_REMOVED -var action = CometChatConstants.REACTION_ADDED; - -BaseMessage modifiedBaseMessage = await CometChatHelper.updateMessageWithReactionInfo( - baseMessage, - messageReaction, - action -); -``` +--- - - +## Next Steps + + + + Send text, media, and custom messages to users and groups + + + Listen for incoming messages in real-time and fetch missed messages + + + Create and manage message threads + + + Mention users and groups in messages + + diff --git a/sdk/flutter/real-time-listeners.mdx b/sdk/flutter/real-time-listeners.mdx index e1685bb8e..0ba1a4508 100644 --- a/sdk/flutter/real-time-listeners.mdx +++ b/sdk/flutter/real-time-listeners.mdx @@ -1,26 +1,235 @@ --- title: "All Real Time Listeners" +sidebarTitle: "Real-Time Listeners" +description: "Learn how to register and manage real-time event listeners for messages, users, groups, calls, connections, login, and AI in the CometChat Flutter SDK." --- + +```dart +// Message Listener - receive messages in real-time +CometChat.addMessageListener("message_listener", MessageListener( + onTextMessageReceived: (TextMessage message) { + debugPrint("Text received: ${message.text}"); + }, + onMediaMessageReceived: (MediaMessage message) { + debugPrint("Media received: ${message.attachment?.fileUrl}"); + }, +)); + +// User Listener - track user online/offline status +CometChat.addUserListener("user_listener", UserListener( + onUserOnline: (User user) { + debugPrint("${user.name} is online"); + }, + onUserOffline: (User user) { + debugPrint("${user.name} is offline"); + }, +)); + +// Group Listener - track group membership changes +CometChat.addGroupListener("group_listener", GroupListener( + onGroupMemberJoined: (action, joinedUser, joinedGroup) { + debugPrint("${joinedUser.name} joined ${joinedGroup.name}"); + }, + onGroupMemberLeft: (action, leftUser, leftGroup) { + debugPrint("${leftUser.name} left ${leftGroup.name}"); + }, +)); + +// Call Listener - track incoming/outgoing calls +CometChat.addCallListener("call_listener", CallListener( + onIncomingCallReceived: (Call call) { + debugPrint("Incoming call from: ${call.sender?.name}"); + }, + onOutgoingCallAccepted: (Call call) { + debugPrint("Call accepted"); + }, +)); + +// Connection Listener - monitor WebSocket connection +CometChat.addConnectionListener("conn_listener", ConnectionListener( + onConnected: () => debugPrint("Connected"), + onDisconnected: () => debugPrint("Disconnected"), +)); + +// Remove listeners when no longer needed +CometChat.removeMessageListener("message_listener"); +CometChat.removeUserListener("user_listener"); +CometChat.removeGroupListener("group_listener"); +CometChat.removeCallListener("call_listener"); +CometChat.removeConnectionListener("conn_listener"); +``` + + +CometChat provides real-time event listeners to keep your app updated with live changes. These listeners notify your app when messages are received, users come online/offline, group membership changes occur, calls are initiated, and connection state changes. + + +**Listener Cleanup Required:** Always remove listeners when they're no longer needed (e.g., on widget dispose or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + + +CometChat provides 7 listener types: + +1. [MessageListener](#message-listener) +2. [UserListener](#user-listener) +3. [GroupListener](#group-listener) +4. [CallListener](#call-listener) +5. [ConnectionListener](#connection-listener) +6. [LoginListener](#login-listener) +7. [AIAssistantListener](#ai-assistant-listener) + +## Message Listener + +The `MessageListener` class provides you with live events related to messages. Below are the callback methods provided by the `MessageListener` class. + +### MessageListener Events + +| Method | Parameter Type | Description | +| ------ | -------------- | ----------- | +| `onTextMessageReceived(TextMessage message)` | [`TextMessage`](/sdk/reference/messages#textmessage) | Triggered when a text message is received | +| `onMediaMessageReceived(MediaMessage message)` | [`MediaMessage`](/sdk/reference/messages#mediamessage) | Triggered when a media message is received | +| `onCustomMessageReceived(CustomMessage message)` | [`CustomMessage`](/sdk/reference/messages#custommessage) | Triggered when a custom message is received | +| `onTypingStarted(TypingIndicator typingIndicator)` | [`TypingIndicator`](/sdk/reference/auxiliary#typingindicator) | Triggered when a user starts typing in a user/group conversation | +| `onTypingEnded(TypingIndicator typingIndicator)` | [`TypingIndicator`](/sdk/reference/auxiliary#typingindicator) | Triggered when a user stops typing in a user/group conversation | +| `onMessagesDelivered(MessageReceipt messageReceipt)` | [`MessageReceipt`](/sdk/reference/auxiliary#messagereceipt) | Triggered when messages are marked as delivered for a conversation | +| `onMessagesRead(MessageReceipt messageReceipt)` | [`MessageReceipt`](/sdk/reference/auxiliary#messagereceipt) | Triggered when messages are marked as read for a conversation | +| `onMessagesDeliveredToAll(MessageReceipt messageReceipt)` | [`MessageReceipt`](/sdk/reference/auxiliary#messagereceipt) | Triggered when messages are delivered to all participants | +| `onMessagesReadByAll(MessageReceipt messageReceipt)` | [`MessageReceipt`](/sdk/reference/auxiliary#messagereceipt) | Triggered when messages are read by all participants | +| `onMessageEdited(BaseMessage message)` | [`BaseMessage`](/sdk/reference/messages#basemessage) | Triggered when a message is edited in a user/group conversation | +| `onMessageDeleted(BaseMessage message)` | [`BaseMessage`](/sdk/reference/messages#basemessage) | Triggered when a message is deleted in a user/group conversation | +| `onMessageModerated(BaseMessage message)` | [`BaseMessage`](/sdk/reference/messages#basemessage) | Triggered when a message is moderated | +| `onTransientMessageReceived(TransientMessage message)` | [`TransientMessage`](/sdk/reference/auxiliary#transientmessage) | Triggered when a transient message is received | +| `onInteractiveMessageReceived(InteractiveMessage message)` | `InteractiveMessage` | Triggered when an interactive message is received | +| `onInteractionGoalCompleted(InteractionReceipt receipt)` | `InteractionReceipt` | Triggered when an interaction goal is achieved | +| `onMessageReactionAdded(ReactionEvent reactionEvent)` | `ReactionEvent` | Triggered when a reaction is added to a message | +| `onMessageReactionRemoved(ReactionEvent reactionEvent)` | `ReactionEvent` | Triggered when a reaction is removed from a message | +| `onAIAssistantMessageReceived(AIAssistantMessage message)` | `AIAssistantMessage` | Triggered when an AI assistant message is received | +| `onAIToolResultReceived(AIToolResultMessage message)` | `AIToolResultMessage` | Triggered when an AI tool result message is received | +| `onAIToolArgumentsReceived(AIToolArgumentMessage message)` | `AIToolArgumentMessage` | Triggered when AI tool arguments are received | + +To add the `MessageListener`, you need to use the `addMessageListener()` method provided by the `CometChat` class. + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `listenerId` | `String` | A unique identifier for the listener. No two listeners should share the same ID. | +| `listener` | `MessageListener` | An instance of a class that implements the `MessageListener` mixin | + + + +```dart +class Class_Name with MessageListener { + + //CometChat.addMessageListener("listenerId", this); + @override + void onTextMessageReceived(TextMessage textMessage) { + + } + + @override + void onMediaMessageReceived(MediaMessage mediaMessage) { + + } + + @override + void onCustomMessageReceived(CustomMessage customMessage) { + + } + + @override + void onTypingStarted(TypingIndicator typingIndicator) { + + } + + @override + void onTypingEnded(TypingIndicator typingIndicator) { + + } + + + @override + void onMessagesDelivered(MessageReceipt messageReceipt) { + + } + + @override + void onMessagesRead(MessageReceipt messageReceipt) { + + } + + @override + void onMessageEdited(BaseMessage message) { + + } + + @override + void onMessageDeleted(BaseMessage message) { + + } + + @override + void onInteractionGoalCompleted(InteractionReceipt receipt) { + + + } + + @override + void onInteractiveMessageReceived(InteractiveMessage message) { + + } + + + @Override + public void onTransientMessageReceived(TransientMessage transientMessage) { + + } + + @Override + public void onMessageReactionAdded(ReactionEvent reactionEvent) { + + } + + @Override + public void onMessageReactionRemoved(ReactionEvent reactionEvent) { + + } -CometChat provides 4 listeners viz. +} +``` + + + + + +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. -1. [UserListener](#user-listener) -2. [GroupListener](#group-listener) -3. [MessageListener](#message-listener) +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. + + + +```dart +CometChat.removeMessageListener(UNIQUE_LISTENER_ID) +``` + + ## User Listener The `UserListener` class provides you with live events related to users. Below are the callback methods provided by the `UserListener` class. -| Method | Information | -| -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `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. | +### UserListener Events + +| Method | Parameter Type | Description | +| ------ | -------------- | ----------- | +| `onUserOnline(User user)` | [`User`](/sdk/reference/entities#user) | 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)` | [`User`](/sdk/reference/entities#user) | 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. +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `listenerId` | `String` | A unique identifier for the listener. No two listeners should share the same ID. | +| `listener` | `UserListener` | An instance of a class that implements the `UserListener` mixin | + ```dart @@ -61,18 +270,25 @@ CometChat.removeUserListener(UNIQUE_LISTENER_ID) The `GroupListener` class provides you with all the real-time events related to groups. Below are the callback methods provided by the `GroupListener` class. -| Method | Information | -| ----------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | -| `onGroupMemberJoined(Action action, User joinedUser, Group joinedGroup)` | This method is triggered when a user joins any group. All the members present in the group will receive this event. | -| `onGroupMemberLeft(Action action, User leftUser, Group leftGroup)` | This method is triggered when a user who was a member of any group leaves the group. All the members of the group receive this event. | -| `onGroupMemberKicked(Action action, User kickedUser, User kickedBy, Group kickedFrom)` | This method is triggered when a user is kicked from a group. All the members including the user receive this event | -| `onGroupMemberBanned(Action action, User bannedUser, User bannedBy, Group bannedFrom)` | This method is triggered when a user is banned from a group. All the members including the user receive this event | -| `onGroupMemberUnbanned(Action action, User unbannedUser, User unbannedBy, Group unbannedFrom)` | This method is triggered when a user is banned from a group. All the members of the group receive this event. | -| `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. | +### GroupListener Events + +| Method | Parameter Types | Description | +| ------ | --------------- | ----------- | +| `onGroupMemberJoined(Action action, User joinedUser, Group joinedGroup)` | [`Action`](/sdk/reference/messages#action), [`User`](/sdk/reference/entities#user), [`Group`](/sdk/reference/entities#group) | Triggered when a user joins any group. All the members present in the group will receive this event. | +| `onGroupMemberLeft(Action action, User leftUser, Group leftGroup)` | [`Action`](/sdk/reference/messages#action), [`User`](/sdk/reference/entities#user), [`Group`](/sdk/reference/entities#group) | Triggered when a user who was a member of any group leaves the group. All the members of the group receive this event. | +| `onGroupMemberKicked(Action action, User kickedUser, User kickedBy, Group kickedFrom)` | [`Action`](/sdk/reference/messages#action), [`User`](/sdk/reference/entities#user), [`User`](/sdk/reference/entities#user), [`Group`](/sdk/reference/entities#group) | Triggered when a user is kicked from a group. All the members including the user receive this event. | +| `onGroupMemberBanned(Action action, User bannedUser, User bannedBy, Group bannedFrom)` | [`Action`](/sdk/reference/messages#action), [`User`](/sdk/reference/entities#user), [`User`](/sdk/reference/entities#user), [`Group`](/sdk/reference/entities#group) | Triggered when a user is banned from a group. All the members including the user receive this event. | +| `onGroupMemberUnbanned(Action action, User unbannedUser, User unbannedBy, Group unbannedFrom)` | [`Action`](/sdk/reference/messages#action), [`User`](/sdk/reference/entities#user), [`User`](/sdk/reference/entities#user), [`Group`](/sdk/reference/entities#group) | Triggered when a user is unbanned from a group. All the members of the group receive this event. | +| `onGroupMemberScopeChanged(Action action, User updatedBy, User updatedUser, String scopeChangedTo, String scopeChangedFrom, Group group)` | [`Action`](/sdk/reference/messages#action), [`User`](/sdk/reference/entities#user), [`User`](/sdk/reference/entities#user), `String`, `String`, [`Group`](/sdk/reference/entities#group) | 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)` | [`Action`](/sdk/reference/messages#action), [`User`](/sdk/reference/entities#user), [`User`](/sdk/reference/entities#user), [`Group`](/sdk/reference/entities#group) | 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. +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `listenerId` | `String` | A unique identifier for the listener. No two listeners should share the same ID. | +| `listener` | `GroupListener` | An instance of a class that implements the `GroupListener` mixin | + ```dart @@ -135,105 +351,244 @@ CometChat.removeGroupListener(UNIQUE_LISTENER_ID) -## Message Listener +## Call Listener -The `MessageListener` class provides you with live events related to messages. Below are the callback methods provided by the `MessageListener` class. +The `CallListener` class provides you with real-time events related to calls. Below are the callback methods provided by the `CallListener` class. -| Method | Information | -| --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | -| `onTextMessageReceived(TextMessage message)` | This event is triggered when a Text Message is received. | -| `onMediaMessageReceived(MediaMessage message)` | This event is triggered when a Media Message is received. | -| `onCustomMessageReceived(CustomMessage message)` | This event is triggered when a Custom Message is received. | -| `onTypingStarted(TypingIndicator typingIndicator)` | This event is triggered when a user starts typing in a user/group conversation | -| `onTypingEnded(TypingIndicator typingIndicator)` | This event is triggered when a user stops typing in a user/group conversation. | -| `onMessagesDelivered(MessageReceipt messageReceipt)` | This event is triggered when a set of messages are marked as delivered for any particular conversation. | -| `onMessagesRead(MessageReceipt messageReceipt)` | This event is triggered when a set of messages are marked as read for any particular conversation. | -| `onMessageEdited(BaseMessage message)` | This method is triggered when a particular message has been edited in a user/group conversation. | -| `onMessageDeleted(BaseMessage message)` | This event is triggered when a particular message is deleted in a user/group conversation. | -| `onInteractiveMessageReceived(InteractiveMessage message)` | This event is triggered when an Interactive Message is received. | -| `onInteractionGoalCompleted(InteractionReceipt receipt)` | This event is triggered when an interaction Goal is achieved. | -| `onTransientMessageReceived(TransientMessage transientMessage)` | This event is triggered when a Transient Message is received. | -| `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. | +### CallListener Events -To add the `MessageListener`, you need to use the `addMessageListener()` method provided by the `CometChat` class. +| Method | Parameter Type | Description | +| ------ | -------------- | ----------- | +| `onIncomingCallReceived(Call call)` | [`Call`](/sdk/reference/messages#call) | Triggered when an incoming call is received | +| `onOutgoingCallAccepted(Call call)` | [`Call`](/sdk/reference/messages#call) | Triggered when an outgoing call is accepted by the receiver | +| `onOutgoingCallRejected(Call call)` | [`Call`](/sdk/reference/messages#call) | Triggered when an outgoing call is rejected by the receiver | +| `onIncomingCallCancelled(Call call)` | [`Call`](/sdk/reference/messages#call) | Triggered when an incoming call is cancelled by the caller | +| `onCallEndedMessageReceived(Call call)` | [`Call`](/sdk/reference/messages#call) | Triggered when a call ended message is received | + +To add the `CallListener`, you need to use the `addCallListener()` method provided by the `CometChat` class. + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `listenerId` | `String` | A unique identifier for the listener. No two listeners should share the same ID. | +| `listener` | `CallListener` | An instance of a class that implements the `CallListener` mixin | ```dart -class Class_Name with MessageListener { +class Class_Name with CallListener { + //CometChat.addCallListener("UNIQUE_LISTENER_ID", this); - //CometChat.addMessageListener("listenerId", this); - @override - void onTextMessageReceived(TextMessage textMessage) { + @override + void onIncomingCallReceived(Call call) { } @override - void onMediaMessageReceived(MediaMessage mediaMessage) { + void onOutgoingCallAccepted(Call call) { } @override - void onCustomMessageReceived(CustomMessage customMessage) { + void onOutgoingCallRejected(Call call) { } - @override - void onTypingStarted(TypingIndicator typingIndicator) { + @override + void onIncomingCallCancelled(Call call) { } @override - void onTypingEnded(TypingIndicator typingIndicator) { + void onCallEndedMessageReceived(Call call) { } +} +``` + + + + + +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 no longer needed, remove it using the `removeCallListener()` method. + + + +```dart +CometChat.removeCallListener(UNIQUE_LISTENER_ID) +``` + + + + + +## Connection Listener + +The `ConnectionListener` class provides you with real-time events related to the WebSocket connection status. Below are the callback methods provided by the `ConnectionListener` class. + +### ConnectionListener Events + +| Method | Parameter Type | Description | +| ------ | -------------- | ----------- | +| `onConnected()` | — | Triggered when the SDK successfully establishes a connection to the WebSocket server | +| `onConnecting()` | — | Triggered when the SDK is attempting to establish a connection to the WebSocket server | +| `onDisconnected()` | — | Triggered when the SDK gets disconnected due to network fluctuations or other issues | +| `onFeatureThrottled()` | — | Triggered when CometChat automatically toggles off certain features to prevent performance loss | +| `onConnectionError(CometChatException error)` | `CometChatException` | Triggered when an error occurs while maintaining the WebSocket connection | + +To add the `ConnectionListener`, you need to use the `addConnectionListener()` method provided by the `CometChat` class. + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `listenerId` | `String` | A unique identifier for the listener. No two listeners should share the same ID. | +| `listener` | `ConnectionListener` | An instance of a class that implements the `ConnectionListener` mixin | + + + +```dart +class Class_Name with ConnectionListener { + //CometChat.addConnectionListener("UNIQUE_LISTENER_ID", this); @override - void onMessagesDelivered(MessageReceipt messageReceipt) { + void onConnected() { } @override - void onMessagesRead(MessageReceipt messageReceipt) { + void onConnecting() { } @override - void onMessageEdited(BaseMessage message) { + void onDisconnected() { } @override - void onMessageDeleted(BaseMessage message) { + void onFeatureThrottled() { } @override - void onInteractionGoalCompleted(InteractionReceipt receipt) { - + void onConnectionError(CometChatException error) { } +} +``` + + + + + +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 `ConnectionListener` is no longer needed, remove it using the `removeConnectionListener()` method. + + + +```dart +CometChat.removeConnectionListener(UNIQUE_LISTENER_ID) +``` + + + + + +## Login Listener + +The `LoginListener` class provides you with real-time events related to user authentication. Below are the callback methods provided by the `LoginListener` class. + +### LoginListener Events + +| Method | Parameter Type | Description | +| ------ | -------------- | ----------- | +| `loginSuccess(User user)` | [`User`](/sdk/reference/entities#user) | Triggered when a user successfully logs in | +| `loginFailure(CometChatException e)` | `CometChatException` | Triggered when a login attempt fails | +| `logoutSuccess()` | — | Triggered when a user successfully logs out | +| `logoutFailure(CometChatException e)` | `CometChatException` | Triggered when a logout attempt fails | + +To add the `LoginListener`, you need to use the `addLoginListener()` method provided by the `CometChat` class. + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `listenerId` | `String` | A unique identifier for the listener. No two listeners should share the same ID. | +| `listener` | `LoginListener` | An instance of a class that implements the `LoginListener` mixin | + + + +```dart +class Class_Name with LoginListener { + //CometChat.addLoginListener("UNIQUE_LISTENER_ID", this); + @override - void onInteractiveMessageReceived(InteractiveMessage message) { + void loginSuccess(User user) { } + @override + void loginFailure(CometChatException e) { + + } - @Override - public void onTransientMessageReceived(TransientMessage transientMessage) { + @override + void logoutSuccess() { } - @Override - public void onMessageReactionAdded(ReactionEvent reactionEvent) { + @override + void logoutFailure(CometChatException e) { } - @Override - public void onMessageReactionRemoved(ReactionEvent reactionEvent) { +} +``` + + + + + +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 `LoginListener` is no longer needed, remove it using the `removeLoginListener()` method. + + + +```dart +CometChat.removeLoginListener(UNIQUE_LISTENER_ID) +``` + + + + + +## AI Assistant Listener + +The `AIAssistantListener` class provides you with real-time events related to AI assistant interactions. Below are the callback methods provided by the `AIAssistantListener` class. + +### AIAssistantListener Events + +| Method | Parameter Type | Description | +| ------ | -------------- | ----------- | +| `onAIAssistantEventReceived(AIAssistantBaseEvent aiAssistantBaseEvent)` | [`AIAssistantBaseEvent`](/sdk/reference/messages#aiassistantbaseevent) | Triggered when an AI assistant event is received | + +To add the `AIAssistantListener`, you need to use the `addAIAssistantListener()` method provided by the `CometChat` class. + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `listenerId` | `String` | A unique identifier for the listener. No two listeners should share the same ID. | +| `listener` | `AIAssistantListener` | An instance of a class that implements the `AIAssistantListener` mixin | + + + +```dart +class Class_Name with AIAssistantListener { + //CometChat.addAIAssistantListener("UNIQUE_LISTENER_ID", this); + + @override + void onAIAssistantEventReceived(AIAssistantBaseEvent aiAssistantBaseEvent) { } @@ -246,4 +601,39 @@ class Class_Name with MessageListener { 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. +Once the `AIAssistantListener` is no longer needed, remove it using the `removeAIAssistantListener()` method. + + + +```dart +CometChat.removeAIAssistantListener(UNIQUE_LISTENER_ID) +``` + + + + + +--- + +## Next Steps + + + + Handle incoming messages in real-time using message listeners + + + Track when users come online or go offline + + + Show real-time typing status in conversations + + + Track message delivery and read status + + + Monitor SDK connection to CometChat servers + + + Monitor user login and logout events + + diff --git a/sdk/flutter/receive-messages.mdx b/sdk/flutter/receive-messages.mdx index 92246df7f..f4f376439 100644 --- a/sdk/flutter/receive-messages.mdx +++ b/sdk/flutter/receive-messages.mdx @@ -1,14 +1,29 @@ --- title: "Receive A Message" +sidebarTitle: "Receive Messages" +description: "Learn how to receive real-time messages and fetch missed or historical messages using the CometChat Flutter SDK." --- + +| Field | Value | +| --- | --- | +| Key Classes | `MessageListener`, `MessagesRequest`, `MessagesRequestBuilder` | +| Key Methods | `addMessageListener()`, `removeMessageListener()`, `fetchPrevious()`, `fetchNext()`, `getLastDeliveredMessageId()`, `getUnreadMessageCount()` | +| Listener Events | `onTextMessageReceived`, `onMediaMessageReceived`, `onCustomMessageReceived`, `onTypingStarted`, `onTypingEnded`, `onMessagesDelivered`, `onMessagesRead`, `onMessageEdited`, `onMessageDeleted`, `onInteractiveMessageReceived`, `onMessageReactionAdded`, `onMessageReactionRemoved` | +| Prerequisites | SDK initialized, user logged in | + + Receiving messages with CometChat has two parts: 1. Adding a listener to receive [Real-time Messages](/sdk/flutter/receive-messages#real-time-messages) when your app is running 2. Calling a method to retrieve [Missed Messages](/sdk/flutter/receive-messages#missed-messages) when your app was not running + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) + + ## Real-time Messages *In other words, as a recipient, how do I receive messages when my app is running?* @@ -55,8 +70,39 @@ onInteractiveMessageReceived(InteractiveMessage message) { | ---------- | ---------------------------------------------------------------------------------------------- | | listenerID | An ID that uniquely identifies that listener. We recommend using the activity or fragment name | +### MessageListener Events + +The `MessageListener` mixin provides the following event callbacks. All events are verified against the Flutter SDK source. + +| Event | Parameter Type | Description | +| --- | --- | --- | +| `onTextMessageReceived` | [`TextMessage`](/sdk/reference/messages#textmessage) | Triggered when a text message is received | +| `onMediaMessageReceived` | [`MediaMessage`](/sdk/reference/messages#mediamessage) | Triggered when a media message (image, video, audio, file) is received | +| `onCustomMessageReceived` | [`CustomMessage`](/sdk/reference/messages#custommessage) | Triggered when a custom message is received | +| `onTypingStarted` | [`TypingIndicator`](/sdk/reference/auxiliary#typingindicator) | Triggered when a user starts typing | +| `onTypingEnded` | [`TypingIndicator`](/sdk/reference/auxiliary#typingindicator) | Triggered when a user stops typing | +| `onMessagesDelivered` | [`MessageReceipt`](/sdk/reference/auxiliary#messagereceipt) | Triggered when messages are delivered to the recipient | +| `onMessagesRead` | [`MessageReceipt`](/sdk/reference/auxiliary#messagereceipt) | Triggered when messages are read by the recipient | +| `onMessagesDeliveredToAll` | [`MessageReceipt`](/sdk/reference/auxiliary#messagereceipt) | Triggered when messages are delivered to all group members | +| `onMessagesReadByAll` | [`MessageReceipt`](/sdk/reference/auxiliary#messagereceipt) | Triggered when messages are read by all group members | +| `onMessageEdited` | [`BaseMessage`](/sdk/reference/messages#basemessage) | Triggered when a message is edited | +| `onMessageDeleted` | [`BaseMessage`](/sdk/reference/messages#basemessage) | Triggered when a message is deleted | +| `onTransientMessageReceived` | [`TransientMessage`](/sdk/reference/auxiliary#transientmessage) | Triggered when a transient (non-persistent) message is received | +| `onInteractiveMessageReceived` | `InteractiveMessage` | Triggered when an interactive message is received | +| `onInteractionGoalCompleted` | `InteractionReceipt` | Triggered when an interaction goal is completed | +| `onMessageReactionAdded` | `ReactionEvent` | Triggered when a reaction is added to a message | +| `onMessageReactionRemoved` | `ReactionEvent` | Triggered when a reaction is removed from a message | +| `onMessageModerated` | [`BaseMessage`](/sdk/reference/messages#basemessage) | Triggered when a message is moderated | +| `onAIAssistantMessageReceived` | `AIAssistantMessage` | Triggered when an AI assistant message is received | +| `onAIToolResultReceived` | `AIToolResultMessage` | Triggered when an AI tool result is received | +| `onAIToolArgumentsReceived` | `AIToolArgumentMessage` | Triggered when AI tool arguments are received | + We recommend you remove the listener once the activity or fragment is not in use. Typically, this can be added in the `dispose()` method. + +Always remove message listeners when they're no longer needed (e.g., in the `dispose()` method of your StatefulWidget). Failing to remove listeners can cause memory leaks and duplicate event handling. + + ```dart @@ -119,6 +165,94 @@ messageRequest.fetchNext(onSuccess: (List list) { + +**On Success** — A `List` containing the fetched messages (each item is a BaseMessage object): + + + +**BaseMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `501` | +| `metadata` | object | Custom metadata attached to the message | `{}` | +| `receiver` | object | Receiver user object | [See below ↓](#fetch-missed-user-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `null` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `sentAt` | number | Epoch timestamp when the message was sent | `1745554729` | +| `receiverUid` | string | UID of the receiver | `"cometchat-uid-1"` | +| `type` | string | Type of the message | `"text"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `null` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `0` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `0` | +| `replyCount` | number | Number of replies to this message | `0` | +| `sender` | object | Sender user object | [See below ↓](#fetch-missed-user-sender-object) | +| `receiverType` | string | Type of the receiver | `"user"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `0` | +| `parentMessageId` | number | ID of the parent message (for threads) | `0` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"message"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` | +| `updatedAt` | number | Epoch timestamp when the message was last updated | `1745554729` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `quotedMessageId` | number | ID of the quoted message | `null` | +| `quotedMessage` | object | The quoted message object | `null` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-2"` | +| `name` | string | Display name of the sender | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-1"` | +| `name` | string | Display name of the receiver | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to fetch the requested data."` | +| `details` | string | Additional technical details | `"An unexpected error occurred while processing the request."` | + + + ### For a Particular Group Conversation @@ -151,6 +285,94 @@ messageRequest.fetchNext(onSuccess: (List list) { + +**On Success** — A `List` containing the fetched messages (each item is a BaseMessage object): + + + +**BaseMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `502` | +| `metadata` | object | Custom metadata attached to the message | `{}` | +| `receiver` | object | Receiver group object | [See below ↓](#fetch-missed-group-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `null` | +| `conversationId` | string | Unique conversation identifier | `"group_cometchat-uid-1"` | +| `sentAt` | number | Epoch timestamp when the message was sent | `1745554729` | +| `receiverUid` | string | GUID of the receiver group | `"cometchat-uid-1"` | +| `type` | string | Type of the message | `"text"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `null` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `0` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `0` | +| `replyCount` | number | Number of replies to this message | `0` | +| `sender` | object | Sender user object | [See below ↓](#fetch-missed-group-sender-object) | +| `receiverType` | string | Type of the receiver | `"group"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `0` | +| `parentMessageId` | number | ID of the parent message (for threads) | `0` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"message"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` | +| `updatedAt` | number | Epoch timestamp when the message was last updated | `1745554729` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `quotedMessageId` | number | ID of the quoted message | `null` | +| `quotedMessage` | object | The quoted message object | `null` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-2"` | +| `name` | string | Display name of the sender | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-1"` | +| `name` | string | Display name of the receiver | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to fetch the requested data."` | +| `details` | string | Additional technical details | `"An unexpected error occurred while processing the request."` | + + + ## Unread Messages *In other words, as a logged-in user, how do I fetch the messages I've not read?* @@ -190,6 +412,94 @@ messageRequest.fetchPrevious(onSuccess: (List list) { + +**On Success** — A `List` containing the fetched messages (each item is a BaseMessage object): + + + +**BaseMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `503` | +| `metadata` | object | Custom metadata attached to the message | `{}` | +| `receiver` | object | Receiver user object | [See below ↓](#fetch-unread-user-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `null` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `sentAt` | number | Epoch timestamp when the message was sent | `1745554729` | +| `receiverUid` | string | UID of the receiver | `"cometchat-uid-1"` | +| `type` | string | Type of the message | `"text"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `null` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `1745554730` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `0` | +| `replyCount` | number | Number of replies to this message | `0` | +| `sender` | object | Sender user object | [See below ↓](#fetch-unread-user-sender-object) | +| `receiverType` | string | Type of the receiver | `"user"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `0` | +| `parentMessageId` | number | ID of the parent message (for threads) | `0` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"message"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` | +| `updatedAt` | number | Epoch timestamp when the message was last updated | `1745554729` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `quotedMessageId` | number | ID of the quoted message | `null` | +| `quotedMessage` | object | The quoted message object | `null` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-2"` | +| `name` | string | Display name of the sender | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-1"` | +| `name` | string | Display name of the receiver | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to fetch the requested data."` | +| `details` | string | Additional technical details | `"An unexpected error occurred while processing the request."` | + + + ### For a Particular Group Conversation @@ -223,10 +533,98 @@ messageRequest.fetchPrevious(onSuccess: (List list) { + +**On Success** — A `List` containing the fetched messages (each item is a BaseMessage object): + + + +**BaseMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `504` | +| `metadata` | object | Custom metadata attached to the message | `{}` | +| `receiver` | object | Receiver user object | [See below ↓](#fetch-unread-group-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `null` | +| `conversationId` | string | Unique conversation identifier | `"group_cometchat-uid-1"` | +| `sentAt` | number | Epoch timestamp when the message was sent | `1745554729` | +| `receiverUid` | string | GUID of the receiver group | `"cometchat-uid-1"` | +| `type` | string | Type of the message | `"text"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `null` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `1745554730` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `0` | +| `replyCount` | number | Number of replies to this message | `0` | +| `sender` | object | Sender user object | [See below ↓](#fetch-unread-group-sender-object) | +| `receiverType` | string | Type of the receiver | `"group"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `0` | +| `parentMessageId` | number | ID of the parent message (for threads) | `0` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"message"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` | +| `updatedAt` | number | Epoch timestamp when the message was last updated | `1745554729` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `quotedMessageId` | number | ID of the quoted message | `null` | +| `quotedMessage` | object | The quoted message object | `null` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-2"` | +| `name` | string | Display name of the sender | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-1"` | +| `name` | string | Display name of the receiver | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to fetch the requested data."` | +| `details` | string | Additional technical details | `"An unexpected error occurred while processing the request."` | + + + 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 `is` operator to check the type of object. +The list of messages received is in the form of objects of [`BaseMessage`](/sdk/reference/messages#basemessage) class. 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`](/sdk/reference/messages#action) or [`Call`](/sdk/reference/messages#call) class. You can use the `is` operator to check the type of object. @@ -267,6 +665,94 @@ messageRequest.fetchPrevious(onSuccess: (List list) { + +**On Success** — A `List` containing the fetched messages (each item is a BaseMessage object): + + + +**BaseMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `505` | +| `metadata` | object | Custom metadata attached to the message | `{}` | +| `receiver` | object | Receiver user object | [See below ↓](#fetch-history-user-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `null` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `sentAt` | number | Epoch timestamp when the message was sent | `1745554729` | +| `receiverUid` | string | UID of the receiver | `"cometchat-uid-1"` | +| `type` | string | Type of the message | `"text"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `null` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `0` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `0` | +| `replyCount` | number | Number of replies to this message | `0` | +| `sender` | object | Sender user object | [See below ↓](#fetch-history-user-sender-object) | +| `receiverType` | string | Type of the receiver | `"user"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `0` | +| `parentMessageId` | number | ID of the parent message (for threads) | `0` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"message"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` | +| `updatedAt` | number | Epoch timestamp when the message was last updated | `1745554729` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `quotedMessageId` | number | ID of the quoted message | `null` | +| `quotedMessage` | object | The quoted message object | `null` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-2"` | +| `name` | string | Display name of the sender | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-1"` | +| `name` | string | Display name of the receiver | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to fetch the requested data."` | +| `details` | string | Additional technical details | `"An unexpected error occurred while processing the request."` | + + + Calling the `fetchPrevious()` method on the same object repeatedly allows you to fetch all the previous messages in a paginated way. ### For a Particular Group Conversation @@ -301,6 +787,94 @@ messageRequest.fetchPrevious(onSuccess: (List list) {
+ +**On Success** — A `List` containing the fetched messages (each item is a BaseMessage object): + + + +**BaseMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `506` | +| `metadata` | object | Custom metadata attached to the message | `{}` | +| `receiver` | object | Receiver user object | [See below ↓](#fetch-history-group-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `null` | +| `conversationId` | string | Unique conversation identifier | `"group_cometchat-uid-1"` | +| `sentAt` | number | Epoch timestamp when the message was sent | `1745554729` | +| `receiverUid` | string | GUID of the receiver group | `"cometchat-uid-1"` | +| `type` | string | Type of the message | `"text"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `null` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `0` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `0` | +| `replyCount` | number | Number of replies to this message | `0` | +| `sender` | object | Sender user object | [See below ↓](#fetch-history-group-sender-object) | +| `receiverType` | string | Type of the receiver | `"group"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `0` | +| `parentMessageId` | number | ID of the parent message (for threads) | `0` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"message"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` | +| `updatedAt` | number | Epoch timestamp when the message was last updated | `1745554729` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `quotedMessageId` | number | ID of the quoted message | `null` | +| `quotedMessage` | object | The quoted message object | `null` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-2"` | +| `name` | string | Display name of the sender | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-1"` | +| `name` | string | Display name of the receiver | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to fetch the requested data."` | +| `details` | string | Additional technical details | `"An unexpected error occurred while processing the request."` | + + + 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 @@ -356,6 +930,94 @@ messageRequest.fetchPrevious(onSuccess: (List list) {
+ +**On Success** — A `List` containing the fetched messages (each item is a BaseMessage object): + + + +**BaseMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `507` | +| `metadata` | object | Custom metadata attached to the message | `{}` | +| `receiver` | object | Receiver user object | [See below ↓](#fetch-search-user-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `null` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `sentAt` | number | Epoch timestamp when the message was sent | `1745554729` | +| `receiverUid` | string | UID of the receiver | `"cometchat-uid-1"` | +| `type` | string | Type of the message | `"text"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `null` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `0` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `0` | +| `replyCount` | number | Number of replies to this message | `0` | +| `sender` | object | Sender user object | [See below ↓](#fetch-search-user-sender-object) | +| `receiverType` | string | Type of the receiver | `"user"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `0` | +| `parentMessageId` | number | ID of the parent message (for threads) | `0` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"message"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` | +| `updatedAt` | number | Epoch timestamp when the message was last updated | `1745554729` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `quotedMessageId` | number | ID of the quoted message | `null` | +| `quotedMessage` | object | The quoted message object | `null` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-2"` | +| `name` | string | Display name of the sender | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-1"` | +| `name` | string | Display name of the receiver | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to fetch the requested data."` | +| `details` | string | Additional technical details | `"An unexpected error occurred while processing the request."` | + + + ### For a Particular Group Conversation @@ -388,6 +1050,94 @@ messageRequest.fetchPrevious(onSuccess: (List list) { + +**On Success** — A `List` containing the fetched messages (each item is a BaseMessage object): + + + +**BaseMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `508` | +| `metadata` | object | Custom metadata attached to the message | `{}` | +| `receiver` | object | Receiver group object | [See below ↓](#fetch-search-group-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `null` | +| `conversationId` | string | Unique conversation identifier | `"group_cometchat-guid-1"` | +| `sentAt` | number | Epoch timestamp when the message was sent | `1745554729` | +| `receiverUid` | string | GUID of the receiver group | `"cometchat-guid-1"` | +| `type` | string | Type of the message | `"text"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `null` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `0` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `0` | +| `replyCount` | number | Number of replies to this message | `0` | +| `sender` | object | Sender user object | [See below ↓](#fetch-search-group-sender-object) | +| `receiverType` | string | Type of the receiver | `"group"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `0` | +| `parentMessageId` | number | ID of the parent message (for threads) | `0` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"message"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` | +| `updatedAt` | number | Epoch timestamp when the message was last updated | `1745554729` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `quotedMessageId` | number | ID of the quoted message | `null` | +| `quotedMessage` | object | The quoted message object | `null` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-2"` | +| `name` | string | Display name of the sender | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-1"` | +| `name` | string | Display name of the receiver | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to fetch the requested data."` | +| `details` | string | Additional technical details | `"An unexpected error occurred while processing the request."` | + + + ## Unread Messages Count *In other words, as a logged-in user, how do I find out the number of unread messages that I have?* @@ -639,3 +1389,22 @@ CometChat.getUnreadMessageCountForAllGroups(hideMessagesFromBlockedUsers: hideMe
In the `onSuccess()` callback, you will receive a `Map` which will contain the `GUIDs` of the groups as the key and the unread message counts as the values. + +--- + +## Next Steps + + + + Track when messages are delivered and read by recipients + + + Show real-time typing status in conversations + + + Allow users to edit previously sent messages + + + Remove messages from conversations + + diff --git a/sdk/flutter/recording.mdx b/sdk/flutter/recording.mdx index 54935f250..765b7ccd5 100644 --- a/sdk/flutter/recording.mdx +++ b/sdk/flutter/recording.mdx @@ -1,10 +1,42 @@ --- title: "Recording" +sidebarTitle: "Recording" +description: "Learn how to implement call recording for voice and video calls in your Flutter application using the CometChat SDK." --- + +```dart +// Enable recording button in call settings +CallSettings callSettings = (CallSettingsBuilder() + ..showCallRecordButton = true + ..startRecordingOnCallStart = false // Optional: auto-start recording + ..listener = this +).build(); -This section will guide you to implement call recording feature for the voice and video calls. +// Start recording manually +CometChatCalls.startRecording(onSuccess: (success) { + debugPrint("Recording started"); +}, onError: (error) { + debugPrint("Error: $error"); +}); + +// Stop recording +CometChatCalls.stopRecording(onSuccess: (success) { + debugPrint("Recording stopped"); +}, onError: (error) { + debugPrint("Error: $error"); +}); +``` + +**Recordings are available on the [CometChat Dashboard](https://app.cometchat.com) → Calls section.** + + +Record voice and video calls for playback, compliance, or archival purposes. Recording is built on top of the [Call Session](/sdk/flutter/direct-call) — you add recording listeners to your call settings and optionally control recording programmatically. + + +**Available via:** SDK | [Dashboard](https://app.cometchat.com) + ## Implementation @@ -63,6 +95,29 @@ debugPrint("Error $error");
+ +**On Success** — A `String` message confirming that recording has started: + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `message` | string | Success confirmation message | `"Recording started successfully"` | + + + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to start recording."` | +| `details` | string | Additional technical details | `"An error occurred while attempting to start the call recording."` | + + + ### Stop Recording You can use the stopRecording() method to stop call recording. @@ -80,3 +135,49 @@ debugPrint("Error $error");
+ + +**On Success** — A `String` message confirming that recording has stopped: + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `message` | string | Success confirmation message | `"Recording stopped successfully"` | + + + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to stop recording."` | +| `details` | string | Additional technical details | `"An error occurred while attempting to stop the call recording."` | + + + +## Downloading Recordings + +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". + +--- + +## Next Steps + + + + Implement ringing call flows with accept/reject functionality + + + Retrieve and display call history for users and groups + + + Start call sessions without the ringing flow + + + Install and initialize the Calls SDK + + diff --git a/sdk/flutter/resources-overview.mdx b/sdk/flutter/resources-overview.mdx index ef8fe0d02..8003c043b 100644 --- a/sdk/flutter/resources-overview.mdx +++ b/sdk/flutter/resources-overview.mdx @@ -1,10 +1,61 @@ --- title: "Resources" sidebarTitle: "Overview" +description: "Access rate limits, extensions, webhooks, and other resources for the CometChat Flutter SDK." --- + +- [All Real-Time Listeners](/sdk/flutter/all-real-time-listeners) — Complete listener reference +- [Upgrading from v3](/sdk/flutter/upgrading-from-v3-guide) — Migration guide +- [Rate Limits](/sdk/flutter/rate-limits) — API rate limit details +- [Extensions](/sdk/flutter/extensions-overview) — Available extensions +- [Webhooks](/sdk/flutter/webhooks-overview) — Webhook configuration +- [Error Codes](/sdk/flutter/error-codes) — SDK error code reference +- [Best Practices](/sdk/flutter/best-practices) — Recommended patterns +- [Troubleshooting](/sdk/flutter/troubleshooting) — Common issues and solutions +- [Notifications](/sdk/flutter/notifications) — Push notification configuration + 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/flutter/real-time-listeners) guide. + +If you're upgrading from v3, we recommend reading our [Upgrading from v3](/sdk/flutter/upgrading-from-v3-guide) guide. + +### Additional Resources + +- [Flutter UI Kit Documentation](/ui-kit/flutter/overview) — Pre-built UI components for Flutter +- [CometChat Dashboard](https://app.cometchat.com) — Manage your app settings, users, and features +- [Sample Apps](https://github.com/cometchat) — Explore sample Flutter applications + +--- + +## Next Steps + + + + Complete reference for all CometChat event listeners + + + Step-by-step migration guide from SDK v3 to v4 + + + Understand API rate limits and quotas + + + Explore available extensions for your app + + + Complete SDK error code reference + + + Recommended patterns and practices + + + Common issues and solutions + + + Push notification preferences and configuration + + diff --git a/sdk/flutter/retrieve-conversations.mdx b/sdk/flutter/retrieve-conversations.mdx index 7008851cc..cb43d8cc9 100644 --- a/sdk/flutter/retrieve-conversations.mdx +++ b/sdk/flutter/retrieve-conversations.mdx @@ -1,20 +1,82 @@ --- title: "Retrieve Conversations" +sidebarTitle: "Retrieve Conversations" +description: "Fetch, filter, tag, and search conversations using the CometChat Flutter SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +```dart +// Fetch conversations list +ConversationsRequest request = (ConversationsRequestBuilder() + ..limit = 30 +).build(); + +await request.fetchNext( + onSuccess: (List conversations) { + for (Conversation conv in conversations) { + debugPrint("Conversation: ${conv.conversationId}"); + } + }, + onError: (CometChatException e) => debugPrint("Error: ${e.message}"), +); + +// Get a specific conversation +CometChat.getConversation("UID", "user", + onSuccess: (Conversation conv) => debugPrint("Got: ${conv.conversationId}"), + onError: (CometChatException e) => debugPrint("Error: ${e.message}"), +); + +// Tag a conversation +CometChat.tagConversation("UID", "user", ["archived"], + onSuccess: (Conversation conv) => debugPrint("Tagged: ${conv.conversationId}"), + onError: (CometChatException e) => debugPrint("Error: ${e.message}"), +); + +// Convert message to conversation +Conversation conversation = CometChat.getConversationFromMessage(message); +``` + + +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 + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) + + *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: +Fetching using this builder will return [`Conversation`](/sdk/reference/entities#conversation) objects. + +### ConversationsRequestBuilder Parameters + +The `ConversationsRequestBuilder` to fetch conversations with various filters. + +| Property | Type | Description | +|----------|------|-------------| +| `limit` | `int?` | Number of conversations to fetch per request. Default is 30, max is 50. | +| `conversationType` | `String?` | Filter by `CometChatConversationType.user` or `CometChatConversationType.group`. If not set, both types are returned. | +| `withUserAndGroupTags` | `bool?` | Include user/group tags in the response. Default is `false`. | +| `withTags` | `bool?` | Include conversation tags in the response. Default is `false`. | +| `tags` | `List?` | Fetch only conversations matching the specified tags. | +| `userTags` | `List?` | Fetch only user conversations where the user has the specified tags. | +| `groupTags` | `List?` | Fetch only group conversations where the group has the specified tags. | +| `includeBlockedUsers` | `bool?` | Include conversations with blocked users. Default is `false`. | +| `withBlockedInfo` | `bool?` | Include blocked user information (`hasBlockedMe`, `blockedByMe`). Default is `false`. | +| `searchKeyword` | `String?` | Search conversations by user or group name. Requires Conversation & Advanced Search. | +| `unread` | `bool?` | Fetch only conversations with unread messages. Requires Conversation & Advanced Search. Default is `false`. | +| `setPage` | `int?` | Fetch conversations from a particular page. | +| `hideAgentic` | `bool?` | Exclude AI agent conversations from results. Default is `false`. | +| `onlyAgentic` | `bool?` | Fetch only AI agent conversations. Default is `false`. | ### 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. @@ -23,19 +85,16 @@ ConversationsRequest conversationRequest = (ConversationsRequestBuilder() ..limit = 50 ).build(); ``` - - -### 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: + +The default value for `limit` is 30 and the max value is 50. + -* user - Only fetches user conversation. -* group - Only fetches group conversations. +### Set Conversation Type -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. @@ -45,14 +104,14 @@ ConversationsRequest conversationRequest = (ConversationsRequestBuilder() ..conversationType = CometChatConversationType.user ).build(); ``` - - +When conversations are fetched successfully, the response will include an array of [`Conversation`](/sdk/reference/entities#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 `Conversation` object. Default is `false`. @@ -62,14 +121,48 @@ ConversationsRequest conversationRequest = (ConversationsRequestBuilder() ..withUserAndGroupTags = true ).build(); ``` + + + +When conversations are fetched successfully, the response will include `tags` arrays on the `conversationWith` objects (user or group). +### Set User Tags + +Fetch user conversations where the user has specific tags. + + + +```dart +ConversationsRequest conversationRequest = (ConversationsRequestBuilder() + ..limit = 50 + ..userTags = ["tag1"] +).build(); +``` + +When conversations are fetched successfully, the response will include only user conversations where the user has the specified tags. + +### Set Group Tags + +Fetch group conversations where the group has specific tags. + + + +```dart +ConversationsRequest conversationRequest = (ConversationsRequestBuilder() + ..limit = 50 + ..groupTags = ["tag1"] +).build(); +``` + +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` +Use `withTags = true` to include conversation tags in the response. Default is `false`. @@ -79,14 +172,12 @@ ConversationsRequest conversationRequest = (ConversationsRequestBuilder() ..withTags = true ).build(); ``` - - ### Set Tags -This method helps you fetch the conversations based on the specified tags. +Fetch conversations that have specific tags. @@ -98,14 +189,12 @@ ConversationsRequest conversationRequest = (ConversationsRequestBuilder() ..tags = tags ).build(); ``` - - ### 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. @@ -115,14 +204,14 @@ ConversationsRequest conversationRequest = (ConversationsRequestBuilder() ..includeBlockedUsers = true ).build(); ``` - - +When conversations are fetched successfully, the response includes conversations with blocked users. To also get blocked info details (`blockedByMe`, `hasBlockedMe`), 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 `withBlockedInfo = true` to include blocked user information in the response. @@ -132,14 +221,12 @@ ConversationsRequest conversationRequest = (ConversationsRequestBuilder() ..withBlockedInfo = true ).build(); ``` - - ### Search Conversations -This method helps you search a conversation based on User or Group name. +Use `searchKeyword` to search conversations by user or group name. @@ -155,14 +242,14 @@ This feature is only available with `Conversation & Advanced Search`. The `Conve ..searchKeyword = "Hiking" ).build(); ``` -
-
+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 `unread = true` to fetch only conversations with unread messages. @@ -178,16 +265,50 @@ This feature is only available with `Conversation & Advanced Search`. The `Conve ..unread = true ).build(); ``` +
+
+ +When conversations are fetched successfully, the response includes only conversations with unread messages (`unreadMessageCount` > 0). +### Hide Agentic Conversations + +Use `hideAgentic = true` to exclude AI agent conversations from the list. + + + +```dart +ConversationsRequest conversationRequest = (ConversationsRequestBuilder() + ..limit = 50 + ..hideAgentic = true +).build(); +``` + + +### Only Agentic Conversations +Use `onlyAgentic = true` to fetch only AI agent conversations. + + + +```dart +ConversationsRequest conversationRequest = (ConversationsRequestBuilder() + ..limit = 50 + ..onlyAgentic = true +).build(); +``` + -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. + +`hideAgentic` and `onlyAgentic` 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. -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. @@ -202,14 +323,170 @@ conversationRequest.fetchNext( }, onError: (CometChatException e){ - } + }); ``` - - -The `Conversation`object consists of the below fields: + +**On Success** — A `List` containing conversation objects with their associated user/group and last message details: + + + +**Conversation Object (per item in list):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `conversationType` | string | Type of conversation | `"user"` | +| `conversationWith` | object | User or Group the conversation is with | [See below ↓](#fetch-conversations-conversationwith-user-object) | +| `lastMessage` | object | Last message in the conversation | [See below ↓](#fetch-conversations-lastmessage-object) | +| `updatedAt` | number | Epoch timestamp of last update | `1745554729` | +| `unreadMessageCount` | number | Count of unread messages | `2` | +| `tags` | array | Tags associated with the conversation | `[]` | +| `unreadMentionsCount` | number | Count of unread mentions | `0` | +| `lastReadMessageId` | number | ID of the last read message | `398` | +| `latestMessageId` | number | ID of the latest message | `401` | + +--- + + + +**`conversationWith` Object (User):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-2"` | +| `name` | string | Display name of the user | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + +--- + + + +**`conversationWith` Object (Group):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Unique identifier of the group | `"cometchat-guid-1"` | +| `name` | string | Display name of the group | `"Flutter Devs"` | +| `icon` | string | Group icon URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `description` | string | Group description | `"A group for Flutter developers"` | +| `membersCount` | number | Number of members in the group | `5` | +| `metadata` | object | Custom metadata | `{}` | +| `joinedAt` | number | Epoch timestamp when the user joined | `1745500000` | +| `hasJoined` | boolean | Whether the current user has joined | `true` | +| `createdAt` | number | Epoch timestamp when the group was created | `1745400000` | +| `owner` | string | UID of the group owner | `"cometchat-uid-1"` | +| `updatedAt` | number | Epoch timestamp of last update | `1745554729` | +| `tags` | array | Group tags | `[]` | +| `type` | string | Group type | `"public"` | +| `scope` | string | Scope of the current user in the group | `"admin"` | +| `password` | string | Group password (for password-protected groups) | `null` | +| `isBannedFromGroup` | boolean | Whether the current user is banned | `false` | + +--- + + + +**`lastMessage` Object (TextMessage):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `401` | +| `metadata` | object | Custom metadata attached to the message | `{}` | +| `receiver` | object | Receiver user object | [See below ↓](#fetch-conversations-lastmessage-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `null` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `sentAt` | number | Epoch timestamp when the message was sent | `1745554729` | +| `receiverUid` | string | UID of the receiver | `"cometchat-uid-2"` | +| `type` | string | Type of the message | `"text"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `null` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `1745554730` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `0` | +| `replyCount` | number | Number of replies to this message | `0` | +| `sender` | object | Sender user object | [See below ↓](#fetch-conversations-lastmessage-sender-object) | +| `receiverType` | string | Type of the receiver | `"user"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `0` | +| `parentMessageId` | number | ID of the parent message (for threads) | `-1` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"message"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `1745554730` | +| `updatedAt` | number | Epoch timestamp when the message was last updated | `1745554729` | +| `text` | string | The text content of the message | `"Hey, are you available for a call?"` | +| `tags` | array | List of tags associated with the message | `[]` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `mentionedUsers` | array | List of mentioned users | `[]` | +| `hasMentionedMe` | boolean | Whether the current user is mentioned | `false` | +| `reactions` | array | List of reactions on the message | `[]` | +| `moderationStatus` | string | Moderation status of the message | `null` | +| `quotedMessageId` | number | ID of the quoted message | `null` | + +--- + + + +**`lastMessage.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-2"` | +| `name` | string | Display name of the sender | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + +--- + + + +**`lastMessage.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-1"` | +| `name` | string | Display name of the receiver | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to fetch the requested data."` | +| `details` | string | Additional technical details | `"An unexpected error occurred while retrieving conversations."` | + + + +The `Conversation` object consists of the below fields: | Field | Information | | --------------------- | -------------------------------------------------------------------- | @@ -225,16 +502,13 @@ The `Conversation`object consists of the below fields: *In other words, as a logged-in user, how do I tag a conversation?* -In order 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: +Use `tagConversation()` to add tags to a conversation. - 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` | Array of tags to add | @@ -252,11 +526,142 @@ CometChat.tagConversation(conversationWith, conversationType, tags, } ); ``` - - + +**On Success** — A `Conversation` object containing the updated conversation with the applied tags: + + + +**Conversation Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `conversationType` | string | Type of conversation | `"user"` | +| `conversationWith` | object | User or Group the conversation is with | [See below ↓](#tag-conversation-conversationwith-user-object) | +| `lastMessage` | object | Last message in the conversation | [See below ↓](#tag-conversation-lastmessage-object) | +| `updatedAt` | number | Epoch timestamp of last update | `1745554729` | +| `unreadMessageCount` | number | Count of unread messages | `0` | +| `tags` | array | Tags associated with the conversation | `["archived"]` | +| `unreadMentionsCount` | number | Count of unread mentions | `0` | +| `lastReadMessageId` | number | ID of the last read message | `398` | +| `latestMessageId` | number | ID of the latest message | `401` | + +--- + + + +**`conversationWith` Object (User):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-1"` | +| `name` | string | Display name of the user | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`lastMessage` Object (TextMessage):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `401` | +| `metadata` | object | Custom metadata attached to the message | `{}` | +| `receiver` | object | Receiver user object | [See below ↓](#tag-conversation-lastmessage-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `null` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `sentAt` | number | Epoch timestamp when the message was sent | `1745554729` | +| `receiverUid` | string | UID of the receiver | `"cometchat-uid-1"` | +| `type` | string | Type of the message | `"text"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `null` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `1745554730` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `0` | +| `replyCount` | number | Number of replies to this message | `0` | +| `sender` | object | Sender user object | [See below ↓](#tag-conversation-lastmessage-sender-object) | +| `receiverType` | string | Type of the receiver | `"user"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `0` | +| `parentMessageId` | number | ID of the parent message (for threads) | `-1` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"message"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `1745554730` | +| `updatedAt` | number | Epoch timestamp when the message was last updated | `1745554729` | +| `text` | string | The text content of the message | `"Hey, are you available for a call?"` | +| `tags` | array | List of tags associated with the message | `[]` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `mentionedUsers` | array | List of mentioned users | `[]` | +| `hasMentionedMe` | boolean | Whether the current user is mentioned | `false` | +| `reactions` | array | List of reactions on the message | `[]` | +| `moderationStatus` | string | Moderation status of the message | `null` | +| `quotedMessageId` | number | ID of the quoted message | `null` | + +--- + + + +**`lastMessage.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-1"` | +| `name` | string | Display name of the sender | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`lastMessage.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-1"` | +| `name` | string | Display name of the receiver | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to tag the conversation."` | +| `details` | string | Additional technical details | `"An unexpected error occurred while tagging the conversation."` | + + + 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. @@ -267,13 +672,12 @@ The tags for conversations are one-way. This means that if user A tags a convers *In other words, as a logged-in user, 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. - -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` | @@ -288,11 +692,142 @@ CometChat.getConversation(conversationWith, conversationType, } ); ``` - - + +**On Success** — A `Conversation` object containing the details of the requested conversation: + + + +**Conversation Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `conversationType` | string | Type of conversation | `"user"` | +| `conversationWith` | object | User or Group the conversation is with | [See below ↓](#get-conversation-conversationwith-user-object) | +| `lastMessage` | object | Last message in the conversation | [See below ↓](#get-conversation-lastmessage-object) | +| `updatedAt` | number | Epoch timestamp of last update | `1745554729` | +| `unreadMessageCount` | number | Count of unread messages | `0` | +| `tags` | array | Tags associated with the conversation | `[]` | +| `unreadMentionsCount` | number | Count of unread mentions | `0` | +| `lastReadMessageId` | number | ID of the last read message | `398` | +| `latestMessageId` | number | ID of the latest message | `401` | + +--- + + + +**`conversationWith` Object (User):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-1"` | +| `name` | string | Display name of the user | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`lastMessage` Object (TextMessage):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `401` | +| `metadata` | object | Custom metadata attached to the message | `{}` | +| `receiver` | object | Receiver user object | [See below ↓](#get-conversation-lastmessage-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `null` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `sentAt` | number | Epoch timestamp when the message was sent | `1745554729` | +| `receiverUid` | string | UID of the receiver | `"cometchat-uid-1"` | +| `type` | string | Type of the message | `"text"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `null` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `1745554730` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `0` | +| `replyCount` | number | Number of replies to this message | `0` | +| `sender` | object | Sender user object | [See below ↓](#get-conversation-lastmessage-sender-object) | +| `receiverType` | string | Type of the receiver | `"user"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `0` | +| `parentMessageId` | number | ID of the parent message (for threads) | `-1` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"message"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `1745554730` | +| `updatedAt` | number | Epoch timestamp when the message was last updated | `1745554729` | +| `text` | string | The text content of the message | `"Hey, are you available for a call?"` | +| `tags` | array | List of tags associated with the message | `[]` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `mentionedUsers` | array | List of mentioned users | `[]` | +| `hasMentionedMe` | boolean | Whether the current user is mentioned | `false` | +| `reactions` | array | List of reactions on the message | `[]` | +| `moderationStatus` | string | Moderation status of the message | `null` | +| `quotedMessageId` | number | ID of the quoted message | `null` | + +--- + + + +**`lastMessage.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-1"` | +| `name` | string | Display name of the sender | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`lastMessage.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-1"` | +| `name` | string | Display name of the receiver | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to fetch the requested data."` | +| `details` | string | Additional technical details | `"An unexpected error occurred while retrieving the conversation."` | + + + ## Convert Messages to Conversations As per our [Receive Messages](/sdk/flutter/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. @@ -302,13 +837,28 @@ As per our [Receive Messages](/sdk/flutter/receive-messages) guide, for real-tim ```dart Conversation conversation = CometChat.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. + -While converting `Message` object to `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 + + + Track message delivery and read status + + + Listen for incoming messages in real-time + + diff --git a/sdk/flutter/retrieve-group-members.mdx b/sdk/flutter/retrieve-group-members.mdx index 518ba2801..1eaa8a1ba 100644 --- a/sdk/flutter/retrieve-group-members.mdx +++ b/sdk/flutter/retrieve-group-members.mdx @@ -1,17 +1,65 @@ --- title: "Retrieve Group Members" +sidebarTitle: "Retrieve Members" +description: "Fetch and filter group members by scope, status, and search keyword using the CometChat Flutter SDK with pagination support." --- + +```dart +// Retrieve group members with pagination +GroupMembersRequest request = (GroupMembersRequestBuilder("GROUP_ID") + ..limit = 30 +).build(); + +await request.fetchNext( + onSuccess: (List members) { + for (GroupMember member in members) { + debugPrint("Member: ${member.name}, Scope: ${member.scope}"); + } + }, + onError: (CometChatException e) => debugPrint("Error: ${e.message}"), +); + +// Filter by scope (admin, moderator, participant) +GroupMembersRequest scopedRequest = (GroupMembersRequestBuilder("GROUP_ID") + ..limit = 30 + ..scopes = ["admin", "moderator"] +).build(); + +// Search members +GroupMembersRequest searchRequest = (GroupMembersRequestBuilder("GROUP_ID") + ..limit = 30 + ..searchKeyword = "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 -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. +In order to fetch the list of groups members for a group, you can use the `GroupMembersRequest` class. -The `GroupMembersRequestBuilder` class allows you to set the below parameters: + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) + + +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 `GUID` of the group for which the members are to be fetched must be specified in the constructor of the `GroupMembersRequestBuilder` class. +### GroupMembersRequestBuilder + +| Parameter | Type | Description | +|-----------|------|-------------| +| `guid` | `String` | **(Required, constructor)** Group ID for the group whose members are to be fetched. | +| `limit` | `int?` | Maximum number of members to fetch per request. Max `100`, default `30`. | +| `searchKeyword` | `String?` | Search string to filter members by name. | +| `scopes` | `List?` | Filter members by scope (`"admin"`, `"moderator"`, `"participant"`). | +| `status` | `String?` | Filter members by online status (`"online"`, `"offline"`). If not set, returns all members. | +| `setPage` | `int?` | Fetch group members from a particular page number. | + ### Set Limit This method sets the limit i.e. the number of members that should be fetched in a single iteration. @@ -68,6 +116,37 @@ GroupMembersRequest groupMembersRequest = (GroupMembersRequestBuilder(GUID)
+Relevant fields to access on returned members: + +| Field | Property | Return Type | Description | +|-------|----------|-------------|-------------| +| scope | `scope` | `String` | Scope of the member in the group (`"admin"`, `"moderator"`, or `"participant"`) | + +### Set Status + +Filters members by online status: + +| Value | Description | +|-------|-------------| +| `"online"` | Only online members | +| `"offline"` | Only offline members | + +If not set, returns all members regardless of status. + + + +```dart +String GUID = "GUID"; +GroupMembersRequest groupMembersRequest = (GroupMembersRequestBuilder(GUID) + ..limit = 20 + ..status = "online" +).build(); +``` + + + + + 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 depending on the limit set. @@ -90,3 +169,54 @@ groupMembersRequest.fetchNext(onSuccess: (List groupMemberList){
+ +The `fetchNext()` method returns a list of [`GroupMember`](/sdk/reference/entities#groupmember) objects. `GroupMember` extends [`User`](/sdk/reference/entities#user) and adds group-specific fields. + + +**On Success** — A `List` containing the group members for the specified group (each item is a `GroupMember` object): + + + +**GroupMember Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-1"` | +| `name` | string | Display name of the user | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | +| `scope` | string | Member scope in the group | `"admin"` | +| `joinedAt` | number | Epoch timestamp when the member joined the group | `1745550000` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_GUID_NOT_FOUND"` | +| `message` | string | Human-readable error message | `"The specified group does not exist."` | +| `details` | string | Additional technical details | `"Please verify the group ID and try again."` | + + + +--- + +## Next Steps + + + + Add new members to your groups + + + Remove or ban members from groups + + diff --git a/sdk/flutter/retrieve-groups.mdx b/sdk/flutter/retrieve-groups.mdx index 23417e0b0..d5182cea2 100644 --- a/sdk/flutter/retrieve-groups.mdx +++ b/sdk/flutter/retrieve-groups.mdx @@ -1,8 +1,53 @@ --- title: "Retrieve Groups" +sidebarTitle: "Retrieve Groups" +description: "Fetch, filter, and search groups using the CometChat Flutter SDK. Includes pagination, tag-based filtering, joined-only groups, and online member counts." --- + +```dart +// Retrieve groups with pagination +GroupsRequest request = (GroupsRequestBuilder() + ..limit = 30 + ..searchKeyword = "search_term" +).build(); + +await request.fetchNext( + onSuccess: (List groups) { + for (Group group in groups) { + debugPrint("Group: ${group.name}"); + } + }, + onError: (CometChatException e) => debugPrint("Error: ${e.message}"), +); + +// Get a specific group by GUID +await CometChat.getGroup( + "GROUP_ID", + onSuccess: (Group group) => debugPrint("Group: ${group.name}"), + onError: (CometChatException e) => debugPrint("Error: ${e.message}"), +); + +// Fetch only joined groups +GroupsRequest joinedRequest = (GroupsRequestBuilder() + ..limit = 30 + ..joinedOnly = true +).build(); + +// Get online member count +CometChat.getOnlineGroupMemberCount(["GUID"], + onSuccess: (Map count) => debugPrint("Count: $count"), + onError: (CometChatException e) => debugPrint("Error: ${e.message}"), +); +``` + + +Retrieve groups allows you to fetch the list of groups you've joined and groups that are available, as well as get details for a specific group. + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) + ## Retrieve List of Groups @@ -10,9 +55,22 @@ title: "Retrieve Groups" 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. +Use `GroupsRequestBuilder` to fetch groups with filtering, searching, and pagination. + +### GroupsRequestBuilder + +| Parameter | Type | Description | +|-----------|------|-------------| +| `limit` | `int?` | Maximum number of groups to fetch per request. Max `100`, default `30`. | +| `searchKeyword` | `String?` | Search string to filter groups by name. | +| `joinedOnly` | `bool?` | When `true`, returns only groups the logged-in user has joined. Default `false`. | +| `tags` | `List?` | List of tags to filter groups by. Only groups with the specified tags are returned. | +| `withTags` | `bool?` | When `true`, includes tag data in the returned group objects. Default `false`. | +| `setPage` | `int?` | Fetch groups from a particular page number. | + ### 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. @@ -28,7 +86,7 @@ GroupsRequest groupsRequest = (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. @@ -45,7 +103,7 @@ GroupsRequest 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. +When `true`, returns only groups the logged-in user has joined or is a part of. @@ -62,7 +120,7 @@ GroupsRequest 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. +Filters groups by specified tags. The list fetched will only contain the groups that have been tagged with the specified tags. @@ -81,7 +139,7 @@ GroupsRequest groupsRequest = (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. @@ -98,7 +156,7 @@ GroupsRequest 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. -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, 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 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. @@ -120,6 +178,44 @@ groupsRequest.fetchNext(onSuccess: (List groupList) { + +**On Success** — A `List` containing the fetched groups. Each `Group` object has the following structure: + + + +**Group Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Unique identifier for the group | `"cometchat-guid-1"` | +| `name` | string | Display name of the group | `"Tech Enthusiasts"` | +| `icon` | string | URL of the group icon | `null` | +| `description` | string | Description of the group | `"A group for tech lovers"` | +| `membersCount` | number | Number of members in the group | `12` | +| `metadata` | object | Custom metadata attached to the group | `{}` | +| `joinedAt` | number | Epoch timestamp when the logged-in user joined the group | `1745554729` | +| `hasJoined` | boolean | Whether the logged-in user has joined the group | `true` | +| `createdAt` | number | Epoch timestamp when the group was created | `1745554729` | +| `owner` | string | UID of the group owner | `"cometchat-uid-1"` | +| `updatedAt` | number | Epoch timestamp when the group was last updated | `1745554729` | +| `tags` | array | List of tags associated with the group | `[]` | +| `type` | string | Type of the group (public, private, password) | `"public"` | +| `scope` | string | Scope of the logged-in user in the group | `"admin"` | +| `password` | string | Password for password-protected groups | `null` | +| `isBannedFromGroup` | boolean | Whether the logged-in user is banned from the group | `false` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to fetch the requested data."` | +| `details` | string | Additional technical details | `"An unexpected error occurred while processing the request."` | + + + ## Retrieve Particular Group Details *In other words, as a logged-in user, how do I retrieve information for a specific group?* @@ -146,7 +242,45 @@ CometChat.getGroup(GUID, onSuccess: (Group group) { | --------- | ------------------------------------------------------------ | | `GUID` | The GUID of the group for whom the details are to be fetched | -On success, the `Group` object containing the details of the group is returned. +On success, the [`Group`](/sdk/reference/entities#group) object containing the details of the group is returned. + + +**On Success** — A `Group` object containing all details of the requested group: + + + +**Group Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Unique identifier for the group | `"cometchat-guid-1"` | +| `name` | string | Display name of the group | `"Tech Enthusiasts"` | +| `icon` | string | URL of the group icon | `null` | +| `description` | string | Description of the group | `"A group for tech lovers"` | +| `membersCount` | number | Number of members in the group | `12` | +| `metadata` | object | Custom metadata attached to the group | `{}` | +| `joinedAt` | number | Epoch timestamp when the logged-in user joined the group | `1745554729` | +| `hasJoined` | boolean | Whether the logged-in user has joined the group | `true` | +| `createdAt` | number | Epoch timestamp when the group was created | `1745554729` | +| `owner` | string | UID of the group owner | `"cometchat-uid-1"` | +| `updatedAt` | number | Epoch timestamp when the group was last updated | `1745554729` | +| `tags` | array | List of tags associated with the group | `[]` | +| `type` | string | Type of the group (public, private, password) | `"public"` | +| `scope` | string | Scope of the logged-in user in the group | `"admin"` | +| `password` | string | Password for password-protected groups | `null` | +| `isBannedFromGroup` | boolean | Whether the logged-in user is banned from the group | `false` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_GUID_NOT_FOUND"` | +| `message` | string | Human-readable error message | `"The specified group does not exist."` | +| `details` | string | Additional technical details | `"Please provide a valid GUID for the group."` | + + ## Get online group member count @@ -172,3 +306,41 @@ CometChat.getOnlineGroupMemberCount(guids, This method returns a `Map` with the GUID of the group as the key and the online member count for that group as the value. + + +**On Success** — A `Map` containing the GUID of each group as the key and the online member count as the value: + + + +**Map Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `cometchat-guid-1` | number | Online member count for the group | `3` | +| `cometchat-guid-11` | number | Online member count for the group | `7` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to fetch the requested data."` | +| `details` | string | Additional technical details | `"An unexpected error occurred while processing the request."` | + + + + +--- + +## Next Steps + + + + Create new public, private, or password-protected groups + + + Get the list of members in a group + + diff --git a/sdk/flutter/retrieve-users.mdx b/sdk/flutter/retrieve-users.mdx index 4483e77bb..1331d8932 100644 --- a/sdk/flutter/retrieve-users.mdx +++ b/sdk/flutter/retrieve-users.mdx @@ -1,34 +1,96 @@ --- title: "Retrieve Users" +sidebarTitle: "Retrieve Users" +description: "Fetch, filter, search, and sort users using the CometChat Flutter SDK. Includes pagination, role-based filtering, tag support, and online user counts." --- + +```dart +// Fetch users list +UsersRequest usersRequest = (UsersRequestBuilder()..limit = 30).build(); +usersRequest.fetchNext( + onSuccess: (List userList) => debugPrint("Users: $userList"), + onError: (CometChatException e) => debugPrint("Error: ${e.message}") +); + +// Get specific user details +CometChat.getUser("UID", + onSuccess: (User user) => debugPrint("User: $user"), + onError: (CometChatException e) => debugPrint("Error: ${e.message}") +); + +// Get logged-in user +User? user = await CometChat.getLoggedInUser(); + +// Get online user count +CometChat.getOnlineUserCount( + onSuccess: (int count) => debugPrint("Online: $count"), + onError: (CometChatException e) => debugPrint("Error: ${e.message}") +); +``` + + +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. + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) + + +### User Object Fields + +| Field | Type | Description | +|-------|------|-------------| +| `uid` | `String` | Unique user ID | +| `name` | `String` | Display name of the user | +| `avatar` | `String?` | URL of the user's avatar image | +| `status` | `String` | Online status of the user (`"online"` or `"offline"`) | +| `lastActiveAt` | `int?` | Epoch timestamp when the user was last active | +| `role` | `String` | Role assigned to the user | +| `tags` | `List` | Tags associated with the user | ## 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 current user's details. Returns `null` if no user is logged in. ```dart -User user = await CometChat.getLoggedInUser() +User? user = await CometChat.getLoggedInUser(); ``` - - -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. ## 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. +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. + +### UsersRequestBuilder Parameters + +| Parameter | Type | Description | +|-----------|------|-------------| +| `limit` | `int?` | Number of users to fetch per request | +| `searchKeyword` | `String?` | Filters users by a search string | +| `searchIn` | `List?` | Specifies which user properties to search (`"uid"`, `"name"`). Works with `searchKeyword`. | +| `userStatus` | `String?` | Filters by online status (`CometChatUserStatus.online` or `CometChatUserStatus.offline`) | +| `hideBlockedUsers` | `bool?` | When `true`, excludes users blocked by the logged-in user | +| `roles` | `List?` | Filters users by specified roles | +| `friendsOnly` | `bool?` | When `true`, returns only friends of the logged-in user | +| `tags` | `List?` | Filters users by specified tags | +| `withTags` | `bool?` | When `true`, includes tag data in the returned user objects | +| `uids` | `List?` | Fetches specific users by their UIDs. Maximum 25 per request. | +| `sortBy` | `String?` | Sorts the user list by a specific property. Default sort order: `status → name → UID`. Pass `"name"` to sort by `name → UID`. | +| `sortByOrder` | `String?` | Sets the sort order. Default is ascending (`"asc"`). Use `"desc"` for descending. | The `UsersRequestBuilder` class allows you to set the below parameters: ### 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. @@ -37,14 +99,12 @@ UsersRequest usersRequest = (UsersRequestBuilder() ..limit = 50 ).build(); ``` - - ### 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. @@ -54,19 +114,33 @@ UsersRequest usersRequest = (UsersRequestBuilder() ..searchKeyword = "abc" ).build(); ``` - + +### Search In + +Specifies which user properties to search. Works with `searchKeyword`. By default, searches both UID and name. + + + +```dart +UsersRequest usersRequest = (UsersRequestBuilder() + ..limit = 50 + ..searchKeyword = "super" + ..searchIn = ["uid", "name"] + ).build(); +``` + ### 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: -* CometChatUserStatus.online - will return the list of only online users. -* CometChatUserStatus.offline - will return the list of only offline users. +- `CometChatUserStatus.online` — Only online users +- `CometChatUserStatus.offline` — Only offline users -If this parameter is not set, will return all the available users. +If not set, returns all users. @@ -76,16 +150,12 @@ UsersRequest usersRequest = (UsersRequestBuilder() ..userStatus = CometChatUserStatus.online ).build(); ``` - - -If this parameter is not set, will return all users. - ### 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. @@ -95,14 +165,12 @@ UsersRequest usersRequest = (UsersRequestBuilder() ..hideBlockedUsers = true ).build(); ``` - - ### Set Roles -This method allows you to fetch the users based on multiple roles. +Filters users by specified roles. @@ -115,14 +183,12 @@ UsersRequest usersRequest = (UsersRequestBuilder() ..roles = roles ).build(); ``` - - ### 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. @@ -132,14 +198,12 @@ UsersRequest usersRequest = (UsersRequestBuilder() ..friendsOnly = true ).build(); ``` - - ### 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. @@ -152,34 +216,27 @@ UsersRequest usersRequest = (UsersRequestBuilder() ..tags = tags ).build(); ``` - - ### 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. ```dart -List tags = []; -tags.add("tag1"); -tags.add("tag2"); UsersRequest usersRequest = (UsersRequestBuilder() ..limit = 50 ..withTags = true ).build(); ``` - - ### 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. @@ -192,14 +249,40 @@ UsersRequest usersRequest = (UsersRequestBuilder() ..uids = 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`. + + +```dart +UsersRequest usersRequest = (UsersRequestBuilder() + ..limit = 30 + ..sortBy = "name" + ).build(); +``` + -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. +### Sort By Order + +Sets the sort order. Default is ascending (`"asc"`). Use `"desc"` for descending. + + + +```dart +UsersRequest usersRequest = (UsersRequestBuilder() + ..limit = 30 + ..sortByOrder = "desc" + ).build(); +``` + + -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 depending on the limit set. +After configuring the builder, call `build()` to get the `UsersRequest` object, then call `fetchNext()` to retrieve users. @@ -214,14 +297,48 @@ usersRequest.fetchNext(onSuccess: (List userList){ debugPrint("User List Fetch Failed: ${e.message}"); }); ``` - - +The `fetchNext()` method returns a list of [`User`](/sdk/reference/entities#user) objects. + + +**On Success** — A list of `User` objects matching the request filters. Each item in the list contains: + + + +**User Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-1"` | +| `name` | string | Display name of the user | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to fetch the requested data."` | +| `details` | string | Additional technical details | `"An unexpected error occurred while processing the request."` | + + + ## 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. @@ -234,9 +351,7 @@ CometChat.getUser(UID, onSuccess: (User user){ debugPrint("User Fetch Failed: ${e.message}"); }); ``` - - The `getUser()` method takes the following parameters: @@ -247,9 +362,43 @@ The `getUser()` method takes the following parameters: On success, the `User` object containing the details of the user is returned. -## Get online user count + +**On Success** — A `User` object containing the details of the requested user: + + + +**User Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-1"` | +| `name` | string | Display name of the user | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | -To get the total count of online users for your app, you can use the `getOnlineUserCount()` method. + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_UID_NOT_FOUND"` | +| `message` | string | Human-readable error message | `"The specified UID does not exist."` | +| `details` | string | Additional technical details | `"Please verify the UID and try again."` | + + + +## Get Online User Count + +Use `getOnlineUserCount()` to get the total number of online users in your app. @@ -260,7 +409,45 @@ CometChat.getOnlineUserCount(onSuccess: (int count){ debugPrint("User Count Fetch Failed: ${e.message}"); }); ``` - - + +`getOnlineUserCount()` resolves with an `int` representing the total count of currently online users in your app. + + +**On Success** — An `int` value representing the total count of online users: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `count` | number | Total number of online users | `12` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to fetch the requested data."` | +| `details` | string | Additional technical details | `"An unexpected error occurred while processing the request."` | + + + +--- + +## Next Steps + + + + Monitor and manage real-time user online/offline status + + + Block and unblock users to control interactions + + + Create, update, and delete users programmatically + + + Explore all user-related features and capabilities + + diff --git a/sdk/flutter/send-message.mdx b/sdk/flutter/send-message.mdx index fc2b812b6..57cc58dfa 100644 --- a/sdk/flutter/send-message.mdx +++ b/sdk/flutter/send-message.mdx @@ -1,15 +1,72 @@ --- -title: "Send A Message" +title: "Send Messages" +sidebarTitle: "Send Messages" +description: "Send text, media, and custom messages to users and groups using the CometChat Flutter SDK." --- + +| Field | Value | +| --- | --- | +| Key Classes | [`TextMessage`](/sdk/reference/messages#textmessage), [`MediaMessage`](/sdk/reference/messages#mediamessage), [`CustomMessage`](/sdk/reference/messages#custommessage) | +| Key Methods | `CometChat.sendMessage()`, `CometChat.sendMediaMessage()`, `CometChat.sendCustomMessage()` | +| Receiver Types | `CometChatReceiverType.user`, `CometChatReceiverType.group` | +| Message Types | `CometChatMessageType.text`, `CometChatMessageType.image`, `CometChatMessageType.video`, `CometChatMessageType.audio`, `CometChatMessageType.file`, `CometChatMessageType.custom` | +| Prerequisites | SDK initialized, user logged in | -Using CometChat, you can send three types of messages: +```dart +// Send text message to user +TextMessage textMessage = TextMessage( + text: "Hello!", + receiverUid: "UID", + receiverType: CometChatReceiverType.user, + type: CometChatMessageType.text, +); +CometChat.sendMessage(textMessage, onSuccess: (msg) {}, onError: (e) {}); + +// Send text message to group +TextMessage groupMessage = TextMessage( + text: "Hello group!", + receiverUid: "GUID", + receiverType: CometChatReceiverType.group, + type: CometChatMessageType.text, +); +CometChat.sendMessage(groupMessage, onSuccess: (msg) {}, onError: (e) {}); + +// Send media message (image) +MediaMessage mediaMessage = MediaMessage( + receiverUid: "UID", + receiverType: CometChatReceiverType.user, + type: CometChatMessageType.image, + file: "path/to/image.jpg", +); +CometChat.sendMediaMessage(mediaMessage, onSuccess: (msg) {}, onError: (e) {}); + +// Send custom message +CustomMessage customMessage = CustomMessage( + receiverUid: "UID", + receiverType: CometChatReceiverType.user, + type: "location", + customData: {"latitude": "50.6192", "longitude": "-72.6818"}, +); +CometChat.sendCustomMessage(customMessage, onSuccess: (msg) {}, onError: (e) {}); +``` + + + +CometChat supports three types of messages: + +| Type | Method | Use Case | +| --- | --- | --- | +| [Text](#text-message) | `CometChat.sendMessage()` | Plain text messages | +| [Media](#media-message) | `CometChat.sendMediaMessage()` | Images, videos, audio, files | +| [Custom](#custom-message) | `CometChat.sendCustomMessage()` | Location, polls, or any structured data | -1. A [Text Message](/sdk/flutter/send-message#text-message), the most common and standard message type. -2. A [Media Message](/sdk/flutter/send-message#media-message), for sending photos, videos and files. -3. A [Custom Message](/sdk/flutter/send-message#custom-message), for sending completely custom data using Map structures. -4. A [Interactive Messages](/sdk/flutter/interactive-messages) , for sending end-user interactive messages of type form, card and custom Interactive +You can also send [Interactive Messages](/sdk/flutter/interactive-messages) for forms, cards, and custom UI elements. + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) + 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. @@ -17,7 +74,7 @@ You can also send metadata along with a text or media message. Think, for exampl *In other words, as a sender, 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, you need to use the `sendMessage()` method and pass a [`TextMessage`](/sdk/reference/messages#textmessage) object to it. ### Add Metadata @@ -110,6 +167,99 @@ 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** — A `TextMessage` object containing all details of the sent message: + + + +**TextMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `401` | +| `metadata` | object | Custom metadata attached to the message | `{}` | +| `receiver` | object | Receiver user object | [See below ↓](#send-text-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `null` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `sentAt` | number | Epoch timestamp when the message was sent | `1745554729` | +| `receiverUid` | string | UID of the receiver | `"cometchat-uid-2"` | +| `type` | string | Type of the message | `"text"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `null` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `0` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `0` | +| `replyCount` | number | Number of replies to this message | `0` | +| `sender` | object | Sender user object | [See below ↓](#send-text-sender-object) | +| `receiverType` | string | Type of the receiver | `"user"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `0` | +| `parentMessageId` | number | ID of the parent message (for threads) | `-1` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"message"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` | +| `updatedAt` | number | Epoch timestamp when the message was last updated | `1745554729` | +| `text` | string | The text content of the message | `"messageText"` | +| `tags` | array | List of tags associated with the message | `[]` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `mentionedUsers` | array | List of mentioned users | `[]` | +| `hasMentionedMe` | boolean | Whether the current user is mentioned | `false` | +| `reactions` | array | List of reactions on the message | `[]` | +| `moderationStatus` | string | Moderation status of the message | `null` | +| `quotedMessageId` | number | ID of the quoted message | `null` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-1"` | +| `name` | string | Display name of the sender | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-2"` | +| `name` | string | Display name of the receiver | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_EMPTY_MESSAGE_TEXT"` | +| `message` | string | Human-readable error message | `"The text message body is empty."` | +| `details` | string | Additional technical details | `"Please provide a non-empty text for the message."` | + + + ### 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. @@ -131,42 +281,52 @@ Once the text message object is ready, you need to use the `sendMessage()` metho ```dart String receiverID = "UID"; - String messageText = "Hello CometChat!"; - String receiverType = CometChatReceiverType.user; - - TextMessage textMessage = - TextMessage(receiverID, messageText, receiverType); - - CometChat.sendMessage( - textMessage, - onSuccess: (TextMessage message) { - print("Message sent successfully: ${message.toString()}"); - }, - onError: (CometChatException e) { - print("Message sending failed with exception: ${e.message}"); - }, - ); +String messageText = "Hello CometChat!"; +String receiverType = CometChatReceiverType.user; +String type = CometChatMessageType.text; + +TextMessage textMessage = TextMessage( + text: messageText, + receiverUid: receiverID, + receiverType: receiverType, + type: type, +); +textMessage.quotedMessageId = 10; + +CometChat.sendMessage(textMessage, + onSuccess: (TextMessage message) { + debugPrint("Message sent successfully: ${message.toString()}"); + }, + onError: (CometChatException e) { + debugPrint("Message sending failed with exception: ${e.message}"); + }, +); ``` ```dart String receiverID = "GUID"; - String messageText = "Hello CometChat!"; - String receiverType = CometChatReceiverType.group; - - TextMessage textMessage = - TextMessage(receiverID, messageText, receiverType); - - CometChat.sendMessage( - textMessage, - onSuccess: (TextMessage message) { - print("Message sent successfully: ${message.toString()}"); - }, - onError: (CometChatException e) { - print("Message sending failed with exception: ${e.message}"); - }, - ); +String messageText = "Hello CometChat!"; +String receiverType = CometChatReceiverType.group; +String type = CometChatMessageType.text; + +TextMessage textMessage = TextMessage( + text: messageText, + receiverUid: receiverID, + receiverType: receiverType, + type: type, +); +textMessage.quotedMessageId = 10; + +CometChat.sendMessage(textMessage, + onSuccess: (TextMessage message) { + debugPrint("Message sent successfully: ${message.toString()}"); + }, + onError: (CometChatException e) { + debugPrint("Message sending failed with exception: ${e.message}"); + }, +); ``` @@ -179,15 +339,108 @@ The `TextMessage` class constructor takes the following parameters: | -------------- | ---------------------------------------------------------------------------------------------------------------------------- | -------- | | `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 | +| `receiverType` | The type of the receiver- `CometChatReceiverType.user` (user) or `CometChatReceiverType.group` (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** — A `TextMessage` object containing all details of the sent quoted message: + + + +**TextMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `402` | +| `metadata` | object | Custom metadata attached to the message | `{}` | +| `receiver` | object | Receiver user object | [See below ↓](#send-quoted-text-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `null` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `sentAt` | number | Epoch timestamp when the message was sent | `1745554800` | +| `receiverUid` | string | UID of the receiver | `"cometchat-uid-2"` | +| `type` | string | Type of the message | `"text"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `null` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `0` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `0` | +| `replyCount` | number | Number of replies to this message | `0` | +| `sender` | object | Sender user object | [See below ↓](#send-quoted-text-sender-object) | +| `receiverType` | string | Type of the receiver | `"user"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `0` | +| `parentMessageId` | number | ID of the parent message (for threads) | `-1` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"message"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` | +| `updatedAt` | number | Epoch timestamp when the message was last updated | `1745554800` | +| `text` | string | The text content of the message | `"Hello CometChat!"` | +| `tags` | array | List of tags associated with the message | `[]` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `mentionedUsers` | array | List of mentioned users | `[]` | +| `hasMentionedMe` | boolean | Whether the current user is mentioned | `false` | +| `reactions` | array | List of reactions on the message | `[]` | +| `moderationStatus` | string | Moderation status of the message | `null` | +| `quotedMessageId` | number | ID of the quoted message | `401` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-1"` | +| `name` | string | Display name of the sender | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-2"` | +| `name` | string | Display name of the receiver | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_EMPTY_MESSAGE_TEXT"` | +| `message` | string | Human-readable error message | `"The text message body is empty."` | +| `details` | string | Additional technical details | `"Please provide a non-empty text for the 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. +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 @@ -234,26 +487,65 @@ mediaMessage.tags = tags; +### Set Quoted Message + +To quote a message in a media message, use the `quotedMessageId` property of the MediaMessage class. + + + +```dart +mediaMessage.quotedMessageId = 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. - + ```dart -String receiverID; +String receiverID = "cometchat-uid-1"; String messageType = CometChatMessageType.image; -String receiverType = CometChatConversationType.user ; +String receiverType = CometChatConversationType.user; String filePath = "storage/emulated/0/Download/46.jpg"; MediaMessage mediaMessage = MediaMessage( -receiverType: receiverType, -type: messageType, -receiverUid: receiverID, -file: filePath); + receiverType: receiverType, + type: messageType, + receiverUid: receiverID, + file: filePath, +); await CometChat.sendMediaMessage(mediaMessage, onSuccess: (MediaMessage message) { - debugPrint("Media message sent successfully:${mediaMessage.metadata}"); + debugPrint("Media message sent successfully: ${mediaMessage.metadata}"); + }, onError: (e) { + debugPrint("Media message sending failed with exception: ${e.message}"); + } +); +``` + + + + +```dart +String receiverID = "cometchat-guid-1"; +String messageType = CometChatMessageType.image; +String receiverType = CometChatConversationType.group; +String filePath = "storage/emulated/0/Download/46.jpg"; +MediaMessage mediaMessage = MediaMessage( + receiverType: receiverType, + type: messageType, + receiverUid: receiverID, + file: filePath, +); + +await CometChat.sendMediaMessage(mediaMessage, + onSuccess: (MediaMessage message) { + debugPrint("Media message sent successfully: ${mediaMessage.metadata}"); }, onError: (e) { debugPrint("Media message sending failed with exception: ${e.message}"); } @@ -273,11 +565,126 @@ The `MediaMessage` class constructor takes the following parameters: | messageType | The type of the message that needs to be sent which, in this case, can be:
1. `CometChatMessageType.image` (image)
2. `CometChatMessageType.video` (video)
3. `CometChatMessageType.audio` (audio)
4. `CometChatMessageType.file` (file) | Required | | receiverType | The type of the receiver to whom the message is to be sent, i.e., `CometChatReceiverType.user` (user) or `CometChatReceiverType.group` (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 that is available in the MediaMessage class. For more information, you can refer to the below code snippet: + +**On Success** — A `MediaMessage` object containing all details of the sent media message: + + + +**MediaMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `403` | +| `metadata` | object | Custom metadata attached to the message | `{}` | +| `receiver` | object | Receiver user object | [See below ↓](#send-media-file-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `null` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `sentAt` | number | Epoch timestamp when the message was sent | `1745554900` | +| `receiverUid` | string | UID of the receiver | `"cometchat-uid-2"` | +| `type` | string | Type of the message | `"image"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `null` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `0` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `0` | +| `replyCount` | number | Number of replies to this message | `0` | +| `sender` | object | Sender user object | [See below ↓](#send-media-file-sender-object) | +| `receiverType` | string | Type of the receiver | `"user"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `0` | +| `parentMessageId` | number | ID of the parent message (for threads) | `0` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"message"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` | +| `updatedAt` | number | Epoch timestamp when the message was last updated | `1745554900` | +| `tags` | array | List of tags associated with the message | `[]` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `mentionedUsers` | array | List of mentioned users | `[]` | +| `hasMentionedMe` | boolean | Whether the current user is mentioned | `false` | +| `reactions` | array | List of reactions on the message | `[]` | +| `caption` | string | Caption text for the media message | `null` | +| `attachment` | object | File attachment details | [See below ↓](#send-media-file-attachment-object) | +| `file` | string | Local file path | `"storage/emulated/0/Download/46.jpg"` | +| `files` | array | List of additional file paths | `null` | +| `attachments` | array | List of additional attachments | `null` | +| `moderationStatus` | string | Moderation status of the message | `null` | +| `quotedMessageId` | number | ID of the quoted message | `null` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-1"` | +| `name` | string | Display name of the sender | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-2"` | +| `name` | string | Display name of the receiver | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + +--- + + + +**`attachment` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `fileUrl` | string | URL of the uploaded file | `"https://data-us.cometchat.io/assets/images/46.jpg"` | +| `fileName` | string | Name of the file | `"46.jpg"` | +| `fileExtension` | string | File extension | `"jpg"` | +| `fileMimeType` | string | MIME type of the file | `"image/jpeg"` | +| `fileSize` | number | File size in bytes | `24576` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_FILE_TOO_LARGE"` | +| `message` | string | Human-readable error message | `"The file size exceeds the allowed limit."` | +| `details` | string | Additional technical details | `"Maximum allowed file size is 25 MB."` | + + + +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`](/sdk/reference/auxiliary#attachment) class that is available in the MediaMessage class. For more information, you can refer to the below code snippet: - + ```dart +String receiverID = "cometchat-uid-1"; +String messageType = CometChatMessageType.image; +String receiverType = CometChatConversationType.user; + MediaMessage mediaMessage = MediaMessage( receiverType: receiverType, type: messageType, @@ -289,12 +696,43 @@ String fileName = "test"; String fileExtension = "png"; String fileMimeType = "image/png"; -Attachment attach = Attachment(fileUrl,fileName,fileExtension,fileMimeType,null); -mediaMessage.attachment= attach; +Attachment attach = Attachment(fileUrl, fileName, fileExtension, fileMimeType, null); +mediaMessage.attachment = attach; await CometChat.sendMediaMessage(mediaMessage, onSuccess: (MediaMessage message) { - debugPrint( "Media message sent successfully: ${mediaMessage}"); + debugPrint("Media message sent successfully: ${mediaMessage}"); + }, onError: (CometChatException e) { + debugPrint("Media message sending failed with exception: ${e.message}"); + } +); +``` + + + + +```dart +String receiverID = "cometchat-guid-1"; +String messageType = CometChatMessageType.image; +String receiverType = CometChatConversationType.group; + +MediaMessage mediaMessage = MediaMessage( + receiverType: receiverType, + type: messageType, + receiverUid: receiverID, + file: null); + +String fileUrl = "https://pngimg.com/uploads/mario/mario_PNG125.png"; +String fileName = "test"; +String fileExtension = "png"; +String fileMimeType = "image/png"; + +Attachment attach = Attachment(fileUrl, fileName, fileExtension, fileMimeType, null); +mediaMessage.attachment = attach; + +await CometChat.sendMediaMessage(mediaMessage, + onSuccess: (MediaMessage message) { + debugPrint("Media message sent successfully: ${mediaMessage}"); }, onError: (CometChatException e) { debugPrint("Media message sending failed with exception: ${e.message}"); } @@ -307,6 +745,117 @@ await CometChat.sendMediaMessage(mediaMessage, 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** — A `MediaMessage` object containing all details of the sent media message (via URL): + + + +**MediaMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `404` | +| `metadata` | object | Custom metadata attached to the message | `{}` | +| `receiver` | object | Receiver user object | [See below ↓](#send-media-url-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `null` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `sentAt` | number | Epoch timestamp when the message was sent | `1745555000` | +| `receiverUid` | string | UID of the receiver | `"cometchat-uid-2"` | +| `type` | string | Type of the message | `"image"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `null` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `0` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `0` | +| `replyCount` | number | Number of replies to this message | `0` | +| `sender` | object | Sender user object | [See below ↓](#send-media-url-sender-object) | +| `receiverType` | string | Type of the receiver | `"user"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `0` | +| `parentMessageId` | number | ID of the parent message (for threads) | `0` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"message"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` | +| `updatedAt` | number | Epoch timestamp when the message was last updated | `1745555000` | +| `tags` | array | List of tags associated with the message | `[]` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `mentionedUsers` | array | List of mentioned users | `[]` | +| `hasMentionedMe` | boolean | Whether the current user is mentioned | `false` | +| `reactions` | array | List of reactions on the message | `[]` | +| `caption` | string | Caption text for the media message | `null` | +| `attachment` | object | File attachment details | [See below ↓](#send-media-url-attachment-object) | +| `file` | string | Local file path | `null` | +| `files` | array | List of additional file paths | `null` | +| `attachments` | array | List of additional attachments | `null` | +| `moderationStatus` | string | Moderation status of the message | `null` | +| `quotedMessageId` | number | ID of the quoted message | `null` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-1"` | +| `name` | string | Display name of the sender | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-2"` | +| `name` | string | Display name of the receiver | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + +--- + + + +**`attachment` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `fileUrl` | string | URL of the file | `"https://pngimg.com/uploads/mario/mario_PNG125.png"` | +| `fileName` | string | Name of the file | `"test"` | +| `fileExtension` | string | File extension | `"png"` | +| `fileMimeType` | string | MIME type of the file | `"image/png"` | +| `fileSize` | number | File size in bytes | `null` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_INVALID_MESSAGE_TYPE"` | +| `message` | string | Human-readable error message | `"The message type provided is not supported."` | +| `details` | string | Additional technical details | `"Supported types are image, video, audio, and file."` | + + + 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 get and set the caption you can use the `.caption` variable . 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 `Map`. ## Custom Message @@ -317,7 +866,7 @@ CometChat allows you to send custom messages which are neither text nor media me In order to send a custom message, you need to use the `sendCustomMessage()` method. -The `sendCustomMessage()` methods takes an object of the `CustomMessage` which can be obtained using the below constructor. +The `sendCustomMessage()` methods takes an object of the [`CustomMessage`](/sdk/reference/messages#custommessage) which can be obtained using the below constructor. @@ -336,15 +885,35 @@ CustomMessage customMessage = CustomMessage( receiverUid: UID, 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: +The `CustomMessage` class constructor takes the following parameters: -1. `receiverUid` - 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 `Map`. +| Parameter | Description | Required | +| --- | --- | --- | +| `receiverUid` | UID of the user or GUID of the group to which the message is to be sent | Yes | +| `receiverType` | Type of the receiver — `CometChatConversationType.user` or `CometChatConversationType.group` | Yes | +| `type` | Custom message type string (e.g., `"location"`, `"poll"`) | Yes | +| `customData` | The data to be passed as the message in the form of a `Map` | Yes | +| `subType` | Optional sub-type for the custom message | No | 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 `subtype` field. +### Add Metadata + +To send custom data along with a custom message, you can use the `metadata` property and pass a `Map` to it. + + + +```dart +Map metadata = {}; +metadata["priority"] = "high"; +metadata["source"] = "mobile"; +customMessage.metadata = metadata; +``` + + + + + ### Add Tags To add a tag to a message you can assign value in `.tags` variable of the CustomMessage Class. `tags` accepts a list of tags. @@ -361,6 +930,20 @@ textMessage.tags = tags; +### Set Quoted Message + +To quote a message in a custom message, use the `quotedMessageId` property of the CustomMessage class. + + + +```dart +customMessage.quotedMessageId = 10; +``` + + + + + Once the object of `CustomMessage` class is ready you can send the custom message using the `sendCustomMessage()` method. @@ -426,6 +1009,101 @@ The above sample explains how custom messages can be used to share the location On success, you will receive an object of `CustomMessage` class. + +**On Success** — A `CustomMessage` object containing all details of the sent custom message: + + + +**CustomMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `405` | +| `metadata` | object | Custom metadata attached to the message | `{}` | +| `receiver` | object | Receiver user object | [See below ↓](#send-custom-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `null` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `sentAt` | number | Epoch timestamp when the message was sent | `1745555100` | +| `receiverUid` | string | UID of the receiver | `"cometchat-uid-2"` | +| `type` | string | Type of the message | `"custom"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `null` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `0` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `0` | +| `replyCount` | number | Number of replies to this message | `0` | +| `sender` | object | Sender user object | [See below ↓](#send-custom-sender-object) | +| `receiverType` | string | Type of the receiver | `"user"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `0` | +| `parentMessageId` | number | ID of the parent message (for threads) | `0` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"custom"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` | +| `updatedAt` | number | Epoch timestamp when the message was last updated | `1745555100` | +| `customData` | object | Custom data payload | `{"latitude": "19.0760", "longitude": "72.8777"}` | +| `tags` | array | List of tags associated with the message | `[]` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `mentionedUsers` | array | List of mentioned users | `[]` | +| `hasMentionedMe` | boolean | Whether the current user is mentioned | `false` | +| `reactions` | array | List of reactions on the message | `[]` | +| `text` | string | Conversation text for notifications | `null` | +| `updateConversation` | boolean | Whether to update the conversation's last message | `false` | +| `sendNotification` | boolean | Whether to send a push notification | `false` | +| `quotedMessageId` | number | ID of the quoted message | `null` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-1"` | +| `name` | string | Display name of the sender | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-2"` | +| `name` | string | Display name of the receiver | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to send the custom message."` | +| `details` | string | Additional technical details | `"An unexpected error occurred while processing the request."` | + + + ### Update Conversation *How can I decide whether the custom message should update the last message of a conversation?* @@ -565,3 +1243,22 @@ CometChat.sendCustomMessage(customMessage, onSuccess: (CustomMessage message) { It is also possible to send interactive messages from CometChat , to know more [click here](/sdk/flutter/interactive-messages) + +--- + +## Next Steps + + + + Handle incoming messages in real-time + + + Modify sent messages after delivery + + + Send forms, cards, and interactive elements + + + Remove messages from conversations + + diff --git a/sdk/flutter/session-timeout.mdx b/sdk/flutter/session-timeout.mdx index 23470881f..34b7676aa 100644 --- a/sdk/flutter/session-timeout.mdx +++ b/sdk/flutter/session-timeout.mdx @@ -1,25 +1,47 @@ --- -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." --- + +```dart +// Set custom timeout (in seconds) +CallSettings callSettings = (CallSettingsBuilder() + ..setIdleTimeoutPeriod = 300 // 5 minutes + ..listener = this // CometChatCallsEventsListener +).build(); -Available since v4.1.0 +// Handle session timeout in your CometChatCallsEventsListener +@override +void onSessionTimeout() { + debugPrint("Session timed out"); + CometChatCalls.endSession( + onSuccess: (success) { /* Close calling screen */ }, + onError: (e) { debugPrint("Error: $e"); }, + ); +} +``` -## Overview +- Default idle timeout: 180 seconds (3 minutes) alone in a session +- Warning dialog appears 60 seconds before auto-termination +- Listen for `onSessionTimeout` to handle auto-termination +- Customize with `setIdleTimeoutPeriod` in CallSettingsBuilder (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: +*Available since v4.1.0* -1. After 120 seconds of being alone in the session, the participant will see a dialog box +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. -2. This dialog provides options to either: +## How It Works - * Stay in the call - * Leave immediately +When a participant is alone in a session: -3. If no action is taken within the next 60 seconds, the call will automatically end +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 -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. +The default timeout is 180 seconds (3 minutes). ### Session Timeout Flow @@ -32,3 +54,72 @@ 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. + +## Configuration + +Set a custom timeout period using `setIdleTimeoutPeriod` in `CallSettingsBuilder`. The warning dialog will always appear 60 seconds before the configured timeout. + +```dart +CallSettings callSettings = (CallSettingsBuilder() + ..setIdleTimeoutPeriod = 300 // 5 minutes + ..defaultLayout = true + ..listener = callEventsListener +).build(); +``` + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `setIdleTimeoutPeriod` | `int` | Idle timeout in seconds. Warning appears 60 seconds before auto-termination. Default: `180` seconds. *v4.1.0+* | + +## Handling the Timeout Event + +Listen for `onSessionTimeout` in your `CometChatCallsEventsListener` to clean up when the call auto-terminates: + +```dart +String listenerId = "UNIQUE_LISTENER_ID"; + +class YourClassName extends State with CometChatCallsEventsListener { + @override + void initState() { + super.initState(); + CometChatCalls.addCallsEventListeners(listenerId, this); + } + + @override + void dispose() { + super.dispose(); + CometChatCalls.removeCallsEventListeners(listenerId); + } + + @override + void onSessionTimeout() { + debugPrint("Session timed out due to inactivity"); + CometChatCalls.endSession( + onSuccess: (success) { + debugPrint("Session ended"); + // Close the calling screen + }, + onError: (e) { + debugPrint("Error ending session: $e"); + }, + ); + } + + // ... other listener methods +} +``` + +See [Direct Call — Call Listeners](/sdk/flutter/direct-call#call-listeners) for the full list of events. + +--- + +## Next Steps + + + + Implement voice and video calls with ringing functionality + + + Implement calling without the Chat SDK + + diff --git a/sdk/flutter/setup.mdx b/sdk/flutter/setup.mdx index 18e05e09f..c98060603 100644 --- a/sdk/flutter/setup.mdx +++ b/sdk/flutter/setup.mdx @@ -1,43 +1,75 @@ --- title: "Setup" +sidebarTitle: "Setup" +description: "Install, configure, and initialize the CometChat Flutter SDK in your application." --- - -🚀 **v5 Beta Available** — The Flutter Chat SDK v5 is now available in beta with significant improvements. [Check out the v5 Overview →](/sdk/flutter/v5/overview) - +{/* TL;DR for Agents and Quick Reference */} + -### Get your Application Keys +```yaml +# Install (pubspec.yaml) +cometchat_sdk: ^4.0.33 +``` -[Signup for CometChat](https://app.cometchat.com/) and then: +```dart +import 'package:cometchat_sdk/cometchat_sdk.dart'; -1. Create a new app -2. Head over to the **API Keys** section and note the **Auth Key**, **App ID** & **Region** +AppSettings appSettings = (AppSettingsBuilder() + ..subscriptionType = CometChatSubscriptionType.allUsers + ..region = "APP_REGION" + ..autoEstablishSocketConnection = true +).build(); - -Minimum Requirement +CometChat.init("APP_ID", appSettings, + onSuccess: (msg) => debugPrint("Init success"), + onError: (e) => debugPrint("Init failed: ${e.message}") +); -* Android API Level 21 -* AndroidX Compatibility -* iOS 11 or higher -* Flutter SDK 1.2 or higher +// Login (dev only) +CometChat.login("UID", "AUTH_KEY", + onSuccess: (user) => debugPrint("Login success"), + onError: (e) => debugPrint("Login failed: ${e.message}") +); +``` + +**Prerequisites:** Flutter SDK 1.2+, Android API Level 21+, iOS 11+ +**Credentials:** App ID, Region, Auth Key (dev) or Auth Token (prod) from [CometChat Dashboard](https://app.cometchat.com) + + +## Prerequisites - +| Requirement | Version | +|-------------|---------| +| Flutter SDK | 1.2 or higher | +| Android API Level | 21 or higher | +| AndroidX | Required | +| iOS | 11 or higher | + +Get your credentials from the [CometChat Dashboard](https://app.cometchat.com): + +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 + +**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. + -1. Add the following code in your `pubspec.yaml` file and run `pub get` command. +## Installation + +Add the following dependency to your `pubspec.yaml` file and run `pub get`: -```dart -cometchat_sdk: ^4.1.1 +```yaml +cometchat_sdk: ^4.0.33 ``` - - -2. Add following code to podfile inside iOS section of your app +### iOS Setup + +1. Add the following to your Podfile inside the iOS section of your app: @@ -62,50 +94,36 @@ end end ``` - - -3. For iOS, change the deployment target to `11` or higher. -4. For iOS, navigate to your iOS folder in terminal or CMD and do `pod install` . For apple chip system use rosetta terminal. -5. For iOS you can set the Enabled Bitcode settings to **NO** present in build settings of XCODE project +2. Change the deployment target to `11` or higher. +3. Navigate to your iOS folder in terminal and run `pod install`. For Apple Silicon systems, use a Rosetta terminal. +4. Set **Enabled Bitcode** to **NO** in the Build Settings of your Xcode project. -Import CometChat SDK using following code in dart +### Import the SDK + ```dart import 'package:cometchat_sdk/cometchat_sdk.dart'; ``` - - -## Initialise 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. +## Initialization -The `AppSettings` class allows you to configure three settings: - -* **Region**: The region where you app was created. -* **[Presence Subscription](/sdk/flutter/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 [Connection Behaviour](/sdk/flutter/connection-behaviour) section. The default value for this property is **true.** -* **adminHost(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. -* **clientHost(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. +The `init()` method initializes the SDK and must be called before any other CometChat method. Call it once at app startup, typically in your root widget's `initState()` or `main()` function. ```dart -String region = "REGION"; +String region = "APP_REGION"; String appId = "APP_ID"; AppSettings appSettings= (AppSettingsBuilder() @@ -124,35 +142,101 @@ CometChat.init(appId, appSettings, } ); ``` - - -We suggest you call the `init()` method on app startup. +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 | +| `appSettings` | `AppSettings` | Configuration object built with `AppSettingsBuilder` | +| `onSuccess` | `Function(String)` | Callback triggered on successful initialization | +| `onError` | `Function(CometChatException)` | Callback triggered on initialization failure | + +### AppSettings Options + +| Property | Type | Description | Default | +|----------|------|-------------|---------| +| `subscriptionType` | `String?` | Presence subscription type (`CometChatSubscriptionType.allUsers`, `.roles`, `.friends`) | — | +| `roles` | `List?` | Roles to subscribe to when using role-based presence | — | +| `region` | `String?` | Region where your app was created (`us`, `eu`, `in`) | Required | +| `autoEstablishSocketConnection` | `bool` | Let SDK manage WebSocket connections automatically | `true` | +| `adminHost` | `String?` | Custom admin URL (dedicated deployment) | — | +| `clientHost` | `String?` | Custom client URL (dedicated deployment) | — | + +### Presence Subscription + +Choose how to subscribe to user presence (online/offline status): + +```dart +// All users +AppSettings appSettings = (AppSettingsBuilder() + ..subscriptionType = CometChatSubscriptionType.allUsers + ..region = region +).build(); + +// Specific roles +AppSettings appSettings = (AppSettingsBuilder() + ..subscriptionType = CometChatSubscriptionType.roles + ..roles = ["admin", "moderator"] + ..region = region +).build(); + +// Friends only +AppSettings appSettings = (AppSettingsBuilder() + ..subscriptionType = CometChatSubscriptionType.friends + ..region = region +).build(); +``` + +See [User Presence](/sdk/flutter/user-presence) for more details. + + +**On Success** — A `String` message confirming SDK initialization: -## Auto Mode Connection +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `message` | `String` | Success confirmation message | `"Initialization completed successfully"` | + - + -Know more about auto mode connection [click here](/sdk/flutter/connection-behaviour) +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | `String` | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | `String` | Human-readable error message | `"SDK initialization failed."` | +| `details` | `String` | Additional technical details | `"Please verify your App ID and region, then try again."` | + - +### WebSocket Connection -| App State | Behaviour | -| ----------------- | --------------------------------------- | -| App in foreground | Connected with WebSocket | -| App in background | Immediately disconnected with WebSocket | +By default, the SDK manages WebSocket connections automatically. To manage them manually: -## Manual Mode Connection +```dart +AppSettings appSettings = (AppSettingsBuilder() + ..region = region + ..autoEstablishSocketConnection = false +).build(); +``` - +See [Connection Behaviour](/sdk/flutter/connection-behaviour) for manual control. -Know more about manual mode connection [click here](/sdk/flutter/connection-behaviour) +--- - +## Next Steps -| App State | Behaviour | -| ----------------- | ------------------------------------------------------------------------------------------------------------------ | -| 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. | + + + Log in users with Auth Key or Auth Token + + + Send your first message + + diff --git a/sdk/flutter/standalone-calling.mdx b/sdk/flutter/standalone-calling.mdx index cd1352adc..9d4c20c8e 100644 --- a/sdk/flutter/standalone-calling.mdx +++ b/sdk/flutter/standalone-calling.mdx @@ -1,7 +1,41 @@ --- title: "Standalone Calling" +sidebarTitle: "Standalone Calling" +description: "Implement video and audio calling using only the CometChat Calls SDK without the Chat SDK for applications that need calling capabilities without full chat infrastructure." --- + + +```dart +// 1. Generate call token (requires user auth token from REST API) +CometChatCalls.generateToken(sessionId, userAuthToken, + onSuccess: (GenerateToken token) { + // Use token.token to start session + }, + onError: (e) {}, +); + +// 2. Configure and start call session +CallSettings callSettings = (CallSettingsBuilder() + ..defaultLayout = true + ..setAudioOnlyCall = false + ..listener = this +).build(); + +CometChatCalls.startSession(generatedToken, callSettings, + onSuccess: (Widget? callingWidget) { + // Display callingWidget in your UI + }, + onError: (e) {}, +); + +// 3. End session +CometChatCalls.endSession(onSuccess: (s) {}, onError: (e) {}); +``` + +**Prerequisites:** [Calls SDK Setup](/sdk/flutter/calling-setup), User Auth Token from [REST API](/rest-api/auth-tokens/create) + + ## 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. @@ -59,6 +93,29 @@ CometChatCalls.generateToken( | `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. | + +**On Success** — A `GenerateToken` object containing the call token for the session: + + + +**GenerateToken Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `token` | string | The generated call token used to start a session | `"v1.us-west-2.calls.a]..."` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to generate the call token."` | +| `details` | string | Additional technical details | `"The session ID or auth token provided is invalid."` | + + + ## Start Call Session Use the `startSession()` method to join a call session. This method requires a call token (generated in the previous step) and a `CallSettings` object that configures the call UI and behavior. @@ -85,6 +142,29 @@ CometChatCalls.startSession( ); ``` + +**On Success** — A `Widget?` representing the call UI to be displayed in your application: + + + +**Widget Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `callingWidget` | Widget? | A Flutter widget containing the call UI. Display this widget in your screen to show the call interface. | `Widget` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to start the call session."` | +| `details` | string | Additional technical details | `"The call token provided is invalid or expired."` | + + + ### Call Settings Configure the call experience using the following `CallSettingsBuilder` properties: @@ -413,3 +493,23 @@ CometChatCalls.endSession( }, ); ``` + + +--- + +## Next Steps + + + + Implement ringing call flows using the Chat SDK + + + Add call recording to your voice and video calls + + + Set up the CometChat Calls SDK in your Flutter app + + + Implement direct calling with the Chat SDK integration + + diff --git a/sdk/flutter/threaded-messages.mdx b/sdk/flutter/threaded-messages.mdx index 330506158..d2b1e40f9 100644 --- a/sdk/flutter/threaded-messages.mdx +++ b/sdk/flutter/threaded-messages.mdx @@ -1,11 +1,51 @@ --- title: "Threaded Messages" +sidebarTitle: "Threaded Messages" +description: "Send, receive, and fetch threaded messages using the CometChat Flutter SDK." --- + +| Field | Value | +| --- | --- | +| Key Classes | `TextMessage`, `MediaMessage`, `CustomMessage`, `MessagesRequest`, `MessagesRequestBuilder` | +| Key Methods | `CometChat.sendMessage()`, `CometChat.sendMediaMessage()`, `CometChat.sendCustomMessage()`, `MessagesRequest.fetchPrevious()` | +| Key Properties | `parentMessageId`, `hideReplies` | +| Listener Events | `onTextMessageReceived`, `onMediaMessageReceived`, `onCustomMessageReceived` | +| Prerequisites | SDK initialized, user logged in | -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. +```dart +// Send a message in a thread (attach to parent message) +TextMessage textMessage = TextMessage( + text: "Reply in thread", + receiverUid: "UID", + receiverType: CometChatReceiverType.user, + type: CometChatMessageType.text, +); +textMessage.parentMessageId = 103; // Parent message ID +CometChat.sendMessage(textMessage, onSuccess: (msg) {}, onError: (e) {}); + +// Fetch messages from a thread +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..uid = "UID" + ..parentMessageId = 103 + ..limit = 50).build(); +messageRequest.fetchPrevious(onSuccess: (List list) {}, onError: (e) {}); + +// Exclude threaded messages from main conversation +MessagesRequest request = (MessagesRequestBuilder() + ..uid = "UID" + ..hideReplies = true + ..limit = 50).build(); +``` + + + +Threaded messages (or threads) are messages started from a particular parent message. Each thread is attached to a parent message. + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) + ## Send Message in a Thread @@ -15,17 +55,14 @@ A message can be categorized as: 1. Text Message 2. Media Message -3. Custom Message. +3. Custom Message 4. Interactive 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 `parentMessageId` parameter provided by the object of the `TextMessage`, `MediaMessage` and `CustomMessage` class. The id specified in the `parentMessageId` parameter maps the message sent to the particular thread. +Set the `parentMessageId` on the message object to indicate which thread the message belongs to. The id specified in the `parentMessageId` parameter maps the message sent to the particular thread. Any message type — [`TextMessage`](/sdk/reference/messages#textmessage), [`MediaMessage`](/sdk/reference/messages#mediamessage), [`CustomMessage`](/sdk/reference/messages#custommessage), or Interactive Message — can be sent in a thread. -**Example to Send a Text Message in a thread in a user conversation.** - + ```dart String receiverID = "UID"; String messagesText = "Hello"; @@ -37,27 +74,159 @@ TextMessage textMessage = TextMessage( receiverUid: receiverID, receiverType: receiverType, type: type); -textMessage.parentMessageId = 103 +textMessage.parentMessageId = 103; + +CometChat.sendMessage(textMessage, onSuccess: (TextMessage message) { + debugPrint("Message sent successfully: $message"); +}, onError: (CometChatException e) { + debugPrint("Message sending failed with exception: ${e.message}"); +}); +``` + + + + +```dart +String receiverID = "GUID"; +String messagesText = "Hello"; +String receiverType = CometChatConversationType.group; +String type = CometChatMessageType.text; + +TextMessage textMessage = TextMessage( + text: messagesText, + receiverUid: receiverID, + receiverType: receiverType, + type: type); +textMessage.parentMessageId = 103; -CometChat.sendMessage(textMessage,onSuccess: (TextMessage message) { -debugPrint("Message sent successfully: $message"); +CometChat.sendMessage(textMessage, onSuccess: (TextMessage message) { + debugPrint("Message sent successfully: $message"); }, onError: (CometChatException e) { -debugPrint("Message sending failed with exception: ${e.message}"); + debugPrint("Message sending failed with exception: ${e.message}"); }); ``` +`TextMessage` Parameters: + +| Parameter | Type | Description | Required | +| --- | --- | --- | --- | +| `text` | `String` | The text content of the message | Yes | +| `receiverUid` | `String` | The `UID` of the user or `GUID` of the group to send the message to | Yes | +| `receiverType` | `String` | The type of the receiver — `CometChatConversationType.user` or `CometChatConversationType.group` | Yes | +| `type` | `String` | The type of the message — `CometChatMessageType.text` | Yes | +| `parentMessageId` | `int` | The ID of the parent message to send this message as a thread reply | Yes (for threads) | + + +**On Success** — A `TextMessage` object containing all details of the sent threaded message: + + + +**TextMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `601` | +| `metadata` | object | Custom metadata attached to the message | `{}` | +| `receiver` | object | Receiver user object | [See below ↓](#send-thread-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `null` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `sentAt` | number | Epoch timestamp when the message was sent | `1745554729` | +| `receiverUid` | string | UID of the receiver | `"cometchat-uid-2"` | +| `type` | string | Type of the message | `"text"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `null` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `0` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `0` | +| `replyCount` | number | Number of replies to this message | `0` | +| `sender` | object | Sender user object | [See below ↓](#send-thread-sender-object) | +| `receiverType` | string | Type of the receiver | `"user"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `0` | +| `parentMessageId` | number | ID of the parent message (for threads) | `103` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"message"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` | +| `updatedAt` | number | Epoch timestamp when the message was last updated | `1745554729` | +| `text` | string | The text content of the message | `"Hello"` | +| `tags` | array | List of tags associated with the message | `[]` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `mentionedUsers` | array | List of mentioned users | `[]` | +| `hasMentionedMe` | boolean | Whether the current user is mentioned | `false` | +| `reactions` | array | List of reactions on the message | `[]` | +| `moderationStatus` | string | Moderation status of the message | `null` | +| `quotedMessageId` | number | ID of the quoted message | `null` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-1"` | +| `name` | string | Display name of the sender | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-2"` | +| `name` | string | Display name of the receiver | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to send the message."` | +| `details` | string | Additional technical details | `"An unexpected error occurred while processing the request."` | + + + The above snippet shows how a message with the text "Hello" can be sent in the thread with `parentMessageId` 103. Similarly, using the `parentMessageId` parameter, Media and Custom Messages can be sent in threads too. ### Receiving Real-Time Messages -The procedure to receive real-time messages is exactly the same as mentioned in the [Receive Messages](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. +The procedure to receive real-time messages is exactly the same as mentioned in the [Receive Messages](receive-messages) section. Use the `MessageListener` class to listen for incoming thread messages. Check if the received message belongs to the active thread using the `parentMessageId` field. + + +Always remove message listeners when they're no longer needed (e.g., in the `dispose()` method). Failing to remove listeners can cause memory leaks and duplicate event handling. + +```dart +CometChat.removeMessageListener("listenerId"); +``` + @@ -94,14 +263,17 @@ void onCustomMessageReceived(CustomMessage customMessage) { ### Fetch all the messages for any particular thread. -You can fetch all the messages belonging to a particular thread by using the `MessagesRequest` class. +Use `MessagesRequestBuilder` with `parentMessageId` to fetch messages belonging to a specific thread. Call `fetchPrevious()` to get messages (max 100 per request), returned as [`BaseMessage`](/sdk/reference/messages#basemessage) objects. Call `fetchPrevious()` again on the same object to get the next set. -The `MessageRequestBuilder` builds the `MessageRequest` object using the following functions: -1. parentMessageId: Takes the parentId of the message as argument whose thread needs to be requested. -2. build(): returns the MessageRequest object. +`MessagesRequestBuilder` Parameters: -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. +| Parameter | Type | Description | Required | +| --- | --- | --- | --- | +| `uid` | `String` | The `UID` of the user whose conversation thread messages are to be fetched | Yes (for user threads) | +| `guid` | `String` | The `GUID` of the group whose conversation thread messages are to be fetched | Yes (for group threads) | +| `parentMessageId` | `int` | The ID of the parent message whose thread messages are to be fetched | Yes | +| `limit` | `int` | Number of messages to fetch in a single request (max 100) | No | @@ -123,12 +295,100 @@ messageRequest.fetchPrevious(onSuccess: (List list) { + +**On Success** — A `List` containing the fetched thread messages (each item is a BaseMessage object): + + + +**BaseMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `602` | +| `metadata` | object | Custom metadata attached to the message | `{}` | +| `receiver` | object | Receiver user object | [See below ↓](#fetch-thread-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `null` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `sentAt` | number | Epoch timestamp when the message was sent | `1745554729` | +| `receiverUid` | string | UID of the receiver | `"cometchat-uid-1"` | +| `type` | string | Type of the message | `"text"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `null` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `0` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `0` | +| `replyCount` | number | Number of replies to this message | `0` | +| `sender` | object | Sender user object | [See below ↓](#fetch-thread-sender-object) | +| `receiverType` | string | Type of the receiver | `"user"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `0` | +| `parentMessageId` | number | ID of the parent message (for threads) | `103` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"message"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` | +| `updatedAt` | number | Epoch timestamp when the message was last updated | `1745554729` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `quotedMessageId` | number | ID of the quoted message | `null` | +| `quotedMessage` | object | The quoted message object | `null` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-2"` | +| `name` | string | Display name of the sender | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-1"` | +| `name` | string | Display name of the receiver | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to fetch the requested data."` | +| `details` | string | Additional technical details | `"An unexpected error occurred while processing the request."` | + + + ## 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` parameter 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. +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. Use `hideReplies = true` on the `MessagesRequestBuilder` to exclude threaded messages from the list. - + ```dart String UID = "cometchat-uid-1"; @@ -144,7 +404,133 @@ messageRequest.fetchNext(onSuccess: (List list) { }); ``` + + + +```dart +String GUID = "cometchat-guid-1"; + +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..guid = GUID + ..hideReplies = true + ..limit = 50).build(); + +messageRequest.fetchNext(onSuccess: (List list) { + debugPrint("Message fetching Successful"); + }, onError: (CometChatException e) { + debugPrint("Message fetching failed with exception: ${e.message}"); + }); +``` + -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. \ No newline at end of file + + +**On Success** — A `List` containing the fetched messages excluding threaded replies (each item is a BaseMessage object): + + + +**BaseMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | number | Unique message ID | `603` | +| `metadata` | object | Custom metadata attached to the message | `{}` | +| `receiver` | object | Receiver user object | [See below ↓](#fetch-exclude-thread-receiver-object) | +| `editedBy` | string | UID of the user who edited the message | `null` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` | +| `sentAt` | number | Epoch timestamp when the message was sent | `1745554729` | +| `receiverUid` | string | UID of the receiver | `"cometchat-uid-1"` | +| `type` | string | Type of the message | `"text"` | +| `readAt` | number | Epoch timestamp when the message was read | `0` | +| `deletedBy` | string | UID of the user who deleted the message | `null` | +| `deliveredAt` | number | Epoch timestamp when the message was delivered | `0` | +| `deletedAt` | number | Epoch timestamp when the message was deleted | `0` | +| `replyCount` | number | Number of replies to this message | `0` | +| `sender` | object | Sender user object | [See below ↓](#fetch-exclude-thread-sender-object) | +| `receiverType` | string | Type of the receiver | `"user"` | +| `editedAt` | number | Epoch timestamp when the message was edited | `0` | +| `parentMessageId` | number | ID of the parent message (for threads) | `0` | +| `readByMeAt` | number | Epoch timestamp when read by the current user | `0` | +| `category` | string | Message category | `"message"` | +| `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` | +| `updatedAt` | number | Epoch timestamp when the message was last updated | `1745554729` | +| `unreadRepliesCount` | number | Count of unread replies | `0` | +| `quotedMessageId` | number | ID of the quoted message | `null` | +| `quotedMessage` | object | The quoted message object | `null` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-2"` | +| `name` | string | Display name of the sender | `"George Alan"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-1"` | +| `name` | string | Display name of the receiver | `"Andrew Joseph"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | string | Human-readable error message | `"Failed to fetch the requested data."` | +| `details` | string | Additional technical details | `"An unexpected error occurred while processing the request."` | + + + +The response is a list of `BaseMessage` objects, excluding any messages that are replies within a thread. Only top-level messages in the conversation are returned. + +--- + +## Next Steps + + + + Learn how to send text, media, and custom messages + + + Handle incoming messages in real-time + + + Add emoji reactions to messages + + + Understand message types and hierarchy + + diff --git a/sdk/flutter/transfer-group-ownership.mdx b/sdk/flutter/transfer-group-ownership.mdx index 5c2b8b668..d5c67b622 100644 --- a/sdk/flutter/transfer-group-ownership.mdx +++ b/sdk/flutter/transfer-group-ownership.mdx @@ -1,14 +1,33 @@ --- title: "Transfer Group Ownership" +sidebarTitle: "Transfer Ownership" +description: "Transfer ownership of a CometChat group to another member using the Flutter SDK." --- + +```dart +// Transfer group ownership to another member +CometChat.transferGroupOwnership( + guid: "GROUP_ID", + uid: "NEW_OWNER_UID", + onSuccess: (String message) => debugPrint("Ownership transferred: $message"), + onError: (CometChatException e) => debugPrint("Error: ${e.message}"), +); +``` + +**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?* +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. The group is represented by a [`Group`](/sdk/reference/entities#group) object and the new owner by a [`User`](/sdk/reference/entities#user) object. See [Leave Group](/sdk/flutter/leave-group). -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. +## Transfer Ownership -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 group member. + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) + @@ -27,3 +46,50 @@ CometChat.transferGroupOwnership(guid: GUID,uid: UID, + +This method takes the below parameters: + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `guid` | `String` | The GUID of the group for which ownership needs to be transferred | +| `uid` | `String` | The UID of the member who should become the new owner | +| `onSuccess` | `Function(String)` | Callback triggered on successful ownership transfer | +| `onError` | `Function(CometChatException)` | Callback triggered on error | + +On success, the new owner gets admin scope and the previous owner becomes a participant. + + +**On Success** — A `String` message confirming the ownership transfer: + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `message` | string | Success confirmation message | `"cometchat-guid-1 ownership transferred successfully"` | + + + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_NOT_A_MEMBER"` | +| `message` | string | Human-readable error message | `"The target user is not a member of the group."` | +| `details` | string | Additional technical details | `"Ownership can only be transferred to an existing group member."` | + + + +--- + +## Next Steps + + + + Leave a group after transferring ownership + + + Promote or demote group members + + diff --git a/sdk/flutter/transient-messages.mdx b/sdk/flutter/transient-messages.mdx index e39b5e46f..9b7654664 100644 --- a/sdk/flutter/transient-messages.mdx +++ b/sdk/flutter/transient-messages.mdx @@ -1,28 +1,90 @@ --- title: "Transient Messages" +sidebarTitle: "Transient Messages" +description: "Send and receive ephemeral real-time messages that are not stored on the server using the CometChat Flutter SDK. Ideal for live reactions and temporary indicators." --- + +| Field | Value | +| --- | --- | +| Key Classes | `TransientMessage` | +| Key Methods | `CometChat.sendTransientMessage()` | +| Receiver Types | `CometChatReceiverType.user`, `CometChatReceiverType.group` | +| Listener Events | `onTransientMessageReceived` | +| Prerequisites | SDK initialized, user logged in | + +```dart +// Send transient message (not stored on server) +Map data = {"LIVE_REACTION": "heart"}; +TransientMessage transientMessage = TransientMessage( + receiverId: "UID", + receiverType: CometChatReceiverType.user, + data: data, +); +CometChat.sendTransientMessage(transientMessage, + onSuccess: () => debugPrint("Sent"), + onError: (e) => debugPrint("Error: ${e.message}"), +); + +// Receive transient messages +CometChat.addMessageListener("LISTENER_ID", MessageListener( + onTransientMessageReceived: (TransientMessage message) { + debugPrint("Received: ${message.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 | UI Kits + + ## 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. - + ```dart String receiverId = "cometchat-uid-2"; -Map data= {}; -data["LIVE_REACTION"] = "heart"; - -TransientMessage transientMessage = TransientMessage( receiverId:receiverId , receiverType: CometChatReceiverType.user , data: data, ); - -CometChat.sendTransientMessage(transientMessage, onSuccess: (){ - debugPrint("Transient Message Sent"); - }, onError: (CometChatException e){ - debugPrint("Transient message sending failed with exception: ${e.message}"); +Map data = {}; +data["LIVE_REACTION"] = "heart"; + +TransientMessage transientMessage = TransientMessage( + receiverId: receiverId, + receiverType: CometChatReceiverType.user, + data: data, +); + +CometChat.sendTransientMessage(transientMessage, onSuccess: () { + debugPrint("Transient Message Sent"); +}, onError: (CometChatException e) { + debugPrint("Transient message sending failed with exception: ${e.message}"); +}); +``` + + + + +```dart +String receiverId = "cometchat-guid-1"; +Map data = {}; +data["LIVE_REACTION"] = "heart"; + +TransientMessage transientMessage = TransientMessage( + receiverId: receiverId, + receiverType: CometChatReceiverType.group, + data: data, +); + +CometChat.sendTransientMessage(transientMessage, onSuccess: () { + debugPrint("Transient Message Sent"); +}, onError: (CometChatException e) { + debugPrint("Transient message sending failed with exception: ${e.message}"); }); ``` @@ -30,10 +92,37 @@ CometChat.sendTransientMessage(transientMessage, onSuccess: (){ +`TransientMessage` Parameters: + +| Parameter | Type | Description | Required | +| --- | --- | --- | --- | +| `receiverId` | `String` | The `UID` of the user or `GUID` of the group to send the transient message to | Yes | +| `receiverType` | `String` | The type of the receiver — `CometChatReceiverType.user` or `CometChatReceiverType.group` | Yes | +| `data` | `Map` | A map to provide custom data with the transient message | Yes | +| `sender` | `User?` | The sender of the transient message (set automatically by the SDK) | No | + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | `String` | Error code identifier | `"ERR_CHAT_API_FAILURE"` | +| `message` | `String` | Human-readable error message | `"Failed to send the transient message."` | +| `details` | `String` | Additional technical details | `"An unexpected error occurred while sending the transient message."` | + + + ## 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., in the `dispose()` method). Failing to remove listeners can cause memory leaks and duplicate event handling. + +```dart +CometChat.removeMessageListener("listenerId"); +``` + + You will receive the transient message in the `onTransientMessageReceived()` method of the registered `MessageListener` class. @@ -55,11 +144,24 @@ void onTransientMessageReceived(TransientMessage message) { -The `TransientMessage` class consists of the below parameters: +The received object is a `TransientMessage` with the following fields: + +| Parameter | Type | Description | +| --- | --- | --- | +| `sender` | `User?` | An object of the `User` class holding all the information related to the sender of the transient message. | +| `receiverId` | `String` | Unique ID of the receiver. This can be the `UID` of the user or `GUID` of the group the transient message is sent to. | +| `receiverType` | `String` | The type of the receiver — `CometChatReceiverType.user` or `CometChatReceiverType.group`. | +| `data` | `Map` | A map containing the custom data sent with the transient message. | + +--- + +## Next Steps -| 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 - `CometChatReceiverType.user` (user) or `CometChatReceiverType.``group `(group) | -| **data** | A Map to provide data. | + + + Learn how to send persistent text and media messages + + + Show real-time typing status to users + + diff --git a/sdk/flutter/troubleshooting.mdx b/sdk/flutter/troubleshooting.mdx new file mode 100644 index 000000000..de534d190 --- /dev/null +++ b/sdk/flutter/troubleshooting.mdx @@ -0,0 +1,191 @@ +--- +title: "Troubleshooting" +sidebarTitle: "Troubleshooting" +description: "Common failure modes and fixes for the CometChat Flutter SDK." +--- + +Find solutions to common issues when building with the CometChat Flutter 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 | +| `pod install` fails | Run `pod install --repo-update` in the `ios/` directory | +| Android build fails | Verify `minSdkVersion` meets SDK requirement | + + + +--- + +## 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()` resolves before calling other methods. Use `await` | +| 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 | Not logged in or invalid receiver | Ensure `login()` completes. Verify receiver UID/GUID exists | +| Messages sent but not received | Listener not registered | Register `MessageListener` with `onTextMessageReceived` | +| Duplicate messages | Multiple listeners | Use unique listener IDs. Remove old listeners in `dispose()` | +| Wrong conversation | Wrong receiver type | Use `CometChatReceiverType.user` for 1:1, `CometChatReceiverType.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 | Set `metadata` before calling 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 admin to add you | +| Owner can't leave | Ownership not transferred | Call `transferGroupOwnership()` first | +| Password join fails | Wrong password | Pass correct password as the `password` parameter | +| `fetchNext()` returns same results | New request object | Reuse the same `GroupsRequest` instance | +| Scope filter returns nothing | Invalid strings | Use `CometChatMemberScope.admin`, `.moderator`, `.participant` | +| 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 | Not installed | Add `cometchat_calls_sdk` to `pubspec.yaml` and run `flutter pub get` | +| No audio/video | Permissions denied | Check device permissions for camera/microphone. Add required entries to `Info.plist` (iOS) and `AndroidManifest.xml` (Android) | +| 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 `CallListener` at app root level | +| Call ended event not received | Wrong callback | Use `onCallEndedMessageReceived` in `CallListener` for call-end messages | +| Black screen after joining | Widget not visible | Ensure the call widget has proper dimensions and is in the widget tree | + +--- + +## 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 | +| Connection drops frequently | Network instability | Use `ConnectionListener` 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)` was set | +| `connect()` doesn't work | Not logged in | Ensure user is logged in first | + +--- + +## Listeners + +| Symptom | Cause | Fix | +|---------|-------|-----| +| 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 widget mounts (in `initState()`) | +| Receipt events not triggering | Receipts not sent | Call `markAsDelivered()`/`markAsRead()` explicitly | + +--- + +## Typing, Receipts & Reactions + +| Symptom | Cause | Fix | +|---------|-------|-----| +| Typing indicator stuck | `endTyping()` not called | Call on send, focus lost, 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 | Update UI state when `onMessageReactionAdded` fires | +| Duplicate reactions | No check before adding | Check `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 | + +--- + +## Platform-Specific — iOS + +| Symptom | Cause | Fix | +|---------|-------|-----| +| `pod install` fails | Outdated CocoaPods cache | Run `pod install --repo-update` in the `ios/` directory | +| Build fails on simulator | Architecture mismatch | Add `arm64` to excluded architectures for simulator builds in Xcode | +| "Module not found" error | Pods not installed | Run `cd ios && pod install` after adding the dependency | +| Camera/microphone not working | Missing `Info.plist` entries | Add `NSCameraUsageDescription` and `NSMicrophoneUsageDescription` to `ios/Runner/Info.plist` | +| Push notifications not received | APNs not configured | Configure APNs certificates in Dashboard and register token with `CometChatNotifications.registerPushToken()` | + +## Platform-Specific — Android + +| Symptom | Cause | Fix | +|---------|-------|-----| +| Build fails with "minSdk" error | API level too low | Set `minSdkVersion` in `android/app/build.gradle` to the required level | +| Multidex error | Too many methods | Enable multidex in `android/app/build.gradle`: `multiDexEnabled true` | +| Camera/microphone not working | Missing permissions | Add `CAMERA`, `RECORD_AUDIO`, and `MODIFY_AUDIO_SETTINGS` to `AndroidManifest.xml` | +| FCM notifications not received | FCM not configured | Configure FCM in Dashboard and register token with `CometChatNotifications.registerPushToken()` | +| ProGuard stripping SDK classes | Missing ProGuard rules | Add CometChat ProGuard rules to `proguard-rules.pro` | + +--- + +## Error Codes + +For the complete SDK error code reference, see [Error Codes](/sdk/flutter/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/flutter/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 + + + Open a support ticket + + diff --git a/sdk/flutter/typing-indicators.mdx b/sdk/flutter/typing-indicators.mdx index 9f04279c7..19640d53d 100644 --- a/sdk/flutter/typing-indicators.mdx +++ b/sdk/flutter/typing-indicators.mdx @@ -1,8 +1,43 @@ --- title: "Typing Indicators" +sidebarTitle: "Typing Indicators" +description: "Send and receive real-time typing indicators using the CometChat Flutter SDK." --- + +| Field | Value | +| --- | --- | +| Key Classes | `TypingIndicator` | +| Key Methods | `CometChat.startTyping()`, `CometChat.endTyping()` | +| Receiver Types | `CometChatReceiverType.user`, `CometChatReceiverType.group` | +| Listener Events | `onTypingStarted`, `onTypingEnded` | +| Prerequisites | SDK initialized, user logged in | + +```dart +// Start typing indicator to user +CometChat.startTyping(receiverUid: "UID", receiverType: CometChatReceiverType.user); + +// Start typing indicator to group +CometChat.startTyping(receiverUid: "GUID", receiverType: CometChatReceiverType.group); + +// Stop typing indicator +CometChat.endTyping(receiverUid: "UID", receiverType: CometChatReceiverType.user); + +// Listen for typing indicators +CometChat.addMessageListener("listenerId", MessageListener( + onTypingStarted: (TypingIndicator typingIndicator) { }, + onTypingEnded: (TypingIndicator typingIndicator) { }, +)); +``` + + + +Typing indicators let users know when someone is actively typing a message, creating a more engaging real-time chat experience. + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) + ## Send a Typing Indicator @@ -10,68 +45,93 @@ title: "Typing Indicators" ### 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()` to notify the receiver that the logged-in user has started typing. The receiver will receive this information in the `onTypingStarted()` method of the `MessageListener` class. - + ```dart CometChat.startTyping( - receaverUid: "UID", - receiverType: CometChatReceiverType.user, - ); + receiverUid: "UID", + receiverType: CometChatReceiverType.user, +); ``` - + ```dart CometChat.startTyping( - receaverUid: "GUID", - receiverType: CometChatReceiverType.group, - ); + receiverUid: "GUID", + receiverType: CometChatReceiverType.group, +); ``` +`startTyping()` Parameters: + +| Parameter | Type | Description | Required | +| --- | --- | --- | --- | +| `receiverUid` | `String` | The `UID` of the user or `GUID` of the group to send the typing indicator to | Yes | +| `receiverType` | `String` | The type of the receiver — `CometChatReceiverType.user` or `CometChatReceiverType.group` | Yes | + +`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. +Use `endTyping()` to notify the receiver that the logged-in user has stopped typing. The receiver will receive this information in the `onTypingEnded()` method of the `MessageListener` class. - + ```dart CometChat.endTyping( - receaverUid: "UID", - receiverType: CometChatReceiverType.user); + receiverUid: "UID", + receiverType: CometChatReceiverType.user, +); ``` - + ```dart CometChat.endTyping( - receaverUid: "GUID", - receiverType: CometChatReceiverType.group); + receiverUid: "GUID", + receiverType: CometChatReceiverType.group, +); ``` - -Custom Data +`endTyping()` Parameters: + +| Parameter | Type | Description | Required | +| --- | --- | --- | --- | +| `receiverUid` | `String` | The `UID` of the user or `GUID` of the group to send the typing indicator to | Yes | +| `receiverType` | `String` | The type of the receiver — `CometChatReceiverType.user` or `CometChatReceiverType.group` | Yes | -You can use the `metadata` field of the `TypingIndicator` class to pass additional data along with the typing indicators. The metadata field is a Map and can be set using the `.metadata` parameter of the `TypingIndicator` class. This data will be received at the receiver end and can be obtained using the same parameter. +`endTyping()` returns `void` — the typing indicator is sent as a fire-and-forget operation. + +Use the `metadata` field of the `TypingIndicator` class to pass additional custom data along with the typing indicators. The metadata field is a `Map` and can be set using the `.metadata` property. This data will be received at the receiver end and can be obtained using the same property. ## Real-time Typing Indicators *In other words, as a recipient, 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 [`TypingIndicator`](/sdk/reference/auxiliary#typingindicator) events. + + +Always remove listeners when they're no longer needed (e.g., in the `dispose()` method). Failing to remove listeners can cause memory leaks and duplicate event handling. + +```dart +CometChat.removeMessageListener("listenerId"); +``` + @@ -97,11 +157,25 @@ void onTypingEnded(TypingIndicator typingIndicator) { -The `TypingIndicator` class consists of the below parameters: +The received object is a `TypingIndicator` with the following fields: + +| Parameter | Type | Description | +| --- | --- | --- | +| `sender` | [`User`](/sdk/reference/entities#user) | An object of the `User` class holding all the information related to the sender of the typing indicator. | +| `receiverId` | `String` | `UID` of the receiver. This is the ID of the group or the user the typing indicator is being sent to. | +| `receiverType` | `String` | Indicates if the typing indicator is to a user or a group — `CometChatReceiverType.user` or `CometChatReceiverType.group`. | +| `metadata` | `Map?` | Optional metadata to provide additional data. | +| `lastTimestamp` | `DateTime` | The timestamp of the last typing indicator event. | + +--- + +## Next Steps -| Parameter | Information | -| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `sender` | An object of the `User` class holding all the information related to the sender of the typing indicator. | -| `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 | + + + Track message delivery and read status + + + Send ephemeral real-time messages like live reactions + + diff --git a/sdk/flutter/update-group.mdx b/sdk/flutter/update-group.mdx index c9353f983..8371e41af 100644 --- a/sdk/flutter/update-group.mdx +++ b/sdk/flutter/update-group.mdx @@ -1,14 +1,44 @@ --- title: "Update A Group" +sidebarTitle: "Update Group" +description: "Update group details such as name, description, icon, and metadata using the CometChat Flutter SDK." --- + +```dart +// Update a group +Group group = Group(guid: "GROUP_ID", name: "New Name", type: CometChatGroupType.public); +group.description = "Updated description"; +group.icon = "https://example.com/icon.png"; + +await CometChat.updateGroup( + group: group, + onSuccess: (Group group) => debugPrint("Updated: ${group.name}"), + onError: (CometChatException e) => debugPrint("Error: ${e.message}"), +); +``` + + +Update a group's name, icon, description, or metadata. The GUID and group type cannot be changed after creation. See the [Group Class](/sdk/flutter/create-group#group-class) reference for all editable fields. ## 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. +You can update the existing details of the group using the `updateGroup()` method. Pass a [`Group`](/sdk/reference/entities#group) object with the updated values. + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) + + +### Parameters + +| Parameter | Type | Description | +|-----------|------|-------------| +| `group` | `Group` | An instance of the [`Group`](/sdk/reference/entities#group) class with updated values | +| `onSuccess` | `Function(Group group)?` | Callback triggered on successful group update | +| `onError` | `Function(CometChatException excep)?` | Callback triggered on error | @@ -32,12 +62,67 @@ String GUID = "GUID"; -This method takes an instance of the `Group` class as a parameter which should contain the data that you wish to update. + +**On Success** — A `Group` object containing all details of the updated group: + + + +**Group Object:** -| Parameter | Description | -| --------- | ---------------------------- | -| `group` | an instance of class `Group` | +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Unique identifier for the group | `"cometchat-guid-1"` | +| `name` | string | Display name of the group | `"Hello Group!"` | +| `icon` | string | URL of the group icon | `null` | +| `description` | string | Description of the group | `null` | +| `membersCount` | number | Number of members in the group | `5` | +| `metadata` | object | Custom metadata attached to the group | `{}` | +| `joinedAt` | number | Epoch timestamp when the logged-in user joined the group | `1745554729` | +| `hasJoined` | boolean | Whether the logged-in user has joined the group | `true` | +| `createdAt` | number | Epoch timestamp when the group was created | `1745554729` | +| `owner` | string | UID of the group owner | `"cometchat-uid-1"` | +| `updatedAt` | number | Epoch timestamp when the group was last updated | `1745554800` | +| `tags` | array | List of tags associated with the group | `[]` | +| `type` | string | Type of the group (public, private, password) | `"public"` | +| `scope` | string | Scope of the logged-in user in the group | `"admin"` | +| `password` | string | Password for password-protected groups | `null` | +| `isBannedFromGroup` | boolean | Whether the logged-in user is banned from the group | `false` | + + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_GUID_NOT_FOUND"` | +| `message` | string | Human-readable error message | `"The specified group does not exist."` | +| `details` | string | Additional technical details | `"Please provide a valid GUID for the group."` | + + 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/flutter/create-group#group-class) +For more information on the `Group` class, please check [here](/sdk/flutter/create-group#group-class). + + +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()`. + + +--- + +## Next Steps + + + + Permanently delete a group + + + Fetch and filter groups with pagination + + + Create new public, private, or password-protected groups + + + Overview of all group management features + + diff --git a/sdk/flutter/upgrading-from-v3-guide.mdx b/sdk/flutter/upgrading-from-v3-guide.mdx index fad427ece..fac6456f5 100644 --- a/sdk/flutter/upgrading-from-v3-guide.mdx +++ b/sdk/flutter/upgrading-from-v3-guide.mdx @@ -1,37 +1,71 @@ --- title: "Upgrading From V3" +sidebarTitle: "Upgrading From V3" +description: "Migrate your CometChat Flutter SDK integration from v3 to v4 with updated dependencies and import statements." --- + +Key changes from v3 to v4: +- Chat SDK: `cometchat_sdk` (replaces `cometchat_pro_sdk`) +- Calls SDK: `cometchat_calls_sdk` (replaces `cometchat_pro_calls_sdk`) +- Import: `import 'package:cometchat_sdk/cometchat_sdk.dart'` +- Import Calls: `import 'package:cometchat_calls_sdk/cometchat_calls_sdk.dart'` + -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/flutter/setup) first, then update your dependencies and imports as shown below. -Please follow the [Setup](/sdk/flutter/setup) instructions to upgrade to the latest V4 version. +## Update Dependencies -## Chat Import Change +| SDK | v3 Package | v4 Package | +| --- | --- | --- | +| Chat SDK | `cometchat_pro_sdk` | `cometchat_sdk` | +| Calls SDK | `cometchat_pro_calls_sdk` | `cometchat_calls_sdk` | -Remove all the imports of CometChat Flutter v3 SDK or replace it with single import statement +Remove the v3 packages from `pubspec.yaml` and add the v4 packages: - - -```dart -import 'package:cometchat_sdk/cometchat_sdk.dart'; +```yaml +dependencies: + cometchat_sdk: ^4.0.33 # replaces cometchat_pro_sdk + cometchat_calls_sdk: ^4.0.0 # replaces cometchat_pro_calls_sdk ``` - +Then run: - +```bash +flutter pub get +``` -## Calling Import Change +## Update Import Statements -Remove all the imports of CometChat Flutter v3 SDK or replace it with single import statement +Find and replace all import statements across your project: + +| SDK | v3 Import | v4 Import | +| --- | --- | --- | +| Chat SDK | `import 'package:cometchat_pro_sdk/cometchat_pro_sdk.dart'` | `import 'package:cometchat_sdk/cometchat_sdk.dart'` | +| Calls SDK | `import 'package:cometchat_pro_calls_sdk/cometchat_pro_calls_sdk.dart'` | `import 'package:cometchat_calls_sdk/cometchat_calls_sdk.dart'` | - - ```dart +// v4 Chat SDK +import 'package:cometchat_sdk/cometchat_sdk.dart'; + +// v4 Calls SDK import 'package:cometchat_calls_sdk/cometchat_calls_sdk.dart'; ``` - + +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. + + +--- + +## Next Steps - + + + Install and configure the CometChat Flutter SDK + + + Learn the core concepts behind CometChat v4 + + diff --git a/sdk/flutter/user-management.mdx b/sdk/flutter/user-management.mdx index b58d3da36..6d23237b5 100644 --- a/sdk/flutter/user-management.mdx +++ b/sdk/flutter/user-management.mdx @@ -1,88 +1,251 @@ --- title: "User Management" +sidebarTitle: "User Management" +description: "Create, update, and manage CometChat users programmatically using the Flutter SDK. Includes user creation, profile updates, and the User class reference." --- + +```dart +// Create a user +User user = User(uid: "user1", name: "Kevin"); +CometChat.createUser(user, "AUTH_KEY", onSuccess: (User user) { + debugPrint("User created: ${user.name}"); +}, onError: (CometChatException e) { + debugPrint("Error: ${e.message}"); +}); + +// Update a user (requires API Key) +User updatedUser = User(uid: "user1", name: "Kevin Fernandez"); +CometChat.updateUser(updatedUser, "AUTH_KEY", onSuccess: (User user) { + debugPrint("User updated: ${user.name}"); +}, onError: (CometChatException e) { + debugPrint("Error: ${e.message}"); +}); + +// Update logged-in user (no auth key needed) +User currentUser = User(name: "New Name"); +CometChat.updateCurrentUserDetails(currentUser, onSuccess: (User user) { + debugPrint("User updated: ${user.name}"); +}, onError: (CometChatException e) { + debugPrint("Error: ${e.message}"); +}); +``` -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. - -Summing up- - -**When a user registers in your app** +**Note:** User creation/deletion should ideally happen on your backend via the [REST API](https://api-explorer.cometchat.com). + -1. You add the user details in your database -2. You create a user in CometChat +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. -**When a user logs into your app** +The typical flow: +1. User registers in your app → Create user in CometChat +2. User logs into your app → [Log user into CometChat](/sdk/flutter/authentication-overview) -1. You log in the user to your app -2. You [log in the user to CometChat](https://app.cometchat.com/login) + +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 +## 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/create-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). -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. + +**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. + -For more details on the fields present in the User class, please check [this](/sdk/flutter/user-management#user-class) +For client-side creation (development only), use `createUser()`: ```dart -String authKey = "AUTH_KEY";//Replace with the auth key of app -User user = User( uid: "usr1" , name: "Kevin" );//Replace with name and uid of user - -CometChat.createUser(user, authKey, onSuccess: (User user){ - debugPrint("Create User succesful ${user}"); - - }, onError: (CometChatException e){ - debugPrint("Create User Failed with exception ${e.message}"); - - }); +String authKey = "AUTH_KEY"; // Replace with the auth key of app +User user = User(uid: "usr1", name: "Kevin"); // Replace with name and uid of user + +CometChat.createUser(user, authKey, onSuccess: (User user) { + debugPrint("Create User successful $user"); +}, onError: (CometChatException e) { + debugPrint("Create User Failed with exception ${e.message}"); +}); ``` - - +### Parameters + +| Parameter | Type | Description | +|-----------|------|-------------| +| `user` | `User` | A `User` object containing the details of the user to be created. The `uid` and `name` fields are required. | +| `authKey` | `String` | Your CometChat Auth Key. Use only for development — never expose in production client code. | +| `onSuccess` | `Function(User user)` | Callback triggered on successful user creation, returning the created `User` object. | +| `onError` | `Function(CometChatException excep)` | Callback triggered on failure, returning a `CometChatException` with error details. | + +Returns a [`User`](/sdk/reference/entities#user) object. See [User Class](#user-class) for all available fields. + + +**On Success** — A `User` object containing all details of the created user: + + + +**User Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"usr1"` | +| `name` | string | Display name of the user | `"Kevin"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `null` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | List of tags associated with the user | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `0` | + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_UID_NOT_FOUND"` | +| `message` | string | Human-readable error message | `"The specified UID does not exist."` | +| `details` | string | Additional technical details | `"Please provide a valid UID for the user."` | + + UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. -## 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). + +For client-side updates (development only), use `updateUser()`: + + + +```dart +String apiKey = "AUTH_KEY"; // Replace with the auth key of app +User user = User(uid: "usr1", name: "Kevin Fernandez"); + +CometChat.updateUser(user, apiKey, onSuccess: (User user) { + debugPrint("User updated: $user"); +}, onError: (CometChatException e) { + debugPrint("Update User Failed with exception ${e.message}"); +}); +``` + + + +Ensure the [`User`](/sdk/reference/entities#user) object has the correct `UID` set. + +### Parameters + +| Parameter | Type | Description | +|-----------|------|-------------| +| `user` | `User` | A `User` object with the `uid` of the user to update and the fields to change. | +| `apiKey` | `String` | Your CometChat Auth Key. Use only for development — never expose in production client code. | +| `onSuccess` | `Function(User retUser)` | Callback triggered on successful update, returning the updated `User` object. | +| `onError` | `Function(CometChatException excep)` | Callback triggered on failure, returning a `CometChatException` with error details. | + +Returns a [`User`](/sdk/reference/entities#user) object. See [User Class](#user-class) for all available fields. -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. + +**On Success** — A `User` object containing all details of the updated user: -Please make sure the `User` object provided to the `updateUser()` method has the `UID` of the user to be updated set. +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"usr1"` | +| `name` | string | Display name of the user | `"Kevin Fernandez"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `null` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | List of tags associated with the user | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `0` | + -## 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. +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_UID_NOT_FOUND"` | +| `message` | string | Human-readable error message | `"The specified UID does not exist."` | +| `details` | string | Additional technical details | `"Please provide a valid UID for the user."` | + + +## Updating Logged-in User + +Use `updateCurrentUserDetails()` to update the current user without an Auth Key. Note: You cannot update the user's role with this method. ```dart User user = User(name: 'Updated Name'); - CometChat.updateCurrentUserDetails(user, onSuccess: (User updatedUser) { - debugPrint("Updated User: $updatedUser"); - }, onError: (CometChatException e) { - debugPrint("Updated User exception : ${e.message}"); - }); + debugPrint("Updated User: $updatedUser"); +}, onError: (CometChatException e) { + debugPrint("Updated User exception : ${e.message}"); +}); ``` - - +### Parameters + +| Parameter | Type | Description | +|-----------|------|-------------| +| `user` | `User` | A `User` object with the fields to update. The `uid` is ignored — only the logged-in user is updated. | +| `onSuccess` | `Function(User retUser)` | Callback triggered on successful update, returning the updated `User` object. | +| `onError` | `Function(CometChatException excep)` | Callback triggered on failure, returning a `CometChatException` with error details. | + +The method returns a [`User`](/sdk/reference/entities#user) object. + + +**On Success** — A `User` object containing all details of the updated user: + + + +**User Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-1"` | +| `name` | string | Display name of the user | `"Updated Name"` | +| `link` | string | Profile link | `null` | +| `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `metadata` | object | Custom metadata | `{}` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `statusMessage` | string | Status message | `null` | +| `tags` | array | List of tags associated with the user | `[]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` | + + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code identifier | `"ERR_UID_NOT_FOUND"` | +| `message` | string | Human-readable error message | `"The specified UID does not exist."` | +| `details` | string | Additional technical details | `"Please provide a valid UID for the user."` | + + 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 @@ -100,3 +263,20 @@ 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 and filter user lists with pagination. + + + Monitor real-time online/offline status. + + + Block and unblock users. + + + Log users into CometChat. + + diff --git a/sdk/flutter/user-presence.mdx b/sdk/flutter/user-presence.mdx index a9721a3d9..c1f0fecea 100644 --- a/sdk/flutter/user-presence.mdx +++ b/sdk/flutter/user-presence.mdx @@ -1,30 +1,62 @@ --- title: "User Presence" +sidebarTitle: "User Presence" +description: "Track when users come online or go offline in real-time using CometChat's presence subscription system." --- +{/* TL;DR for Agents and Quick Reference */} + +```dart +// Configure presence subscription during init +AppSettings appSettings = (AppSettingsBuilder() + ..subscriptionType = CometChatSubscriptionType.allUsers // or .roles, .friends + ..region = "REGION" + ..autoEstablishSocketConnection = true +).build(); + +await CometChat.init("APP_ID", appSettings, onSuccess: (msg) {}, onError: (e) {}); + +// Listen for presence changes +CometChat.addUserListener("UNIQUE_LISTENER_ID", UserListener( + onUserOnline: (User user) { + debugPrint("${user.name} is online"); + }, + onUserOffline: (User user) { + debugPrint("${user.name} is offline"); + }, +)); + +// Remove listener when done +CometChat.removeUserListener("UNIQUE_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. + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) + ## Real-time Presence *In other words, 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. - -In the `AppSettings` class, you can set the type of presence you wish to receive. +Configure presence subscription in `AppSettings` during SDK initialization. The `AppSettingsBuilder` provides three subscription options: -For presence subscription, the `AppSettingsBuilder` provides 3 methods : +| Method | Description | +| ------ | ----------- | +| `subscribePresenceForAllUsers()` | Receive presence updates for all users | +| `subscribePresenceForRoles(List roles)` | Receive presence updates only for users with specified roles | +| `subscribePresenceForFriends()` | Receive presence updates only for friends | -* `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. +If none of these methods are called, no presence events will be delivered. -If none of the above methods are set, 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/flutter/setup) for details. + -For every activity or fragment you wish to receive user events in, you need to register the `UserListener` using the `addUserListener()` method. - -We suggest adding the listener in the `init` method of the activity or the fragment where you wish to receive these events in. +Register a `UserListener` to receive presence events. We suggest adding the listener in the `init` method of the activity or the fragment where you wish to receive these events in. @@ -53,9 +85,23 @@ void onUserOffline(User user) { | ------------ | ----------------------------------------------------------------------------------------------- | | `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. +### UserListener Events + +| Event | Description | +| ----- | ----------- | +| `onUserOnline(User user)` | Triggered when a subscribed user comes online | +| `onUserOffline(User user)` | Triggered when a subscribed user goes offline | + +Each callback receives a [`User`](/sdk/reference/entities#user) object with presence information. -We recommend you remove the listener once the listener is not in use. +Relevant fields to access on returned users: + +| Field | Type | Description | +|-------|------|-------------| +| `status` | `String` | Online status of the user (`"online"` or `"offline"`) | +| `lastActiveAt` | `int` | Timestamp when the user was last active | + +Remove the listener when no longer needed: @@ -69,11 +115,15 @@ CometChat.removeUserListener(listenerID); + +Always remove listeners when they're no longer needed (e.g., in the `dispose()` method). 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?* -When you [retrieve the list of users](/sdk/flutter/retrieve-users) , in the[User](/sdk/flutter/user-management#user-class) object, you will receive 2 keys: +When you [retrieve the list of users](/sdk/flutter/retrieve-users), in the [User](/sdk/flutter/user-management) object, you will receive 2 keys: 1. `status` - This will hold either of the two values : @@ -81,3 +131,22 @@ When you [retrieve the list of users](/sdk/flutter/retrieve-users) , in the[User * `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 a **Last seen** for that user. + +--- + +## Next Steps + + + + Fetch user lists with filtering and pagination + + + Create and update users programmatically + + + Monitor SDK connection to CometChat servers + + + Block and unblock users in your app + + diff --git a/sdk/flutter/users-overview.mdx b/sdk/flutter/users-overview.mdx index 3a340e5e3..32e83bbb2 100644 --- a/sdk/flutter/users-overview.mdx +++ b/sdk/flutter/users-overview.mdx @@ -1,10 +1,37 @@ --- title: "Users" sidebarTitle: "Overview" +description: "Overview of CometChat user functionality including user management, retrieval, and presence tracking in the Flutter SDK." --- + +- [User Management](/sdk/flutter/user-management) — Create and update users +- [Retrieve Users](/sdk/flutter/retrieve-users) — Fetch and filter user lists +- [User Presence](/sdk/flutter/user-presence) — Track online/offline status +- [Block Users](/sdk/flutter/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. +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. -You can begin with [user management](/sdk/flutter/user-management) to sync your users to CometChat. Once that is done, you can [retrieve users](/sdk/flutter/retrieve-users) and display them in your app. +- [User Management](/sdk/flutter/user-management) — Create users when they sign up, update profiles, and delete accounts +- [Retrieve Users](/sdk/flutter/retrieve-users) — Fetch and filter user lists with pagination, search, and role-based filtering +- [User Presence](/sdk/flutter/user-presence) — Monitor real-time online/offline status and subscribe to presence changes +- [Block Users](/sdk/flutter/block-users) — Block and unblock users to prevent all communication + +## Next Steps + + + + Create, update, and delete users in CometChat. + + + Fetch user lists with filtering, sorting, and pagination. + + + Monitor real-time online/offline status of users. + + + Block and unblock users to control communication. + + diff --git a/sdk/flutter/video-view-customisation.mdx b/sdk/flutter/video-view-customisation.mdx index d48d8ccdf..2b2446d02 100644 --- a/sdk/flutter/video-view-customisation.mdx +++ b/sdk/flutter/video-view-customisation.mdx @@ -1,16 +1,21 @@ --- title: "Video View Customisation" +sidebarTitle: "Video View Customisation" +description: "Learn how to customize the main video container appearance and controls in CometChat Flutter calling." --- + +- **Class:** `MainVideoContainerSetting` +- **Apply via:** `CallSettingsBuilder..setMainVideoContainerSetting(videoSettings)` +- **Customizable elements:** Aspect ratio, full screen button, name label, zoom button, user list button +- **Position constants:** `POSITION_TOP_LEFT`, `POSITION_TOP_RIGHT`, `POSITION_BOTTOM_LEFT`, `POSITION_BOTTOM_RIGHT` +- **Requires:** [Default Calling](/sdk/flutter/default-call) or [Direct Calling](/sdk/flutter/direct-call) setup + -This section will guide you to customise the main video container. +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 - -Once you have decided to implement [Default Calling](/sdk/flutter/default-call) or [Direct Calling](/sdk/flutter/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/flutter/default-call) or [Direct Calling](/sdk/flutter/direct-call). +Before you begin, make sure you've set up [Ringing](/sdk/flutter/default-call) or [Call Session](/sdk/flutter/direct-call). ## Main Video Container Setting @@ -40,3 +45,22 @@ videoSettings.setFullScreenButtonParams(VideoStreamsPosition.POSITION_TOP_RIGHT, + +--- + +## Next Steps + + + + Implement default audio/video calling + + + Implement direct calling without call events + + + Enable screen sharing and presenter features + + + Record calls for playback + + diff --git a/sdk/flutter/webhooks-overview.mdx b/sdk/flutter/webhooks-overview.mdx index 598d43500..db3e4f451 100644 --- a/sdk/flutter/webhooks-overview.mdx +++ b/sdk/flutter/webhooks-overview.mdx @@ -1,4 +1,115 @@ --- title: "Webhooks" +sidebarTitle: "Webhooks" +description: "Configure server-side webhooks to receive real-time notifications for messages, users, groups, calls, and moderation events in your Flutter application." url: "/fundamentals/webhooks-overview" ---- \ No newline at end of file +--- + + + +Webhooks send HTTP POST requests to your server when events occur: + +**Setup Requirements:** +- HTTPS endpoint (SSL required) +- Publicly accessible URL +- Support POST method with `application/json` +- Return HTTP 200 OK to acknowledge receipt + +**Event Categories:** +- **Messages:** `message_sent`, `message_edited`, `message_deleted`, `message_read_receipt` +- **Users:** `user_blocked`, `user_unblocked`, `user_connection_status_changed` +- **Groups:** `group_created`, `group_member_added`, `group_member_left` +- **Calls:** `call_initiated`, `call_started`, `call_ended`, `recording_generated` +- **Moderation:** `moderation_engine_approved`, `moderation_engine_blocked` + +**Configure via:** [CometChat Dashboard](https://app.cometchat.com) → Your App → Webhooks + + +CometChat Webhooks enable real-time, event-driven communication with your server by sending HTTP POST requests for specific events such as messages, user actions, group updates, calls, and moderation results. + +You can use webhooks to build custom workflows such as sending SMS or email notifications, logging activity, syncing with external systems, or triggering automation. + + +Webhooks are configured at the application level through the CometChat Dashboard, not within the Flutter SDK. The SDK handles real-time events via listeners, while webhooks deliver events to your backend server. + + +--- + +## When to Use Webhooks vs SDK Listeners + +| Use Case | Solution | +| --- | --- | +| Real-time updates in Flutter app | SDK Listeners (`CometChatMessageEvents`, `CometChatUserEvents`) | +| Server-side processing | Webhooks | +| Push notifications to offline users | Webhooks | +| Analytics and logging | Webhooks | +| Third-party integrations | Webhooks | +| Syncing with external databases | Webhooks | + +--- + +## Setting Up Webhooks + +Webhooks are configured through the CometChat Dashboard: + + + + Go to [CometChat Dashboard](https://app.cometchat.com) → Your App → Webhooks + + + Click **Create Webhook** and enter your HTTPS endpoint URL + + + Choose which events should trigger webhook calls (messages, users, groups, calls, moderation) + + + Set up Basic Authentication with username/password for security + + + +--- + +## Webhook Endpoint Requirements + +Your webhook endpoint must meet these criteria: + +1. **Use HTTPS** – All webhook URLs must be secured with SSL +2. **Be publicly accessible** – Your server should be reachable from the internet +3. **Support POST method** – Events are delivered as `HTTP POST` requests with `application/json` content +4. **Return HTTP 200 OK** – Acknowledge receipt within 2 seconds + +--- + +## Best Practices + + + Enable `retryOnFailure` when setting up webhooks. CometChat retries failed deliveries after 10 seconds, then 30 seconds. Use unique event IDs to deduplicate retries. + + + For long processing tasks, enqueue events to systems like Kafka, RabbitMQ, or AWS SQS, and process them asynchronously. Respond within 2 seconds to prevent timeouts. + + + Return appropriate HTTP status codes: `200 OK` for success, `4xx` for client errors, `5xx` for server issues. + + + Maintain detailed logs of incoming webhook requests and responses. Track failures, latency, and retry attempts. + + +--- + +## Next Steps + + + + Handle events directly in your Flutter app with SDK listeners + + + Explore additional SDK resources and documentation + + + View all webhook event payloads and details + + + Learn how to create and manage webhooks via REST API + + diff --git a/sdk/ios/additional-message-filtering.mdx b/sdk/ios/additional-message-filtering.mdx index 03075fa48..d4e3f28ca 100644 --- a/sdk/ios/additional-message-filtering.mdx +++ b/sdk/ios/additional-message-filtering.mdx @@ -1,542 +1,170 @@ --- -title: "Additional Message Filtering" +title: "Message Filtering" +sidebarTitle: "Message Filtering" +description: "Advanced filtering options for fetching messages using MessagesRequestBuilder in the CometChat iOS SDK." --- + +```swift +// Filter by category and type +let mediaRequest = MessagesRequest.MessageRequestBuilder() + .set(uid: "cometchat-uid-1") + .set(categories: ["message"]) + .set(types: ["image", "video", "audio", "file"]) + .set(limit: 50) + .build() -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. +// Unread messages only +let unreadRequest = MessagesRequest.MessageRequestBuilder() + .set(uid: "cometchat-uid-1") + .set(unread: true) + .set(limit: 50) + .build() -Steps to generate an object of the MessagesRequest class: +// Fetch with pagination +messagesRequest.fetchPrevious(onSuccess: { messages in }, onError: { error in }) +messagesRequest.fetchNext(onSuccess: { messages in }, onError: { error in }) +``` -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. +**Key methods:** `set(uid:)`, `set(guid:)`, `set(limit:)`, `set(categories:)`, `set(types:)`, `setTags(_:)`, `set(unread:)`, `setParentMessageId(parentMessageId:)`, `set(messageID:)`, `set(timeStamp:)`, `hideReplies(hide:)`, `hideDeletedMessages(hide:)` + -Once you have an object of the `MessagesRequest` class, you can call either the `fetchNext()` method or the `fetchPrevious()` method using the object. +The `MessagesRequest` class fetches messages based on various parameters. It uses the Builder design pattern via `MessagesRequestBuilder`. -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. +| Method | Description | +| --- | --- | +| `fetchNext()` | Returns messages after the specified parameters | +| `fetchPrevious()` | Returns 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. +Messages are paginated with a maximum of 100 per request. Call `fetchPrevious()`/`fetchNext()` repeatedly on the same object to get subsequent pages. -Now that you are clear how to use the `MessagesRequest` class, below are the various options available: +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 type checking to determine the specific type. ## Number of messages fetched -*In other words, how do I set the number of messages fetched in a single iteration* +Set the number of messages to fetch per request using `setLimit()`. Maximum is 100. -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`. - - - ```swift -var limit = 50; +var limit = 50 let messagesRequest = MessagesRequest.MessageRequestBuilder() -.set(limit: limit) -.build(); + .set(limit: limit) + .build() ``` - - - - ## Messages for a user conversation -\*In other words, how do I fetch messages between me and any user \* +Use `set(uid:)` to fetch messages between the logged-in user and a specific 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. - - - ```swift -var limit = 30; +var limit = 30 let messagesRequest = MessagesRequest.MessageRequestBuilder() -.set(uid: "cometchat-uid-1") -.set(limit: limit) -.build(); + .set(uid: "cometchat-uid-1") + .set(limit: limit) + .build() ``` - - - - ## Messages for a group conversation -*In other words, 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. +Use `set(guid:)` to fetch messages from a group. - - ```swift -var limit = 30; +var limit = 30 let messagesRequest = MessagesRequest.MessageRequestBuilder() -.set(guid: "cometchat-guid-1") -.set(limit: limit) -.build(); + .set(guid: "cometchat-guid-1") + .set(limit: limit) + .build() ``` - - - - - -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. - +If neither `set(uid:)` nor `set(guid:)` is used, all messages for the logged-in user will be fetched across all conversations. ## 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 `set(messageID:)` to fetch messages before or after a specific message ID. Use `fetchNext()` to get messages after, or `fetchPrevious()` to get messages before. - - ```swift -var limit = 30; +var limit = 30 let messagesRequest = MessagesRequest.MessageRequestBuilder() -.set(messageID: 100) -.set(limit: limit) -.build(); + .set(messageID: 100) + .set(limit: limit) + .build() ``` - - - - -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. - ## Messages before/after a given time -\*In other words, how do I fetch messages before or after a particular date or time \* +Use `set(timeStamp:)` with a Unix timestamp to fetch messages before or after a specific 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. - - - ```swift -var limit = 30; +var limit = 30 let messagesRequest = MessagesRequest.MessageRequestBuilder() -.set(timeStamp: 151268736300) -.set(limit: limit) -.build(); + .set(timeStamp: 151268736300) + .set(limit: limit) + .build() ``` - - - - -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. - ## 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. - - - -```swift -var limit = 30; -let messagesRequest = MessagesRequest.MessageRequestBuilder() -.set(unread: true) -.set(limit: limit) -.build(); -``` - - - - - -This method along with `setGUID()` or `setUID()` can be used to fetch unread messages for a particular group or user conversation respectively. - -## 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. - - - -```swift -var limit = 30; -let messagesRequest = MessagesRequest.MessageRequestBuilder() -.hideMessagesFromBlockedUsers(true) -.set(limit: limit) -.build(); -``` - - - - - -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 - -\*In other words, 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. - - - -```swift -var limit = 30; -let messagesRequest = MessagesRequest.MessageRequestBuilder() -.setUpdatedAfter(timeStamp: 151432132100) -.set(limit: limit) -.build(); -``` - - - - - -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. - -## Updated messages only - -\*In other words, how do I fetch messages that have been updated after a particular date or time \* +Use `set(unread:)` to fetch only unread messages. -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. - - - ```swift -var limit = 30; +var limit = 30 let messagesRequest = MessagesRequest.MessageRequestBuilder() -.setUpdatedAfter(timeStamp: 151432132100) -.updatesOnly(onlyUpdates: true) -.set(limit: limit) -.build(); + .set(unread: true) + .set(limit: limit) + .build() ``` - - - - -## Messages for a specific category - -\*In other words, how do I fetch messages belonging to a specific category \* - -We recommend before trying this, you refer to the [Message structure and hierarchy guide](/sdk/ios/message-structure-and-hierarchy) to get familiar with the various categories of messages. - -This can be easily achieved using the `setCategory()` method. This method takes the category as the input and fetches all the messages belonging to that category. - ## Messages for multiple categories -*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/ios/message-structure-and-hierarchy) to get familiar with the various categories of messages. +Use `set(categories:)` with an array of category names. See [Message structure and hierarchy](/sdk/ios/message-structure-and-hierarchy) for available 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. - - - ```swift -var limit = 30; +var limit = 30 let messagesRequest = MessagesRequest.MessageRequestBuilder() -.set(limit: limit) -.set(categories: ["message","call","action"]) -.build(); + .set(limit: limit) + .set(categories: ["message", "call", "action"]) + .build() ``` - - - - -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. - ## 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/ios/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. - - - -```swift -var limit = 30; -let messagesRequest = MessagesRequest.MessageRequestBuilder() -.set(limit: limit) -.set(types: ["text","image"]) -.build(); -``` - - - - - -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. - -## 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 \* - -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. - - - -```swift -var limit = 30; -let messagesRequest = MessagesRequest.MessageRequestBuilder() -.set(limit: limit) -.setParentMessageId(parentMessageId: 100) -.build(); -``` - - - - - -The above code snippet returns the messages that belong to the thread with parent id 100. - -## Hide threaded messages in user/group conversations - -\*In other words, 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. - - - -```swift -var limit = 30; -let messagesRequest = MessagesRequest.MessageRequestBuilder() -.set(limit: limit) -.hideReplies(hide: true) -.build(); -``` - - - - - -## Hide deleted messages in user/group conversations +Use `set(types:)` with an array of type names. -*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. - - - ```swift +var limit = 30 let messagesRequest = MessagesRequest.MessageRequestBuilder() -.hideDeletedMessages(hide: true) -.build() + .set(limit: limit) + .set(types: ["text", "image"]) + .build() ``` - - - - ## Messages by tags -*In other words, 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. +Use `setTags()` with an array of tag names to fetch only messages with those tags. - - ```swift var limit = 30 let tags = ["pinned"] let messagesRequest = MessagesRequest.MessageRequestBuilder() -.setLimit(50) -.setTags(tags) -.build(); -``` - - - - - -## 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 information. When set to `false` , the SDK will not fetch tags information associated with messages. The default value for this parameter is `false` . - - - -```swift -var limit = 30; -let messagesRequest = MessagesRequest.MessageRequestBuilder() -.setLimit(50) -.withTags(true) -.build(); -``` - - - - - -## 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 `has(links: Bool)` 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`. - - - -This feature is only available with `Conversation & Advanced Search`. 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) - - - - - -```swift -var limit = 30; -let messagesRequest = MessagesRequest.MessageRequestBuilder() -.setLimit(50) -.set(uid: "cometchat-uid-1") -.has(links: true) -.build(); -``` - - - - - -## 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 `has(attachments: Bool)` 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`. - - - -This feature is only available with `Conversation & Advanced Search`. 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) - - - - - -```swift -var limit = 30; -let messagesRequest = MessagesRequest.MessageRequestBuilder() -.setLimit(50) -.set(uid: "cometchat-uid-1") -.has(attachments: true) -.build(); -``` - - - - - -## 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 `has(reactions: Bool)` 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`. - - - -This feature is only available with `Conversation & Advanced Search`. 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) - - - - - -```swift -var limit = 30; -let messagesRequest = MessagesRequest.MessageRequestBuilder() -.setLimit(50) -.set(uid: "cometchat-uid-1") -.has(reactions: true) -.build(); -``` - - - - - -## 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 `has(mentions: Bool)` 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`. - - - -This feature is only available with `Conversation & Advanced Search`. 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) - - - - - -```swift -var limit = 30; -let messagesRequest = MessagesRequest.MessageRequestBuilder() -.setLimit(50) -.set(uid: "cometchat-uid-1") -.has(mentions: true) -.build(); -``` - - - - - -## 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 `set(mentionedUIDs: [String])` 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. - - - -This feature is only available with `Conversation & Advanced Search`. 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) - - - - - -```swift -var limit = 30; -let mentionedUids = ["cometchat-uid-1"] -let messagesRequest = MessagesRequest.MessageRequestBuilder() -.setLimit(50) -.set(uid: "cometchat-uid-1") -.set(mentionedUIDs: mentionedUids) -.build(); + .setLimit(50) + .setTags(tags) + .build() ``` - - - - -## 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 `set(attachmentTypes: [CometChat.AttachmentType])` method. This method accepts an array of `CometChat.AttachmentType` enum values as input. When provided, it filters the results to include only those messages that contain attachments matching the specified types. Supported attachment types include `.image`, `.audio`, `.video`, and `.file`. - - - -This feature is only available with `Conversation & Advanced Search`. 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) - - - - - -```swift -var limit = 30; -let messagesRequest = MessagesRequest.MessageRequestBuilder() -.setLimit(50) -.set(uid: "cometchat-uid-1") -.set(attachmentTypes: [.image, .video]) -.build(); -``` - - +--- - +## Next Steps + + + + Listen for incoming messages in real-time + + + Organize conversations with message threads + + + Understand message categories and types + + diff --git a/sdk/ios/ai-agents.mdx b/sdk/ios/ai-agents.mdx index 2a920c71f..4428d3e9c 100644 --- a/sdk/ios/ai-agents.mdx +++ b/sdk/ios/ai-agents.mdx @@ -1,43 +1,93 @@ --- title: "AI Agents" +sidebarTitle: "AI Agents" +description: "Integrate AI Agents for intelligent automated interactions using the CometChat iOS SDK with real-time streaming events." --- -# 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). +| Feature | Description | +| --- | --- | +| [AI Agents](#agent-run-lifecycle-and-message-flow) | Intelligent automated conversations with real-time streaming | +| [AI Moderation](/sdk/ios/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) | -> **Note:** -> Currently, an Agent only responds to **Text Messages**. +```swift +// Listen for real-time AI Agent events (streaming) +CometChat.addAIAssistantListener("LISTENER_ID", self) + +// Listen for persisted agentic messages +// Conform to CometChatMessageDelegate +func onAIAssistantMessageReceived(_ msg: AIAssistantMessage) { } +func onAIToolResultMessageReceived(_ msg: AIToolResultMessage) { } +func onAIToolArgumentsMessageReceived(_ msg: AIToolArgumentMessage) { } + +// Cleanup +CometChat.removeAIAssistantListener("LISTENER_ID") +CometChat.removeMessageListener("LISTENER_ID") +``` -## Agent Run Lifecycle and Message Flow +**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 + -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. +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). -- A user sends a text message to an Agent. -- The platform starts a run and streams real-time events via the **`AIAssistantEventsDelegate`**. -- After the run completes, persisted Agentic Messages arrive via the **`CometChatMessageDelegate`**. + +Agents only respond to text messages. + -### Real-time Events +## Sending a Message to an AI Agent + +Send a text message to an agent's UID like any other user: + + + + ```swift + let agentUID = "ai-agent-uid" + let textMessage = TextMessage( + receiverUid: agentUID, + text: "What's the weather today?", + receiverType: .user + ) + + CometChat.sendTextMessage(message: textMessage) { sentMessage in + print("Message sent to agent") + } onError: { error in + print("Error: \(error?.errorDescription)") + } + ``` + + + +## Agent Run Lifecycle and Message Flow -Events are received via the **`onAIAssistantEventReceived`** method of the **`AIAssistantEventsDelegate`** protocol 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. +When a user sends a text message to an Agent: +1. The platform starts a run and streams real-time events via `AIAssistantEventsDelegate` +2. After the run completes, persisted Agentic Messages arrive via `CometChatMessageDelegate` +### Real-time Events + +Events are received via `onAIAssistantEventReceived` as [`AIAssistantBaseEvent`](/sdk/reference/messages#aiassistantbaseevent) objects, 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. Text Message events are always emitted and carry the assistant's reply incrementally. + + + + ```swift import CometChatSDK @@ -45,16 +95,12 @@ class AIAssistantEventHandler: AIAssistantEventsDelegate { private let sdkStreamListenerId = "unique_listener_id" - /// Call this to start listening to AI Assistant events func addListener() { CometChat.addAIAssistantListener(sdkStreamListenerId, self) - print("AIAssistantListener added successfully.") } - /// Call this to remove the AI Assistant listener func removeListener() { CometChat.removeAIAssistantListener(sdkStreamListenerId) - print("AIAssistantListener removed successfully.") } func onAIAssistantEventReceived(_ event: AIAssistantBaseEvent) { @@ -62,27 +108,21 @@ class AIAssistantEventHandler: AIAssistantEventsDelegate { } } ``` - -#### 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 **`CometChatMessageDelegate`** after the run completes. +After the run completes, these messages arrive via `CometChatMessageDelegate`: -- `AIAssistantMessage`: The full assistant reply. -- `AIToolResultMessage`: The final output of a tool call. -- `AIToolArgumentMessage`: The arguments that were passed to a tool. +| Message Type | Description | +|--------------|-------------| +| `AIAssistantMessage` | The full assistant reply | +| `AIToolResultMessage` | The final output of a tool call | +| `AIToolArgumentMessage` | The arguments passed to a tool | + + ```swift import CometChatSDK @@ -90,7 +130,6 @@ let listenerId = "unique_listener_id" class MessageHandler: CometChatMessageDelegate { - // Adding the MessageListener // CometChat.addMessageListener(listenerId, self) func onAIAssistantMessageReceived(_ aiAssistantMessage: AIAssistantMessage) { @@ -105,4 +144,29 @@ class MessageHandler: CometChatMessageDelegate { print("AI Tool Arguments Message Received: \(aiToolArgumentMessage)") } } -``` \ No newline at end of file +``` + + + + +Always remove listeners when they're no longer needed (e.g., on view dismissal). 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/ios/ai-moderation.mdx b/sdk/ios/ai-moderation.mdx index eda461d9a..c399f9291 100644 --- a/sdk/ios/ai-moderation.mdx +++ b/sdk/ios/ai-moderation.mdx @@ -1,22 +1,45 @@ --- title: "AI Moderation" +sidebarTitle: "AI Moderation" +description: "Automatically moderate chat messages using AI to detect and block inappropriate content in real-time with the CometChat iOS SDK." --- -## 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. +```swift +// Send message - check moderation status +CometChat.sendTextMessage(message: textMessage) { sentMessage in + if let msg = sentMessage as? TextMessage { + let status = msg.getModerationStatus() // "pending" | "approved" | "disapproved" + } +} + +// Listen for moderation results +func onMessageModerated(moderatedMessage: BaseMessage) { + if let msg = moderatedMessage as? TextMessage { + let status = msg.getModerationStatus() + // Handle "approved" or "disapproved" + } +} +``` + +**Supported types:** Text, Image, Video messages only +**Statuses:** `"pending"` -> `"approved"` or `"disapproved"` + + +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 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 -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 @@ -46,15 +69,13 @@ sequenceDiagram ## Supported Message Types -Moderation is triggered **only** for the following message types: - | Message Type | Moderated | Notes | |--------------|-----------|-------| -| Text Messages | ✅ | Content analyzed for inappropriate text | -| Image Messages | ✅ | Images scanned for unsafe content | -| Video Messages | ✅ | Videos analyzed for prohibited content | -| Custom Messages | ❌ | Not subject to AI moderation | -| Action Messages | ❌ | Not subject to AI moderation | +| Text Messages | Yes | Content analyzed for inappropriate text | +| Image Messages | Yes | Images scanned for unsafe content | +| Video Messages | Yes | Videos analyzed for prohibited content | +| Custom Messages | No | Not subject to AI moderation | +| Action Messages | No | Not subject to AI moderation | ## Moderation Status @@ -78,11 +99,9 @@ When you send a text, image, or video message, check the initial moderation stat let textMessage = TextMessage(receiverUid: receiverUID, text: "Hello, how are you?", receiverType: .user) CometChat.sendTextMessage(message: textMessage) { sentMessage in - // Check moderation status if let message = sentMessage as? TextMessage { if message.getModerationStatus() == "pending" { print("Message is under moderation review") - // Show pending indicator in UI } } } onError: { error in @@ -95,10 +114,8 @@ When you send a text, image, or video message, check the initial moderation stat TextMessage *textMessage = [[TextMessage alloc] initWithReceiverUid:receiverUID text:@"Hello, how are you?" receiverType:ReceiverTypeUser]; [CometChat sendTextMessageWithMessage:textMessage onSuccess:^(TextMessage *sentMessage) { - // Check moderation status if ([[sentMessage getModerationStatus] isEqualToString:@"pending"]) { NSLog(@"Message is under moderation review"); - // Show pending indicator in UI } } onError:^(CometChatException *error) { NSLog(@"Message sending failed: %@", error.errorDescription); @@ -109,7 +126,7 @@ When you send a text, image, or video message, check the initial moderation stat ### Step 2: Listen for Moderation Results -Implement the `onMessageModerated` delegate method to receive moderation results in real-time: +Register a message listener to receive moderation results in real-time: @@ -121,25 +138,9 @@ Implement the `onMessageModerated` delegate method to receive moderation results switch message.getModerationStatus() { case "approved": print("Message \(message.id) approved") - // Update UI to show message normally - case "disapproved": print("Message \(message.id) blocked") - // Handle blocked message (hide or show warning) handleDisapprovedMessage(message) - - default: - break - } - } else if let message = moderatedMessage as? MediaMessage { - switch message.getModerationStatus() { - case "approved": - print("Media message \(message.id) approved") - - case "disapproved": - print("Media message \(message.id) blocked") - handleDisapprovedMessage(message) - default: break } @@ -162,19 +163,8 @@ Implement the `onMessageModerated` delegate method to receive moderation results if ([[textMessage getModerationStatus] isEqualToString:@"approved"]) { NSLog(@"Message %d approved", message.id); - // Update UI to show message normally } else if ([[textMessage getModerationStatus] isEqualToString:@"disapproved"]) { NSLog(@"Message %d blocked", message.id); - // Handle blocked message (hide or show warning) - [self handleDisapprovedMessage:message]; - } - } else if ([message isKindOfClass:[MediaMessage class]]) { - MediaMessage *mediaMessage = (MediaMessage *)message; - - if ([[mediaMessage getModerationStatus] isEqualToString:@"approved"]) { - NSLog(@"Media message %d approved", message.id); - } else if ([[mediaMessage getModerationStatus] isEqualToString:@"disapproved"]) { - NSLog(@"Media message %d blocked", message.id); [self handleDisapprovedMessage:message]; } } @@ -182,9 +172,6 @@ Implement the `onMessageModerated` delegate method to receive moderation results // Register the delegate [CometChat addMessageListener:@"MODERATION_LISTENER" delegate:self]; - - // Don't forget to remove the listener when done - // [CometChat removeMessageListener:@"MODERATION_LISTENER"]; ``` @@ -217,13 +204,9 @@ When a message is disapproved, handle it appropriately in your UI: - (void)handleDisapprovedMessage:(BaseMessage *)message { int messageId = message.id; - // Option 1: Hide the message completely [self hideMessageFromUI:messageId]; - - // Option 2: Show a placeholder message [self showBlockedPlaceholder:messageId text:@"This message was blocked by moderation"]; - // Option 3: Notify the sender (if it's their message) if ([message.sender.uid isEqualToString:currentUserUID]) { [self showNotification:@"Your message was blocked due to policy violation"]; } @@ -231,3 +214,26 @@ When a message is disapproved, handle it appropriately in your UI: ``` + + +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 + + + + 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/ios/all-real-time-delegates-listeners.mdx b/sdk/ios/all-real-time-delegates-listeners.mdx index ba8a2d67b..4248972da 100644 --- a/sdk/ios/all-real-time-delegates-listeners.mdx +++ b/sdk/ios/all-real-time-delegates-listeners.mdx @@ -1,8 +1,20 @@ --- title: "All Real Time Delegates (Listeners)" +description: "Complete reference for all CometChat iOS SDK real-time delegates including User, Group, Message, and Call listeners." --- + +- **User delegate:** `CometChat.userdelegate = self` (conform to `CometChatUserDelegate`) — `onUserOnline(user:)`, `onUserOffline(user:)` +- **Group delegate:** `CometChat.groupdelegate = self` (conform to `CometChatGroupDelegate`) — member joined/left/kicked/banned events +- **Message delegate:** `CometChat.messagedelegate = self` (conform to `CometChatMessageDelegate`) — message received/edited/deleted/reaction events +- **Call delegate:** `CometChat.calldelegate = self` (conform to `CometChatCallDelegate`) — incoming/outgoing call events +- **Login delegate:** `CometChat.addLoginListener(_:_:)` (conform to `CometChatLoginDelegate`) — login/logout success/failure events +- **Connection delegate:** `CometChat.addConnectionListener(_:_:)` (conform to `CometChatConnectionDelegate`) — connection status events +- **AI Assistant delegate:** `CometChat.addAIAssistantListener(_:_:)` (conform to `AIAssistantEventsDelegate`) — AI events +- **Related:** [User Presence](/sdk/ios/user-presence) · [Receive Message](/sdk/ios/receive-message) · [Ringing](/sdk/ios/default-calling) + + CometChat provides 4 listeners (Delegates) viz. @@ -19,8 +31,8 @@ The `CometChat` provides you with live events related to users. Below are the ca | Delegate Method | Information | | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **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. | +| **onUserOnline(user:** [`User`](/sdk/reference/entities#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`](/sdk/reference/entities#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. | In order to use the Delegate methods you must add protocol conformance `CometChatUserDelegate` as Shown Below: @@ -83,15 +95,15 @@ The `CometChatGroupDelegate` provides you with all the real-time events related | Method | Information | | ------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | -| **onGroupMemberJoined(action: Action, joinedUser: User, joinedGroup: Group)** | This method is triggered when a user joins any group. All the members present in the group will receive this event. | -| **onGroupMemberLeft(action: Action, leftUser: User, leftGroup: Group)** | This method is triggered when a user who was a member of any group leaves the group. All the members of the group receive this event. | -| **onGroupMemberKicked(action: Action, kickedUser: User, kickedBy: User, kickedFrom: Group)** | This method is triggered when a user is kicked from a group. All the members including the user receive this event | -| **onGroupMemberBanned(action: Action, bannedUser: User, bannedBy: User, bannedFrom: Group)** | This method is triggered when a user is banned from a group. All the members including the user receive this event | -| **onGroupMemberUnbanned(action: Action, unbannedUser: User, unbannedBy: User, unbannedFrom: Group)** | This method is triggered when a user is banned from a group. All the members of the group receive this event. | -| **onGroupMemberScopeChanged(action: Action, updatedBy: User, updatedUser: User, scopeChangedTo: String, scopeChangedFrom: String, 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, addedby: User, userAdded: User, addedTo: Group)** | This method is triggered when a user is added to any group. All the members including the user himself receive this event. | +| **onGroupMemberJoined(action:** [`Action`](/sdk/reference/messages#action)**, joinedUser:** [`User`](/sdk/reference/entities#user)**, joinedGroup:** [`Group`](/sdk/reference/entities#group)**)** | This method is triggered when a user joins any group. All the members present in the group will receive this event. | +| **onGroupMemberLeft(action:** [`Action`](/sdk/reference/messages#action)**, leftUser:** [`User`](/sdk/reference/entities#user)**, leftGroup:** [`Group`](/sdk/reference/entities#group)**)** | This method is triggered when a user who was a member of any group leaves the group. All the members of the group receive this event. | +| **onGroupMemberKicked(action:** [`Action`](/sdk/reference/messages#action)**, kickedUser:** [`User`](/sdk/reference/entities#user)**, kickedBy:** [`User`](/sdk/reference/entities#user)**, kickedFrom:** [`Group`](/sdk/reference/entities#group)**)** | This method is triggered when a user is kicked from a group. All the members including the user receive this event | +| **onGroupMemberBanned(action:** [`Action`](/sdk/reference/messages#action)**, bannedUser:** [`User`](/sdk/reference/entities#user)**, bannedBy:** [`User`](/sdk/reference/entities#user)**, bannedFrom:** [`Group`](/sdk/reference/entities#group)**)** | This method is triggered when a user is banned from a group. All the members including the user receive this event | +| **onGroupMemberUnbanned(action:** [`Action`](/sdk/reference/messages#action)**, unbannedUser:** [`User`](/sdk/reference/entities#user)**, unbannedBy:** [`User`](/sdk/reference/entities#user)**, unbannedFrom:** [`Group`](/sdk/reference/entities#group)**)** | This method is triggered when a user is banned from a group. All the members of the group receive this event. | +| **onGroupMemberScopeChanged(action:** [`Action`](/sdk/reference/messages#action)**, updatedBy:** [`User`](/sdk/reference/entities#user)**, updatedUser:** [`User`](/sdk/reference/entities#user)**, scopeChangedTo: String, scopeChangedFrom: String, group:** [`Group`](/sdk/reference/entities#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`](/sdk/reference/messages#action)**, addedby:** [`User`](/sdk/reference/entities#user)**, userAdded:** [`User`](/sdk/reference/entities#user)**, addedTo:** [`Group`](/sdk/reference/entities#group)**)** | This method is triggered when a user is added to any group. All the members including the user himself receive this event. | -You can receive live events related to groups, In order to receive user Events, you must add protocol conformance `CometChatGroupDelegate` as shown below: +You can receive live events related to groups. In order to receive group events, you must add protocol conformance `CometChatGroupDelegate` as shown below: @@ -99,27 +111,27 @@ You can receive live events related to groups, In order to receive user Events, extension AppDelegate: CometChatGroupDelegate { func onGroupMemberJoined(action: ActionMessage, joinedUser: User, joinedGroup: Group) { - print("\(joinedUser.name) joined the group \(joinedGroup.name).") + print("\\(joinedUser.name) joined the group \\(joinedGroup.name).") } func onGroupMemberLeft(action: ActionMessage, leftUser: User, leftGroup: Group) { - print("\(leftUser.name) left the group \(leftGroup.name).") + print("\\(leftUser.name) left the group \\(leftGroup.name).") } func onGroupMemberKicked(action: ActionMessage, kickedUser: User, kickedBy: User, kickedFrom: Group) { - print("\(kickedUser.name) kicked from the group \(kickedFrom.name) by \(kickedBy.name).") + print("\\(kickedUser.name) kicked from the group \\(kickedFrom.name) by \\(kickedBy.name).") } func onGroupMemberBanned(action: ActionMessage, bannedUser: User, bannedBy: User, bannedFrom: Group) { - print("\(bannedUser.name) banned from the group \(bannedFrom.name) by \(bannedBy.name).") + print("\\(bannedUser.name) banned from the group \\(bannedFrom.name) by \\(bannedBy.name).") } func onGroupMemberUnbanned(action: ActionMessage, unbannedUser: User, unbannedBy: User, unbannedFrom: Group) { - print("\(unbannedUser.name) unbanned from the group \(unbannedFrom.name) by \(unbannedBy.name).") + print("\\(unbannedUser.name) unbanned from the group \\(unbannedFrom.name) by \\(unbannedBy.name).") } func onGroupMemberScopeChanged(action: ActionMessage, scopeChangeduser: User, scopeChangedBy: User, scopeChangedTo: String, scopeChangedFrom: String, group: Group) { - print("\(scopeChangedUser.name) scope changed from \(scopeChangedFrom) to \(scopeChangedTo) by \(scopeChangedBy.name) in the group \(group.name).") + print("\\(scopeChangedUser.name) scope changed from \\(scopeChangedFrom) to \\(scopeChangedTo) by \\(scopeChangedBy.name) in the group \\(group.name).") } } ``` @@ -184,19 +196,28 @@ The `CometChatMessageDelegate` provides you with live events related to messages | **Method** | Information | | ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------- | -| **onTextMessageReceived(textMessage: TextMessage)** | This event is triggered when a Text Message is received. | -| **onMediaMessageReceived(mediaMessage: MediaMessage)** | This event is triggered when a Media Message is received. | -| **onCustomMessageReceived(customMessage: CustomMessage)** | This event is triggered when a Custom Message is received. | -| **onTypingStarted(typingDetails : TypingIndicator)** | This event is triggered when a user starts typing in a user/group conversation. | -| **onTypingEnded(typingDetails : TypingIndicator)** | This event is triggered when a user stops typing in a user/group conversation. | -| **onMessagesDelivered(receipt : MessageReceipt)** | This event is triggered when a set of messages are marked as delivered for any particular conversation. | -| **onMessagesRead(receipt : MessageReceipt)** | This event is triggered when a set of messages are marked as read for any particular conversation. | -| **onMessageEdited(message: BaseMessage)** | This method is triggered when a particular message has been edited in a user/group conversation. | -| **onMessageDeleted(message: BaseMessage)** | This event is triggered when a particular message is deleted in a user/group conversation. | -| **onInteractiveMessageReceived(message: InteractiveMesage)** | This event is triggered when an Interactive Message is received. | -| **onInteractionGoalCompleted(receipt: InteractionReceipt)** | This event is triggered when an interaction Goal is achieved. | - -In order to receive incoming messages, you must add protocol conformance `CometChatMessageDelegate` as Shown Below : +| **onTextMessageReceived(textMessage:** [`TextMessage`](/sdk/reference/messages#textmessage)**)** | This event is triggered when a Text Message is received. | +| **onMediaMessageReceived(mediaMessage:** [`MediaMessage`](/sdk/reference/messages#mediamessage)**)** | This event is triggered when a Media Message is received. | +| **onCustomMessageReceived(customMessage:** [`CustomMessage`](/sdk/reference/messages#custommessage)**)** | This event is triggered when a Custom Message is received. | +| **onTypingStarted(_ typingDetails:** [`TypingIndicator`](/sdk/reference/auxiliary#typingindicator)**)** | This event is triggered when a user starts typing in a user/group conversation. | +| **onTypingEnded(_ typingDetails:** [`TypingIndicator`](/sdk/reference/auxiliary#typingindicator)**)** | This event is triggered when a user stops typing in a user/group conversation. | +| **onTransisentMessageReceived(_ message:** [`TransientMessage`](/sdk/reference/auxiliary#transientmessage)**)** | This event is triggered when a transient message is received. | +| **onMessagesDelivered(receipt:** [`MessageReceipt`](/sdk/reference/auxiliary#messagereceipt)**)** | This event is triggered when a set of messages are marked as delivered for any particular conversation. | +| **onMessagesRead(receipt:** [`MessageReceipt`](/sdk/reference/auxiliary#messagereceipt)**)** | This event is triggered when a set of messages are marked as read for any particular conversation. | +| **onMessagesDeliveredToAll(receipt:** [`MessageReceipt`](/sdk/reference/auxiliary#messagereceipt)**)** | This event is triggered when messages are delivered to all participants in a group. | +| **onMessagesReadByAll(receipt:** [`MessageReceipt`](/sdk/reference/auxiliary#messagereceipt)**)** | This event is triggered when messages are read by all participants in a group. | +| **onMessageEdited(message:** [`BaseMessage`](/sdk/reference/messages#basemessage)**)** | This method is triggered when a particular message has been edited in a user/group conversation. | +| **onMessageDeleted(message:** [`BaseMessage`](/sdk/reference/messages#basemessage)**)** | This event is triggered when a particular message is deleted in a user/group conversation. | +| **onInteractiveMessageReceived(interactiveMessage: InteractiveMessage)** | This event is triggered when an Interactive Message is received. | +| **onInteractionGoalCompleted(_ receipt: InteractionReceipt)**| This event is triggered when an interaction Goal is achieved. | +| **onMessageReactionAdded(reactionEvent: ReactionEvent)** | This event is triggered when a reaction is added to a message. | +| **onMessageReactionRemoved(reactionEvent: ReactionEvent)** | This event is triggered when a reaction is removed from a message. | +| **onMessageModerated(_ message:** [`BaseMessage`](/sdk/reference/messages#basemessage)**)** | This event is triggered when a message is moderated. | +| **onAIAssistantMessageReceived(_ message: AIAssistantMessage)** | This event is triggered when an AI Assistant message is received. | +| **onAIToolResultMessageReceived(_ message: AIToolResultMessage)** | This event is triggered when an AI Tool result message is received. | +| **onAIToolArgumentsMessageReceived(_ message: AIToolArgumentMessage)** | This event is triggered when an AI Tool arguments message is received. | + +In order to receive incoming messages, you must add protocol conformance `CometChatMessageDelegate` as shown below: @@ -216,39 +237,71 @@ extension ViewController: CometChatMessageDelegate { } func onMessageEdited(message: BaseMessage) { - print("received edited message successfully.") + print("Message edited successfully.") } func onMessageDeleted(message: BaseMessage) { - print("received deleted message successfully.") + print("Message deleted successfully.") } - func onTypingStarted(typingDetails : TypingIndicator) { + func onTypingStarted(_ typingDetails: TypingIndicator) { print("Typing started received successfully") } - func onTypingEnded(typingDetails : TypingIndicator) { + func onTypingEnded(_ typingDetails: TypingIndicator) { print("Typing ended received successfully") } - func onMessageDelivered(receipt : MessageReceipt) { - print("Message delivered receipt received.") + func onTransisentMessageReceived(_ message: TransientMessage) { + print("Transient message received.") + } + + func onMessagesDelivered(receipt: MessageReceipt) { + print("Messages delivered receipt received.") + } + + func onMessagesRead(receipt: MessageReceipt) { + print("Messages read receipt received.") } - func onMessageRead(receipt : MessageReceipt) { - print("Message read receipt received.") + func onMessagesDeliveredToAll(receipt: MessageReceipt) { + print("Messages delivered to all receipt received.") } - func onMessageRead(receipt : MessageReceipt) { - print("Message read receipt received.") + func onMessagesReadByAll(receipt: MessageReceipt) { + print("Messages read by all receipt received.") } - func onInteractiveMessageReceived(message: InteractiveMesage) { + func onInteractiveMessageReceived(interactiveMessage: InteractiveMessage) { print("InteractiveMessage received successfully.") } - func onInteractionGoalCompleted(receipt: InteractionReceipt) { - print("InteractiionGoal receipt received.") + func onInteractionGoalCompleted(_ receipt: InteractionReceipt) { + print("Interaction goal completed.") + } + + func onMessageReactionAdded(reactionEvent: ReactionEvent) { + print("Reaction added to message.") + } + + func onMessageReactionRemoved(reactionEvent: ReactionEvent) { + print("Reaction removed from message.") + } + + func onMessageModerated(_ message: BaseMessage) { + print("Message moderated.") + } + + func onAIAssistantMessageReceived(_ message: AIAssistantMessage) { + print("AI Assistant message received.") + } + + func onAIToolResultMessageReceived(_ message: AIToolResultMessage) { + print("AI Tool result message received.") + } + + func onAIToolArgumentsMessageReceived(_ message: AIToolArgumentMessage) { + print("AI Tool arguments message received.") } } ``` @@ -269,34 +322,39 @@ extension ViewController: CometChatMessageDelegate { The `CometChatCallDelegate` provides you with live events related to calls. Below are the callback methods provided by the `CometChatCallDelegate`. -| Method | Information | -| -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **onIncomingCallReceived(Call call)** | This event is triggered when the logged-in user receives an incoming call. The details of the call can be obtained from the Call object received as the method parameter. | -| **onOutgoingCallAccepted(Call 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 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 | +| Method | Information | +| ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **onIncomingCallReceived(incomingCall:** [`Call`](/sdk/reference/messages#call)**?, error:** [`CometChatException`](/sdk/reference/auxiliary#cometchatexception)**?)** | This event is triggered when the logged-in user receives an incoming call. The details of the call can be obtained from the Call object received as the method parameter. | +| **onOutgoingCallAccepted(acceptedCall:** [`Call`](/sdk/reference/messages#call)**?, error:** [`CometChatException`](/sdk/reference/auxiliary#cometchatexception)**?)** | 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(rejectedCall:** [`Call`](/sdk/reference/messages#call)**?, error:** [`CometChatException`](/sdk/reference/auxiliary#cometchatexception)**?)** | 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(canceledCall:** [`Call`](/sdk/reference/messages#call)**?, error:** [`CometChatException`](/sdk/reference/auxiliary#cometchatexception)**?)** | 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(endedCall:** [`Call`](/sdk/reference/messages#call)**?, error:** [`CometChatException`](/sdk/reference/auxiliary#cometchatexception)**?)** | This event is triggered when a call ended message is received. The details of the call can be obtained from the Call object received as the method parameter | -In order to receive all `call` events, you must add protocol conformance `CometChatCallDelegate` as Shown Below : +In order to receive all `call` events, you must add protocol conformance `CometChatCallDelegate` as shown below: ```swift extension ViewController: CometChatCallDelegate { - func onIncomingCallReceived(incomingCall: Call ? , error : CometChatException ? ) { - print(" Incoming call " + incomingCall!.stringValue()); + func onIncomingCallReceived(incomingCall: Call?, error: CometChatException?) { + print("Incoming call " + (incomingCall?.stringValue() ?? "")) + } + + func onOutgoingCallAccepted(acceptedCall: Call?, error: CometChatException?) { + print("Outgoing call accepted " + (acceptedCall?.stringValue() ?? "")) } - func onOutgoingCallAccepted(acceptedCall: Call ? , error : CometChatException ? ) { - print("Outgoing call " + acceptedCall!.stringValue()); + func onOutgoingCallRejected(rejectedCall: Call?, error: CometChatException?) { + print("Rejected call " + (rejectedCall?.stringValue() ?? "")) } - func onOutgoingCallRejected(rejectedCall: Call ? , error : CometChatException ? ) { - print("Rejected call " + rejectedCall!.stringValue()); + func onIncomingCallCancelled(canceledCall: Call?, error: CometChatException?) { + print("Cancelled call " + (canceledCall?.stringValue() ?? "")) } - func onIncomingCallCanceled(canceledCall: Call ? , error : CometChatException ? ) { - print("Cancelled call " + canceledCall!.stringValue()); + func onCallEndedMessageReceived(endedCall: Call?, error: CometChatException?) { + print("Call ended " + (endedCall?.stringValue() ?? "")) } } ``` @@ -316,7 +374,7 @@ extension ViewController: CometChatCallDelegate { [CometChat setCalldelegate:self]; } -- (void)onIncomingCallCanceledWithCanceledCall:(Call * _Nullable)canceledCall error:(CometChatException * _Nullable)error { +- (void)onIncomingCallCancelledWithCanceledCall:(Call * _Nullable)canceledCall error:(CometChatException * _Nullable)error { NSLog(@"Incoming call cancelled %@",[canceledCall stringValue]); } @@ -332,6 +390,10 @@ extension ViewController: CometChatCallDelegate { NSLog(@"Outgoing call rejected %@",[rejectedCall stringValue]); } +- (void)onCallEndedMessageReceivedWithEndedCall:(Call * _Nullable)endedCall error:(CometChatException * _Nullable)error { + NSLog(@"Call ended %@",[endedCall stringValue]); +} + @end ``` @@ -346,3 +408,174 @@ extension ViewController: CometChatCallDelegate { *** + +## Login Delegate Methods + +The `CometChatLoginDelegate` provides you with live events related to login and logout. Below are the callback methods provided by the `CometChatLoginDelegate`. + +| Method | Information | +| ------------------------------------------------ | ------------------------------------------------------------------------------------------------------- | +| **onLoginSuccess(user:** [`User`](/sdk/reference/entities#user)**)** | This event is triggered when a user successfully logs in. | +| **onLoginFailed(error:** [`CometChatException`](/sdk/reference/auxiliary#cometchatexception)**?)** | This event is triggered when a login attempt fails. | +| **onLogoutSuccess()** | This event is triggered when a user successfully logs out. | +| **onLogoutFailed(error:** [`CometChatException`](/sdk/reference/auxiliary#cometchatexception)**?)** | This event is triggered when a logout attempt fails. | + +In order to receive login/logout events, you must add protocol conformance `CometChatLoginDelegate` as shown below: + + + +```swift +extension ViewController: CometChatLoginDelegate { + + func onLoginSuccess(user: User) { + print("Login successful for user: " + user.stringValue()) + } + + func onLoginFailed(error: CometChatException?) { + print("Login failed with error: " + (error?.errorDescription ?? "Unknown error")) + } + + func onLogoutSuccess() { + print("Logout successful") + } + + func onLogoutFailed(error: CometChatException?) { + print("Logout failed with error: " + (error?.errorDescription ?? "Unknown error")) + } +} +``` + + + + + +To add the login listener: + +```swift +CometChat.addLoginListener("unique_listener_id", self) +``` + +To remove the login listener: + +```swift +CometChat.removeLoginListener("unique_listener_id") +``` + +*** + +## Connection Delegate Methods + +The `CometChatConnectionDelegate` provides you with live events related to the WebSocket connection status. Below are the callback methods provided by the `CometChatConnectionDelegate`. + +| Method | Information | +| ------------------------------------------------ | ------------------------------------------------------------------------------------------------------- | +| **connecting()** | This event is triggered when the SDK is attempting to establish a connection. | +| **connected()** | This event is triggered when the SDK successfully establishes a connection. | +| **disconnected()** | This event is triggered when the SDK disconnects from the server. | +| **onfeatureThrottled()** | This event is triggered when a feature is throttled due to rate limiting. | +| **onConnectionError(error:** [`CometChatException`](/sdk/reference/auxiliary#cometchatexception)**)** | This event is triggered when there is an error in the connection. | + +In order to receive connection events, you must add protocol conformance `CometChatConnectionDelegate` as shown below: + + + +```swift +extension ViewController: CometChatConnectionDelegate { + + func connecting() { + print("Connecting to CometChat...") + } + + func connected() { + print("Connected to CometChat") + } + + func disconnected() { + print("Disconnected from CometChat") + } + + func onfeatureThrottled() { + print("Feature throttled") + } + + func onConnectionError(error: CometChatException) { + print("Connection error: " + error.errorDescription) + } +} +``` + + + + + +To add the connection listener: + +```swift +CometChat.addConnectionListener("unique_listener_id", self) +``` + +To remove the connection listener: + +```swift +CometChat.removeConnectionListener("unique_listener_id") +``` + +*** + +## AI Assistant Events Delegate + +The `AIAssistantEventsDelegate` provides you with live events related to AI Assistant features. Below are the callback methods provided by the `AIAssistantEventsDelegate`. + +| Method | Information | +| --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | +| **onAIAssistantEventReceived(_ event: AIAssistantBaseEvent)** | This event is triggered when an AI Assistant event is received. | + +In order to receive AI Assistant events, you must add protocol conformance `AIAssistantEventsDelegate` as shown below: + + + +```swift +extension ViewController: AIAssistantEventsDelegate { + + func onAIAssistantEventReceived(_ event: AIAssistantBaseEvent) { + print("AI Assistant event received: " + event.stringValue()) + } +} +``` + + + + + +To add the AI Assistant listener: + +```swift +CometChat.addAIAssistantListener("unique_listener_id", self) +``` + +To remove the AI Assistant listener: + +```swift +CometChat.removeAIAssistantListener("unique_listener_id") +``` + +*** + +--- + +## Next Steps + + + + Monitor user online/offline status + + + Handle incoming messages in real time + + + Monitor the SDK connection state + + + Listen for login and logout events + + diff --git a/sdk/ios/authentication-overview.mdx b/sdk/ios/authentication-overview.mdx index f063e4f66..906b8ffdf 100644 --- a/sdk/ios/authentication-overview.mdx +++ b/sdk/ios/authentication-overview.mdx @@ -1,38 +1,128 @@ --- 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 iOS SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +```swift +// Check existing session +let user = CometChat.getLoggedInUser() + +// Login with Auth Key (development only) +CometChat.login(UID: "cometchat-uid-1", authKey: "AUTH_KEY", onSuccess: { user in + print("Logged in: \(user.stringValue())") +}, onError: { error in + print("Login failed: \(error.errorDescription)") +}) + +// Login with Auth Token (production) +CometChat.login(authToken: "AUTH_TOKEN", onSuccess: { user in + print("Logged in: \(user.stringValue())") +}, onError: { error in + print("Login failed: \(error.errorDescription)") +}) + +// Logout +CometChat.logout(onSuccess: { _ in + print("Logged out") +}, onError: { error in + print("Logout failed: \(error.errorDescription)") +}) +``` + +**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` + + +After [initializing](/sdk/ios/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. + +### How It Works + +```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) +``` + +## Before You Log In -## Create User +### Create a User -Before you log in a user, you must add the user to CometChat. +A user must exist in CometChat before they can 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. +- **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. - -Sample Users +You can also create users from the client side using `createUser()` (development only): + + + +```swift +let authKey = "AUTH_KEY" +let uid = "user1" +let name = "Kevin" + +let newUser = User(uid: uid, name: name) + +CometChat.createUser(user: newUser, apiKey: authKey, onSuccess: { (user) in + print("User created: \(user.stringValue())") +}) { (error) in + print("Error: \(String(describing: error?.description))") +} +``` + + +```objc +NSString *authKey = @"AUTH_KEY"; +User *newUser = [[User alloc] initWithUid:@"user1" name:@"Kevin"]; -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`. +[CometChat createUserWithUser:newUser apiKey:authKey onSuccess:^(User * user) { + NSLog(@"User created: %@", [user stringValue]); +} onError:^(CometChatException * error) { + NSLog(@"Error: %@", [error errorDescription]); +}]; +``` + + - + +`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/ios/user-management) for full details. + -Once initialization is successful, you will need to log the user into CometChat using the `login()` method. +### Check for an Existing Session -We recommend you call the CometChat login method once your user logs into your app. The login method needs to be called only once but the getLoggedInUser() needs to be checked every-time when the app starts and if it returns null then you need to call the login method. +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. -*** +```swift +if let user = CometChat.getLoggedInUser() { + // User is already logged in — proceed to your app +} +``` -## Login using Auth Key +If `getLoggedInUser()` returns `nil`, no active session exists and you need to call `login()`. -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. +## Login with Auth Key -The login method needs to be called in the following scenarios: +Auth Key login is the simplest way to get started. Pass a UID and your Auth Key directly from the client. -1. When the user is logging into the App for the first time. -2. If the CometChat.getLoggedInUser() function returns nil. + +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. + @@ -41,147 +131,119 @@ let uid = "cometchat-uid-1" let authKey = "AUTH_KEY" if CometChat.getLoggedInUser() == nil { - - CometChat.login(UID: uid, authkey: authKey, onSuccess: { (user) in - - print("Login successful : " + user.stringValue()) - - }) { (error) in - - print("Login failed with error: " + error.errorDescription); - - } - + CometChat.login(UID: uid, authKey: authKey, onSuccess: { (user) in + print("Login successful: " + user.stringValue()) + }) { (error) in + print("Login failed with error: " + error.errorDescription) + } } ``` - - + ```objc NSString *uid = @"cometchat-uid-1"; -NSString *authkey = @"YOUR_AUTH_KEY"; - -[CometChat loginWithUID:uid authkey:authey onSuccess:^(User * user) { - - NSLog(@"Login successful : %@",[user stringValue]); +NSString *authKey = @"AUTH_KEY"; +[CometChat loginWithUID:uid authKey:authKey onSuccess:^(User * user) { + NSLog(@"Login successful: %@", [user stringValue]); } onError:^(CometChatException * error) { - - NSLog(@"Login failed with error:%@",[error errorDescription]); - + NSLog(@"Login failed with error: %@", [error errorDescription]); }]; ``` - - -| Parameter | Description | -| --------- | ------------------------------------------------ | -| UID | The UID of the user that you would like to login | -| authKey | CometChat Auth Key | - -The `login()` method returns the `User` object containing all the information of the logged-in user. - -*** - -## Login using Auth Token +| Parameter | Description | +| --------- | ----------- | +| UID | The UID of the user to log in | +| authKey | Your CometChat Auth Key | -This advanced authentication procedure does not use the Auth Key directly in your client code thus ensuring safety. +On success, the callback returns a [`User`](/sdk/reference/entities#user) object containing the logged-in user's details. -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. +## Login with Auth Token -The login method needs to be called in the following scenarios: +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. When the user is logging into the App for the first time. -2. If the CometChat.getLoggedInUser() function returns nil. +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()`. ```swift -let authToken = "YOUR_AUTH_TOKEN"; +let authToken = "AUTH_TOKEN" if CometChat.getLoggedInUser() == nil { - - CometChat.login(authToken: authToken , onSuccess: { (user) in - - print("Login successful : " + user.stringValue()) - + CometChat.login(authToken: authToken, onSuccess: { (user) in + print("Login successful: " + user.stringValue()) }) { (error) in - - print("Login failed with error: " + error.errorDescription); + print("Login failed with error: " + error.errorDescription) } - } ``` - - + ```objc -NSString *authToken = @"YOUR_AUTH_TOKEN"; +NSString *authToken = @"AUTH_TOKEN"; [CometChat loginWithAuthToken:authToken onSuccess:^(User * user) { - - __ Login Successful - NSLog(@"Login Successful : %@",[user stringValue]); - + NSLog(@"Login successful: %@", [user stringValue]); } onError:^(CometChatException * error) { - - __ Login error - NSLog(@"Login failed with exception: %@",[error errorDescription]); - + NSLog(@"Login failed with error: %@", [error errorDescription]); }]; ``` - - -| Parameter | Description | -| --------- | ---------------------------------------------- | -| authToken | Auth Token of the user you would like to login | - -The `login()` method returns the `User` object containing all the information of the logged-in user. +| Parameter | Description | +| --------- | ----------- | +| authToken | Auth Token generated on your server for the user | -*** +On success, the callback returns a [`User`](/sdk/reference/entities#user) object containing the logged-in user's details. ## Logout -You can use the `logout()` method to log out the user from CometChat. +Call `logout()` when your user logs out of your app. This clears the local session. ```swift CometChat.logout(onSuccess: { (response) in - - print("Logout successfully.") - + print("Logout completed successfully") }) { (error) in - - print("logout failed with error: " + error.errorDescription); + print("Logout failed with error: " + error.errorDescription) } ``` - - + ```objc [CometChat logoutOnSuccess:^(NSString * response) { - - __ Logout Success - NSLog(@"%@", response); - + NSLog(@"Logout completed successfully"); } onError:^(CometChatException * error) { - - __ Logout error - NSLog(@"%@",[error errorDescription]); + NSLog(@"Logout failed: %@", [error errorDescription]); }]; ``` - - + +--- + +## Next Steps + + + + Send your first text, media, or custom message + + + Create, update, and delete users programmatically + + + Monitor the SDK connection state in real time + + + Implement voice and video calls with ringing + + diff --git a/sdk/ios/block-users.mdx b/sdk/ios/block-users.mdx index 13f62c70a..eaa4c5956 100644 --- a/sdk/ios/block-users.mdx +++ b/sdk/ios/block-users.mdx @@ -1,14 +1,33 @@ --- title: "Block Users" +sidebarTitle: "Block Users" +description: "Block and unblock users, and retrieve the list of blocked users using the CometChat iOS SDK." --- + +```swift +// Block users +CometChat.blockUsers(["UID1", "UID2"], + onSuccess: { print("Blocked") }, onError: { error in }) -## Block Users +// Unblock users +CometChat.unblockUsers(["UID1", "UID2"], + onSuccess: { users in }, onError: { error in }) -*In other words, as a logged-in user, how do I block a user from sending me messages?* +// Get blocked users list +let request = BlockedUserRequest.BlockedUserRequestBuilder.set(limit: 30).build() +request.fetchNext(onSuccess: { users in }, onError: { error in }) +``` -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 an array of string as a parameter that holds the list of UIDs to be blocked. +**Directions:** `.byMe` | `.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. @@ -25,9 +44,7 @@ CometChat.blockUsers(blockUsers, onSuccess: { }) ``` - - ```objc NSMutableArray *users = [NSMutableArray alloc]init]; @@ -44,16 +61,14 @@ NSMutableArray *users = [NSMutableArray alloc]init]; NSLog(@"Blocked user failed with error: %@", error.errorDescription); }]; ``` - - -In the `onSuccess()` callback, you receive a dictionary 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. +Returns a dictionary with UIDs as keys and `"success"` or `"fail"` as values based on if the block operation for each UID was successful. ## Unblock Users -You can unblock the already blocked users using the `unblockUsers()` method. You can unblock multiple users in a single operation. The`unblockUsers()` method takes an array of string as a parameter that holds the list of UIDs to be unblocked. +Unblock previously blocked users using `unblockUsers()` with an array of UIDs. @@ -70,9 +85,7 @@ CometChat.unblockUsers(unblockUsers, onSuccess: { (users) in }) ``` - - ```objc NSMutableArray *users = [NSMutableArray alloc]init]; @@ -89,32 +102,30 @@ NSMutableArray *users = [NSMutableArray alloc]init]; NSLog(@"unblocked user failed with error : %@", error.errorDescription); }]; ``` - - -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. +Returns a dictionary with UIDs as keys and `"success"` or `"fail"` as values based on if the unblock operation for each UID was successful. -## Get list of blocked users +## Get List of Blocked Users -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. +Use `BlockedUsersRequestBuilder` to fetch blocked users with filtering and pagination. -The `BlockedUsersRequestBuilder` class allows you to set the below parameters: +### Set Limit -1. `set(limit: Int)` - 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. ```swift let blockedUserRequest = BlockedUserRequest.BlockedUserRequestBuilder.set(limit: 20).build(); ``` - - -2. `set(searchKeyword: String)` - This method allows you to set the search string based on which the blocked users are to be fetched. +### Set Search Keyword + +Filters blocked users by a search string. @@ -124,12 +135,16 @@ let blockedUserRequest = BlockedUserRequest.BlockedUserRequestBuilder .set(limit: 20) .build(); ``` - - -3. `set(direction: CometChat.Blocked)` - This can hold one of the below values: a. CometChat.Blocked.byMe - This will ensure that the list of blocked users only contains the users blocked by the logged-in user. b. CometChat.Blocked.me - setting the direction to this will return only the list of users that have blocked the logged-in user. c. CometChat.Blocked.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. +### Set Direction + +Filters by block direction: + +- `.byMe` — Users blocked by the logged-in user +- `.me` — Users who have blocked the logged-in user +- `.both` — Both directions (default) @@ -140,14 +155,10 @@ let blockedUserRequest = BlockedUserRequest.BlockedUserRequestBuilder .set(direction: .both) .build(); ``` - - -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. @@ -164,9 +175,7 @@ blockedUserRequest.fetchNext(onSuccess : { (users) in }) ``` - - ```objc BlockedUserRequest *blockedUserRequest = [[[BlockedUserRequestBuilder alloc]initWithLimit:2] build]; @@ -175,13 +184,39 @@ BlockedUserRequest *blockedUserRequest = [[[BlockedUserRequestBuilder alloc]init NSLog(@"Blocked user list fetched successfully.") -} OnError:^ (CometChatException *error){ +} onError:^ (CometChatException *error){ NSLog(@"Fetching block user list failed with error: %@", error.errorDescription); }]; ``` - - + +The `fetchNext()` method returns an array of [`User`](/sdk/reference/entities#user) objects representing blocked users. + +Relevant fields to access on returned users: + +| Field | Type | Description | +|-------|------|-------------| +| blockedByMe | Bool | Whether the logged-in user has blocked this user | +| hasBlockedMe | Bool | Whether this user has blocked the logged-in user | + +--- + +## 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/ios/call-logs.mdx b/sdk/ios/call-logs.mdx index 91bf66538..3def1d984 100644 --- a/sdk/ios/call-logs.mdx +++ b/sdk/ios/call-logs.mdx @@ -1,20 +1,35 @@ --- title: "Call Logs" +sidebarTitle: "Call Logs" +description: "Fetch, filter, and retrieve call history including duration, participants, and recording status using the CometChat iOS Calls SDK." --- + +```swift +let callLogRequest = CometChatCallsSDK.CallLogsRequest.CallLogsBuilder() + .set(authToken: CometChat.getUserAuthToken()) + .set(limit: 30) + .set(callCategory: .call) + .build() -## Overview +callLogRequest.fetchNext(onSuccess: { logs in }, onError: { error in }) -CometChat's iOS 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. +// Get details for a specific call session +CometChatCalls.getCallDetail(authToken: CometChat.getUserAuthToken(), sessionID: "SESSION_ID", + onSuccess: { callLogs in }, onError: { error in }) +``` + +**Filters:** `.set(callType:)`, `.set(callStatus:)`, `.set(callCategory:)`, `.set(callDirection:)`, `.set(hasRecording:)`, `.set(uid:)`, `.set(guid:)` + -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. +Call logs let you retrieve and display call history — who called whom, when, how long, and whether it was recorded. Use `CallLogsBuilder` to fetch and filter logs, and `getCallDetail()` to get details for a specific session. -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 iOS application. +Before you begin, make sure you've completed the [Calls SDK Setup](/sdk/ios/calling-overview). -## Fetching Call Logs +## Fetch Call Logs -To fetch all call logs in your iOS application, you should use the `CallLogRequestBuilder`, This builder allows you to customize the call logs fetching process according to your needs. +Build a request with `CallLogsBuilder`, then call `fetchNext()` or `fetchPrevious()` to retrieve logs. Call either method repeatedly on the same builder instance to paginate through results. ```swift var callLogRequest = CometChatCallsSDK.CallLogsRequest.CallLogsBuilder() @@ -24,23 +39,23 @@ var callLogRequest = CometChatCallsSDK.CallLogsRequest.CallLogsBuilder() .build() ``` -`CallLogRequestBuilder` has the following settings available. +### Builder Settings | Setting | Description | | --------------------------------- | ------------------------------------------------------------ | -| set(limit: Int) | Specifies the number of call logs to fetch. | -| set(callType: CallType) | Sets the type of calls to fetch (call or meet). | -| set(callStatus: CallStatus) | Sets the status of calls to fetch (initiated, ongoing, etc.) | -| setg(hasRecording: HasRecording) | Sets whether to fetch calls that have recordings. | -| set(callCategory: CallCategory) | Sets the category of calls to fetch (call or meet). | -| set(callDirection: CallDirection) | Sets the direction of calls to fetch (incoming or outgoing) | -| set(uid: String) | Sets the UID of the user whose call logs to fetch. | -| set(guid: String) | Sets the GUID of the user whose call logs to fetch. | -| set(authToken: String) | Sets the Auth token of the logged-in user. | +| `set(limit: Int)` | Specifies the number of call logs to fetch. | +| `set(callType: CallType)` | Sets the type of calls to fetch (call or meet). | +| `set(callStatus: CallStatus)` | Sets the status of calls to fetch (initiated, ongoing, etc.) | +| `set(hasRecording: HasRecording)` | Sets whether to fetch calls that have recordings. | +| `set(callCategory: CallCategory)` | Sets the category of calls to fetch (call or meet). | +| `set(callDirection: CallDirection)` | Sets the direction of calls to fetch (incoming or outgoing) | +| `set(uid: String)` | Sets the UID of the user whose call logs to fetch. | +| `set(guid: String)` | Sets the GUID of the group whose call logs to fetch. | +| `set(authToken: String)` | Sets the Auth token of the logged-in user. | ### Fetch Next -The**`fetchNext()`**method retrieves the next set of call logs. +Retrieves the next set of call logs: ```swift var callLogRequest = CometChatCallsSDK.CallLogsRequest.CallLogsBuilder() @@ -56,9 +71,11 @@ callLogRequest.fetchNext() { [weak self] callLogs in } ``` +The `fetchNext()` and `fetchPrevious()` methods return an array of [`CallLog`](/sdk/reference/calls#calllog) objects. + ### Fetch Previous -The**`fetchPrevious()`**method retrieves the previous set of call logs. +Retrieves the previous set of call logs: ```swift var callLogRequest = CometChatCallsSDK.CallLogsRequest.CallLogsBuilder() @@ -76,7 +93,7 @@ callLogRequest.fetchPrevious() { [weak self] callLogs in ## 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 success and error callback. Upon success, this function will return a list of call details, as multiple calls can be initiated for one session ID. +Retrieve details for a specific call session using `getCallDetail()`. This method requires the auth token and session ID. Multiple calls can share the same session ID, so the result is an array. ```swift var sessionID = "SESSION_ID"; @@ -87,4 +104,126 @@ CometChatCalls.getCallDetail(authToken: CometChat.getUserAuthToken(), sessionID: } ``` -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. + +## Filter Examples + +The following examples demonstrate how to use various filters with the `CallLogsBuilder`. + +### Filter by Call Type + + + +```swift +var callLogRequest = CometChatCallsSDK.CallLogsRequest.CallLogsBuilder() + .set(authToken: CometChat.getUserAuthToken()) + .set(limit: 30) + .set(callType: .audio) + .build() +``` + + +```swift +var callLogRequest = CometChatCallsSDK.CallLogsRequest.CallLogsBuilder() + .set(authToken: CometChat.getUserAuthToken()) + .set(limit: 30) + .set(callType: .video) + .build() +``` + + + +### Filter by Call Direction + + + +```swift +var callLogRequest = CometChatCallsSDK.CallLogsRequest.CallLogsBuilder() + .set(authToken: CometChat.getUserAuthToken()) + .set(limit: 30) + .set(callDirection: .incoming) + .build() +``` + + +```swift +var callLogRequest = CometChatCallsSDK.CallLogsRequest.CallLogsBuilder() + .set(authToken: CometChat.getUserAuthToken()) + .set(limit: 30) + .set(callDirection: .outgoing) + .build() +``` + + + +### Filter by Recording Status + + + +```swift +var callLogRequest = CometChatCallsSDK.CallLogsRequest.CallLogsBuilder() + .set(authToken: CometChat.getUserAuthToken()) + .set(limit: 30) + .set(hasRecording: true) + .build() +``` + + +```swift +var callLogRequest = CometChatCallsSDK.CallLogsRequest.CallLogsBuilder() + .set(authToken: CometChat.getUserAuthToken()) + .set(limit: 30) + .set(hasRecording: false) + .build() +``` + + + +### Filter by User + +```swift +var callLogRequest = CometChatCallsSDK.CallLogsRequest.CallLogsBuilder() + .set(authToken: CometChat.getUserAuthToken()) + .set(limit: 30) + .set(uid: "cometchat-uid-2") + .build() +``` + +### Filter by Group + +```swift +var callLogRequest = CometChatCallsSDK.CallLogsRequest.CallLogsBuilder() + .set(authToken: CometChat.getUserAuthToken()) + .set(limit: 30) + .set(guid: "cometchat-guid-1") + .build() +``` + +### Filter by Call Category (Meetings) + +```swift +var callLogRequest = CometChatCallsSDK.CallLogsRequest.CallLogsBuilder() + .set(authToken: CometChat.getUserAuthToken()) + .set(limit: 30) + .set(callCategory: .meet) + .build() +``` + +--- + +## 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/ios/calling-overview.mdx b/sdk/ios/calling-overview.mdx index 4883e77b1..334bdca6b 100644 --- a/sdk/ios/calling-overview.mdx +++ b/sdk/ios/calling-overview.mdx @@ -3,6 +3,21 @@ title: "Calling" sidebarTitle: "Overview" --- + + +Choose your calling approach: +- **Ringing** → [Default Calling](/sdk/ios/default-calling) — Full call flow with notifications, accept/reject +- **Call Session** → [Direct Calling](/sdk/ios/direct-calling) — Session-based calling with custom UI +- **Standalone** → [Standalone Calling](/sdk/ios/standalone-calling) — Calls SDK only, no Chat SDK needed + +```ruby +# Install Calls SDK via CocoaPods +pod 'CometChatCallsSDK', '~> 4.0' +``` + +**Features:** Recording, Video View Customization, Presenter Mode, Call Logs, Session Timeout + + ## Overview CometChat provides voice and video calling capabilities for your iOS application. This guide helps you choose the right implementation approach based on your use case. @@ -81,3 +96,22 @@ Use this when you want: Configure automatic call termination when participants are inactive. + +--- + +## Next Steps + + + + Install and initialize the CometChat Calls SDK + + + Implement the complete ringing call flow + + + Start and manage call sessions directly + + + Use calling without the Chat SDK + + diff --git a/sdk/ios/calling-setup.mdx b/sdk/ios/calling-setup.mdx index 1c689f31b..c56f150c2 100644 --- a/sdk/ios/calling-setup.mdx +++ b/sdk/ios/calling-setup.mdx @@ -1,9 +1,33 @@ --- -title: "Setup" +title: "Calls SDK Setup" +sidebarTitle: "Setup" +description: "Install and initialize the CometChat Calls SDK for iOS to enable voice and video calling in your application." --- + +```ruby +# CocoaPods +pod 'CometChatCallsSDK' +``` + +```swift +import CometChatCallsSDK + +let callAppSettings = CallAppSettingsBuilder() + .setAppId("APP_ID") + .setRegion("REGION") + .build() + +CometChatCalls.init(callsAppSettings: callAppSettings) { success in + print("Calls SDK ready") +} onError: { error in + print("Init failed: \(error?.errorDescription ?? "")") +} +``` +**Required:** App ID, Region from [CometChat Dashboard](https://app.cometchat.com) + The **CometChatCalls** is developed to keep developers in mind and aims to reduce development efforts significantly. Let's start to integrate Calls Kit into your project. *** @@ -260,12 +284,29 @@ From the above CallAppSettings, pass the settings to the init() method. guard let callAppSettings = callAppSettings else { return } CometChatCalls.init(callsAppSettings: callAppSettings) { success in - print("CometChatCalls init success: \\(success)") + print("CometChatCalls init success: \(success)") } onError: { error in - print("CometChatCalls init error: \\(String(describing: error?.errorDescription))") + print("CometChatCalls init error: \(String(describing: error?.errorDescription))") } ``` - - + +--- + +## Next Steps + + + + Implement the complete ringing call flow + + + Start and manage call sessions + + + Use Calls SDK without the Chat SDK + + + Compare calling approaches and features + + diff --git a/sdk/ios/connection-status.mdx b/sdk/ios/connection-status.mdx index 5d296174f..a604d934c 100644 --- a/sdk/ios/connection-status.mdx +++ b/sdk/ios/connection-status.mdx @@ -1,101 +1,121 @@ --- title: "Connection Status" +sidebarTitle: "Connection Status" +description: "Monitor real-time WebSocket connection status and respond to connectivity changes using the CometChat iOS SDK." --- + +```swift +// Get current status: "connecting" | "connected" | "disconnected" +let status = CometChat.getConnectionStatus?.value + +// Listen for connection changes +// Conform to CometChatConnectionDelegate +CometChat.addConnectionListener("LISTENER_ID", self as CometChatConnectionDelegate) + +func connecting() { print("Connecting...") } +func connected() { print("Connected") } +func disconnected() { print("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. This can be achieved by registering for the events using the `CometChatConnectionDelegate` class. +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 + +| Value | Callback | Description | +|-------|----------|-------------| +| `"connected"` | `connected()` | SDK has an active connection to CometChat servers | +| `"connecting"` | `connecting()` | SDK is attempting to establish or re-establish a connection | +| `"disconnected"` | `disconnected()` | SDK is disconnected due to network issues or other errors | + +## Get Current Status + +Use `getConnectionStatus` to check the current connection state at any time: + + + +```swift +var connectionStatus = CometChat.getConnectionStatus?.value +``` + + -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. +## Listen for Connection Changes -In order to use the Delegate methods you must add protocol conformance `CometChatConnectionDelegate` as `CometChat.conectiondelegate = self` . Here is the example of CometChatConnectionDelegate: +Register a `CometChatConnectionDelegate` to receive real-time connection state updates. We recommend adding this in your `AppDelegate` and in your app's first view controller after login. ```swift extension AppDelegate: CometChatConnectionDelegate { - func connecting() { - - print("connecting") - } + func connecting() { + print("connecting") + } - func connected() { - - print("connected") - } + func connected() { + print("connected") + } - func disconnected() { - - print("disconnected") - } + func disconnected() { + print("disconnected") + } } ``` - - ```objc @interface ViewController () - @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; - [CometChat connectiondelegate:self]; } -- (void)connecting() { - +- (void)connecting { NSLog(@"Connecting"); } -- (void)connected() { - +- (void)connected { NSLog(@"Connected"); } -- (void)disconnected() { - +- (void)disconnected { NSLog(@"Disconnected"); } ``` - - - - -We recommend you to add the Connection Status delegate in your AppDelegate and in your app's first view controller that opens when you log in. - - - -You can also get the current connection status by using `getConnectionStatus` property provided by CometChat SDK - - - -```swift -var connectionStatus = CometChat.getConnectionStatus?.value -``` + +Always remove connection listeners when they're no longer needed. Failing to remove listeners can cause memory leaks and duplicate event handling. + - - - - -The `CometChat.getConnectionStatus` method will return either of the below 3 values: +--- -1. connecting -2. connected -3. disconnected +## Next Steps + + + + Manage WebSocket connection behavior + + + Install and initialize the CometChat SDK + + + Authenticate users with the CometChat SDK + + + Overview of the CometChat iOS SDK + + diff --git a/sdk/ios/create-group.mdx b/sdk/ios/create-group.mdx index 1310a124a..0739bd380 100644 --- a/sdk/ios/create-group.mdx +++ b/sdk/ios/create-group.mdx @@ -1,143 +1,121 @@ --- title: "Create A Group" +sidebarTitle: "Create Group" +description: "Create public, private, or password-protected groups and optionally add members during creation using the CometChat iOS SDK." --- + - -## Create a Group - -*In other words, 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 a parameter that takes all the information related to the group. So, in order to create a group, you will have to create an object of the group and assign all the values to the group. - -To create a group, you can use either of the below two initializers: - -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) 2.`CometChatConstants.GROUP_TYPE_PASSWORD` (password) 3.`CometChatConstants.GROUP_TYPE_PRIVATE` (private) - - - ```swift -1. let GroupTobeCreated = Group(GUID: String, name: String, groupType: CometChatConstants.groupType, password: String?) - -2. let GroupTobeCreated = Group(GUID: String, name: String, groupType: CometChatConstants.groupType, password: String?, icon: String, description: String) +// Create a group +let group = Group(guid: "GUID", name: "Group Name", groupType: .public, password: nil) +CometChat.createGroup(group: group, + onSuccess: { group in }, onError: { error in }) + +// Create group with members +let members = [GroupMember(UID: "UID", groupMemberScope: .participant)] +CometChat.createGroupWithMembers(group: group, members: members, banMembers: [], + onSuccess: { response in }, onError: { error in }) ``` - +**Group types:** `.public` | `.password` | `.private` +**Member scopes:** `.admin` | `.moderator` | `.participant` + - -```objc -1. Group *GroupTobeCreated = [[Group alloc]initWithGuid:(NSString * _Nonnull) name:(NSString * _Nonnull) groupType:(enum groupType) password:(NSString * _Nullable)]; +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. -2. Group *GroupTobeCreated = [[Group alloc]initWithGuid:(NSString * _Nonnull) name:(NSString * _Nonnull) groupType:(enum groupType) password:(NSString * _Nullable) icon:(NSString * _Nonnull) description:(NSString * _Nonnull)]; -``` +## Create a Group - +Use `createGroup()` to create a new group. Pass a [`Group`](/sdk/reference/entities#group) object with the group details. - +| Group Type | Constant | Description | +| --- | --- | --- | +| Public | `.public` | Any user can join | +| Password | `.password` | Users must provide the correct password | +| Private | `.private` | Users must be added by an admin/moderator | ```swift -let guid = "cometchat-guid-11"; -let groupName = "TestGroup1"; -let password = ""; //mandatory in case of password protected group type +let guid = "cometchat-guid-11" +let groupName = "TestGroup1" +let password = "" // mandatory in case of password protected group type -let group = Group(guid: guid, name: groupName, groupType: .private, password: password); +let group = Group(guid: guid, name: groupName, groupType: .private, password: password) CometChat.createGroup(group: group, onSuccess: { (group) in - - print("Group created successfully. " + group.stringValue()) - -}) { (error) in - - print("Group creation failed with error:" + error!.errorDescription); -} + print("Group created successfully. " + group.stringValue()) +}, onError: { (error) in + print("Group creation failed with error:" + error!.errorDescription) +}) ``` - - ```objc NSString *guid = @"cometchat-guid-101"; NSString *name = @"TestGroup1"; -NSString *password = nil ; // mandatory in case of password protected group type +NSString *password = nil; // mandatory in case of password protected group type Group *group = [[Group alloc]initWithGuid:guid name:name groupType:groupTypePublic password:password]; [CometChat createGroupWithGroup:group onSuccess:^(Group * group) { - - NSLog(@"Group created successfully. %@",[group stringValue]); - + NSLog(@"Group created successfully. %@", [group stringValue]); } onError:^(CometChatException * error) { - - NSLog(@"Group creation failed with error: %@",[error errorDescription]); + NSLog(@"Group creation failed with error: %@", [error errorDescription]); }]; ``` - - -The `createGroup()` method takes the following parameters: +| Parameter | Description | +| --------- | ----------- | +| group | An instance of [`Group`](/sdk/reference/entities#group) class | -| Parameter | Description | -| --------- | ---------------------------- | -| 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. +On success, returns a [`Group`](/sdk/reference/entities#group) object with the created group's details. - 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. - -To create an object of `Group` class, you can use either of the below two constructors: +## Add Members While Creating a Group -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)` +Use `createGroupWithMembers()` to create a group and add members in one operation. -The `groupType` needs to be either of the below 3 values: +Parameters: +- `group` — The [`Group`](/sdk/reference/entities#group) object +- `members` — Array of [`GroupMember`](/sdk/reference/entities#groupmember) objects to add +- `banMembers` — Array of UIDs to ban (can be empty) -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: - -* new CometChat.GroupMember(String UID, String scope) +Create a [`GroupMember`](/sdk/reference/entities#groupmember) with: `GroupMember(UID:groupMemberScope:)` ```swift -let group = Group(guid: "cometchat-uid-group1" , name: "Hello Group", groupType: .public, password: nil) -let members = [GroupMember(UID: "cometchat-uid-4", groupMemberScope: .participant)] +let group = Group(guid: "cometchat-uid-group1", name: "Hello Group", groupType: .public, password: nil) + +let members = [ + GroupMember(UID: "cometchat-uid-4", groupMemberScope: .participant) +] + let banMembers = ["cometchat-uid-2"] -CometChat.createGroupWithMembers(group: group, members: members, banMembers: banMembers, onSuccess: { - dict in - print("Group created successfully",dict) - }, onError: { (error) in - print("Some error occured while creating group \(String(describing: error?.errorDescription))") - } -) +CometChat.createGroupWithMembers(group: group, members: members, banMembers: banMembers, onSuccess: { response in + print("Group created successfully", response) +}, onError: { (error) in + print("Error: \(String(describing: error?.errorDescription))") +}) ``` - - +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 +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 | @@ -148,10 +126,29 @@ CometChat.createGroupWithMembers(group: group, members: members, banMembers: ban | description | Yes | Description about the group | | owner | Yes | UID of the owner of the group. | | metadata | Yes | Additional data for the group as Dictionary | -| createdAt | No | The Unix timestamp of the time the group was created | -| updatedAt | No | The Unix timestamp of the time the group was last updated | -| hasJoined | No | A boolean to determine if the logged-in user is a member of the group. | -| joinedAt | No | The Unix timestamp of the time the logged-in user joined the group. | +| createdAt | No | The unix timestamp of the time the group was created | +| updatedAt | No | The unix timestamp of the time the group was last updated | +| hasJoined | No | A boolean to determine if the logged in user is a member of the group. | +| joinedAt | No | The unix timestamp of the time the logged in user joined the group. | | 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/ios/default-calling.mdx b/sdk/ios/default-calling.mdx index c0f5e5ebb..4b71f9815 100644 --- a/sdk/ios/default-calling.mdx +++ b/sdk/ios/default-calling.mdx @@ -1,7 +1,30 @@ --- title: "Ringing" +sidebarTitle: "Ringing" +description: "Implement a complete calling workflow with ringing, incoming/outgoing call UI, accept/reject/cancel functionality using the CometChat iOS SDK." --- + + +```swift +// Initiate a call +let call = Call(receiverId: "UID", callType: .video, receiverType: .user) +CometChat.initiateCall(call: call) { call in } onError: { error in } + +// Listen for call events (CometChatCallDelegate) +func onIncomingCallReceived(incomingCall: Call?, error: CometChatException?) { /* show incoming UI */ } +func onOutgoingCallAccepted(acceptedCall: Call?, error: CometChatException?) { /* start session */ } +func onOutgoingCallRejected(rejectedCall: Call?, error: CometChatException?) { /* dismiss UI */ } +func onIncomingCallCanceled(canceledCall: Call?, error: CometChatException?) { /* dismiss UI */ } + +// Accept / Reject / Cancel +CometChat.acceptCall(sessionID: sessionId) { call in } onError: { error in } +CometChat.rejectCall(sessionID: sessionId, status: .rejected) { call in } onError: { error in } +CometChat.rejectCall(sessionID: sessionId, status: .cancelled) { call in } onError: { error in } +``` + +**Flow:** Initiate \u2192 Receiver notified \u2192 Accept/Reject \u2192 Start session + ## 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**. @@ -22,7 +45,7 @@ After the call is accepted, you need to start the call session. See the [Call Se ## Initiate Call -The `initiateCall()` method sends a call request to a user or a group. On success, the receiver gets an `onIncomingCallReceived()` callback. +The `initiateCall()` method sends a call request to a user or a group. On success, the receiver gets an `onIncomingCallReceived()` callback. The method returns a [`Call`](/sdk/reference/messages#call) object. @@ -157,11 +180,11 @@ Set your view controller as the CometChat call delegate in `viewDidLoad()`: `Com | Event | Description | | ----- | ----------- | -| `onIncomingCallReceived(incomingCall: Call)` | Invoked when an incoming call is received. Display incoming call UI here. | -| `onOutgoingCallAccepted(acceptedCall: Call)` | Invoked on the caller's device when the receiver accepts. Start the call session here. | -| `onOutgoingCallRejected(rejectedCall: Call)` | Invoked on the caller's device when the receiver rejects. Dismiss outgoing call UI. | -| `onIncomingCallCanceled(canceledCall: Call)` | Invoked on the receiver's device when the caller cancels. Dismiss incoming call UI. | -| `onCallEndedMessageReceived(endedCall: Call)` | Invoked when a call ends. Update call history here. | +| `onIncomingCallReceived(incomingCall:` [`Call`](/sdk/reference/messages#call)`)` | Invoked when an incoming call is received. Display incoming call UI here. | +| `onOutgoingCallAccepted(acceptedCall:` [`Call`](/sdk/reference/messages#call)`)` | Invoked on the caller's device when the receiver accepts. Start the call session here. | +| `onOutgoingCallRejected(rejectedCall:` [`Call`](/sdk/reference/messages#call)`)` | Invoked on the caller's device when the receiver rejects. Dismiss outgoing call UI. | +| `onIncomingCallCanceled(canceledCall:` [`Call`](/sdk/reference/messages#call)`)` | Invoked on the receiver's device when the caller cancels. Dismiss incoming call UI. | +| `onCallEndedMessageReceived(endedCall:` [`Call`](/sdk/reference/messages#call)`)` | Invoked when a call ends. Update call history here. | ## Accept Call @@ -270,7 +293,7 @@ let authToken = CometChat.getUserAuthToken() ?? "" CometChatCalls.generateToken(authToken: authToken as NSString, sessionID: sessionId) { token in // Step 2: Configure call settings - let callSettings = CometChatCalls.CallSettingsBuilder + let callSettings = CometChatCalls.callSettingsBuilder .setDefaultLayout(true) .setIsAudioOnly(false) .setDelegate(self) @@ -361,3 +384,224 @@ CometChat.rejectCall(sessionID: sessionID, status: status, onSuccess: { call in ``` + +--- + +## Call Status Reference + +| Status | Description | Usage | +|--------|-------------|-------| +| `.initiated` | Call has been initiated | After initiateCall | +| `.ongoing` | Call is in progress | During active call | +| `.unanswered` | Call was not answered | Timeout/no answer | +| `.rejected` | Receiver rejected the call | rejectCall(.rejected) | +| `.busy` | Receiver is on another call | rejectCall(.busy) | +| `.cancelled` | Caller cancelled before answer | rejectCall(.cancelled) | +| `.ended` | Call has ended | After endCall | + +--- + +## Call Type Reference + +| Type | Description | +|------|-------------| +| `.audio` | Voice call only | +| `.video` | Video call with audio | + +--- + +## Receiver Type Reference + +| Type | Description | +|------|-------------| +| `.user` | One-to-one call with a user | +| `.group` | Group call | + +--- + +## Common Error Codes + +| Error Code | Description | Resolution | +|------------|-------------|------------| +| `ERR_CALL_NOT_FOUND` | Call session not found | Verify session ID | +| `ERR_CALL_ALREADY_INITIATED` | Call already in progress | End current call first | +| `ERR_CALL_ALREADY_JOINED` | Already joined the call | Cannot join twice | +| `ERR_CALL_BUSY` | User is on another call | Try again later | +| `ERR_CALL_CANCELLED` | Call was cancelled | Initiate new call | +| `ERR_CALL_REJECTED` | Call was rejected | User declined | +| `ERR_CALL_ENDED` | Call has already ended | Initiate new call | +| `ERR_INVALID_SESSION_ID` | Invalid session ID | Check session ID | +| `ERR_USER_NOT_LOGGED_IN` | User not authenticated | Login first | +| `ERR_CALLING_SELF` | Cannot call yourself | Use different receiver | +| `ERROR_CALL_IN_PROGRESS` | Another call is active | End previous call first | + +--- + +## Complete Calling Example + +A complete implementation showing the full calling flow from initiation to end. + + + + +```swift +import CometChatSDK +import CometChatCallsSDK + +class CallViewController: UIViewController, CometChatCallDelegate, CallsEventsDelegate { + + var callView: UIView! + var currentSessionId: String? + + override func viewDidLoad() { + super.viewDidLoad() + CometChat.calldelegate = self + setupCallView() + } + + func setupCallView() { + callView = UIView(frame: view.bounds) + view.addSubview(callView) + } + + // MARK: - Initiate Call + func initiateVideoCall(to receiverId: String) { + let call = Call(receiverId: receiverId, callType: .video, receiverType: .user) + + CometChat.initiateCall(call: call) { [weak self] call in + self?.currentSessionId = call?.sessionID + // Show outgoing call UI + } onError: { error in + print("Error: \(error?.errorDescription ?? "")") + } + } + + // MARK: - CometChatCallDelegate + func onIncomingCallReceived(incomingCall: Call?, error: CometChatException?) { + guard let call = incomingCall else { return } + currentSessionId = call.sessionID + // Show incoming call UI with accept/reject buttons + } + + func onOutgoingCallAccepted(acceptedCall: Call?, error: CometChatException?) { + guard let sessionId = acceptedCall?.sessionID else { return } + startCallSession(sessionID: sessionId) + } + + func onOutgoingCallRejected(rejectedCall: Call?, error: CometChatException?) { + // Dismiss outgoing call UI + } + + func onIncomingCallCanceled(canceledCall: Call?, error: CometChatException?) { + // Dismiss incoming call UI + } + + func onCallEndedMessageReceived(endedCall: Call?, error: CometChatException?) { + CometChat.clearActiveCall() + CometChatCalls.endSession() + } + + // MARK: - Accept/Reject Call + func acceptCall() { + guard let sessionId = currentSessionId else { return } + + CometChat.acceptCall(sessionID: sessionId) { [weak self] call in + self?.startCallSession(sessionID: sessionId) + } onError: { error in + print("Error: \(error?.errorDescription ?? "")") + } + } + + func rejectCall() { + guard let sessionId = currentSessionId else { return } + + CometChat.rejectCall(sessionID: sessionId, status: .rejected) { call in + // Dismiss incoming call UI + } onError: { error in + print("Error: \(error?.errorDescription ?? "")") + } + } + + // MARK: - Start Call Session + func startCallSession(sessionID: String) { + guard let authToken = CometChat.getUserAuthToken() else { return } + + CometChatCalls.generateToken( + authToken: authToken as NSString, + sessionID: sessionID as NSString + ) { [weak self] token in + guard let self = self else { return } + + let tokenStr = (token as? [String: Any])?["token"] as? String ?? token as? String + guard let callToken = tokenStr else { return } + + let callSettings = CometChatCalls.callSettingsBuilder + .setDefaultLayout(true) + .setIsAudioOnly(false) + .setDelegate(self) + .build() + + DispatchQueue.main.async { + CometChatCalls.startSession( + callToken: callToken, + callSetting: callSettings, + view: self.callView + ) { success in + print("Call session started") + } onError: { error in + print("Error: \(error?.errorDescription ?? "")") + } + } + } onError: { error in + print("Token error: \(error?.errorDescription ?? "")") + } + } + + // MARK: - CallsEventsDelegate + func onCallEndButtonPressed() { + guard let sessionId = currentSessionId else { return } + + CometChat.endCall(sessionID: sessionId) { call in + CometChat.clearActiveCall() + CometChatCalls.endSession() + } onError: { error in + print("Error: \(error?.errorDescription ?? "")") + } + } + + func onCallEnded() { + CometChat.clearActiveCall() + CometChatCalls.endSession() + } + + func onUserJoined(rtcUser: RTCUser) { + print("User joined: \(rtcUser.name ?? "")") + } + + func onUserLeft(rtcUser: RTCUser) { + print("User left: \(rtcUser.name ?? "")") + } +} +``` + + + + +--- + +## 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/ios/delete-conversation.mdx b/sdk/ios/delete-conversation.mdx index a9a805f8b..9cc16aabb 100644 --- a/sdk/ios/delete-conversation.mdx +++ b/sdk/ios/delete-conversation.mdx @@ -1,32 +1,75 @@ --- -title: "Delete A Conversation" +title: "Delete Conversation" +sidebarTitle: "Delete Conversation" +description: "Delete user or group conversations using the CometChat iOS SDK." --- + +```swift +// Delete user conversation +CometChat.deleteConversation(conversationWith: "UID", conversationType: .user, + onSuccess: { msg in }, onError: { err in }) + +// Delete group conversation +CometChat.deleteConversation(conversationWith: "GUID", conversationType: .group, + onSuccess: { msg in }, onError: { err in }) +``` + +**Note:** Deletes only for the logged-in user. Use [REST API](https://api-explorer.cometchat.com/reference/deletes-conversation) to delete for all participants. + -In case you want to delete a conversation, you can use the `deleteConversation()` method. + +This operation is irreversible. Deleted conversations cannot be recovered for the logged-in user. + -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. - + ```swift -CometChat.deleteConversation(conversationWith: "cometchat-uid-1", conversationType: .user, onSuccess: { message in - print("Conversation deleted",message) -}, onError: {error in - print("delete Convearstion failed with error: \(error?.errorDescription)") +CometChat.deleteConversation(conversationWith: "cometchat-uid-1", conversationType: .user, onSuccess: { (message) in + print("Conversation deleted: \(message)") +}, onError: { (error) in + print("Error: \(error?.errorDescription)") +}) +``` + + +```swift +CometChat.deleteConversation(conversationWith: "group-guid-1", conversationType: .group, onSuccess: { (message) in + print("Conversation deleted: \(message)") +}, onError: { (error) in + print("Error: \(error?.errorDescription)") }) ``` - - -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). +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). + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| conversationWith | `String` | Yes | UID of user or GUID of group | +| conversationType | `CometChat.ConversationType` | Yes | `.user` or `.group` | + +On success, returns a confirmation message string. + +--- -The `deleteConversation()` method takes the following parameters: +## Next Steps -| 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 | + + + 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/ios/delete-group.mdx b/sdk/ios/delete-group.mdx index c305f4093..e22cd161d 100644 --- a/sdk/ios/delete-group.mdx +++ b/sdk/ios/delete-group.mdx @@ -1,10 +1,32 @@ --- title: "Delete A Group" +sidebarTitle: "Delete Group" +description: "Delete a group permanently using the CometChat iOS SDK. Only group admins can perform this operation." --- + +```swift +// Delete a group (owner only) +CometChat.deleteGroup(GUID: "GUID", onSuccess: { response in }, onError: { error in }) +``` + +**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. + -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. +## Delete a Group + +Use `deleteGroup()` with the group's GUID. + +| Parameter | Description | +|-----------|-------------| +| `GUID` | The GUID of the group you would like to delete | @@ -12,38 +34,40 @@ To delete a group you need to use the `deleteGroup()` method. The user must be a let GUID = "GUID"; CometChat.deleteGroup(GUID: GUID, onSuccess: { (response) in - - print("Group deleted successfully.") - + print("Group deleted successfully.") }) { (error) in - - print("Group delete failed with error: " + error!.errorDescription); + print("Group delete failed with error: " + error!.errorDescription); } ``` - - ```objc NSString *guid = @"cometchat-guid-101"; [CometChat deleteGroupWithGUID:guid onSuccess:^(NSString * response) { - NSLog(@"Group deleted successfully."); - } onError:^(CometChatException * error) { - NSLog(@"Group deletion failed with error: %@",[error errorDescription]); - }]; ``` - - -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/ios/delete-message.mdx b/sdk/ios/delete-message.mdx index 9d2192d20..8f0375002 100644 --- a/sdk/ios/delete-message.mdx +++ b/sdk/ios/delete-message.mdx @@ -1,85 +1,122 @@ --- -title: "Delete A Message" +title: "Delete Message" +sidebarTitle: "Delete Message" +description: "Delete messages using the CometChat iOS SDK." --- + +```swift +// Delete a message +CometChat.delete(messageId: 12345, onSuccess: { msg in + print("Deleted:", msg.id, msg.deletedAt) +}, onError: { err in }) + +// Listen for real-time deletions +extension VC: CometChatMessageDelegate { + func onMessageDeleted(message: BaseMessage) { + print("Deleted:", message.id, message.deletedAt) + } +} +``` -While [deleting a Message](/sdk/ios/delete-message#delete-a-message) is straightforward, receiving events for deleted messages with CometChat has two parts: +**Who can delete:** Message sender, Group admin, Group moderator +**Deleted fields:** `deletedAt` (timestamp), `deletedBy` (user who deleted) + -1. Adding a listener to receive [real-time message deletes](/sdk/ios/delete-message#real-time-message-delete-events) when your app is running. -2. Calling a method to retrieve [missed message deletes](/sdk/ios/delete-message#missed-message-delete-events) when your app was not running. +Deleting a message is straightforward. Receiving delete events has two parts: -## Delete a Message +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 -*In other words, as a sender, how do I delete a message?* +## 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 `CometChat.delete(messageId:)` with the message ID. - - ```swift -CometChat.delete(messageId: 12345, onSuccess: { (baseMessage) in - - print("message deleted successfully. \(baseMessage)") - -}) { (error) in - - print("delete message failed with error: \(error.errorDescription)") -} +CometChat.delete(messageId: 12345, onSuccess: { (message) in + print("Message deleted: \(message)") +}, onError: { (error) in + print("Error: \(error.errorDescription)") +}) ``` - - - +The deleted message object is returned with `deletedAt` (timestamp) and `deletedBy` (UID of deleter) fields set. -Once the message is deleted, In the `onSuccess()` callback, you get an object of the `BaseMessage` class, with the `deletedAt` fieldset 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 `delete()` method returns a [`BaseMessage`](/sdk/reference/messages#basemessage) object. -By default, CometChat allows certain roles to delete a message. + +This is a soft delete — message content is still available on the object. Check `deletedAt > 0` to identify deleted messages. + -| User Role | Conversation Type | Deletion Capabilities | -| --------------- | ----------------------- | ------------------------- | -| Message Sender | One-on-one Conversation | Messages they've sent | -| Message Sender | Group Conversation | Messages they've sent | -| Group Admin | Group Conversation | All messages in the group | -| Group Moderator | Group Conversation | All messages in the group | +| User | Conversation Type | Deletion Capabilities | +|------|-------------------|----------------------| +| Message Sender | One-on-one | Own messages only | +| Message Sender | Group | Own messages only | +| Group Admin | Group | All messages | +| Group Moderator | Group | All messages | ## 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 the message being edited, you must add protocol conformance `CometChatMessageDelegate` as Shown Below : +The `onMessageDeleted` callback receives a [`BaseMessage`](/sdk/reference/messages#basemessage) object with the `deletedAt` and `deletedBy` fields set. - - ```swift -extension ViewController: CometChatMessageDelegate { +extension YourViewController: CometChatMessageDelegate { - func onMessageDeleted(message: BaseMessage) { - - print("received deleted message successfully.") + func onMessageDeleted(message: BaseMessage) { + print("Message deleted: \(message.id)") + print("Deleted at: \(message.deletedAt)") + print("Deleted by: \(message.deletedBy ?? "")") } } -``` - - - +// Register the delegate: +CometChat.messagedelegate = self +``` ## 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 fetching message history, deleted messages have `deletedAt` and `deletedBy` fields set. Additionally, an [`Action`](/sdk/reference/messages#action) message is added to history indicating the deletion. -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, 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 and `Action` message informing you that the message with id 50 has been deleted. +The [`Action`](/sdk/reference/messages#action) object contains: +- `action` — `deleted` +- `actionOn` — The deleted message object +- `actionBy` — User who deleted the message +- `actionFor` — Receiver (User or Group) -For the message deleted event, in the `Action` object received, the following fields can help you get the relevant information- +```swift +for message in messages { + if message.deletedAt > 0 { + print("Message \(message.id) was deleted at \(message.deletedAt)") + } -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. + if let actionMessage = message as? ActionMessage { + if actionMessage.action == .messageDeleted { + print("Delete action detected") + } + } +} +``` +You must be the message sender or a group admin/moderator to delete a message. + -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. +--- - +## 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/ios/delivery-read-receipts.mdx b/sdk/ios/delivery-read-receipts.mdx index 954a85e65..281a53b30 100644 --- a/sdk/ios/delivery-read-receipts.mdx +++ b/sdk/ios/delivery-read-receipts.mdx @@ -1,68 +1,73 @@ --- title: "Delivery & Read Receipts" +sidebarTitle: "Delivery & Read Receipts" +description: "Mark messages as delivered, read, or unread and receive real-time receipt events using the CometChat iOS SDK." --- + +| Method | Description | +| --- | --- | +| `markAsDelivered(baseMessage:)` | Mark a message as delivered | +| `markAsRead(baseMessage:)` | Mark a message as read | +| `markConversationAsDelivered(conversationWithId:receiverType:)` | Mark entire conversation as delivered | +| `markConversationAsRead(conversationWithId:receiverType:)` | Mark entire conversation as read | +| `markMessageAsUnread(baseMessage:receiverType:)` | Mark a message as unread | +| `getMessageReceipts(_:)` | Get delivery/read receipts for a message | -## Mark Messages as Delivered +```swift +// Mark as delivered/read (pass message object) +CometChat.markAsDelivered(baseMessage: baseMessage) +CometChat.markAsRead(baseMessage: baseMessage) -*In other words, as a recipient, how do I inform the sender that I've received a message?* +// Mark entire conversation +CometChat.markConversationAsRead(conversationWithId: uid, receiverType: .user) { _ in } onError: { _ in } -You can mark the messages for a particular conversation as read using the `markAsDelivered()` method. This method takes the below parameters as input: +// Listen for receipt events (CometChatMessageDelegate) +func onMessagesDelivered(receipt: MessageReceipt) { } +func onMessagesRead(receipt: MessageReceipt) { } +func onMessagesDeliveredToAll(receipt: MessageReceipt) { } // Groups only +func onMessagesReadByAll(receipt: MessageReceipt) { } // Groups only +``` + -| **messageId** | **The ID of the message above which all the messages for a particular conversation are to be marked as read.** | -| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| receiverId | In the case of one-to-one conversation, the sender'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) | -| messageSender | 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 conversation and group conversation can be marked as delivered using this method. +## Mark as Delivered -Ideally, you should mark all the messages as read 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 - -```swift -var messageId = 123 -var receiverId = "cometchat-uid-2" -var senderId = "cometchat-uid-1" -CometChat.markAsDelivered(messageId: messageId, receiverId: receiverId, receiverType: .user, messageSender: senderId) -``` - - - - + ```swift -var messageId = 123 -var receiverId = "cometchat-uid-2" -var senderId = "cometchat-uid-1" -CometChat.markAsDelivered(messageId: messageId, receiverId: receiverId, receiverType: .group, messageSender: senderId) -``` - - - - -```objc -[CometChat markAsDeliveredWithMessageId:messageId receiverId:receiverId receiverType: ReceiverTypeUser messageSender:messageSender] +CometChat.markAsDelivered(baseMessage: baseMessage, onSuccess: { + print("markAsDelivered Success") +}, onError: { error in + print("markAsDelivered error: \(error?.errorDescription ?? "")") +}) ``` - - - + ```objc -[CometChat markAsDeliveredWithMessageId:messageId receiverId:receiverId receiverType: ReceiverTypeUser messageSender:messageSender] +[CometChat markAsDeliveredWithBaseMessage:baseMessage onSuccess:^{ + NSLog(@"markAsDelivered Success"); +} onError:^(CometChatException *error){ + NSLog(@"markAsDelivered error: %@", [error errorDescription]); +}]; ``` - - -This method will mark all the messages before the messageId specified, for the conversation with receiverId and receiverType(user/group) as read. +### Using Parameters -In case you would like to be notified of an error if the receipts fail to go through you can use `markAsDelivered()` method with the callbacks as shown below: +| 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` | +| `messageSender` | UID of the message sender | @@ -70,219 +75,114 @@ In case you would like to be notified of an error if the receipts fail to go thr var messageId = 123 var receiverId = "cometchat-uid-2" var senderId = "cometchat-uid-1" + CometChat.markAsDelivered(messageId: messageId, receiverId: receiverId, receiverType: .user, messageSender: senderId, onSuccess: { - print("markAsDelivered Succces") -}, onError: {(error) in - print("markAsDelivered error message",error?.errorDescription) + print("markAsDelivered Success") +}, onError: { error in + print("markAsDelivered error: \(error?.errorDescription ?? "")") }) ``` - - ```swift var messageId = 123 var receiverId = "cometchat-uid-2" var senderId = "cometchat-uid-1" + CometChat.markAsDelivered(messageId: messageId, receiverId: receiverId, receiverType: .group, messageSender: senderId, onSuccess: { - print("markAsDelivered Succces") -}, onError: {(error) in - print("markAsDelivered error message",error?.errorDescription) + print("markAsDelivered Success") +}, onError: { error in + print("markAsDelivered error: \(error?.errorDescription ?? "")") }) ``` - - - + ```objc int messageId = 123; NSString *receiverId = @"cometchat-uid-2"; NSString *senderId = @"cometchat-uid-1"; -[CometChat markAsDeliveredWithMessageId:messageId receiverId:receiverId receiverType: ReceiverTypeUser messageSender:messageSender onSuccess:^{ + +[CometChat markAsDeliveredWithMessageId:messageId receiverId:receiverId receiverType:ReceiverTypeUser messageSender:senderId onSuccess:^{ NSLog(@"markAsDelivered Success"); } onError:^(CometChatException *error){ - NSLog(@"markAsDelivered error message %@",[error errorDescription]); + NSLog(@"markAsDelivered error: %@", [error errorDescription]); }]; ``` - - - + ```objc int messageId = 123; NSString *receiverId = @"cometchat-uid-2"; NSString *senderId = @"cometchat-uid-1"; -[CometChat markAsDeliveredWithMessageId:messageId receiverId:receiverId receiverType: ReceiverTypeGroup messageSender:messageSender onSuccess:^{ - NSLog(@"markAsDelivered Success"); -} onError:^(CometChatException *error){ - NSLog(@"markAsDelivered error message %@",[error errorDescription]); -}]; -``` - - - - - -Another option the CometChat SDK provides is to pass the entire message object to the markAsDelivered() method. - - - -```swift -CometChat.markAsDelivered(baseMessage : baseMessage) -``` - - - - -```objc -[CometChat markAsDeliveredWithBaseMessage:baseMessage]; -``` - - - - - -In case you would like to be notified of an error if the receipts fail to go through you can use `markAsDelivered()` method with the callbacks as shown below: - - -```swift -CometChat.markAsDelivered(baseMessage : baseMessage, onSuccess: { - print("markAsDelivered Succces") -}, onError: {(error) in - print("markAsDelivered error message",error?.errorDescription) -}) -``` - - - - -```objc -[CometChat markAsDeliveredWithBaseMessage:baseMessage onSuccess:^{ +[CometChat markAsDeliveredWithMessageId:messageId receiverId:receiverId receiverType:ReceiverTypeGroup messageSender:senderId onSuccess:^{ NSLog(@"markAsDelivered Success"); } onError:^(CometChatException *error){ - NSLog(@"markAsDelivered error message %@",[error errorDescription]); + NSLog(@"markAsDelivered error: %@", [error errorDescription]); }]; ``` - - - - -Starting v3, the messages will not be marked delivered internally by the SDK. You will have to use the `markAsDelivered()` method. You will either have to use one of the above method signatures to mark the messages as delivered. +This method marks all messages before the specified `messageId` for the conversation with `receiverId` and `receiverType` as delivered. + +Starting v3, messages are not marked delivered internally by the SDK. You must use `markAsDelivered()` explicitly. ---- - ## 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`. | -| `onSuccess` | The callback listener that will be called on success. | -| `onError` | The callback listener that will be called on error. | - -This method will mark all messages in the conversation as delivered. +Use `markConversationAsDelivered()` to mark all messages in a conversation as delivered. ```swift CometChat.markConversationAsDelivered(conversationWithId: (conversation.conversationWith as? User)?.uid, receiverType: .user) { message in - print(message) + print(message) } onError: { error in - print(error.errorDescription) + print(error.errorDescription) } ``` - ```swift CometChat.markConversationAsDelivered(conversationWithId: (conversation.conversationWith as? Group)?.guid, receiverType: .group) { message in - print(message) + print(message) } onError: { error in - print(error.errorDescription) + print(error.errorDescription) } ``` - - ---- - -## 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: +## Mark as Read -| 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 receipts's receiver Id | -| receiverType | type of the receiver. Could be either of the two values( user or group) | -| messageSender | The UID of the sender of the message. | +Use `markAsRead()` to mark messages as read. You can pass either a message object or individual parameters. -Messages for both user & group conversations can be marked as read using this method. - -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 - -```swift -var messageId = 123 -var receiverId = "abc" -var senderId = "xyz" - -CometChat.markAsRead(messageId: messageId, receiverId: receiverId, receiverType: .user, messageSender: senderId) -``` - - - - + ```swift -var messageId = 123 -var receiverId = "abc" - -CometChat.markAsRead(messageId: messageId, receiverId: receiverId, receiverType: .group) -``` - - - - -```objc -int messageId = 123; -NSString *receiverId = "abc"; - -[CometChat markAsReadWithMessageId:messageId receiverId:receiverId receiverType:ReceiverTypeUser]; +CometChat.markAsRead(baseMessage: baseMessage, onSuccess: { + print("markAsRead Success") +}, onError: { error in + print("markAsRead error: \(error?.errorDescription ?? "")") +}) ``` - - - + ```objc -int messageId = 123; -NSString *receiverId = "abc"; - -[CometChat markAsReadWithMessageId:messageId receiverId:receiverId receiverType:ReceiverTypeUser]; +[CometChat markAsReadWithBaseMessage:baseMessage onSuccess:^{ + NSLog(@"markAsRead Success"); +} onError:^(CometChatException *error){ + NSLog(@"markAsRead error: %@", [error errorDescription]); +}]; ``` - - -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 the `markAsRead()` method with the callbacks as shown below: +### Using Parameters @@ -290,325 +190,234 @@ In case you would like to be notified of an error if the receipts fail to go thr var messageId = 123 var receiverId = "cometchat-uid-2" var senderId = "cometchat-uid-1" + CometChat.markAsRead(messageId: messageId, receiverId: receiverId, receiverType: .user, messageSender: senderId, onSuccess: { - print("markAsRead Succces") -}, onError: {(error) in - print("markAsRead error message",error?.errorDescription) + print("markAsRead Success") +}, onError: { error in + print("markAsRead error: \(error?.errorDescription ?? "")") }) ``` - - ```swift var messageId = 123 var receiverId = "cometchat-uid-2" var senderId = "cometchat-uid-1" + CometChat.markAsRead(messageId: messageId, receiverId: receiverId, receiverType: .group, messageSender: senderId, onSuccess: { - print("markAsRead Succces") -}, onError: {(error) in - print("markAsRead error message",error?.errorDescription) + print("markAsRead Success") +}, onError: { error in + print("markAsRead error: \(error?.errorDescription ?? "")") }) ``` - - - + ```objc int messageId = 123; -NSString *receiverId = "abc"; +NSString *receiverId = @"abc"; [CometChat markAsReadWithMessageId:messageId receiverId:receiverId receiverType:ReceiverTypeUser onSuccess:^{ NSLog(@"markAsRead Success"); } onError:^(CometChatException *error){ - NSLog(@"markAsRead error message %@",[error errorDescription]); + NSLog(@"markAsRead error: %@", [error errorDescription]); }]; ``` - - - + ```objc int messageId = 123; -NSString *receiverId = "abc"; +NSString *receiverId = @"abc"; [CometChat markAsReadWithMessageId:messageId receiverId:receiverId receiverType:ReceiverTypeGroup onSuccess:^{ NSLog(@"markAsRead Success"); } onError:^(CometChatException *error){ - NSLog(@"markAsRead error message %@",[error errorDescription]); + NSLog(@"markAsRead error: %@", [error errorDescription]); }]; ``` - - - - -Another option the CometChat SDK provides is to pass the entire message object to the markAsRead() method. - - - -```swift -CometChat.markAsRead(baseMessage : baseMessage) -``` - - - - -```objc -[CometChat markAsReadWithBaseMessage: baseMessage]; -``` - - - -In case you would like to be notified of an error if the receipts fail to go through you can use the `markAsRead()` method with the callbacks as shown below: - - - -```swift -var messageId = 123 -var receiverId = "cometchat-uid-2" -var senderId = "cometchat-uid-1" -CometChat.markAsRead(baseMessage : baseMessage, onSuccess: { - print("markAsRead Succces") -}, onError: {(error) in - print("markAsRead error message",error?.errorDescription) -}) -``` - - - - -```objc -[CometChat markAsReadWithBaseMessage: baseMessage onSuccess:^{ - NSLog(@"markAsRead Success"); -} onError:^(CometChatException *error){ - NSLog(@"markAsRead error message %@",[error errorDescription]); -}]; -``` - - - - - - - -Starting v3, the `markAsRead()` method working with v2.x is deprecated and will not work. You will either have to use one of the above method signatures to mark the messages as read. - - - ---- - ## 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`. | -| `onSuccess` | The callback listener that will be called on success. | -| `onError` | The callback listener that will be called on error. | - -This method will mark all messages in the conversation as read. +Use `markConversationAsRead()` to mark all messages in a conversation as read. ```swift CometChat.markConversationAsRead(conversationWithId: (conversation.conversationWith as? User)?.uid, receiverType: .user) { message in - print(message) + print(message) } onError: { error in - print(error.errorDescription) + print(error.errorDescription) } ``` - - ```swift CometChat.markConversationAsRead(conversationWithId: (conversation.conversationWith as? Group)?.guid, receiverType: .group) { message in - print(message) + print(message) } onError: { error in - print(error.errorDescription) + print(error.errorDescription) } ``` - - ---- - -## Mark Messages as Unread - -The Mark message 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? +## Real-Time Receipt Events -You can mark the messages for a particular conversation as unread using the `markMessageAsUnread` method. This method takes the below parameters as input: +Implement `CometChatMessageDelegate` to receive delivery and read receipt events. -| 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(baseMessage: BaseMessage, receiverType: CometChat.ReceiverType, onSuccess: (Conversation) -> Void, onError: (CometChatException?) -> ())` 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. | -| onSuccess | The callback listener that will be called on success. | -| onError | The callback listener that will be called on error. | - - -You cannot mark your own messages as unread. This method only works for messages received from other users. - - - - -```swift -CometChat.markMessageAsUnread(baseMessage: message, receiverType: .user) { conversation in - print(conversation) - print(conversation.unreadMessageCount) -} onError: { error in - print(error?.errorDescription) -} -``` - - - -```swift -CometChat.markMessageAsUnread(baseMessage: message, receiverType: .group) { conversation in - print(conversation) - print(conversation.unreadMessageCount) -} onError: { error in - print(error?.errorDescription) -} -``` - - - - ---- - -## 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?* - -### 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. -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. +| 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 | ```swift func onMessagesRead(receipt: MessageReceipt) { - print("onMessagesRead \(receipt.stringValue())") + print("onMessagesRead \(receipt.stringValue())") } - + func onMessagesDelivered(receipt: MessageReceipt) { - print("onMessagesDelivered \(receipt.stringValue())") + print("onMessagesDelivered \(receipt.stringValue())") } func onMessagesDeliveredToAll(receipt: MessageReceipt) { - print("onMessagesDeliveredToAll \(receipt.stringValue())") + print("onMessagesDeliveredToAll \(receipt.stringValue())") } func onMessagesReadByAll(receipt: MessageReceipt) { - print("onMessagesReadByAll \(receipt.stringValue())") + print("onMessagesReadByAll \(receipt.stringValue())") } ``` - - - + ```objc --(void)onMessagesDeliveredWithReceipt:(MessageReceipt *)receipt -{ - NSLog(@"onMessagesDeliveredWithReceipt %@",receipt.stringValue) +-(void)onMessagesDeliveredWithReceipt:(MessageReceipt *)receipt { + NSLog(@"onMessagesDeliveredWithReceipt %@", receipt.stringValue); } --(void)onMessagesReadWithReceipt:(MessageReceipt *)receipt -{ - NSLog(@"onMessagesReadWithReceipt %@",receipt.stringValue) + +-(void)onMessagesReadWithReceipt:(MessageReceipt *)receipt { + NSLog(@"onMessagesReadWithReceipt %@", receipt.stringValue); } --(void)onMessagesDeliveredToAll:(MessageReceipt *)receipt -{ - NSLog(@"onMessagesDeliveredToAll %@",receipt.stringValue) +-(void)onMessagesDeliveredToAll:(MessageReceipt *)receipt { + NSLog(@"onMessagesDeliveredToAll %@", receipt.stringValue); } --(void)onMessagesReadByAll:(MessageReceipt *)receipt -{ - NSLog(@"onMessagesReadByAll %@",receipt.stringValue) + +-(void)onMessagesReadByAll:(MessageReceipt *)receipt { + NSLog(@"onMessagesReadByAll %@", receipt.stringValue); } ``` - - -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: -| 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. | +| Parameter | Information | +| --- | --- | +| `messageId` | The Id of the message prior to which all messages for that conversation have been marked as read. | +| `sender` | User object containing the details of the user who 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` | Timestamp when the message was delivered. Only present if receiptType is delivered. | +| `readAt` | Timestamp when the message was read. Only present when receiptType is read. | -### 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. - -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. + +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 + -### Receipt History for a Single Message +## Get Receipt History -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. ```swift -var messageId = 10101; +var messageId = 10101 -CometChat.getMessageReceipts(messageId, onSuccess: { (receipt) in - - print("getMessageReceipt \(receipt)") -}) { (error) in - print(error?.errorDescription) +CometChat.getMessageReceipts(messageId, onSuccess: { receipt in + print("getMessageReceipt \(receipt)") +}) { error in + print(error?.errorDescription ?? "") } ``` - - - + ```objc -int messageId =10101; +int messageId = 10101; [CometChat getMessageReceipts:messageId onSuccess:^(NSArray * _Nonnull receipt) { - - NSLog(@"getMesssageReceipts %@",receipt); - } onError:^(CometChatException * _Nullable error) { - - NSLog(@"CometChatException %@",error.errorDescription); - }]; + NSLog(@"getMessageReceipts %@", receipt); +} onError:^(CometChatException * _Nullable error) { + NSLog(@"CometChatException %@", error.errorDescription); +}]; ``` - - -You will receive a list of `MessageReceipt` objects in the `onSuccess()` method. +Returns an array of [`MessageReceipt`](/sdk/reference/auxiliary#messagereceipt) objects. - +## Missed Receipts -The following features will be available only if the **Enhanced Messaging Status** feature is enabled for your app. +When fetching messages, each message object includes `deliveredAt` and `readAt` timestamps indicating when the message was delivered and read. -* `onMessagesDeliveredToAll` event, -* `onMessagesReadByAll` event, -* `deliveredAt` field in a group message, -* `readAt` field in a group message. -* `markAsUnread` method. +For group messages, use `getMessageReceipts()` to fetch individual member delivery and read status. - +## Mark as Unread + +Use `markMessageAsUnread()` to mark a message as unread. This is useful for "mark as unread" functionality in conversation lists. + + + +```swift +CometChat.markMessageAsUnread(baseMessage: message, receiverType: .user) { conversation in + print(conversation) + print(conversation.unreadMessageCount) +} onError: { error in + print(error?.errorDescription ?? "") +} +``` + + +```swift +CometChat.markMessageAsUnread(baseMessage: message, receiverType: .group) { conversation in + print(conversation) + print(conversation.unreadMessageCount) +} onError: { error in + print(error?.errorDescription ?? "") +} +``` + + + + +You cannot mark your own messages as unread. This method only works for messages received from other users. + + +--- + +## Next Steps + + + + Show real-time typing status 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/ios/direct-calling.mdx b/sdk/ios/direct-calling.mdx index b525aa90c..c504e3ebf 100644 --- a/sdk/ios/direct-calling.mdx +++ b/sdk/ios/direct-calling.mdx @@ -1,7 +1,32 @@ --- title: "Call Session" +sidebarTitle: "Call Session" +description: "Generate call tokens, start and manage call sessions, configure call settings, and handle call events using the CometChat iOS Calls SDK." --- + + +```swift +let sessionId = "SESSION_ID" +let authToken = CometChat.getUserAuthToken() ?? "" + +// Generate call token +CometChatCalls.generateToken(authToken: authToken as NSString, sessionID: sessionId) { token in + // Build call settings + let callSettings = CometChatCalls.callSettingsBuilder + .setDefaultLayout(true) + .setIsAudioOnly(false) + .setDelegate(self) + .build() + + // Start call session + CometChatCalls.startSession(callToken: token, callSetting: callSettings, view: callView) { _ in } onError: { _ in } +} onError: { error in } + +// End call session +CometChatCalls.endSession() +``` + ## Overview This section demonstrates how to start a call session in an iOS application. Previously known as **Direct Calling**. @@ -39,14 +64,14 @@ CometChatCalls.generateToken(authToken: authToken as NSString, sessionID: sessio | Parameter | Description | | --------- | ----------- | -| `sessionId` | The unique session ID. In ringing flow, this is available in the `Call` object. For standalone calls, generate a random unique string. | +| `sessionId` | The unique session ID. In ringing flow, this is available in the [`Call`](/sdk/reference/messages#call) object. For standalone calls, generate a random unique string. | | `authToken` | The logged-in user's auth token from `CometChat.getUserAuthToken()`. | ## Start Call Session Use the `startSession()` method to join a call session. This method requires a call token (generated in the previous step) and a `CallSettings` object that configures the call UI and behavior. -The `CallSettings` class configures the call UI and behavior. Use `CallSettingsBuilder` to create a `CallSettings` instance with the following required parameters: +The `CallSettings` class configures the call UI and behavior. Use `callSettingsBuilder` to create a `CallSettings` instance with the following required parameters: | Parameter | Description | | --------- | ----------- | @@ -58,7 +83,7 @@ The `CallSettings` class configures the call UI and behavior. Use `CallSettingsB ```swift guard let callToken = self.callToken else { return } -let callSettings = CometChatCalls.CallSettingsBuilder +let callSettings = CometChatCalls.callSettingsBuilder .setDefaultLayout(true) .setIsAudioOnly(false) .setDelegate(self) @@ -73,9 +98,24 @@ CometChatCalls.startSession(callToken: callToken, callSetting: callSettings, vie + + +**callSettingsBuilder Methods:** + +| Method | Type | Description | +|--------|------|-------------| +| setDefaultLayout(_:) | `Bool` | Use default UI layout | +| setIsAudioOnly(_:) | `Bool` | Audio-only mode (no video) | +| setDelegate(_:) | `Any` | Delegate for call events | +| setMode(_:) | `Mode` | Call mode (.default, .single, .spotlight) | +| setStartAudioMuted(_:) | `Bool` | Start with mic muted | +| setStartVideoMuted(_:) | `Bool` | Start with camera off | + + + ### Call Settings -Configure the call experience using the following `CallSettingsBuilder` methods: +Configure the call experience using the following `callSettingsBuilder` methods: | Method | Description | | ------ | ----------- | @@ -103,7 +143,7 @@ Configure the call experience using the following `CallSettingsBuilder` methods: The `CallsEventsDelegate` protocol provides real-time callbacks for call session events, including participant changes, call state updates, and error conditions. -To receive call events, conform to `CallsEventsDelegate` and set the delegate in `CallSettingsBuilder` using `setDelegate(self)`. +To receive call events, conform to `CallsEventsDelegate` and set the delegate in `callSettingsBuilder` using `setDelegate(self)`. @@ -173,6 +213,15 @@ extension ViewController: CallsEventsDelegate { Ending a call session properly is essential to release media resources (camera, microphone, network connections) and update call state across all participants. + + +| Method | Description | +|--------|-------------| +| `CometChat.clearActiveCall()` | Clears the active call from CometChat | +| `CometChatCalls.endSession()` | Ends the call session in CallsSDK | + + + ### Ringing Flow When using the [Ringing](/sdk/ios/default-calling) flow, you must coordinate between the CometChat Chat SDK and the Calls SDK to properly terminate the call. @@ -255,6 +304,7 @@ CometChatCalls.switchCamera() + ### Mute Audio Controls the local audio stream transmission. @@ -280,6 +330,7 @@ CometChatCalls.audioMuted(false) + ### Pause Video Controls the local video stream transmission. @@ -305,6 +356,7 @@ CometChatCalls.videoPaused(false)
+ ### Set Audio Mode Routes the audio output to a specific device. @@ -312,7 +364,7 @@ Routes the audio output to a specific device. ```swift -CometChatCalls.setAudioMode(AudioMode(mode: "SPEAKER")) +CometChatCalls.setAudioMode(mode: "SPEAKER") ``` @@ -322,6 +374,7 @@ CometChatCalls.setAudioMode(AudioMode(mode: "SPEAKER")) + ### Enter PIP Mode Enters Picture-in-Picture mode. @@ -339,6 +392,7 @@ CometChatCalls.enterPIPMode()
+ ### Exit PIP Mode Exits Picture-in-Picture mode. @@ -356,6 +410,7 @@ CometChatCalls.exitPIPMode()
+ ### Switch To Video Call Upgrades an ongoing audio call to a video call. @@ -373,6 +428,7 @@ CometChatCalls.switchToVideoCall()
+ ### Start Recording Starts recording the call session. @@ -390,6 +446,7 @@ CometChatCalls.startRecording()
+ ### Stop Recording Stops an ongoing call recording. @@ -407,6 +464,7 @@ CometChatCalls.stopRecording()
+ ### End Call Terminates the current call session and releases all media resources. @@ -423,3 +481,99 @@ CometChatCalls.endSession() ```
+ + +--- + +## In-Call Methods Reference + +| Method | Parameters | Description | +|--------|------------|-------------| +| `switchCamera()` | None | Toggle front/rear camera | +| `audioMuted(_:)` | `Bool` | Mute/unmute microphone | +| `videoPaused(_:)` | `Bool` | Pause/resume camera | +| `setAudioMode(mode:)` | `String` | Set audio output device | +| `enterPIPMode()` | None | Enter Picture-in-Picture | +| `exitPIPMode()` | None | Exit Picture-in-Picture | +| `switchToVideoCall()` | None | Upgrade audio to video | +| `startRecording()` | None | Start call recording | +| `stopRecording()` | None | Stop call recording | +| `endSession()` | None | End call session | + +--- + +## CallsEventsDelegate Callbacks + +| Callback | Payload | Description | +|----------|---------|-------------| +| `onCallEnded()` | None | Call session terminated | +| `onSessionTimeout()` | None | Call auto-terminated due to inactivity | +| `onCallEndButtonPressed()` | None | User tapped end call button | +| `onUserJoined(rtcUser:)` | `RTCUser` | Remote participant joined | +| `onUserLeft(rtcUser:)` | `RTCUser` | Remote participant left | +| `onUserListChanged(rtcUsers:)` | `[RTCUser]` | Participant list changed | +| `onAudioModeChanged(mode:)` | `[AudioMode]` | Available audio devices changed | +| `onCallSwitchedToVideo(callSwitchedInfo:)` | `CallSwitchRequestInfo` | Audio call upgraded to video | +| `onUserMuted(rtcMutedUser:)` | `RTCMutedUser` | Participant mute state changed | +| `onRecordingToggled(recordingInfo:)` | `RTCRecordingInfo` | Recording started/stopped | + + + + + +| Property | Type | Description | +|----------|------|-------------| +| uid | `String?` | User's unique identifier | +| name | `String?` | User's display name | +| avatar | `String?` | User's avatar URL | + + + + +| Property | Type | Description | +|----------|------|-------------| +| uid | `String?` | User's unique identifier | +| name | `String?` | User's display name | +| audioMuted | `Bool?` | Is audio muted | +| videoMuted | `Bool?` | Is video muted | + + + + +| Property | Type | Description | +|----------|------|-------------| +| isRecording | `Bool?` | Is recording active | +| startedBy | `RTCUser?` | User who started recording | + + + + +| Mode | Description | +|------|-------------| +| `SPEAKER` | Phone speaker | +| `EARPIECE` | Phone earpiece | +| `BLUETOOTH` | Connected Bluetooth device | +| `HEADPHONES` | Wired headphones | + + + + + +--- + +## Next Steps + + + + Implement calls with incoming/outgoing ringing UI + + + Record call sessions for playback + + + Use Calls SDK without the Chat SDK + + + Retrieve and display call history + + diff --git a/sdk/ios/edit-message.mdx b/sdk/ios/edit-message.mdx index e3024ab3b..6cec510be 100644 --- a/sdk/ios/edit-message.mdx +++ b/sdk/ios/edit-message.mdx @@ -1,86 +1,137 @@ --- -title: "Edit A Message" +title: "Edit Message" +sidebarTitle: "Edit Message" +description: "Edit text and custom messages using the CometChat iOS SDK." --- + +```swift +// Edit a text message +let textMessage = TextMessage(receiverUid: "UID", text: "Updated text", receiverType: .user) +textMessage.id = 12345 +CometChat.edit(message: textMessage, onSuccess: { msg in }, onError: { err in }) + +// Listen for real-time edits +extension VC: CometChatMessageDelegate { + func onMessageEdited(message: BaseMessage) { + print("Edited:", message.id, message.editedAt) + } +} +``` + -While [editing a message](/sdk/ios/edit-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/ios/edit-message#real-time-message-edit-events) when your app is running -2. Calling a method to retrieve [missed message edits](/sdk/ios/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. - -### 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 `CometChat.edit(message:)` with a [`TextMessage`](/sdk/reference/messages#textmessage) or [`CustomMessage`](/sdk/reference/messages#custommessage) object. Set the message ID on the object before calling edit. ```swift -let tags = ["pinned"] -textMessage.tags = tags +let textMessage = TextMessage(receiverUid: "cometchat-uid-2", text: "Updated message", receiverType: .user) +textMessage.id = 12345 + +CometChat.edit(message: textMessage, onSuccess: { (message) in + print("Message edited: \(message)") +}, onError: { (error) in + print("Error: \(error.errorDescription)") +}) ``` -Once the message object is ready, you can use the `editMessage()` method and pass the message object to it. - -```swift - let textMessage = TextMessage(receiverUid: receiverID, text: text, receiverType: .user) - textMessage.id = messageID +The edited message object is returned with `editedAt` (timestamp) and `editedBy` (UID of editor) fields set. -CometChat.edit(message: textMessage, onSuccess: { (baseMessage) in +The `edit()` method returns a [`BaseMessage`](/sdk/reference/messages#basemessage) object (or a subclass like [`TextMessage`](/sdk/reference/messages#textmessage)). - print("Message edited successfully. \(baseMessage)") +### Add/Update Tags -}) { (error) in +Use `tags` to update tags when editing. New tags replace existing ones. - print("Message edit failed with error: \(error.errorDescription)") +```swift +let tags = ["pinned", "important"] +let textMessage = TextMessage(receiverUid: "cometchat-uid-2", text: "Pinned message", receiverType: .user) +textMessage.id = 12345 +textMessage.tags = tags -} +CometChat.edit(message: textMessage, onSuccess: {...}, onError: {...}) ``` -The object of the edited message will be returned in the `onSucess()` callback method of the listener. The message object will contain the `editedAt` fieldset 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. - -By default, CometChat allows certain roles to edit a message. +By default, CometChat allows certain users to edit a message: -| User Role | Conversation Type | Edit Capabilities | -| --------------- | ----------------------- | ------------------------- | -| Message Sender | One-on-one Conversation | Messages they've sent | -| Message Sender | Group Conversation | Messages they've sent | -| Group Owner | Group Conversation | All messages in the group | -| Group Moderator | Group Conversation | All messages in the group | +| User | Conversation Type | Edit Capabilities | +|------|-------------------|-------------------| +| Message Sender | One-on-one | Own messages only | +| Message Sender | Group | Own messages only | +| Group Owner | Group | All messages | +| Group Moderator | Group | All messages | ## Real-time Message Edit Events -In order to receive real-time events for the message being edited, you must add protocol conformance `CometChatMessageDelegate` as Shown Below : +The `onMessageEdited` callback receives a [`BaseMessage`](/sdk/reference/messages#basemessage) object with the `editedAt` and `editedBy` fields set. ```swift -extension ViewController: CometChatMessageDelegate { +extension YourViewController: CometChatMessageDelegate { - func onMessageEdited(message: BaseMessage) { + func onMessageEdited(message: BaseMessage) { + print("Message edited: \(message.id)") + print("Edited at: \(message.editedAt)") + print("Edited by: \(message.editedBy ?? "")") - print("received edited message successfully.") + if let textMessage = message as? TextMessage { + print("New text: \(textMessage.text)") + } } } + +// Register the delegate: +CometChat.messagedelegate = self ``` ## 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 fetching message history, edited messages have `editedAt` and `editedBy` fields set. Additionally, an [`Action`](/sdk/reference/messages#action) message is added to history indicating the edit. -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, 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 and `Action` message informing you that the message with id 50 has been edited. +The [`Action`](/sdk/reference/messages#action) object contains: +- `action` — `edited` +- `actionOn` — Updated message object +- `actionBy` — User who edited the message +- `actionFor` — Receiver (User or Group) -For the message edited event, in the `Action` object received, the following fields can help you get the relevant information- +```swift +for message in messages { + if message.editedAt > 0 { + print("Message \(message.id) was edited at \(message.editedAt)") + } -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. + if let actionMessage = message as? ActionMessage { + if actionMessage.action == .messageEdited { + print("Edit action detected") + } + } +} +``` +You must be the message sender or a group admin/moderator to edit a message. + -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/ios/flag-message.mdx b/sdk/ios/flag-message.mdx index 37a2be33a..b71f598ce 100644 --- a/sdk/ios/flag-message.mdx +++ b/sdk/ios/flag-message.mdx @@ -1,7 +1,21 @@ --- title: "Flag Message" +sidebarTitle: "Flag Message" +description: "Flag inappropriate messages for moderation review using the CometChat iOS SDK." --- + + +```swift +// Get available flag reasons +CometChat.getFlagReasons { reasons in } onError: { error in } + +// Flag a message +let detail = FlagDetail(messageId: 12345, reasonId: "spam", remark: "Promotional content") +CometChat.flagMessage(messageId: 12345, detail: detail) { response in } onError: { error in } +``` + + ## 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. @@ -12,10 +26,10 @@ For a complete understanding of how flagged messages are reviewed and managed, s ## Prerequisites -Before using the flag message feature: - -1. Moderation must be enabled for your app in the [CometChat Dashboard](https://app.cometchat.com) -2. Flag reasons should be configured under **Moderation > Advanced Settings** +| Requirement | Location | +|-------------|----------| +| Enable Moderation | CometChat Dashboard > App Settings | +| Configure Flag Reasons | Dashboard > Moderation > Advanced Settings | ## How It Works @@ -43,133 +57,89 @@ sequenceDiagram Before flagging a message, retrieve the list of available flag reasons configured in your Dashboard: - - - ```swift - CometChat.getFlagReasons { reasons in - print("Flag reasons fetched: \(reasons)") - // Use reasons to populate your report dialog UI - for reason in reasons { - print("Reason ID: \(reason.id ?? ""), Title: \(reason.reason ?? "")") - } - } onError: { error in - print("Error fetching flag reasons: \(error?.errorDescription ?? "")") +```swift +CometChat.getFlagReasons { reasons in + print("Flag reasons: \(reasons)") + for reason in reasons { + print("ID: \(reason.id ?? "")") } - ``` - - - -### Response +} onError: { error in + print("Error: \(error?.errorDescription)") +} +``` -The response is an array of `FlagReason` objects containing: +## Flag a Message -| Property | Type | Description | -|----------|------|-------------| -| id | String | Unique identifier for the reason | -| reason | String | Display text for the reason | +Use `flagMessage()` with the message ID and a `FlagDetail` object: -## Flag a Message +```swift +let flagDetail = FlagDetail( + messageId: 12345, + reasonId: "spam", + remark: "This message contains promotional content" +) -To flag a message, use the `flagMessage()` method with the message ID and a `FlagDetail` object: - - - - ```swift - let messageId = 123 // ID of the message to flag - - let flagDetail = FlagDetail( - messageId: messageId, - reasonId: "spam", // Required: ID from getFlagReasons() - remark: "This message contains promotional content" // Optional - ) - - CometChat.flagMessage(messageId: messageId, detail: flagDetail) { response in - print("Message flagged successfully: \(response)") - } onError: { error in - print("Message flagging failed: \(error?.errorDescription ?? "")") - } - ``` - - +CometChat.flagMessage(messageId: 12345, detail: flagDetail) { response in + print("Message flagged: \(response)") +} onError: { error in + print("Error: \(error?.errorDescription)") +} +``` ### Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| -| messageId | Int | Yes | The ID of the message to flag | -| detail | FlagDetail | Yes | Contains flagging details | -| detail.reasonId | String | Yes | ID of the flag reason (from `getFlagReasons()`) | -| detail.remark | String | No | Additional context or explanation from the user | - -### Response - -```json -{ - "message": "Message {id} has been flagged successfully." -} -``` +| messageId | `Int` | Yes | ID of the [`BaseMessage`](/sdk/reference/messages#basemessage) to flag | +| reasonId | `String` | Yes | ID from `getFlagReasons()` | +| remark | `String` | No | Additional context | ## Complete Example -Here's a complete implementation showing how to build a report message flow: - - - - ```swift - class ReportMessageHandler { - private var flagReasons: [FlagReason] = [] - - // Load flag reasons (call this on app init or when needed) - func loadFlagReasons(completion: @escaping ([FlagReason]) -> Void) { - CometChat.getFlagReasons { [weak self] reasons in - self?.flagReasons = reasons - completion(reasons) - } onError: { error in - print("Failed to load flag reasons: \(error?.errorDescription ?? "")") - completion([]) - } - } - - // Get reasons for UI display - func getReasons() -> [FlagReason] { - return flagReasons - } - - // Flag a message with selected reason - func flagMessage( - messageId: Int, - reasonId: String, - remark: String? = nil, - completion: @escaping (Bool, String?) -> Void - ) { - let flagDetail = FlagDetail( - messageId: messageId, - reasonId: reasonId, - remark: remark ?? "" - ) - - CometChat.flagMessage(messageId: messageId, detail: flagDetail) { response in - completion(true, response) - } onError: { error in - completion(false, error?.errorDescription) - } - } - } - - // Usage - let reportHandler = ReportMessageHandler() +```swift +class ReportMessageHandler { + private var flagReasons: [FlagReason] = [] - // Load reasons when app initializes - reportHandler.loadFlagReasons { reasons in - // Display reasons in UI for user to select + func loadFlagReasons(completion: @escaping ([FlagReason]) -> Void) { + CometChat.getFlagReasons { [weak self] reasons in + self?.flagReasons = reasons + completion(reasons) + } onError: { error in + completion([]) + } } - // When user submits the report - reportHandler.flagMessage(messageId: 123, reasonId: "spam", remark: "User is sending promotional links") { success, message in - if success { - showToast("Message reported successfully") + func flagMessage(messageId: Int, reasonId: String, remark: String?) { + let flagDetail = FlagDetail( + messageId: messageId, + reasonId: reasonId, + remark: remark ?? "" + ) + + CometChat.flagMessage(messageId: messageId, detail: flagDetail) { response in + print("Success: \(response)") + } onError: { error in + print("Error: \(error?.errorDescription ?? "")") } } - ``` - - +} +``` + +--- + +## 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/ios/group-add-members.mdx b/sdk/ios/group-add-members.mdx index afd5ede5c..2669814c1 100644 --- a/sdk/ios/group-add-members.mdx +++ b/sdk/ios/group-add-members.mdx @@ -1,15 +1,33 @@ --- 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 iOS SDK." --- + +```swift +// Add members to a group +let member = GroupMember(UID: "UID", groupMemberScope: .participant) +CometChat.addMembersToGroup(guid: "GUID", groupMembers: [member], onSuccess: { response in }, onError: { error in }) + +// Listen for member added events +// Conform to CometChatGroupDelegate +func onMemberAddedToGroup(action: ActionMessage, addedBy: User, addedUser: User, addedTo: Group) { } +``` + + +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. -You can add members to the group using the `addMembersToGroup()` method. This method takes the below parameters: +## Add Members to Group -1. GUID - GUID of the group the members are to be added to. -2. `Array` 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. `Array` bannedMembers - This is the list of UIDs that need to be banned from the Group. This can be set to `nil` if there are no members to be banned. -4. Callback. +Use `addMembersToGroup()` to add members to a group. + +| Parameter | Description | +|-----------|-------------| +| `guid` | The group to add members to | +| `groupMembers` | Array of `GroupMember` objects (UID and scope required) | +| `bannedMembers` | Array of UIDs to ban (can be `nil`) | @@ -21,18 +39,12 @@ let grpmem4 = GroupMember(UID: "member4", groupMemberScope: .admin) let grpmem5 = GroupMember(UID: "member5", groupMemberScope: .moderator) CometChat.addMembersToGroup(guid: "mygroup", groupMembers: [grpmem1, grpmem2, grpmem3, grpmem4, grpmem5], onSuccess: { (response) in - - print("Response from addMembersGroup: \\(response)") - + print("Response from addMembersGroup: \(response)") }, onError : { (error) in - - print("Adding member in a group failed with error: \\(String(describing: error?.errorDescription))") - + print("Adding member in a group failed with error: \(String(describing: error?.errorDescription))") }) ``` - - ```objc GroupMember *grpmem1 = [GroupMember alloc] initWithUID: @"mem1" groupMemberScope: GroupMemberScopeTypeParticipant]; @@ -43,32 +55,23 @@ GroupMember *grpmem5 = [GroupMember alloc] initWithUID: @"mem5" groupMemberScope NSMutableArray members = [[NSMutableArray alloc]initWithObjects:mem1, mem2, mem3, mem4, mem5, nil]; [CometChat addMembersToGroupWithGuid:@"mygroup" groupMembers:members bannedUIDs:nil onSuccess:^(NSDictionary * _Nonnull) { - NSLog(@"AddMembersToGroup response is successfully."); - } onError:^(CometChatException * _Nullable)error { - NSLog(@"AddMembersToGroup is failed with an error %@", [error.errorDescription]); }] ``` - - -In the `onSuccess()` callback, you will receive a dictionary 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 or ban the user failed. +The method returns a response dictionary 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 -To receive Real-Time Events for the same, you need to implement the `onMemberAddedToGroup()` method 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. - -* `onMemberAddedToGroup()` - This method is triggered when other users are added to the group so that the logged in user is informed of the other members added to the group or this method is triggered when the LoggedIn User is added to the Group. +Implement `onMemberAddedToGroup()` in `CometChatGroupDelegate` to receive real-time notifications when members are added. @@ -78,23 +81,18 @@ extension AppDelegate: CometChatGroupDelegate { func onMemberAddedToGroup(action: ActionMessage, addedBy: User, addedUser: User, addedTo: Group) { //When any member is added in the group this function will be called } - } ``` - - ```objc @interface ViewController () - @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; - [CometChat setGroupdelegate:self]; } @@ -104,20 +102,39 @@ extension AppDelegate: CometChatGroupDelegate { @end ``` - - -## Member Added to Group event in Message History + +Set delegate in `viewDidLoad()`: `CometChat.groupdelegate = self`. Remove delegate when view is dismissed to avoid memory leaks. + + +## Missed 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 not running?* +When fetching previous messages, member additions appear as [`Action`](/sdk/reference/messages#action) messages (a subclass of [`BaseMessage`](/sdk/reference/messages#basemessage)). -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. +| 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 | -For the group member added event, in the `Action` object received, the following fields can help you get the relevant information- +--- -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. +## 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/ios/group-change-member-scope.mdx b/sdk/ios/group-change-member-scope.mdx index 1d06892d7..986b23b60 100644 --- a/sdk/ios/group-change-member-scope.mdx +++ b/sdk/ios/group-change-member-scope.mdx @@ -1,103 +1,125 @@ --- title: "Change Member Scope" +sidebarTitle: "Change Scope" +description: "Learn how to change group member scope (admin, moderator, participant) and receive real-time scope change events using the CometChat iOS SDK." --- + +```swift +// Change member scope to admin +CometChat.updateGroupMemberScope(UID: "UID", GUID: "GUID", scope: .admin, onSuccess: { response in }, onError: { error in }) + +// Listen for scope change events +// Conform to CometChatGroupDelegate +func onGroupMemberScopeChanged(action: ActionMessage, scopeChangeduser: User, scopeChangedBy: User, scopeChangedTo: String, scopeChangedFrom: String, group: Group) { } +``` + + +Promote or demote group members between admin, moderator, and participant scopes. Only admins can change member scopes, and only the group owner can change admin scopes. -### Change Scope of a Group Member +## 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 scope within a group. + +| Parameter | Description | +|-----------|-------------| +| `UID` | The UID of the member whose scope you want to change | +| `GUID` | The GUID of the group | +| `scope` | The new scope: `.admin`, `.moderator`, or `.participant` | + +The default scope is `.participant`. Only Admins can change member scopes. ```swift -let guid = "GUID" -let uid = "UID"; -let scope:CometChat.MemberScope = .admin +let guid = "cometchat-guid-1" +let uid = "cometchat-uid-2" +let scope: CometChat.MemberScope = .admin CometChat.updateGroupMemberScope(UID: uid, GUID: guid, scope: scope, onSuccess: { (response) in - - print("Update group member scope changed successfully.") - -}) { (error) in - - print("Update group member scope failed with error: " + error!.errorDescription); -} + print("Scope changed: \(response)") +}, onError: { (error) in + print("Error: \(error?.errorDescription)") +}) ``` - - -This method takes the below parameters: - -| Paramter | Description | -| -------- | --------------------------------------------------------------------------------------------------------- | -| UID | The uid of the member | -| 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. admin 2. moderator 3. 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 +## Real-Time Scope Change Events -## Receive Real-Time 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 whenever a group member's scope changes, you will need to override the `onGroupMemberScopeChanged()` method of the `GroupListener` class. - -You can receive live events related to ChangeMemberScope, In order to receive the Event, you must add protocol conformance `CometChatGroupDelegate` as shown below: +Implement `onGroupMemberScopeChanged()` in `CometChatGroupDelegate` to receive real-time notifications when a member's scope changes. ```swift -extension AppDelegate: CometChatGroupDelegate { - - func onGroupMemberScopeChanged(action: ActionMessage, scopeChangeduser: User, scopeChangedBy: User, scopeChangedTo: String, scopeChangedFrom: String, group: Group) { - - print("\(scopeChangedUser.name) scope changed from \(scopeChangedFrom) to \(scopeChangedTo) by \(scopeChangedBy.name) in the group \(group.name).") - } +class ViewController: UIViewController, CometChatGroupDelegate { + + override func viewDidLoad() { + super.viewDidLoad() + CometChat.groupdelegate = self + } + + func onGroupMemberScopeChanged(action: ActionMessage, scopeChangeduser: User, scopeChangedBy: User, scopeChangedTo: String, scopeChangedFrom: String, group: Group) { + print("\(scopeChangeduser.name ?? "") scope changed") + print("From: \(scopeChangedFrom) To: \(scopeChangedTo)") + } } ``` - - ```objc @interface ViewController () - @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; - [CometChat setGroupdelegate:self]; - } -- (void)onGroupMemberScopeChangedWithAction:(Action *)action user:(User * _Nonnull)user scopeChangedTo:(NSString * _Nonnull)scopeChangedTo scopeChangedFrom:(NSString * _Nonnull)scopeChangedFrom group:(Group * _Nonnull)group { - // user scope changed +- (void)onGroupMemberScopeChangedWithAction:(Action *)action user:(User *)user scopeChangedTo:(NSString *)scopeChangedTo scopeChangedFrom:(NSString *)scopeChangedFrom group:(Group *)group { + // User scope changed } @end ``` - - + +Always remove group delegates when they're no longer needed. Set delegate in `viewDidLoad()`: `CometChat.groupdelegate = self`. + + ## 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 fetching previous messages, scope changes appear as [`Action`](/sdk/reference/messages#action) messages (a subclass of [`BaseMessage`](/sdk/reference/messages#basemessage)). -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. +| 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 | -For the group member scope changed event, in the `Action` object received, the following fields can help you get the relevant information- +--- -1. `action` - `scopeChanged` -2. `actionOn` - User object containing the details of the user whos 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 +## 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/ios/group-kick-member.mdx b/sdk/ios/group-kick-member.mdx index 0def9ac5a..809698738 100644 --- a/sdk/ios/group-kick-member.mdx +++ b/sdk/ios/group-kick-member.mdx @@ -1,343 +1,329 @@ --- title: "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 iOS SDK." --- + +```swift +// Kick a member +CometChat.kickGroupMember(UID: "UID", GUID: "GUID", onSuccess: { response in }, onError: { error in }) + +// Ban a member +CometChat.banGroupMember(UID: "UID", GUID: "GUID", onSuccess: { response in }, onError: { error in }) -There are certain actions that can be performed on the group members: +// Unban a member +CometChat.unbanGroupMember(UID: "UID", GUID: "GUID", onSuccess: { response in }, onError: { error in }) -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 +// Fetch banned members +let request = BannedGroupMembersRequest.BannedGroupMembersRequestBuilder(guid: "GUID") + .set(limit: 30).build() +request.fetchNext(onSuccess: { members in }, onError: { error in }) +``` + -Please note: All the above-mentioned actions can only be performed by the **Admin** or the **Moderator** of the group. +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 -The Admin or Moderator of the group can kick a member out of the group using the `kickUser()` method provided by the CometChat class. This method can be used as shown below: +Admins or Moderators can remove a member using `kickGroupMember()`. The kicked user can rejoin the group later. + +| Parameter | Description | +|-----------|-------------| +| `UID` | The UID of the user to be kicked | +| `GUID` | The GUID of the group from which user is to be kicked | ```swift -let uid = "UID"; // Uid of the user to be kicked -let guid = "GUID"; // guid of the group the user is to be kicked from +let uid = "cometchat-uid-2" +let guid = "cometchat-guid-1" CometChat.kickGroupMember(UID: uid, GUID: guid, onSuccess: { (response) in - - print("\(uid) is kicked from the group \(guid) successfully.") - -}) { (error) in - - print("Group member kicking failed with error: " + error!.errorDescription); -} + print("\(uid) is kicked from the group \(guid) successfully.") +}, onError: { (error) in + print("Error: \(error?.errorDescription)") +}) ``` - - ```objc -NSString *UID = @"UID"; // Uid of the user to be kicked -NSString *GUID = @"GUID"; // guid of the group the user is to be kicked from +NSString *UID = @"cometchat-uid-2"; +NSString *GUID = @"cometchat-guid-1"; [CometChat kickGroupMemberWithUID:UID GUID:GUID onSuccess:^(NSString * response) { - NSLog(@"%@ kicked from the group %@ successfully", UID, GUID); - + NSLog(@"%@ kicked from the group %@ successfully", UID, GUID); } onError:^(CometChatException * error) { - - NSLog(@"Group member kicking failed with error: %@",[error errorDescription]); - + NSLog(@"Error: %@", [error errorDescription]); }]; ``` - - -The `kickGroupMember()` takes the 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. ## 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. + +| Parameter | Description | +|-----------|-------------| +| `UID` | The UID of the user to be banned | +| `GUID` | The GUID of the group from which user is to be banned | ```swift -let uid = "UID"; -let guid = "GUID" ; +let uid = "cometchat-uid-2" +let guid = "cometchat-guid-1" CometChat.banGroupMember(UID: uid, GUID: guid, onSuccess: { (response) in - - print("\(uid) is banned from the group \(guid) successfully.") - -}) { (error) in - - print("Group member baning failed with error: " + error!.errorDescription); -} + print("\(uid) is banned from the group \(guid) successfully.") +}, onError: { (error) in + print("Error: \(error?.errorDescription)") +}) ``` - - ```objc -NSString *UID = @"UID"; -NSString *GUID = @"GUID"; +NSString *UID = @"cometchat-uid-2"; +NSString *GUID = @"cometchat-guid-1"; [CometChat banGroupMemberWithUID:UID GUID:GUID onSuccess:^(NSString * response) { - - NSLog(@"%@ banned from the group %@ successfully", UID, GUID); - + NSLog(@"%@ banned from the group %@ successfully", UID, GUID); } onError:^(CometChatException * error) { - - NSLog(@"Group member baning failed with error: %@",[error errorDescription]); - + NSLog(@"Error: %@", [error errorDescription]); }]; ``` - - -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. -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 group the same group without being unbanned. +## Unban a Group Member -## Unban a Banned Group Member from a Group +Admins or Moderators can unban a previously banned member using `unbanGroupMember()`. -Only Admin or Moderators of the group can unban a previously banned member from the group using the `unbanGroupMember()` method. +| Parameter | Description | +|-----------|-------------| +| `UID` | The UID of the user to be unbanned | +| `GUID` | The GUID of the group from which user is to be unbanned | ```swift -let uid = "cometchat-uid-1"; // Uid of the user to be reinstated -let guid = "cometchat-guid-11" ; // guid of the group the user is to be reinstated into +let uid = "cometchat-uid-2" +let guid = "cometchat-guid-1" CometChat.unbanGroupMember(UID: uid, GUID: guid, onSuccess: { (response) in - - print("\(uid) is unbanned from the group \(guid) successfully.") - -}) { (error) in - - print("Group member unbaning failed with error: " + error!.errorDescription); -} + print("\(uid) is unbanned from the group \(guid) successfully.") +}, onError: { (error) in + print("Error: \(error?.errorDescription)") +}) ``` - - ```objc -NSString *UID = @"UID"; -NSString *GUID = @"GUID"; +NSString *UID = @"cometchat-uid-2"; +NSString *GUID = @"cometchat-guid-1"; [CometChat unbanGroupMemberWithUID:UID GUID:GUID onSuccess:^(NSString * response) { NSLog(@"%@ unbanned from the group %@ successfully", UID, GUID); - } onError:^(CometChatException * error) { - - NSLog(@"Group member unbaning failed with error: %@",[error errorDescription]); - + NSLog(@"Error: %@", [error errorDescription]); }]; ``` - - -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. | - -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. +Use `BannedGroupMembersRequestBuilder` to fetch banned members of a group. The GUID must be specified in the constructor. -The `BannedGroupMembersRequestBuilder` class allows you to set the below parameters: +### Set Limit -The GUID of the group for which the banned members are to be fetched must be specified in the constructor of the `BannedGroupMembersRequestBuilder` class. - -1. `set(limit: Int)` - 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. ```swift -let bannedGroupMembersRequest = BannedGroupMembersRequest.BannedGroupMembersRequestBuilder(guid: guid).set(limit: limit).build(); +let bannedGroupMembersRequest = BannedGroupMembersRequest.BannedGroupMembersRequestBuilder(guid: "cometchat-guid-1") + .set(limit: 30) + .build() ``` - - -2. `set(searchKeyword : String)` - This method allows you to set the search string based on which the banned group members are to be fetched. +### Set Search Keyword + +Filters banned members by a search string. ```swift -let bannedGroupMembersRequest = BannedGroupMembersRequest.BannedGroupMembersRequestBuilder(guid: guid) -.set(limit: limit) -.set(searchKeyword: "abc") -.build(); +let bannedGroupMembersRequest = BannedGroupMembersRequest.BannedGroupMembersRequestBuilder(guid: "cometchat-guid-1") + .set(limit: 30) + .set(searchKeyword: "abc") + .build() ``` - - -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. ```swift -let limit = 10; -let guid = "cometchat-guid-11" +let limit = 30 +let guid = "cometchat-guid-1" -let bannedGroupMembersRequest = BannedGroupMembersRequest.BannedGroupMembersRequestBuilder(guid: guid).set(limit: limit).build(); +let bannedGroupMembersRequest = BannedGroupMembersRequest.BannedGroupMembersRequestBuilder(guid: guid) + .set(limit: limit) + .build() bannedGroupMembersRequest.fetchNext(onSuccess: { (groupMembers) in - - for bannedMember in groupMembers { - - print("Group Member fetched successfully. " + bannedMember.stringValue()) - } - -}) { (error) in - - print("Banned Group Member list fetching failed with error: " + error!.errorDescription); -} + for bannedMember in groupMembers { + print("Banned member: \(bannedMember.stringValue())") + } +}, onError: { (error) in + print("Error: \(error?.errorDescription)") +}) ``` - - ```objc -NSString *GUID = @"GUID"; +NSString *GUID = @"cometchat-guid-1"; NSInteger limit = 30; BannedGroupMembersRequest *bannedGroupMemberRequest = [[[[BannedGroupMembersRequestBuilder alloc]initWithGuid:GUID] setLimitWithLimit:limit] build]; [bannedGroupMemberRequest fetchNextOnSuccess:^(NSArray * bannedMembers) { - for (GroupMember *member in bannedMembers) { - - NSLog(@"Group Member fetched successfully. %@",[member stringValue]); + NSLog(@"Banned member: %@", [member stringValue]); } - } onError:^(CometChatException * error) { - - NSLog(@"Banned Group Member list fetching failed with error: %@",[error ErrorDescription]); + NSLog(@"Error: %@", [error errorDescription]); }]; ``` - - -## Real-Time Group Member Kicked/Banned Events +## Real-Time Kick/Ban/Unban Events -In order to receive user Events for kick/ban/unban you must add protocol conformance `CometChatGroupDelegate` as shown for following methods: +Implement these `CometChatGroupDelegate` 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. methods of the `CometChatGroupDelegate`. +| Method | Triggered When | +|--------|----------------| +| `onGroupMemberKicked()` | A member is kicked | +| `onGroupMemberBanned()` | A member is banned | +| `onGroupMemberUnbanned()` | A member is unbanned | ```swift -extension AppDelegate: CometChatGroupDelegate { - - func onGroupMemberKicked(action: ActionMessage, kickedUser: User, kickedBy: User, kickedFrom: Group) { - - print("\(kickedUser.name) kicked from the group \(kickedFrom.name) by \(kickedBy.name).") - } - - func onGroupMemberBanned(action: ActionMessage, bannedUser: User, bannedBy: User, bannedFrom: Group) { - - print("\(bannedUser.name) banned from the group \(bannedFrom.name) by \(bannedBy.name).") - } - - func onGroupMemberUnbanned(action: ActionMessage, unbannedUser: User, unbannedBy: User, unbannedFrom: Group) { - - print("\(unbannedUser.name) unbanned from the group \(unbannedFrom.name) by \(unbannedBy.name).") - } +class ViewController: UIViewController, CometChatGroupDelegate { + + override func viewDidLoad() { + super.viewDidLoad() + CometChat.groupdelegate = self + } + + func onGroupMemberKicked(action: ActionMessage, kickedUser: User, kickedBy: User, kickedFrom: Group) { + print("\(kickedUser.name ?? "") kicked from \(kickedFrom.name ?? "") by \(kickedBy.name ?? "")") + } + + func onGroupMemberBanned(action: ActionMessage, bannedUser: User, bannedBy: User, bannedFrom: Group) { + print("\(bannedUser.name ?? "") banned from \(bannedFrom.name ?? "") by \(bannedBy.name ?? "")") + } + + func onGroupMemberUnbanned(action: ActionMessage, unbannedUser: User, unbannedBy: User, unbannedFrom: Group) { + print("\(unbannedUser.name ?? "") unbanned from \(unbannedFrom.name ?? "") by \(unbannedBy.name ?? "")") + } } ``` - - ```objc @interface ViewController () - @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; - [CometChat setGroupdelegate:self]; - } -- (void)onGroupMemberBannedWithAction:(Action *)action bannedUser:(User * _Nonnull)bannedUser bannedBy:(User * _Nonnull)bannedBy bannedFrom:(Group * _Nonnull)bannedFrom { - // user was unbanned + +- (void)onGroupMemberKickedWithAction:(Action *)action kickedUser:(User *)kickedUser kickedBy:(User *)kickedBy kickedFrom:(Group *)kickedFrom { + // User was kicked } -- (void)onGroupMemberKickedWithAction:(Action *)action kickedUser:(User * _Nonnull)kickedUser kickedBy:(User * _Nonnull)kickedBy kickedFrom:(Group * _Nonnull)kickedFrom { - // user was kicked +- (void)onGroupMemberBannedWithAction:(Action *)action bannedUser:(User *)bannedUser bannedBy:(User *)bannedBy bannedFrom:(Group *)bannedFrom { + // User was banned } -- (void)onGroupMemberUnbannedWithAction:(Action *)action unbannedUser:(User * _Nonnull)unbannedUser unbannedBy:(User * _Nonnull)unbannedBy unbannedFrom:(Group * _Nonnull)unbannedFrom { - // user was unbanned +- (void)onGroupMemberUnbannedWithAction:(Action *)action unbannedUser:(User *)unbannedUser unbannedBy:(User *)unbannedBy unbannedFrom:(Group *)unbannedFrom { + // User was unbanned } @end ``` - - + +Set delegate in `viewDidLoad()`: `CometChat.groupdelegate = self`. Remove delegate when view is dismissed to avoid memory leaks. + + ## 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 fetching previous messages, kick/ban/unban actions appear as [`Action`](/sdk/reference/messages#action) messages (a subclass of [`BaseMessage`](/sdk/reference/messages#basemessage)). -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. +**Kicked event:** -For group member kicked event, the details can be obtained using the below fields of the `Action` class- +| 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 | -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 +**Banned event:** -For group member banned event, the details can be obtained using the below fields of the `Action` class- +| 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 | -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 +**Unbanned event:** -For group member unbanned event, the details can be obtained using the below fields of the `Action` class- +| 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 | + +--- -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 +## 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/ios/groups-overview.mdx b/sdk/ios/groups-overview.mdx index 99e877026..4443d3dcb 100644 --- a/sdk/ios/groups-overview.mdx +++ b/sdk/ios/groups-overview.mdx @@ -3,8 +3,38 @@ title: "Groups" sidebarTitle: "Overview" --- + +| Field | Value | +| --- | --- | +| Key Class | `CometChat.Group` | +| Group Types | `Public`, `Private`, `Password` | +| Member Roles | `Admin`, `Moderator`, `Participant` | +| Key Methods | `createGroup()`, `joinGroup()`, `leaveGroup()`, `deleteGroup()` | +| Prerequisites | SDK initialized, user logged in | +| Related | [Create Group](/sdk/ios/create-group), [Join Group](/sdk/ios/join-group), [Retrieve Groups](/sdk/ios/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. Each group includes three kinds of users- admin, moderator, member. + +--- + +## 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/ios/increment-app-icon-badge-count.mdx b/sdk/ios/increment-app-icon-badge-count.mdx index fd5bd8392..628616e67 100644 --- a/sdk/ios/increment-app-icon-badge-count.mdx +++ b/sdk/ios/increment-app-icon-badge-count.mdx @@ -1,14 +1,18 @@ --- title: "Increment App Icon Badge Count" +description: "Guide to implementing app icon badge count updates using Notification Service Extension in iOS." --- + +- **Requires:** UNNotificationServiceExtension target in your app +- **Purpose:** Update badge count when push notification received +- **Implementation:** Override `didReceive(_:withContentHandler:)` in extension +- **Related:** [Push Notifications](/sdk/ios/push-notification-overview) · [Prepare for Background](/sdk/ios/prepare-your-app-for-background-updates) - - - + -This guide helps you to set up an incremented badge for the app icon using **Notification Service Extension**. +This guide helps you set up an incremented badge for the app icon using **Notification Service Extension**. *** @@ -18,18 +22,12 @@ This service grabs the data from the push notification payload, the user can mod In our case, we are modifying the data of the push notification and incrementing the badge count when a new push notification is received. -Let's begin to implement an incremented badge count for your app. - *** ### **Step 1: Add UNNotificationServiceExtension inside the app.** 1. Click on `File` --> `New` --> `Targets` --> `Application Extension` --> `Notification Service Extension`. - - - - @@ -44,7 +42,7 @@ Let's begin to implement an incremented badge count for your app. ### **Step 2: Setup App Groups.** -1 . Click on `Project` --> `Targets` --> `Your app Target` --> `Signing & Capabilities` --> `[+]` --> `App Groups`. +1. Click on `Project` --> `Targets` --> `Your app Target` --> `Signing & Capabilities` --> `[+]` --> `App Groups`. @@ -62,13 +60,9 @@ Kindly, create a group name using the combination of 'group' and 'App's bundle i -3. Make sure you've selected the app group which you've created earlier. If it is selected then it will look like a below-mentioned image. - - - - +3. Make sure you've selected the app group which you've created earlier. -4. Click on `Project` --> `Targets` --> `Notification Service Extension Target` --> `Signing & Capabilities` --> \[+] --> `App Groups`. +4. Click on `Project` --> `Targets` --> `Notification Service Extension Target` --> `Signing & Capabilities` --> [+] --> `App Groups`. @@ -91,7 +85,7 @@ Kindly, create a group name using the combination of 'group' and 'App's bundle i ```swift func applicationWillEnterForeground(_ application: UIApplication) { - UserDefaults(suiteName: "group.com.yourApp.bundleId")?.set(1, forKey: "count") + UserDefaults(suiteName: "group.com.yourApp.bundleId")?.set(1, forKey: "count") UIApplication.shared.applicationIconBadgeNumber = 0 } @@ -113,27 +107,27 @@ func applicationWillEnterForeground(_ application: UIApplication) { import UserNotifications class NotificationService: UNNotificationServiceExtension { - + var contentHandler: ((UNNotificationContent) -> Void)? var bestAttemptContent: UNMutableNotificationContent? let defaults = UserDefaults(suiteName: "group.com.yourApp.bundleId") - + override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { self.contentHandler = contentHandler bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) var count: Int = defaults?.value(forKey: "count") as! Int if let bestAttemptContent = bestAttemptContent { - bestAttemptContent.title = "\\(bestAttemptContent.title) " - bestAttemptContent.body = "\\(bestAttemptContent.body) " + bestAttemptContent.title = "\(bestAttemptContent.title) " + bestAttemptContent.body = "\(bestAttemptContent.body) " bestAttemptContent.badge = count as? NSNumber count = count + 1 defaults?.set(count, forKey: "count") contentHandler(bestAttemptContent) } } - + override func serviceExtensionTimeWillExpire() { - + if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent { contentHandler(bestAttemptContent) } @@ -152,3 +146,22 @@ We have implemented it in our push notification sample app. You can download the [Download Push Notification Sample App](https://github.com/cometchat-pro-samples/ios-swift-push-notification-app/archive/master.zip) Or else [view it on Githhub](https://github.com/cometchat/cometchat-push-notification-app-ios). + +--- + +## Next Steps + + + + Set up push notifications for your iOS app + + + Mark messages as delivered via push notification + + + Programmatically remove delivered notifications + + + Keep real-time connection alive in background + + diff --git a/sdk/ios/interactive-messages.mdx b/sdk/ios/interactive-messages.mdx index 8ac2fcbd9..9076366b0 100644 --- a/sdk/ios/interactive-messages.mdx +++ b/sdk/ios/interactive-messages.mdx @@ -1,300 +1,329 @@ --- title: "Interactive Messages" +sidebarTitle: "Interactive Messages" +description: "Create and send interactive messages (forms, cards, schedulers) using the CometChat iOS SDK." --- + +| Method | Description | +| --- | --- | +| `sendInteractiveMessage(message:)` | Send an interactive message | +| `InteractiveMessage()` | Create an interactive message object | +| `InteractionGoal()` | Define completion criteria | -`InteractiveMessage` +```swift +let interMessage = InteractiveMessage() +interMessage.messageCategory = .interactive +interMessage.type = "form" +interMessage.receiverType = .user +interMessage.receiverUid = "cometchat-uid-2" +interMessage.interactiveData = ["title": "Contact Form", "formFields": [...]] -### InteractiveMessage +CometChat.sendInteractiveMessage(message: interMessage, onSuccess: { msg in }, onError: { err in }) -`InteractiveMessage` is a chat message with embedded interactive content. It can contain various properties: +// Listen for interactive events (CometChatMessageDelegate) +func onInteractiveMessageReceived(_ message: InteractiveMessage) { } +func onInteractionGoalCompleted(_ message: InteractiveMessage) { } +``` + +## InteractiveMessage Properties + +| Property | Type | Description | +|----------|------|-------------| +| receiverUid | `String` | UID or GUID of recipient | +| receiverType | `ReceiverType` | `.user` or `.group` | +| type | `String` | `form`, `card`, `scheduler`, or custom | +| interactiveData | `[String: Any]` | JSON structure for content | +| allowSenderInteraction | `Bool` | Can sender interact (default: false) | +| interactionGoal | `InteractionGoal` | Completion criteria | +| messageCategory | `MessageCategory` | `.interactive` | -| Parameter | Description | -| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| receiverId | The `UID` or `GUID` of the recipient | -| 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) | -| messageType | The type of the message that needs to be sent | -| interactiveData | A JSONObject holding structured data for the interactive element. | -| allowSenderInteraction | A boolean determining whether the message sender can interact with the message by default it is set to false. | -| interactionGoal | An `InteractionGoal` object encapsulating the intended outcome of interacting with the `InteractiveMessage` by default it is set to none | +--- -### Interaction +## Interaction Goal Types -An `Interaction` represents a user action involved with an `InteractiveMessage`. It includes: +| Type | Description | Value | +|------|-------------|-------| +| Any Action | Goal completed if any interaction occurs | `.anyAction` | +| Any Of | Goal achieved if any specified interaction occurs | `.anyOf` | +| All Of | Goal completed when all specified interactions occur | `.allOf` | +| None | Goal is never completed | `.none` | -* `elementId`: An identifier for a specific interactive element. -* `interactedAt`: A timestamp indicating when the interaction occurred. +--- -### Goal Completion +## Form Element Types -A key feature of `InteractiveMessage` is checking whether a user's interactions with the message meet the defined `InteractionGoal` +| Element Type | Description | +|--------------|-------------| +| textInput | Single or multi-line text input | +| dropdown | Dropdown select with options | +| checkbox | Multiple selection checkboxes | +| radio | Single selection radio buttons | +| singleSelect | Single selection list | +| button | Action button (submit, navigate) | -| | | | -| -------------------------------- | ---------------------------------------------------------------------- | ----------------------------- | -| **Any Interaction** | The goal is considered completed if there is at least one interaction. | InteractionGoalType.anyAction | -| **Any of Specific Interactions** | The goal is achieved if any of the specified interactions occurred. | InteractionGoalType.anyOf | -| **All of Specific Interactions** | The goal is completed when all specified interactions occur. | InteractionGoalType.allOf | -| **None** | The goal is never completed | InteractionGoalType.none | +--- -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: +## Button Action Types -### Interaction +| Action Type | Description | +|-------------|-------------| +| urlNavigation | Opens a URL in browser | +| apiAction | Makes an API call with specified parameters | +| customAction | Custom action handled by app | -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. +## Send Form Interactive Message -### Goal Completion + + +```swift +let interMessage = InteractiveMessage() +interMessage.messageCategory = .interactive +interMessage.type = "form" +interMessage.receiverType = .user +interMessage.receiverUid = "cometchat-uid-2" +interMessage.allowSenderInteraction = true + +interMessage.interactiveData = [ + "title": "Contact Form", + "formFields": [ + [ + "elementId": "name_field", + "elementType": "textInput", + "label": "Name", + "optional": false + ], + [ + "elementId": "country_dropdown", + "elementType": "dropdown", + "label": "Country", + "options": [ + ["label": "USA", "value": "usa"], + ["label": "UK", "value": "uk"], + ["label": "India", "value": "india"] + ] + ] + ], + "submitElement": [ + "elementId": "submit_btn", + "elementType": "button", + "buttonText": "Submit", + "disableAfterInteracted": true + ], + "goalCompletionText": "Thank you for submitting!" +] + +let goal = InteractionGoal() +goal.elementIds = ["submit_btn"] +goal.interactionType = .anyOf +interMessage.interactionGoal = goal + +CometChat.sendInteractiveMessage(message: interMessage, onSuccess: { message in + print("Interactive message sent: \(message)") +}, onError: { error in + print("Error: \(error?.errorDescription ?? "")") +}) +``` + + -A key feature of `InteractiveMessage` is checking whether a user's interactions with the message meet the defined `InteractionGoal` +--- -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: +## Send Card Interactive Message -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. + + +```swift +let interMessage = InteractiveMessage() +interMessage.messageCategory = .interactive +interMessage.type = "card" +interMessage.receiverType = .user +interMessage.receiverUid = "cometchat-uid-2" +interMessage.allowSenderInteraction = true + +interMessage.interactiveData = [ + "title": "Product Card", + "subtitle": "Special Offer", + "text": "Check out this amazing product with 20% discount!", + "imageUrl": "https://example.com/product.png", + "cardActions": [ + [ + "elementId": "buy_btn", + "elementType": "button", + "buttonText": "Buy Now", + "action": [ + "actionType": "urlNavigation", + "url": "https://example.com/buy" + ] + ], + [ + "elementId": "details_btn", + "elementType": "button", + "buttonText": "View Details", + "action": [ + "actionType": "urlNavigation", + "url": "https://example.com/details" + ] + ] + ] +] -### InteractionGoal +let goal = InteractionGoal() +goal.elementIds = ["buy_btn", "details_btn"] +goal.interactionType = .anyOf +interMessage.interactionGoal = goal -The `InteractionGoal` represents the desired outcome of an interaction with an `InteractiveMessage`. It includes: +CometChat.sendInteractiveMessage(message: interMessage, onSuccess: {...}, onError: {...}) +``` + + -* `elementIds`: A list of identifiers for the interactive elements. -* `type`: The type of interaction goal from the `CometChatConstants`. +--- -### Sending InteractiveMessages +## Send Scheduler 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. + + +```swift +let interMessage = InteractiveMessage() +interMessage.messageCategory = .interactive +interMessage.type = "scheduler" +interMessage.receiverType = .user +interMessage.receiverUid = "cometchat-uid-2" +interMessage.allowSenderInteraction = true + +interMessage.interactiveData = [ + "title": "Schedule a Meeting", + "duration": 30, + "bufferTime": 5, + "availability": [ + "monday": ["09:00-12:00", "14:00-17:00"], + "tuesday": ["09:00-12:00", "14:00-17:00"], + "wednesday": ["09:00-12:00", "14:00-17:00"] + ], + "scheduleElement": [ + "elementId": "schedule_btn", + "elementType": "button", + "buttonText": "Schedule", + "disableAfterInteracted": true + ], + "goalCompletionText": "Meeting scheduled successfully!" +] + +CometChat.sendInteractiveMessage(message: interMessage, onSuccess: {...}, onError: {...}) +``` + + + +--- -Here is an example of how to use it: +## Send Form to Group ```swift let interMessage = InteractiveMessage() - interMessage.messageCategory = .interactive - - let jsonString:[String:Any] = [ - "goalCompletionText": "Goal completed YAY", - "title":"By Shantanu", - "formFields":[ - [ - "defaultValue" : "", - "elementId" : "element1", - "elementType" : "textInput", - "label" : "Name", - "maxLines" : 1, - "optional" : false - ], - [ - "elementId" : "element2", - "elementType" : "textInput", - "label" : "Last Name", - "maxLines" : 1, - "optional" : false - ], - [ - "defaultValue" : "", - "elementId" : "element3", - "elementType" : "textInput", - "label" : "Address", - "maxLines" : 5, - "optional" : false - ], - [ - "defaultOption" : "", - "elementId" : "element4", - "elementType" : "dropdown", - "label" : "Country", - "optional" : false, - "options" : [ - [ - "label" : "INDIA", - "value" : "option1" - ], - [ - "label" : "AUSTRALIA", - "value" : "option2" - ], - [ - "label" : "RUSSIA", - "value" : "option3" - ], - [ - "label" : "AMERICA", - "value" : "option4" - ] - ] - ], - [ - "defaultValue" : [ - ], - "elementId" : "element5", - "elementType" : "checkbox", - "label" : "Country", - "optional" : false, - "options" : [ - [ - "label" : "INDIA", - "value" : "option1" - ], - [ - "label" : "AUSTRALIA", - "value" : "option2" - ], - [ - "label" : "RUSSIA", - "value" : "option3" - ], - [ - "label" : "AMERICA", - "value" : "option4" - ] - ] - ], - [ - "defaultValue" : "", - "elementId" : "element6", - "elementType" : "singleSelect", - "label" : "Country", - "optional" : false, - "options" : [ - [ - "label" : "INDIA", - "value" : "option1" - ], - [ - "label" : "AUSTRALIA", - "value" : "option2" - ] - ] - ], - [ - "defaultValue" : "option1", - "elementId" : "element7", - "elementType" : "radio", - "label" : "Country", - "optional" : false, - "options" : [ - [ - "label" : "INDIA", - "value" : "option1" - ], - [ - "label" : "AUSTRALIA", - "value" : "option2" - ], - [ - "label" : "RUSSIA", - "value" : "option3" - ], - [ - "label" : "AMERICA", - "value" : "option4" - ] - ] - ], - [ - "action" : [ - "actionType" : "urlNavigation", - "url" : "https://www.cometchat.com/" - ], - "buttonText" : "About us", - "disableAfterInteracted" : false, - "elementId" : "element9", - "elementType" : "button" +interMessage.messageCategory = .interactive +interMessage.type = "form" +interMessage.receiverType = .group +interMessage.receiverUid = "cometchat-guid-1" +interMessage.allowSenderInteraction = true + +interMessage.interactiveData = [ + "title": "Group Poll", + "formFields": [ + [ + "elementId": "poll_radio", + "elementType": "radio", + "label": "What's your favorite?", + "optional": false, + "options": [ + ["label": "Option A", "value": "a"], + ["label": "Option B", "value": "b"], + ["label": "Option C", "value": "c"] ] - ], - "submitElement" : [ - "action" : [ - "actionType" : "apiAction", - "dataKey" : "CometChatData", - "headers" : [ - "Content-Type" : "application/json", - "apiKey" : "5797f2d3d103d7d78f085eb46bfd14d5c45ddfdf", - "appId" : "10893f2ae68f59", - "onBehalfOf" : "shantanu" - ], - "method" : "POST", - "payload" : [ - "category" : "message", - "data" : [ - "text" : "Thanks For filling the Form!" - ], - "receiver" : "group_1695921003310", - "receiverType" : "group", - "type" : "text" - ] as [String : Any], - "url" : "https://10893f2ae68f59.api-us.cometchat-staging.com/v3.0/messages" - ] as [String : Any], - "buttonText" : "Submit", - "disableAfterInteracted" : true, - "elementId" : "element8", - "elementType" : "button" - ] as [String : Any] ] - interMessage.interactiveData = jsonString - let goal = InteractionGoal() - goal.elementIds = ["element9","element8"] - goal.interactionType = .allOf - - interMessage.interactionGoal = goal - interMessage.allowSenderInteraction = true - interMessage.type = "form" - interMessage.receiverType = .user - interMessage.receiverUid = "cometchat-uid-1" - interMessage.muid = "1697025959995609" - interMessage.senderUid = CometChat.getLoggedInUser()?.uid ?? "" - interMessage.sender = CometChat.getLoggedInUser() - - CometChat.sendInteractiveMessage(message: interMessage, onSuccess: { - succes in - print("successs",succes) - interMessage.sentAt = Int(Date().timeIntervalSince1970) - }, onError: { - error in - print("errorr",error?.description) - }) + ], + "submitElement": [ + "elementId": "vote_btn", + "elementType": "button", + "buttonText": "Vote", + "disableAfterInteracted": true + ] +] + +CometChat.sendInteractiveMessage(message: interMessage, onSuccess: {...}, onError: {...}) ``` - - -### Event Listeners +--- + +## Interaction Object Properties + +| Property | Type | Description | +|----------|------|-------------| +| elementId | `String` | ID of interacted element | +| interactedAt | `Double` | Timestamp of interaction | -CometChat SDK provides event listeners to handle real-time events related to `InteractiveMessage`. +--- -### On InteractiveMessage Received +## InteractionGoal Object Properties -The `onInteractiveMessageReceived` event listener is triggered when an `InteractiveMessage` is received. +| Property | Type | Description | +|----------|------|-------------| +| elementIds | `[String]` | IDs of target elements | +| interactionType | `InteractionGoalType` | `.anyAction`, `.anyOf`, `.allOf`, `.none` | -Here is an example: +--- + +## Real-time Interactive Message Events + +To receive interactive message events, implement `CometChatMessageDelegate`: ```swift -class DemoClass : CometChatMessageDelegate { +class YourClass: CometChatMessageDelegate { + init() { - CometChat.addMessageListener("sdk-listener", self) + CometChat.addMessageListener("listener-id", self) + } + + func onInteractiveMessageReceived(_ message: InteractiveMessage) { + print("Interactive message received") + print("Type: \(message.type ?? "")") + print("Interactive Data: \(message.interactiveData ?? [:])") } - public func onInteractiveMessageReceived(_ baseMessage: BaseMessage) { - //TODO implement onInteractiveMessageReceived event + + func onInteractionGoalCompleted(_ message: InteractiveMessage) { + print("Interaction goal completed") + print("Message ID: \(message.id)") } } ``` - - -### On Interaction Goal Completed - -The `onInteractionGoalCompleted` event listener is invoked when an interaction goal is achieved. -Here is an example: - -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 `InteractiveMessage`s 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 + + + Add emoji reactions to messages + + + Mention specific users in messages + + diff --git a/sdk/ios/join-group.mdx b/sdk/ios/join-group.mdx index 88d05b124..fcbda076b 100644 --- a/sdk/ios/join-group.mdx +++ b/sdk/ios/join-group.mdx @@ -1,119 +1,139 @@ --- 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 iOS SDK." --- + +```swift +// Join a public group +CometChat.joinGroup(GUID: "GUID", groupType: .public, password: nil, + onSuccess: { group in }, onError: { error in }) + +// Join a password-protected group +CometChat.joinGroup(GUID: "GUID", groupType: .password, password: "password123", + onSuccess: { group in }, onError: { error in }) + +// Listen for member joined events via CometChatGroupDelegate +func onGroupMemberJoined(action: ActionMessage, joinedUser: User, joinedGroup: Group) { } +``` + + +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 -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. ```swift -let guid = "cometchat-guid-11"; -let password = nil; // mandatory in case of password protected group type +let guid = "cometchat-guid-11" +let password: String? = nil // mandatory in case of password protected group type CometChat.joinGroup(GUID: guid, groupType: .public, password: nil, onSuccess: { (group) in - - print("Group joined successfully. " + group.stringValue()) - -}) { (error) in - - print("Group joining failed with error:" + error!.errorDescription); -} + print("Group joined successfully. " + group.stringValue()) +}, onError: { (error) in + print("Group joining failed with error:" + error!.errorDescription) +}) ``` - - ```objc NSString *guid = @"cometchat-guid-101"; -NSString *password = nil ; // mandatory in case of password protected group type +NSString *password = nil; // mandatory in case of password protected group type [CometChat joinGroupWithGUID:guid groupType:groupTypePublic password:password onSuccess:^(Group * group) { - - // Success - NSLog(@"Group joined successfully: %@",[group stringValue]); - + NSLog(@"Group joined successfully: %@", [group stringValue]); } onError:^(CometChatException * error) { - - // Error - NSLog(@"Group joining failed with exception: %@",[error errorDescription]) + NSLog(@"Group joining failed with exception: %@", [error errorDescription]); }]; ``` - - -The `joinGroup()` method takes four 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. .public .private .password | -| password | The password is mandatory in case of a `.password` protected the group. | +| Parameter | Description | +| --------- | ----------- | +| `GUID` | The GUID of the group to join | +| `groupType` | `.public`, `.password`, or `.private` | +| `password` | Required for password-protected groups | -Once you have joined a group successfully, you can send and receive messages in that group. +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. -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. +The method returns a [`Group`](/sdk/reference/entities#group) object with `hasJoined` set to `true`. ## Real-time Group Member Joined Events -*In other words, as a recipient, how do I know when someone joins a group?* - -To receive Real-Time Events for the same, you need to implement the `onMemberAddedToGroup()` method of the `GroupListener` class. +Register a `CometChatGroupDelegate` to receive events when members join. ```swift -extension AppDelegate: CometChatGroupDelegate { - - func onMemberAddedToGroup(action: ActionMessage, addedBy: User, addedUser: User, addedTo: Group) { - //When any member is added in the group this function will be called - } - +class ViewController: UIViewController, CometChatGroupDelegate { + + override func viewDidLoad() { + super.viewDidLoad() + CometChat.groupdelegate = self + } + + func onGroupMemberJoined(action: ActionMessage, joinedUser: User, joinedGroup: Group) { + print("\(joinedUser.name ?? "") joined \(joinedGroup.name ?? "")") + } + + func onMemberAddedToGroup(action: ActionMessage, addedBy: User, addedUser: User, addedTo: Group) { + print("\(addedUser.name ?? "") was added to \(addedTo.name ?? "")") + } } ``` - - ```objc @interface ViewController () - @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; - [CometChat setGroupdelegate:self]; } - (void)onMemberAddedToGroup:(Action *)action addedBy:(User * _Nonnull)addedBy addedUser:(User * _Nonnull)addedUser addedTo:(Group * _Nonnull)addedTo { - //When any member is added in the group this function will be called + // When any member is added in the group this function will be called } @end ``` - - -## Missed Group Member Joined Events + +Always remove group listeners when they're no longer needed (e.g., on view dismissal). Failing to remove listeners can cause memory leaks and duplicate event handling. + -*In other words, as a member of a group, how do I know if someone joins the group when my app is not running?* +## Missed Group Member Joined Events -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 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 -For the group member joined the 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 +## 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/ios/key-concepts.mdx b/sdk/ios/key-concepts.mdx index 2e809f549..b258dc89e 100644 --- a/sdk/ios/key-concepts.mdx +++ b/sdk/ios/key-concepts.mdx @@ -2,7 +2,19 @@ title: "Key Concepts" --- + +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 +137,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/ios/message-structure-and-hierarchy). + +--- + +## Next Steps + + + + Install and initialize the CometChat iOS SDK + + + Log users in and manage auth tokens + + + Send your first text or media message + + + Create and manage group conversations + + diff --git a/sdk/ios/launch-call-screen-on-tap-of-push-notification.mdx b/sdk/ios/launch-call-screen-on-tap-of-push-notification.mdx index 79fa30b74..f58f8764f 100644 --- a/sdk/ios/launch-call-screen-on-tap-of-push-notification.mdx +++ b/sdk/ios/launch-call-screen-on-tap-of-push-notification.mdx @@ -1,14 +1,23 @@ --- title: "Launch Call Screen On Tap Of Push Notification" +description: "Guide to launching the incoming call screen from UI Kit when user taps a call push notification." --- + +- **Requires:** CometChat SDK and UI Kit both configured +- **Implementation:** Handle notification tap in `AppDelegate` or `SceneDelegate` +- **Parse payload:** Extract call session ID from notification payload +- **Launch:** Present `CometChatIncomingCall` view controller +- **Related:** [Ringing](/sdk/ios/default-calling) · [Push Notifications](/sdk/ios/push-notification-overview) · [UI Kit](/ui-kit/ios/overview) + + -This guide helps you to launch an incoming call screen from the UI Kit library on receiving an incoming call notification. +This guide helps you launch an incoming call screen from the UI Kit library on receiving an incoming call notification. @@ -20,7 +29,7 @@ CometChat SDK & UI Kit both need to be configured before launching the call scre ## Step 1. Process push notification payload and grab `Call` object -To present an incoming call screen, firstly you will need a `Call` object. You can grab this from the push notification payload itself of incoming call notification. You need to call `CometChat.processMessage()` method to process push notification payload. +To present an incoming call screen, you need a `Call` object. You can grab this from the push notification payload of the incoming call notification using `CometChat.processMessage()`. @@ -51,9 +60,9 @@ To present an incoming call screen, firstly you will need a `Call` object. You c -## Step 2 . Launch call screen (Method 1) +## Step 2. Launch call screen (Method 1) -You can directly launch the view controller from the app delegate once you receive Call Object. +You can directly launch the view controller from the app delegate once you receive the Call Object. @@ -80,14 +89,14 @@ You can directly launch the view controller from the app delegate once you recei -If you are facing any difficulties while launching the Call Screen from App Delegate, then you can use another method. +If you are facing difficulties launching the Call Screen from App Delegate, use the alternative method below. -## Step 2 . Launch call screen (Method 2) +## Step 2. Launch call screen (Method 2) -You can launch the call screen from your base view controller instead of launching it from the App Delegate. This method uses NotificationCenter to trigger and present Call Screen. +You can launch the call screen from your base view controller using NotificationCenter. -1. In this method you need to fire notification after you receive Call Object. -2. In Notification's user info you can pass Call Object to that desired notification. +1. Fire a notification after you receive the Call Object. +2. Pass the Call Object in the notification's user info. ### Trigger notification from App Delegate @@ -105,7 +114,7 @@ if let call = baseMessage as? Call {
-3. On the other hand, you need to observe for the above notification in your base view controller +3. Observe the notification in your base view controller. @@ -152,3 +161,22 @@ class BaseViewController : UIViewController {
+ +--- + +## Next Steps + + + + Set up default calling with ringing + + + Set up push notifications for your iOS app + + + Open chat window from push notification tap + + + Pre-built UI components for iOS + + diff --git a/sdk/ios/launch-chat-window-on-tap-of-push-notification.mdx b/sdk/ios/launch-chat-window-on-tap-of-push-notification.mdx index 95bb11ea8..0efc8ab26 100644 --- a/sdk/ios/launch-chat-window-on-tap-of-push-notification.mdx +++ b/sdk/ios/launch-chat-window-on-tap-of-push-notification.mdx @@ -1,14 +1,23 @@ --- title: "Launch Chat Window On Tap Of Push Notification" +description: "Guide to launching the chat window from UI Kit when user taps a message push notification." --- + +- **Requires:** CometChat SDK and UI Kit both configured +- **Implementation:** Handle notification tap in `AppDelegate` or `SceneDelegate` +- **Parse payload:** Extract sender UID or group GUID from notification payload +- **Launch:** Present `CometChatMessages` view controller with user/group +- **Related:** [Receive Message](/sdk/ios/receive-message) · [Push Notifications](/sdk/ios/push-notification-overview) · [UI Kit](/ui-kit/ios/overview) + + -This guide helps you to launch a chat window from the UI Kit library on receiving a new message notification. +This guide helps you launch a chat window from the UI Kit library on receiving a new message notification. @@ -20,7 +29,7 @@ CometChat SDK & UI Kit both need to be configured before launching the chat wind ## Step 1. Process push notification payload and grab `User` or `Group` object -To present a chat window, firstly you will need a `User` or a `Group` object. You can grab this from the push notification payload itself of incoming message notification. You need to call `CometChat.processMessage()` method to process push notification payload. +To present a chat window, you need a `User` or a `Group` object. You can grab this from the push notification payload using `CometChat.processMessage()`. @@ -51,12 +60,12 @@ To present a chat window, firstly you will need a `User` or a `Group` object. Yo -## Step 2 . Launch Chat Window +## Step 2. Launch Chat Window -You can launch the chat window from your base view controller after you tap on the Message Notification. This method uses NotificationCenter to trigger and present a chat window. +Launch the chat window from your base view controller using NotificationCenter. -1. In this method you need to fire notification after you receive the `User` or `Group` Object. -2. In Notification's user info you can pass `User` or` Group` Object to that desired notification. +1. Fire a notification after you receive the `User` or `Group` Object. +2. Pass the `User` or `Group` Object in the notification's user info. ### Trigger notification from App Delegate @@ -86,7 +95,7 @@ if let message = baseMessage as? BaseMessage {
-3. On the other hand, you need to observe for the above notification in your base view controller. +3. Observe the notification in your base view controller. @@ -146,3 +155,22 @@ class BaseViewController : UIViewController {
+ +--- + +## Next Steps + + + + Handle incoming messages in real time + + + Set up push notifications for your iOS app + + + Open call screen from push notification tap + + + Pre-built UI components for iOS + + diff --git a/sdk/ios/leave-group.mdx b/sdk/ios/leave-group.mdx index c45e30113..a003c1401 100644 --- a/sdk/ios/leave-group.mdx +++ b/sdk/ios/leave-group.mdx @@ -1,110 +1,132 @@ --- 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 iOS SDK." --- + +```swift +// Leave a group +CometChat.leaveGroup(GUID: "GUID", onSuccess: { response in }, onError: { error in }) + +// Listen for member left events +// Conform to CometChatGroupDelegate +func onGroupMemberLeft(action: ActionMessage, leftUser: User, leftGroup: Group) { } +``` + + +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/ios/transfer-group-ownership). + ## 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. + +| Parameter | Description | +|-----------|-------------| +| `GUID` | The GUID of the group you would like to leave | ```swift -let guid = "cometchat-guid-11"; +let guid = "cometchat-guid-11" CometChat.leaveGroup(GUID: guid, onSuccess: { (response) in - - print("Left group successfully.") - -}) { (error) in - - print("Group leaving failed with error:" + error!.errorDescription); -} + print("Left group successfully.") +}, onError: { (error) in + print("Group leaving failed with error:" + error!.errorDescription) +}) ``` - - ```objc NSString *guid = @"cometchat-guid-101"; [CometChat leaveGroupWithGUID:guid onSuccess:^(NSString * response) { - - NSLog(@"Left group successfully. %@",response); - + NSLog(@"Left group successfully. %@", response); } onError:^(CometChatException * error) { - - NSLog(@"Group leaving failed with error: %@",[error errorDescription]); + NSLog(@"Group leaving failed with error: %@", [error errorDescription]); }]; ``` - - +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 -| Parameter | Description | -| --------- | -------------------------------------------- | -| GUID | The UID of the group you would like to leave | - -Once a group is left, the user will not receive any updates or messages pertaining to the group. - -## Real-time Leave Group Event - -*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 `CometChatGroupDelegate`. In order to receive user Events, you must add protocol conformance `CometChatGroupDelegate` as shown below : +Register a `CometChatGroupDelegate` to receive events when members leave. ```swift -extension AppDelegate: CometChatGroupDelegate { - - func onGroupMemberLeft(action: ActionMessage, leftUser: User, leftGroup: Group) { - - print("\(leftUser.name) left the group \(leftGroup.name).") - } +class ViewController: UIViewController, CometChatGroupDelegate { + + override func viewDidLoad() { + super.viewDidLoad() + CometChat.groupdelegate = self + } + + func onGroupMemberLeft(action: ActionMessage, leftUser: User, leftGroup: Group) { + print("\(leftUser.name ?? "") left the group \(leftGroup.name ?? "").") + } } ``` - - ```objc @interface ViewController () - @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; - [CometChat setGroupdelegate:self]; - } - (void)onGroupMemberLeftWithAction:(ActionMessage *)action leftUser:(User *)leftUser leftGroup:(Group *)leftGroup { - //user was left + // User left the group } -``` +@end +``` - -Do not forget to set your view controller as a CometChat delegate probably in `viewDidLoad()` as `CometChat.groupdelegate = self` + +Set delegate in `viewDidLoad()`: `CometChat.groupdelegate = self`. Remove delegate when view is dismissed to avoid memory leaks. + ## 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 fetching message history, leave events appear as [`Action`](/sdk/reference/messages#action) messages (a subclass of [`BaseMessage`](/sdk/reference/messages#basemessage)) with: -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. +| Field | Value/Type | Description | +|-------|------------|-------------| +| `action` | `"left"` | The action type | +| `actionBy` | [`User`](/sdk/reference/entities#user) | The user who left | +| `actionFor` | [`Group`](/sdk/reference/entities#group) | The group that was left | -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 +## 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/ios/login-listeners.mdx b/sdk/ios/login-listeners.mdx index 2041e436e..de4a497a4 100644 --- a/sdk/ios/login-listeners.mdx +++ b/sdk/ios/login-listeners.mdx @@ -1,8 +1,15 @@ --- title: "Login Listeners" +description: "Guide to monitoring login and logout events using the CometChat iOS SDK CometChatLoginDelegate." --- + +- **Set delegate:** `CometChat.logindelegate = self` (conform to `CometChatLoginDelegate`) +- **Delegate methods:** `onLoginSuccess(user:)`, `onLoginFailed(error:)`, `onLogoutSuccess()`, `onLogoutFailed(error:)` +- **Related:** [Authentication](/sdk/ios/authentication-overview) · [Connection Status](/sdk/ios/connection-status) · [Setup](/sdk/ios/setup) + + CometChat SDK provides you with a mechanism to get real-time status whenever a user logs into CometChat or logs out from CometChat. @@ -10,12 +17,12 @@ Login Listener provides you with the below 4 methods: | Delegate Method | Information | | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------- | -| onLoginSuccess(user: User) | This method is triggered when the user successfully logs into the CometChat SDK. It returns an Object of the User loggedIn. | -| onLoginFailed(error: CometChatException?) | This method is triggered when the user could not successfully log into the CometChat SDK. It returns an Object of the CometChatException. | +| onLoginSuccess(user: [User](/sdk/reference/entities#user)) | This method is triggered when the user successfully logs into the CometChat SDK. It returns an Object of the [User](/sdk/reference/entities#user) loggedIn. | +| onLoginFailed(error: [CometChatException](/sdk/reference/auxiliary#cometchatexception)?) | This method is triggered when the user could not successfully log into the CometChat SDK. It returns an Object of the [`CometChatException`](/sdk/reference/auxiliary#cometchatexception). | | onLogoutSuccess() | This method is called when the user successfully logs out from the CometChat SDK. It does not return anything. | -| onLogoutFailed(error: CometChatException?) | This method is triggered when the user could not successfully log out of the CometChat SDK. It returns an Object of the CometChatException. | +| onLogoutFailed(error: [CometChatException](/sdk/reference/auxiliary#cometchatexception)?) | This method is triggered when the user could not successfully log out of the CometChat SDK. It returns an Object of the [`CometChatException`](/sdk/reference/auxiliary#cometchatexception). | -In order to use the Delegate methods you must add protocol conformance `CometChatLoginDelegate` as `CometChat.logindelegate = self` . Here is the example of CometChatLoginDelegate: +In order to use the Delegate methods you must add protocol conformance `CometChatLoginDelegate` as `CometChat.logindelegate = self`: @@ -25,15 +32,15 @@ extension AppDelegate: CometChatLoginDelegate { func onLoginSuccess(user: User) { print("Login Success") } - + func onLoginFailed(error: CometChatException?) { print("Login Failed") } - + func onLogoutSuccess() { print("Logout Success") } - + func onLogoutFailed(error: CometChatException?) { print("Logout Failed") } @@ -52,27 +59,27 @@ extension AppDelegate: CometChatLoginDelegate { - (void)viewDidLoad { [super viewDidLoad]; - + [CometChat logindelegate:self]; } - (void)onLoginSuccess(user : User) { - + NSLog(@"onLoginSuccess"); } - (void)onLoginFailed(error : CometChatException) { - + NSLog(@"onLoginFailed"); } - (void)onLogoutSuccess() { - + NSLog(@"onLogoutSuccess"); } - (void)onLogoutFailed(error : CometChatException) { - + NSLog(@"onLogoutFailed"); } ``` @@ -80,3 +87,48 @@ extension AppDelegate: CometChatLoginDelegate { + +--- + +## Delegate Methods + +### onLoginSuccess(user: User) + +This method is triggered when the user successfully logs into the CometChat SDK. It returns a [`User`](/sdk/reference/entities#user) object containing all information about the logged-in user. + +--- + +### onLoginFailed(error: CometChatException?) + +This method is triggered when the user could not successfully log into the CometChat SDK. It returns a [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) object with error details. + +--- + +### onLogoutSuccess() + +This method is called when the user successfully logs out from the CometChat SDK. It does not return any data. + +--- + +### onLogoutFailed(error: CometChatException?) + +This method is triggered when the user could not successfully log out of the CometChat SDK. It returns a [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) object with error details. + +--- + +## Next Steps + + + + Login and authentication guide + + + Monitor the SDK connection state in real time + + + Complete reference for all SDK event delegates + + + SDK installation and initialization guide + + diff --git a/sdk/ios/managing-web-socket-connections-manually.mdx b/sdk/ios/managing-web-socket-connections-manually.mdx index 9fdfba9d8..24c89a813 100644 --- a/sdk/ios/managing-web-socket-connections-manually.mdx +++ b/sdk/ios/managing-web-socket-connections-manually.mdx @@ -1,8 +1,17 @@ --- title: "Managing Web Socket Connections Manually" +description: "Guide to manually controlling WebSocket connections in the CometChat iOS SDK for advanced use cases." --- + +- **Connect:** `CometChat.connect()` +- **Disconnect:** `CometChat.disconnect()` +- **Disable auto-connect:** `AppSettings.AppSettingsBuilder().autoEstablishSocketConnection(false).build()` +- **Use case:** Manual control for battery optimization or specific app flows +- **Related:** [Connection Status](/sdk/ios/connection-status) · [Connection Behaviour](/sdk/ios/web-socket-connection-behaviour) · [Setup](/sdk/ios/setup) + + ## Default SDK behaviour on login @@ -12,17 +21,17 @@ When the login method of the SDK is called, the SDK performs the below operation 2. Saves the details of the logged in user locally. 3. Creates a web-socket 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 makes sure that the logged in user starts receiving real-time messages as soon as he logs 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 web-socket 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. +If you wish to connect and disconnect to the web-socket server manually, refer to the section below. ## 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: +The CometChat SDK allows you to take control of the web-socket connection. Follow these 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: +1. While calling the init() function on the app startup, use the `autoEstablishSocketConnection()` method provided by the `AppSettingsBuilder` class. If set to `true`, the SDK manages the web-socket connection internally. If set to `false`, you handle it manually: @@ -31,7 +40,7 @@ let appSettings = AppSettings.AppSettingsBuilder() .setRegion(region: "us") .autoEstablishSocketConnection(false) .build() - + let _ = CometChat.init(appId:"1976246d33493296", appSettings: appSettings, onSuccess: { (Success) in @@ -63,7 +72,7 @@ AppSettings *appSettings = [[[appSettingBuilder autoEstablishSocketConnection:fa 2. You can manage the connection to the web-socket server using the `connect()` and `disconnect()` methods provided by the SDK. 3. **Connect to the web-socket 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. Make sure the user is logged in before calling this method (`CometChat.getLoggedInUser()`). Once connected, you will start receiving all real-time events for the logged in user. @@ -84,7 +93,7 @@ CometChat.connect(); 2. **Disconnect from the web-socket 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 to break the established connection. Once disconnected, you will stop receiving all real-time events. @@ -102,3 +111,22 @@ CometChat.disconnect(); + +--- + +## Next Steps + + + + Monitor the SDK connection state in real time + + + Understand default WebSocket connection lifecycle + + + Complete reference for all SDK event delegates + + + SDK installation and initialization guide + + diff --git a/sdk/ios/marking-delivered-with-push-notification.mdx b/sdk/ios/marking-delivered-with-push-notification.mdx index 8afbcb793..14047cf76 100644 --- a/sdk/ios/marking-delivered-with-push-notification.mdx +++ b/sdk/ios/marking-delivered-with-push-notification.mdx @@ -1,12 +1,21 @@ --- title: "Marking Delivered From Push Notification" +description: "Guide to marking messages as delivered using push notification payload with Notification Service Extension." --- + +- **Requires:** UNNotificationServiceExtension target in your app +- **Purpose:** Mark messages delivered even when app is in background/terminated +- **Implementation:** Call `CometChat.markAsDelivered()` in notification extension +- **Parse payload:** Extract message ID, sender ID, receiver type from notification +- **Related:** [Delivery & Read Receipts](/sdk/ios/delivery-read-receipts) · [Push Notifications](/sdk/ios/push-notification-overview) -Implementing the capability to mark a message as "delivered" through a push notification payload can prove to be a pivotal feature. This functionality serves as an accurate representation, confirming to the sender that their message has indeed reached its intended recipient, thereby enhancing the overall user experience. + -Setting up Mark as delivered from push notification in iOS requires to have Notification extension to your app project. So let's begin with adding a Notification extension to your app project. +Implementing the capability to mark a message as "delivered" through a push notification payload confirms to the sender that their message has reached its intended recipient, enhancing the overall user experience. + +Setting up Mark as delivered from push notification in iOS requires a Notification extension in your app project. @@ -16,7 +25,7 @@ If you already have a Notification extension on your project then you can skip t ### Setting up Notification extension -1. Navigate to your project’s target section and click on the plus iOS +1. Navigate to your project's target section and click on the plus iOS @@ -36,13 +45,13 @@ If you already have a Notification extension on your project then you can skip t * Your notification service extension is ready now, you can see that in the target list. Now we will create app group for the extension. This app group will be needed to share user default between the main application and notification service extension. -4. Click on the notification service extension name on the target list, then select Signing & Capabilities, then click on “+ Capability” from the top. Make sure All is selected besides it. +4. Click on the notification service extension name on the target list, then select Signing & Capabilities, then click on "+ Capability" from the top. Make sure All is selected besides it. -5. Then search for App Group and click on it. You can see a section of the app group section must have been added on the ‘Signing & Capabilities’. +5. Then search for App Group and click on it. You can see a section of the app group section must have been added on the 'Signing & Capabilities'. @@ -54,8 +63,8 @@ If you already have a Notification extension on your project then you can skip t -7. Now we will add the Capability of App Group on the main app’s target as well. Just repeat the same steps that you have done on the notification extension(from step 4). You have to select your main app from the target list, then as we did for the notification extension switch to ‘Signing & Capabilities’, then click on “+ Capability” from the top and select App Group. -8. Then select the same group ID that you have selected on the notification extension target’s app group. If it is not there in the suggested IDs, then add it by clicking on the plus icon. +7. Now add the Capability of App Group on the main app's target as well. Repeat the same steps from step 4 for your main app target. +8. Select the same group ID that you selected on the notification extension target's app group. @@ -90,11 +99,11 @@ end -All the setup is done, let’s see some code now. +All the setup is done, let's see some code now. ## Code for Mark as read -1. Firstly navigate to the cometchat initialization code on you project and add the group ID that you have selected on app groups on the AppSettingsBuilder. +1. Navigate to the CometChat initialization code in your project and add the group ID that you selected on app groups on the AppSettingsBuilder. @@ -110,22 +119,22 @@ let appSettings = AppSettings.AppSettingsBuilder() -2. Now navigate to your notification extension named group that is been created And open its swift file. -3. Then import CometChatSDK on that file and call these 2 functions on the didReceive(\_ request: , withContentHandler: ) function. +2. Navigate to your notification extension group and open its swift file. +3. Import CometChatSDK and call these 2 functions in the `didReceive(_:withContentHandler:)` function. ```swift override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { self.contentHandler = contentHandler - bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) + bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) CometChat.setExtensionGroupID(id: "group.com.comechatcalls.appgroup") //add you group id - + if let bestAttemptContent = bestAttemptContent { - + CometChat.markAsDelivered(withNotificationPayload: bestAttemptContent.userInfo) //send the payload here - + contentHandler(bestAttemptContent) } } @@ -135,7 +144,7 @@ override func didReceive(_ request: UNNotificationRequest, withContentHandler co -And we are finally done, run your notification extension by selecting the notification extension target from the run target on the top. +Run your notification extension by selecting the notification extension target from the run target on the top. @@ -146,3 +155,22 @@ And we are finally done, run your notification extension by selecting the notifi Run the main app target first and make sure you are receiving notifications there. And then run the notification extension target. + +--- + +## Next Steps + + + + Mark messages as delivered and read + + + Set up push notifications for your iOS app + + + Update app icon badge from push notifications + + + Programmatically remove delivered notifications + + diff --git a/sdk/ios/mentions.mdx b/sdk/ios/mentions.mdx index b2ea5ce05..5d423e387 100644 --- a/sdk/ios/mentions.mdx +++ b/sdk/ios/mentions.mdx @@ -1,207 +1,221 @@ --- title: "Mentions" +sidebarTitle: "Mentions" +description: "Send messages with user mentions, retrieve mentioned users, and filter messages by mention metadata using the CometChat iOS SDK." --- + +```swift +// Send a message with a mention (use <@uid:UID> format) +let msg = TextMessage(receiverUid: "UID", text: "Hello <@uid:cometchat-uid-1>", receiverType: .user) +CometChat.sendTextMessage(message: msg) { message in } onError: { error in } + +// Get mentioned users from a message +let mentionedUsers = message.mentionedUsers // Returns [User] +// Check if logged-in user was mentioned +let wasMentioned = message.mentionedMe // Returns Bool + +// Fetch messages with mention tag info +let request = MessagesRequest(builder: MessagesRequest.MessageRequestBuilder() + .set(uid: "UID").set(limit: 30).mentionsWithTagInfo(true)) +request.fetchPrevious { messages in } onError: { error in } +``` + 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. +## Mention Format + +| Format | Example | +|--------|---------| +| `<@uid:USER_UID>` | `<@uid:cometchat-uid-1>` | + +Example message text with mention: +``` +"Hello <@uid:cometchat-uid-1>, how are you?" +``` + +--- ## 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>"` +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>`. ```swift -let receiverID = "UID" -let messageText = "Hello, <@uid:cometchat-uid-1>" -let receiverType = CometChat.ReceiverType.user - -let textMessage = TextMessage(receiverUid: receiverID, text: messageText, receiverType: receiverType) - -CometChat.sendTextMessage(message:textMessage){ textMessage in - print("Message sent successfully: (textMessage.text), mentioned users: (textMessage.getMentionedUsers())") - } onError: { error in - print("Message sending failed with exception: (error?.errorDescription)") - } +let messageText = "Hello <@uid:cometchat-uid-1>, how are you?" +let textMessage = TextMessage(receiverUid: "cometchat-uid-2", text: messageText, receiverType: .user) + +CometChat.sendTextMessage(message: textMessage) { message in + print("Mentioned users: \(message.mentionedUsers)") +} onError: { error in + print("Error: \(error?.errorDescription)") +} ``` - - ```swift -let receiverID = "GUID" -let messageText = "Hello, cometchat-uid-1" -let receiverType = CometChat.ReceiverType.group - -let textMessage = TextMessage(receiverUid: receiverID, text: messageText, receiverType: receiverType) - -CometChat.sendTextMessage(message:textMessage){ textMessage in - print("Message sent successfully: (textMessage.text), mentioned users: (textMessage.getMentionedUsers())") - } onError: { error in - print("Message sending failed with exception: (error?.errorDescription)") - } +let messageText = "Hey <@uid:cometchat-uid-2>, check this out!" +let textMessage = TextMessage(receiverUid: "cometchat-guid-1", text: messageText, receiverType: .group) + +CometChat.sendTextMessage(message: textMessage) { message in + print("Mentioned users: \(message.mentionedUsers)") +} onError: { error in + print("Error: \(error?.errorDescription)") +} ``` - - - -You can mention user in text message and media messages captions - +You can mention users in text messages and media message 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. +## Fetch Mentioned Messages -The SDK allows you to fetch messages in a conversation where the logged-in user is mentioned. The SDK also has other optional filters such as tag info and blocked info. +By default, the SDK will fetch all messages irrespective of whether the logged-in user is mentioned or not. The SDK allows you to fetch messages with additional mention information. -| Setting | Description | -| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `mentionsWithTagInfo(bool value)` | If set to `true`, SDK will fetch a list of messages where users are mentioned and will also fetch the tags of the mentioned users. Default value is `false`. | -| `mentionsWithBlockedInfo(bool value)` | If set to `true`, SDK will fetch a list of messages where users are mentioned and will also fetch their blocked relationship with the logged-in user. Default value is `false`. | +| Setting | Description | +|---------|-------------| +| `mentionsWithTagInfo(true)` | Fetch messages with mentioned users' tags | +| `mentionsWithBlockedInfo(true)` | Fetch messages with blocked relationship info | ### Mentions With Tag Info -To get a list of messages in a conversation where users are mentioned along with the tags of the mentioned users. - ```swift -let UID = "cometchat-uid-1"; - - let messagesRequest = MessagesRequest(builder: MessagesRequest.MessageRequestBuilder().set(uid: UID).set(limit: 50).mentionsWithTagInfo(true)) - - - messagesRequest.fetchPrevious { fetchedMessages in - if let messages = fetchedMessages{ - for message in messages{ - for user in message.mentionedUsers{ - print("mentioned user tags: \(user.tags)") - } - } - } - } onError: { error in - if let err = error{ - print("\(err.errorDescription)") - } +let messagesRequest = MessagesRequest(builder: MessagesRequest.MessageRequestBuilder() + .set(uid: "cometchat-uid-2") + .set(limit: 50) + .mentionsWithTagInfo(true)) + +messagesRequest.fetchPrevious { messages in + for message in messages ?? [] { + for user in message.mentionedUsers { + print("User tags: \(user.tags)") } + } +} onError: { error in + print("Error: \(error?.errorDescription)") +} ``` - - ```swift - let GUID = "cometchat-guid-1"; - - let messagesRequest = MessagesRequest(builder: MessagesRequest.MessageRequestBuilder().set(guid: GUID).set(limit: 50).mentionsWithTagInfo(true)) - - - messagesRequest.fetchNext { fetchedMessages in - if let messages = fetchedMessages{ - for message in messages{ - for user in message.mentionedUsers{ - print("mentioned user tags: \(user.tags)") - } - } - } - } onError: { error in - if let err = error{ - print("\(err.errorDescription)") - } +let messagesRequest = MessagesRequest(builder: MessagesRequest.MessageRequestBuilder() + .set(guid: "cometchat-guid-1") + .set(limit: 50) + .mentionsWithTagInfo(true)) + +messagesRequest.fetchNext { messages in + for message in messages ?? [] { + for user in message.mentionedUsers { + print("User tags: \(user.tags)") } + } +} onError: { error in + print("Error: \(error?.errorDescription)") +} ``` - - ### 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. - ```swift -let UID = "cometchat-uid-1"; - - let messagesRequest = MessagesRequest(builder: MessagesRequest.MessageRequestBuilder().set(uid: UID).set(limit: 50).mentionsWithBlockedInfo(true)) - - - messagesRequest.fetchPrevious { fetchedMessages in - if let messages = fetchedMessages{ - for message in messages{ - for user in message.mentionedUsers{ - print("mentioned user has blocked me? \(user.hasBlockedMe)") - print("mentioned user is blocked by me? \(user.blockedByMe)") - } - } - } - } onError: { error in - if let err = error{ - print("\(err.errorDescription)") - } - } -``` - - - - -```swift -let GUID = "cometchat-guid-1"; - - let messagesRequest = MessagesRequest(builder: MessagesRequest.MessageRequestBuilder().set(guid: GUID).set(limit: 50).mentionsWithBlockedInfo(true)) - - - messagesRequest.fetchNext { fetchedMessages in - if let messages = fetchedMessages{ - for message in messages{ - for user in message.mentionedUsers{ - print("mentioned user has blocked me? \(user.hasBlockedMe)") - print("mentioned user is blocked by me? \(user.blockedByMe)") - } - } - } - } onError: { error in - if let err = error{ - print("\(err.errorDescription)") - } +let messagesRequest = MessagesRequest(builder: MessagesRequest.MessageRequestBuilder() + .set(uid: "cometchat-uid-2") + .set(limit: 50) + .mentionsWithBlockedInfo(true)) + +messagesRequest.fetchPrevious { messages in + for message in messages ?? [] { + for user in message.mentionedUsers { + print("Has blocked me: \(user.hasBlockedMe)") + print("Blocked by me: \(user.blockedByMe)") } + } +} onError: { error in + print("Error: \(error?.errorDescription)") +} ``` - - -## Get Users Mentioned In a Particular Message +--- -To retrieve the list of users mentioned in the particular message, you can use the `mentionedUsers` method on any `BaseMessage`. This method will return an array containing User objects of the mentioned users, or an empty array if no users were mentioned in the message. +## Get Users Mentioned In a Message + +To retrieve the list of users mentioned in a particular message. Returns an array of [`User`](/sdk/reference/entities#user) objects: ```swift -message.mentionedUsers +let mentionedUsers = message.mentionedUsers // Returns [User] ``` - - -## Check if Logged-in user has been mentioned +**Mentioned Users Array:** -To check if the logged-in user has been mentioned in a particular message we can use the `mentionedMe` method on any `BaseMessage`. This method will return a boolean value, `true` if the logged-in user has been mentioned, otherwise `false`. +| Index | UID | Name | +|-------|-----|------| +| 0 | `"cometchat-uid-1"` | `"John Doe"` | +| 1 | `"cometchat-uid-3"` | `"Jane Smith"` | + +--- + +## Check if Logged-in User Was Mentioned + +To check if the logged-in user has been mentioned in a particular message: ```swift -message.mentionedMe +let wasMentioned = message.mentionedMe // Returns Bool ``` - - + +| Property | Type | Description | +|----------|------|-------------| +| mentionedMe | `Bool` | `true` if logged-in user was mentioned | + +--- + +## Mentioned User Properties + +| Property | Type | Description | +|----------|------|-------------| +| uid | `String` | Unique user identifier | +| name | `String` | User's display name | +| avatar | `String?` | User's avatar URL | +| tags | `[String]` | User's tags (with `mentionsWithTagInfo`) | +| hasBlockedMe | `Bool` | Has user blocked logged-in user (with `mentionsWithBlockedInfo`) | +| blockedByMe | `Bool` | Is user blocked by logged-in user (with `mentionsWithBlockedInfo`) | + +--- + +## 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/ios/message-structure-and-hierarchy.mdx b/sdk/ios/message-structure-and-hierarchy.mdx index fef4ec36c..762af59ec 100644 --- a/sdk/ios/message-structure-and-hierarchy.mdx +++ b/sdk/ios/message-structure-and-hierarchy.mdx @@ -2,7 +2,15 @@ title: "Message Structure And Hierarchy" --- + +Message categories and types: +- **message** → `text`, `image`, `video`, `audio`, `file` +- **custom** → Developer-defined types (e.g., `location`, `poll`) +- **action** → `groupMember` (joined/left/kicked/banned), `message` (edited/deleted) +- **call** → `audio`, `video` +- **interactive** → `form`, `card`, `customInteractive` + The below diagram helps you better understand the various message categories and types that a CometChat message can belong to. @@ -80,3 +88,19 @@ 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 + + + Advanced message filtering with RequestBuilder + + diff --git a/sdk/ios/overview.mdx b/sdk/ios/overview.mdx index bf72c3a2e..60a100b95 100644 --- a/sdk/ios/overview.mdx +++ b/sdk/ios/overview.mdx @@ -1,340 +1,121 @@ --- -title: "Overview" +title: "iOS SDK" +sidebarTitle: "Overview" +description: "Add real-time chat, voice, and video to your iOS application with the CometChat SDK." --- - - -This guide demonstrates how to add chat to an iOS application using CometChat. Before you begin, we strongly recommend you read the [Key Concepts](/sdk/ios/key-concepts) guide. - -#### I want to integrate with my app - -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 or Login new user](./overview#register-and-login-your-user) -5. [Integrate our iOS UI Kit](../../ui-kit/ios/getting-started) - -#### I want to explore iOS sample apps. - -Import the app into Xcode and follow the steps mentioned in the `README.md` file. - -[Download Swift Chat App](https://github.com/cometchat/cometchat-chat-sample-app-ios-swift/archive/v4.zip) - -[Download Obj-c Chat App](https://github.com/cometchat-pro/ios-objective-c-chat-app/archive/master.zip) - -[Download iOS SDK from Github](https://github.com/cometchat/chat-sdk-ios) - -*** - -## 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** - - -Minimum Requirement - -1. Xcode 12 or above -2. iOS 11 or higher - - - -*** - -## Add the CometChat Dependency - -### CocoaPods - -We recommend using [CocoaPods](https://cocoapods.org/), as they are the most advanced way of managing iOS project dependencies. Open a terminal window, move to your project directory, and then create a `Podfile` by running the following command. - - - -1. CometChat SDK supports installation through Cocoapods only. Currently, we are supporting Xcode 12 or above versions of Xcode. -2. CometChat SDK includes video calling components. We suggest you run on physical devices to avoid errors. - - - - - -```bash -$ pod init -``` - - - - -Add the following lines to the Podfile. - - - - -```ruby -platform :ios, '12.0' -use_frameworks! - -target 'YourApp' do - pod 'CometChatSDK', '4.1.0' -end -``` - - - - -And then install the `CometChatSDK` framework through CocoaPods. - - - - -```bash -$ pod install -``` - - - - -If you're facing any issues while installing pods then use the below command. - - - -```bash -pod install --repo-update -``` - - - - -Always get the latest version of `CometChatSDK` by command. - - - - -```bash -$ pod update CometChatSDK -``` - - - -### Swift Packages[](#swift-packages "Direct link to Swift Packages") - -To install **Swift Packages** you can use Xcode package manager **.** - -1. Open **Xcode**, go to the project's **General** settings tab and select the project under **Project** in the left column. -2. Go to the **Swift packages** tab and click on the **+** button. - -![Image](/images/a420bc07-1634031189-7ea2eefa96362c62a68a0f87151f85b8.png) - -3. Once the pop-up appears, enter the github repository address in the search bar [`https://github.com/cometchat/chat-sdk-ios`](https://github.com/cometchat/chat-sdk-ios) and set dependency rule to `Up to Next Major Version` and set version as `6` . Then click on the **Add Package** button. - -![Image](/images/b220ea55-jeddfycfr3rgt55jf06ssufo78n3rzvp80ahwupm2bf41xvynzbjor53n8pjwqm1-438a8e2fee0f935ba81fc7ee14dc5ab7.png) - -4. **CometChatSDK** must be checked in the **Package Product** column and click on Add Package. This will add **Package Dependencies** menu in Xcode. - -![Image](/images/d97c347c-1jtrb9jnorzkr2b6mmm06jzf250grq7gazzksch2wqa73ketpyhta0s749njpwdm-1b3966209f90b9a67a5ad7107b8c25ec.png) - -Setup Bitcode - -You can set the Enable Bitcode setting to **YES** present in build settings in your XCode project. - -![Image](/images/47afdab0-1623200428-e5b879b73a5abcf77d5d291426717537.png) - -### Swift Standard Libraries[](#swift-standard-libraries "Direct link to Swift Standard Libraries") - -`CometChatSDK`framework build on Swift, you have to ensure the required libraries are embedded. This can be done by setting the `“Always Embed Swift Standard Libraries”` checkbox in your target’s build settings to “Yes”: - -![Image](/images/6ae89ab8-1623200430-15b0442a710f78a45dd01090dc6a32f1.png) - -### Set Header Search Path[](#set-header-search-path "Direct link to Set Header Search Path") - -Set the `Header Search Paths` to `$SDKROOT/usr/include/libxml2`. - -![Image](/images/e4bea194-1623200431-3688f1650210376bc85f76bc4cc039ac.png) - -## Initialize CometChat[](#initialize-cometchat "Direct link to Initialize CometChat") - -The `init()` method initializes 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 three settings: - -* **Region**: The region where you app was created. -* [Presence Subscription](/sdk/ios/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/ios/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. - -We suggest you call the method on app startup preferably in the `didFinishLaunchingWithOptions:` method of the `AppDelegate` class. - - - +{/* TL;DR for Agents and Quick Reference */} + ```swift import CometChatSDK -class AppDelegate: UIResponder, UIApplicationDelegate{ -{ - var window: UIWindow? - let appId: String = "ENTER APP ID" - let region: String = "ENTER REGION CODE" - -func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { - -let mySettings = AppSettings.AppSettingsBuilder() - .subscribePresenceForAllUsers() - .setRegion(region: region) - .autoEstablishSocketConnection(true) - .build() - - CometChat.init(appId: appId ,appSettings: mySettings,onSuccess: { (isSuccess) in - if (isSuccess) { - print("CometChat SDK intialise successfully.") - } - }) { (error) in - print("CometChat SDK failed intialise with error: \\(error.errorDescription)") - } - return true - } -} -``` - - - - -```objc -#import - -@interface AppDelegate () - -@end - -@implementation AppDelegate - - -- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { - - NSString *region = @"REGION"; - NSString *appID = @"YOUR_APP_ID"; - - AppSettingsBuilder *appSettingBuilder = [[AppSettingsBuilder alloc]init]; - AppSettings *appSettings = [[[appSettingBuilder subscribePresenceForAllUsers]setRegionWithRegion:region]build]; - - [[CometChat alloc]initWithAppId: appID appSettings:appSettings onSuccess:^(BOOL isSuccess) { - NSLog(isSuccess ? @"CometChat Initialize Success:-YES" : @"CometChat Initialize Success:-NO"); - } onError:^(CometChatException * error) { - NSLog(@"Error %@",[error errorDescription]); - }]; - return YES; -} -``` - - - - -Make sure you replace the `appId` with your CometChat **App ID** in the above code. - -## Register and Login your User[](#register-and-login-your-user "Direct link to 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 `API Key` as input parameters and returns the created `User` object if the request is successful. - - - - -```swift -let newUser : User = User(uid: "user1", name: "Kevin") __ Replace with your uid and the name for the user to be created. -let authKey = "AUTH_KEY" __ Replace with your Auth Key. -CometChat.createUser(user: newUser, apiKey: apiKey, onSuccess: { (User) in - print("User created successfully. \\(User.stringValue())") - }) { (error) in - print("The error is \\(String(describing: error?.description))") -} -``` - - - - -Once initialization is successful, you will need to log the user into CometChat using the `login()` method. - -The login method needs to be called in the following scenarios: +// 1. Initialize (once at app startup) +let appSettings = AppSettings.AppSettingsBuilder() + .setRegion(region: "APP_REGION") // e.g. "us", "eu", "in" + .subscribePresenceForAllUsers() + .autoEstablishSocketConnection(true) + .build() -1. When the user is logging into the App for the first time. -2. If the `CometChat.getLoggedInUser()` function returns nil. - - - -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/ios/authentication-overview#login-using-auth-token) instead of an Auth Key to ensure enhanced security. - - - - - -```swift -let uid = "cometchat-uid-1" -let authKey = "YOUR_AUTH_KEY" +CometChat.init(appId: "APP_ID", appSettings: appSettings, onSuccess: { _ in + print("CometChat initialized") +}, onError: { error in + print("Init failed: \(error.errorDescription)") +}) +// 2. Login (check session first) if CometChat.getLoggedInUser() == nil { - - CometChat.login(UID: uid, apiKey: apiKey, onSuccess: { (user) in - - print("Login successful : " + user.stringValue()) - - }) { (error) in - - print("Login failed with error: " + error.errorDescription); - - } - -} -``` - - - - -```objc -NSString *uid = @"cometchat-uid-1"; -NSString *apiKey = @"YOUR_API_KEY"; - -if ([CometChat getLoggedInUser == nil]){ - -[CometChat loginWithUID:uid apiKey:apiKey onSuccess:^(User * user) { - - __ Login Successful - NSLog(@" Login Successful :%@",[user stringValue]); - -} onError:^(CometChatException * error) { - - __ Login error - NSLog(@" Login failed with exception: %@",[error errorDescription]); - -}]; + CometChat.login(UID: "cometchat-uid-1", authKey: "AUTH_KEY", onSuccess: { user in + print("Logged in: \(user.stringValue())") + }, onError: { error in + print("Login failed: \(error.errorDescription)") + }) } ``` - - - - -Make sure you replace the `API_KEY` with your CometChat **ApiKey** 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 containing all the information of the logged in user. - - - -UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. - - - -## Integrate our iOS UI Kit - -Please refer [iOS UI Kit](/ui-kit/ios/overview) section to integrate iOS UI Kit inside your app. +**Credentials:** App ID, Region, Auth Key from [CometChat Dashboard](https://app.cometchat.com) +**Test UIDs:** `cometchat-uid-1` through `cometchat-uid-5` + + +The CometChat iOS SDK lets you add real-time messaging, voice, and video calling to any iOS application — Swift or Objective-C. + +## Requirements + +| Requirement | Minimum Version | +|-------------|-----------------| +| Xcode | 12 | +| iOS | 11 | + +## 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 via CocoaPods or Swift Package Manager and initialize it with your credentials. See [Setup](/sdk/ios/setup). + + + Log in users with Auth Key (development) or Auth Token (production). See [Authentication](/sdk/ios/authentication-overview). + + + Send your first message, make a call, or manage users and groups. + + + +## Features + + + + 1:1 and group chat, threads, reactions, typing indicators, read receipts, and file sharing. + + + 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. + + + +## Sample Apps + +Explore working examples with full source code: + + + + Swift sample app + + + Objective-C sample app + + + +## UI Kits + +Skip the UI work — use pre-built, customizable components: + + + + iOS UI Kit + + + +## Resources + + + + 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/ios/prepare-your-app-for-background-updates.mdx b/sdk/ios/prepare-your-app-for-background-updates.mdx index 9301db484..b42b82998 100644 --- a/sdk/ios/prepare-your-app-for-background-updates.mdx +++ b/sdk/ios/prepare-your-app-for-background-updates.mdx @@ -1,16 +1,21 @@ --- title: "Prepare Your App For Background Updates" +description: "Guide to maintaining real-time connection in background state for iOS apps using CometChat SDK." --- + +- **Purpose:** Keep real-time connection alive when app enters background +- **Enable:** Add Background Modes capability → Enable "Background fetch" and "Remote notifications" +- **Behavior:** Maintains connection for a few seconds in background +- **Use case:** Update UI with new messages when switching between apps +- **Related:** [Connection Status](/sdk/ios/connection-status) · [WebSocket Connection](/sdk/ios/web-socket-connection-behaviour) - - - + -In iOS, when the user enters in the background state, real time connection breaks with the server. So, if the user comes inside the chat window or in the conversation list then it won't update the new messages received from the real time server until it's being fetched from the API. +In iOS, when the user enters the background state, the real time connection breaks with the server. If the user comes inside the chat window or in the conversation list, it won't update the new messages received from the real time server until fetched from the API. -To keep user interaction alive with the application you can add our service which keeps real time connection alive in a background state for a few seconds. If the user is constantly switching between multiple applications at the same time, this service will help to update real time updates on the UI. +To keep user interaction alive, you can add our service which keeps the real time connection alive in background state for a few seconds. If the user is constantly switching between multiple applications, this service will help update real time updates on the UI. ## Background updates behaviour @@ -23,15 +28,13 @@ autoEstablishSocketConnection usage can be found in [Managing Web-Socket connect | autoEstablishSocketConnection | true | Connection is maintained in background for 30 seconds and after that it is killed. | | autoEstablishSocketConnection | false | 1. If `CometChat.connect()` is called and app goes to background the connection is maintained for 30 seconds and after that connection is terminated. 2. If `CometChat.disconnect()` is called and app goes to background the connection not maintained. | - - -Please follow the steps to prepare your app for background states. +Follow the steps below to prepare your app for background states. *** ## Step 1. Add Background Modes in Capabilities -Click on Targets -> Project -> \[+ Capability] -> Add 'Background Modes' section. +Click on Targets -> Project -> [+ Capability] -> Add 'Background Modes' section. @@ -51,7 +54,7 @@ Select 'Background Fetch' and 'Background Processing' options by ticking them. ## Step 3. Add Code in Application class to configure background services for different states. -Add `CometChat.configureServices`method in application class or scene delegate class as shown below. +Add `CometChat.configureServices` method in application class or scene delegate class as shown below. @@ -97,3 +100,22 @@ if CometChat.backgroundTaskEnabled() { *** + +--- + +## Next Steps + + + + Monitor the SDK connection state in real time + + + Understand default WebSocket connection lifecycle + + + Take full control of WebSocket connections + + + Set up push notifications for your iOS app + + diff --git a/sdk/ios/presenter-mode.mdx b/sdk/ios/presenter-mode.mdx index f12090ba6..40dcf425a 100644 --- a/sdk/ios/presenter-mode.mdx +++ b/sdk/ios/presenter-mode.mdx @@ -2,7 +2,30 @@ title: "Presenter Mode" --- + +```swift +// Configure presenter settings +let presenterSettings = CometChatCalls.presentationSettingsBuilder + .setIsPresenter(true) // false for viewer + .setDelegate(self) + .setDefaultLayout(true) + .setStartAudioMuted(true) + .build() + +// Join presentation +CometChatCalls.joinPresentation(callToken: callToken, presenterSettings: presenterSettings, view: callView) { success in + print("Joined presentation") +} onError: { error in + print("Error: \(error?.errorCode)") +} +``` + +**Key points:** +- Up to 5 presenters, up to 100 total participants (presenters + viewers) +- Viewers cannot send audio, video, or screen streams +- Use `setIsPresenter(true)` for presenters, `setIsPresenter(false)` for viewers + ## Overview @@ -221,3 +244,16 @@ extension ViewController: CallsEventsDelegate { In case you wish to achieve a completely customised UI for the Calling experience, you can do so by embedding default iOS buttons to the screen as per your requirement and then use the below methods to achieve different functionalities for the embedded buttons. + +--- + +## Next Steps + + + + Start and manage standard call sessions with full configuration options + + + Record presentation sessions for playback and compliance + + diff --git a/sdk/ios/publishing-app-on-appstore.mdx b/sdk/ios/publishing-app-on-appstore.mdx index ad28821b1..c564b717f 100644 --- a/sdk/ios/publishing-app-on-appstore.mdx +++ b/sdk/ios/publishing-app-on-appstore.mdx @@ -2,7 +2,14 @@ title: "Publishing App On App Store" --- - + + +Key steps to publish your CometChat iOS app: +1. Add a **Run Script Phase** in Build Phases to strip simulator architectures +2. Use the appropriate script for your Xcode version (11.4 vs 11.5+) +3. The script removes unused architecture slices from embedded frameworks +4. For beta SDK versions, update `CFBundleShortVersionString` in `CometChatSDK.framework/Info.plist` (remove "beta" from version string) + diff --git a/sdk/ios/rate-limits.mdx b/sdk/ios/rate-limits.mdx index 17581b144..0e1badaa5 100644 --- a/sdk/ios/rate-limits.mdx +++ b/sdk/ios/rate-limits.mdx @@ -2,7 +2,13 @@ title: "Rate Limits" --- + +- 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 +38,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 + + + + Handle SDK errors gracefully + + + Learn the core concepts behind CometChat + + diff --git a/sdk/ios/reactions.mdx b/sdk/ios/reactions.mdx index 052fc3f21..b5897d78f 100644 --- a/sdk/ios/reactions.mdx +++ b/sdk/ios/reactions.mdx @@ -1,10 +1,30 @@ --- title: "Reactions" +sidebarTitle: "Reactions" +description: "Add, remove, and fetch message reactions in real-time using the CometChat iOS SDK. Includes listener events and helper methods for updating UI." --- + +```swift +// Add a reaction +CometChat.addReaction(messageId: 148, reaction: "\u{1F60A}") { msg in } onError: { err in } + +// Remove a reaction +CometChat.removeReaction(messageId: 148, reaction: "\u{1F60A}") { msg in } onError: { err in } -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 iOS SDK. +// Fetch reactions for a message +let request = ReactionsRequestBuilder().setMessageId(messageId: 148).setLimit(limit: 10).build() +request.fetchNext { reactions in } onError: { error in } + +// Listen for reaction events (CometChatMessageDelegate) +func onMessageReactionAdded(reactionEvent: ReactionEvent) { } +func onMessageReactionRemoved(reactionEvent: ReactionEvent) { } +``` + +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. + +--- ## Add a Reaction @@ -14,206 +34,381 @@ Users can add a reaction to a message by calling `addReaction` with the message ```swift CometChat.addReaction(messageId: 148, reaction: "😴") { message in - - print("message reaction added successfully \(message.getReactions())") - - } onError: { error in - print("some error occured when adding reaction \(error?.errorDescription)") - - } + print("Reactions: \(message.getReactions())") +} onError: { error in + print("Error: \(error?.errorDescription)") +} ``` - -
- You can react on Text, Media and Custom messages. - +--- + ## Remove a Reaction Removing a reaction from a message can be done using the `removeReaction` method. +Both `addReaction()` and `removeReaction()` return a [`BaseMessage`](/sdk/reference/messages#basemessage) object with the updated reactions. + ```swift CometChat.removeReaction(messageId: 148, reaction: "😴") { message in - - print("message reaction removed successfully \(message.getReactions())") - - } onError: { error in - print("some error occured when removing reaction \(error?.errorDescription)") - - } + print("Reactions: \(message.getReactions())") +} onError: { error in + print("Error: \(error?.errorDescription)") +} ``` - - +--- + ## Fetch Reactions for a Message -To get all reactions for a specific message, first create a `ReactionsRequest` using `ReactionsRequestBuilder`. 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 `set(reaction: String)` will allow you to fetch details for specific reaction or emoji. +To get all reactions for a specific message, create a `ReactionsRequest` using `ReactionsRequestBuilder`. -| Methods | Description | -| ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `setMessageId(messageId: Int)` | 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(reaction: String)` | Filters the reactions fetched by the specified reaction type (e.g., "😊", "😂", "👍"). When set, this method will cause the `ReactionsRequest` to only retrieve details of the provided reaction for the given message. | +| Method | Description | +|--------|-------------| +| `setMessageId(messageId: Int)` | Specifies the message ID (required) | +| `setReaction(reaction: String)` | Filter by specific emoji (optional) | +| `setLimit(limit: Int)` | Number of reactions to fetch (max 100) | ### Fetch Next Reactions -The `fetchNext()` method fetches the next set of reactions for the message. - ```swift -var reactionsRequest = ReactionsRequestBuilder().setLimit(limit: 30).setMessageId(messageId: 148).build() - +let reactionsRequest = ReactionsRequestBuilder() + .setLimit(limit: 30) + .setMessageId(messageId: 148) + .build() + reactionsRequest.fetchNext { reactions in - for reaction in reactions{ + for reaction in reactions { + print("Reaction: \(reaction.reaction)") + print("Reacted by: \(reaction.reactedBy?.name ?? "")") + } +} onError: { error in + print("Error: \(error?.errorDescription)") +} +``` + + - print("reaction is \(reaction.stringValue())") - } +### Fetch Reactions for Specific Emoji - } onError: { error in - - print("error caught in fetching next reactions is \(error?.errorDescription)") - } -``` + + +```swift +let reactionsRequest = ReactionsRequestBuilder() + .setLimit(limit: 30) + .setMessageId(messageId: 148) + .setReaction(reaction: "👍") + .build() +reactionsRequest.fetchNext { reactions in + // Only returns 👍 reactions +} onError: { error in + print("Error: \(error?.errorDescription)") +} +``` - ### Fetch Previous Reactions -The `fetchPrevious()` method fetches the previous set of reactions for the message. - ```swift -var reactionsRequest = ReactionsRequestBuilder().setLimit(limit: 30).setMessageId(messageId: 148).build() - reactionsRequest.fetchPrevious { reactions in - for reaction in reactions{ - - print("reaction is \(reaction.stringValue())") - } - - } onError: { error in - - print("error caught in fetching previous reactions is \(error?.errorDescription)") - } + for reaction in reactions { + print("Reaction: \(reaction.stringValue())") + } +} onError: { error in + print("Error: \(error?.errorDescription)") +} ``` - - +--- + ## 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. +Keep the chat interactive with real-time updates for reactions. ```swift let listenerID = "UNIQUE_LISTENER_ID" - CometChat.addMessageListener(listenerID, self) - -extension YourAppViewController: CometChatMessageDelegate { + +extension YourViewController: CometChatMessageDelegate { + func onMessageReactionAdded(reactionEvent: ReactionEvent) { - print("Reaction Added : \(reactionEvent) ") + print("Reaction Added") + print("Reaction: \(reactionEvent.reaction)") + print("Message ID: \(reactionEvent.reaction.messageId)") + print("Reacted By: \(reactionEvent.reaction.reactedBy?.name ?? "")") } func onMessageReactionRemoved(reactionEvent: ReactionEvent) { - print("Reaction Removed : \(reactionEvent) ") + print("Reaction Removed") + print("Reaction: \(reactionEvent.reaction)") } } -``` +// Remove listener when done: +CometChat.removeMessageListener(listenerID) +``` - -## Removing a Reaction Listener +--- + +## Get Reactions List -To stop listening for reaction events, remove the listener as follows: +To retrieve the list of reactions on a particular message. Returns an array of [`ReactionCount`](/sdk/reference/auxiliary#reactioncount) objects: ```swift -let listenerID = "UNIQUE_LISTENER_ID" - -CometChat.removeMessageListener("reactionListener"); +let reactions = message.reactions // Returns [ReactionCount] ``` - - -## Get Reactions List +--- -To retrieve the list of reactions reacted on particular message, you can use the `message.reactions` method. This method will return an array containing the reactions, or an empty array if no one reacted on the message. +## Check if Logged-in User Has Reacted ```swift -message.reactions +for reactionCount in message.reactions { + print("Reaction: \(reactionCount.reaction)") + print("Reacted by me: \(reactionCount.reactedByMe)") +} ``` - - -## Check if Logged-in User has Reacted on Message +--- + +## Update Message With Reaction Info + +When you receive a real-time reaction event, use this method to update the message with the latest reaction information. This keeps your local message state in sync with the server. -To check if the logged-in user has reacted on a particular message or not, You can use the `reactedByMe()` 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`. +### Method Signature ```swift -for reactionCount in message.reactions { - print("isReactedByMe \(reactionCount.reactedByMe)") //Return true is logged-in user reacted on that message, otherwise false -} +CometChat.updateMessageWithReactionInfo( + baseMessage: BaseMessage, + messageReaction: MessageReaction, + action: ReactionAction +) -> BaseMessage ``` - - -## Updated Message With Reaction Info +### Parameters + +| Parameter | Type | Description | +|-----------|------|-------------| +| baseMessage | [`BaseMessage`](/sdk/reference/messages#basemessage) | The message to update | +| messageReaction | `MessageReaction` | Reaction info from event | +| action | `ReactionAction` | `.REACTION_ADDED` or `.REACTION_REMOVED` | -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. +### ReactionAction Enum Values -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 `reactions` property reflects this change immediately. +| Value | Description | +|-------|-------------| +| `.REACTION_ADDED` | A reaction was added to the message | +| `.REACTION_REMOVED` | A reaction was removed from the message | -When you receive a real-time reaction event (`ReactionEvent`), call the `updateMessageWithReactionInfo()` method, passing the BaseMessage instance (`message`), reaction data from the reaction event (`ReactionEvent.reaction`) and reaction event action type (`ReactionAction.REACTION_ADDED` or `ReactionAction.REACTION_REMOVED`) that corresponds to the message being reacted to. +### Usage Example - Reaction Added ```swift -// The message to which the reaction is related -var message : BaseMessage = ... - -// The reaction event data received in real-time -var messageReaction : MessageReaction = ... +extension YourViewController: CometChatMessageDelegate { + + func onMessageReactionAdded(reactionEvent: ReactionEvent) { + // Get the message from your local list + var message: BaseMessage = getMessageFromList(reactionEvent.reaction.messageId) + + // Get the reaction from the event + let messageReaction: MessageReaction = reactionEvent.reaction + + // Update the message with new reaction info + let modifiedMessage = CometChat.updateMessageWithReactionInfo( + baseMessage: message, + messageReaction: messageReaction, + action: .REACTION_ADDED + ) + + // Update your UI with the modified message + updateMessageInList(modifiedMessage) + } +} +``` + + -// The recieved reaction event real-time action type. Can be ReactionAction.REACTION_ADDED or ReactionAction.REACTION_REMOVED -var action = ReactionAction.REACTION_ADDED +### Usage Example - Reaction Removed -var modifiedBaseMessage : BaseMessage = CometChat.updateMessageWithReactionInfo( - baseMessage : baseMessage, - messageReaction : messageReaction, - action : action -) + + +```swift +extension YourViewController: CometChatMessageDelegate { + + func onMessageReactionRemoved(reactionEvent: ReactionEvent) { + // Get the message from your local list + var message: BaseMessage = getMessageFromList(reactionEvent.reaction.messageId) + + // Get the reaction from the event + let messageReaction: MessageReaction = reactionEvent.reaction + + // Update the message with removed reaction info + let modifiedMessage = CometChat.updateMessageWithReactionInfo( + baseMessage: message, + messageReaction: messageReaction, + action: .REACTION_REMOVED + ) + + // Update your UI with the modified message + updateMessageInList(modifiedMessage) + } +} ``` - + + +### Complete Real-Time Handling Example + + +```swift +class ChatViewController: UIViewController, CometChatMessageDelegate { + + var messages: [BaseMessage] = [] + + override func viewDidLoad() { + super.viewDidLoad() + CometChat.addMessageListener("reaction-listener", self) + } + + func onMessageReactionAdded(reactionEvent: ReactionEvent) { + handleReactionEvent(reactionEvent, action: .REACTION_ADDED) + } + + func onMessageReactionRemoved(reactionEvent: ReactionEvent) { + handleReactionEvent(reactionEvent, action: .REACTION_REMOVED) + } + + private func handleReactionEvent(_ event: ReactionEvent, action: ReactionAction) { + let messageId = event.reaction.messageId + + // Find the message in local list + guard let index = messages.firstIndex(where: { $0.id == messageId }) else { + return + } + + // Update message with reaction info + let updatedMessage = CometChat.updateMessageWithReactionInfo( + baseMessage: messages[index], + messageReaction: event.reaction, + action: action + ) + + // Replace in list and refresh UI + messages[index] = updatedMessage + tableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: .none) + } + + deinit { + CometChat.removeMessageListener("reaction-listener") + } +} +``` + -After calling this method, the `message` instance's reactions are updated. You can then use `message.reactions` to get the latest reactions and refresh your UI accordingly. + +**Notes:** +- This is a synchronous method - no callbacks needed +- Always use this method to keep local message state in sync +- The returned message has updated reactions array +- Works with both user and group messages +- Handle both `REACTION_ADDED` and `REACTION_REMOVED` events + + +--- + +## ReactionCount Object Properties + +| Property | Type | Description | +|----------|------|-------------| +| `reaction` | `String` | The reaction emoji | +| `count` | `Int` | Number of users who reacted | +| `reactedByMe` | `Bool` | Whether logged-in user reacted | + +--- + +## MessageReaction Object Properties + +| Property | Type | Description | +|----------|------|-------------| +| `reaction` | `String` | The reaction emoji | +| `reactedBy` | [`User`](/sdk/reference/entities#user)? | User who added the reaction | +| `reactedAt` | `Double` | Unix timestamp when reacted | +| `messageId` | `Int` | ID of the message | + +--- + +## ReactionEvent Object Properties + +| Property | Type | Description | +|----------|------|-------------| +| `reaction` | `Reaction` | The reaction details | +| `receiverId` | `String` | ID of the receiver | +| `receiverType` | `ReceiverType` | `.user` or `.group` | +| `conversationId` | `String` | ID of the conversation | +| `parentMessageId` | `Int` | Parent message ID (for threads) | + +--- + +## Common Error Codes + +| Error Code | Description | Resolution | +|------------|-------------|------------| +| `ERR_MESSAGE_NOT_FOUND` | Message doesn't exist | Verify message ID | +| `ERR_INVALID_REACTION` | Invalid reaction emoji | Use valid emoji | +| `ERR_ALREADY_REACTED` | Already reacted with emoji | Remove first | +| `ERR_REACTION_NOT_FOUND` | Reaction not on message | User hasn't reacted | + +--- + +## Next Steps + + + + Send text, media, and custom messages to users and groups + + + Listen for incoming messages in real-time and fetch missed messages + + + Mention specific users in messages + + + Organize conversations with message threads + + diff --git a/sdk/ios/receive-message.mdx b/sdk/ios/receive-message.mdx index 837b2f29a..f17fe1701 100644 --- a/sdk/ios/receive-message.mdx +++ b/sdk/ios/receive-message.mdx @@ -1,19 +1,28 @@ --- -title: "Receive A Message" +title: "Receive Messages" +sidebarTitle: "Receive Messages" +description: "Receive real-time messages, fetch unread messages, and retrieve message history using the CometChat iOS SDK." --- + +| Field | Value | +| --- | --- | +| Key Classes | `CometChatMessageDelegate`, `MessagesRequest.MessageRequestBuilder` | +| Key Methods | `onTextMessageReceived()`, `onMediaMessageReceived()`, `onCustomMessageReceived()`, `fetchPrevious()`, `fetchNext()` | +| Delegate | `CometChat.messagedelegate = self` | +| Prerequisites | SDK initialized, user logged in | -Receiving messages with CometChat has two parts: + -1. Adding a listener to receive [real-time messages](/sdk/ios/receive-message#real-time-messages) when your app is running -2. Calling a method to retrieve [missed messages](/sdk/ios/receive-message#missed-messages) when your app was not running +Receiving messages with CometChat has two parts: -## Real-time Messages +1. Adding a [real-time listener](#real-time-messages) to receive messages while your app is running +2. Fetching [unread](#unread-messages) or [historical](#message-history) messages when your app starts up or the user scrolls back -*In other words, as a recipient, how do I receive messages when my app is running?* +## Real-Time Messages -In order to receive incoming messages, you must add protocol conformance `CometChatMessageDelegate` as Shown Below : +Register a `CometChatMessageDelegate` 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). @@ -21,25 +30,20 @@ In order to receive incoming messages, you must add protocol conformance `CometC extension ViewController: CometChatMessageDelegate { func onTextMessageReceived(textMessage: TextMessage) { - print("TextMessage received successfully: " + textMessage.stringValue()) } func onMediaMessageReceived(mediaMessage: MediaMessage) { - print("MediaMessage received successfully: " + mediaMessage.stringValue()) } func onCustomMessageReceived(customMessage: CustomMessage) { - print("CustomMessage received successfully: " + customMessage.stringValue()) } } ``` - - - + ```objc @interface ViewController () @end @@ -48,854 +52,158 @@ extension ViewController: CometChatMessageDelegate { - (void)viewDidLoad { [super viewDidLoad]; - - CometChat.messagedelegate = self ; + CometChat.messagedelegate = self; } - (void)onTextMessageReceivedWithTextMessage:(TextMessage *)textMessage { - NSLog(@"TextMessage received successfully: %@",[textMessage stringValue]); } - (void)onMediaMessageReceivedWithMediaMessage:(MediaMessage *)mediaMessage { - NSLog(@"MediaMessage received successfully: %@",[mediaMessage stringValue]); } - (void)onCustomMessageReceivedWithCustomMessage:(CustomMessage *)customMessage { - - NSLog(@"CustomMessage received : %@",[customMessage stringValue]); + NSLog(@"CustomMessage received: %@",[customMessage stringValue]); } @end ``` - - -Do not forget to set your view controller as a CometChat delegate probably in `viewDidLoad()` as `CometChat.messagedelegate = self` - - +Don't forget to set your view controller as the delegate in `viewDidLoad()`: -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. +```swift +CometChat.messagedelegate = self +``` + +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 -*In other words, as a recipient, how do I receive messages that I missed when my app was not running?* - -For most 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 we 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 in a paginated manner +Fetch messages that were sent while the app was offline using `MessagesRequest` with `setMessageId()` set to the last delivered message ID. ### Fetch Missed Messages of a particular one-on-one conversation - - ```swift -let limit = 50; +let limit = 50 let latestId = CometChat.getLastDeliveredMessageId() let UID = "cometchat-uid-2" -let messagesRequest = MessagesRequest.MessageRequestBuilder().set(messageID: latestId).set(uid:UID).set(limit: limit).build(); +let messagesRequest = MessagesRequest.MessageRequestBuilder() + .set(messageID: latestId) + .set(uid: UID) + .set(limit: limit) + .build() messagesRequest.fetchNext(onSuccess: { (messages) in - - for message in messages!{ - + for message in messages! { if let receivedMessage = (message as? TextMessage) { print("Message received successfully. " + receivedMessage.stringValue()) - } - else if let receivedMessage = (message as? MediaMessage) { + } else if let receivedMessage = (message as? MediaMessage) { print("Message received successfully. " + receivedMessage.stringValue()) - } + } } - }) { (error) in - print("Message receiving failed with error: " + error!.errorDescription); } ``` - - - -```objc -NSInteger limit = 50; -NSString *latestMessageId = [CometChat getLatestDeliveredMessageId]; - -MessagesRequest *messageRequest = [[[[[MessageRequestBuilder alloc]init] setWithMessageID: latestMessageId] setWithLimit:limit] build]; - -[messageRequest fetchNextOnSuccess:^(NSArray * messages) { - - for (BaseMessage *message in messages) { - - if ([message isKindOfClass:TextMessage.self]) { - - TextMessage *receivedMessage = (TextMessage *)message; - NSLog(@"TextMessage received successfully. %@",[receivedMessage stringValue]); - } - else if ([messages isKindOfClass:MediaMessage.self]) { - - MediaMessage *receivedMessage = (MediaMessage *)message; - NSLog(@"MediaMessage received successfully. %@",[receivedMessage stringValue]); - } - } - -} onError:^(CometChatException * error) { - - NSLog(@"Message receiving failed with error: %@",[error ErrorDescription]); - -}]; -``` - - - - - ### Fetch Missed Messages of a particular group conversation - - ```swift -let limit = 50; +let limit = 50 let latestId = CometChat.getLastDeliveredMessageId() let GUID = "cometchat-guid-1" -let messagesRequest = MessagesRequest.MessageRequestBuilder().set(messageID: latestId).set(guid:GUID).set(limit: limit).build(); +let messagesRequest = MessagesRequest.MessageRequestBuilder() + .set(messageID: latestId) + .set(guid: GUID) + .set(limit: limit) + .build() messagesRequest.fetchNext(onSuccess: { (messages) in - - for message in messages!{ - + for message in messages! { if let receivedMessage = (message as? TextMessage) { print("Message received successfully. " + receivedMessage.stringValue()) - } - else if let receivedMessage = (message as? MediaMessage) { + } else if let receivedMessage = (message as? MediaMessage) { print("Message received successfully. " + receivedMessage.stringValue()) - } + } } - }) { (error) in - print("Message receiving failed with error: " + error!.errorDescription); } ``` - - - -```objc -NSInteger limit = 50; -NSString *latestMessageId = [CometChat getLatestDeliveredMessageId]; - -MessagesRequest *messageRequest = [[[[[MessageRequestBuilder alloc]init] setWithMessageID: latestMessageId] setWithLimit:limit] build]; - -[messageRequest fetchNextOnSuccess:^(NSArray * messages) { - - for (BaseMessage *message in messages) { - - if ([message isKindOfClass:TextMessage.self]) { - - TextMessage *receivedMessage = (TextMessage *)message; - NSLog(@"TextMessage received successfully. %@",[receivedMessage stringValue]); - } - else if ([messages isKindOfClass:MediaMessage.self]) { - - MediaMessage *receivedMessage = (MediaMessage *)message; - NSLog(@"MediaMessage received successfully. %@",[receivedMessage stringValue]); - } - } - -} onError:^(CometChatException * error) { - - NSLog(@"Message receiving failed with error: %@",[error ErrorDescription]); - -}]; -``` - - - - - ## 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 of a particular one-on-one conversation +Fetch unread messages by adding `setUnread(true)` to the builder. Use `fetchPrevious()` to retrieve them. - - ```swift -let limit = 50; +let limit = 50 let UID = "cometchat-uid-2" -let messagesRequest = MessagesRequest.MessageRequestBuilder().set(unread: true).set(limit: limit).set(uid:UID).build(); - -messagesRequest.fetchPrevious(onSuccess: { (messages) in - - for message in messages!{ - - if let receivedMessage = (message as? TextMessage) { - print("Message received successfully. " + receivedMessage.stringValue()) - } - else if let receivedMessage = (message as? MediaMessage) { - print("Message received successfully. " + receivedMessage.stringValue()) - } - } - -}) { (error) in - - print("Message receiving failed with error: " + error!.errorDescription); -} -``` - - - - -```objc -NSInteger limit = 50; -NSString *uid = "UID"; - -MessagesRequest *messageRequest = [[[[[MessageRequestBuilder alloc] init] setWithUnread:YES] setWithLimit:limit] build]; - -[messageRequest fetchPreviousOnSuccess:^(NSArray * messages) { - for (BaseMessage *message in messages) { - - if ([message isKindOfClass:TextMessage.self]) { - - TextMessage *receivedMessage = (TextMessage *)message; - NSLog(@"TextMessage received successfully. %@",[receivedMessage stringValue]); - } - else if ([messages isKindOfClass:MediaMessage.self]) { - - MediaMessage *receivedMessage = (MediaMessage *)message; - NSLog(@"MediaMessage received successfully. %@",[receivedMessage stringValue]); - } - } - -} onError:^(CometChatException * error) { - - NSLog(@"Message receiving failed with error: %@",[error ErrorDescription]); - -}]; -``` - - - - - -### Fetch Unread Messages of a particular group conversation - - - -```swift -let limit = 50; -let GUID = "cometchat-uid-2" -let messagesRequest = MessagesRequest.MessageRequestBuilder().set(unread: true).set(limit: limit).set(guid:GUID).build(); +let messagesRequest = MessagesRequest.MessageRequestBuilder() + .set(unread: true) + .set(limit: limit) + .set(uid: UID) + .build() messagesRequest.fetchPrevious(onSuccess: { (messages) in - - for message in messages!{ - + for message in messages! { if let receivedMessage = (message as? TextMessage) { print("Message received successfully. " + receivedMessage.stringValue()) - } - else if let receivedMessage = (message as? MediaMessage) { + } else if let receivedMessage = (message as? MediaMessage) { print("Message received successfully. " + receivedMessage.stringValue()) - } + } } - }) { (error) in - print("Message receiving failed with error: " + error!.errorDescription); } ``` - - - -```objc -NSInteger limit = 50; -NSString *uid = "UID"; - -MessagesRequest *messageRequest = [[[[[MessageRequestBuilder alloc] init] setWithUnread:YES] setWithLimit:limit] build]; - -[messageRequest fetchPreviousOnSuccess:^(NSArray * messages) { - - for (BaseMessage *message in messages) { - - if ([message isKindOfClass:TextMessage.self]) { - - TextMessage *receivedMessage = (TextMessage *)message; - NSLog(@"TextMessage received successfully. %@",[receivedMessage stringValue]); - } - else if ([messages isKindOfClass:MediaMessage.self]) { - - MediaMessage *receivedMessage = (MediaMessage *)message; - NSLog(@"MediaMessage received successfully. %@",[receivedMessage stringValue]); - } - } - -} onError:^(CometChatException * error) { - - NSLog(@"Message receiving failed with error: %@",[error ErrorDescription]); - -}]; -``` - - - - - - -BaseMessage - -The list of messages received is in the form of objects of `BaseMessage` class. A BaseMessage can either be a `TextMessage` or a `MediaMessage`. 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 full conversation history using `fetchPrevious()`. Call it repeatedly on the same request object to paginate. -### 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. - - - ```swift -let limit = 50; +let limit = 50 let UID = "cometchat-uid-2" -let messagesRequest = MessagesRequest.MessageRequestBuilder().set(limit: limit).set(uid:UID).build(); +let messagesRequest = MessagesRequest.MessageRequestBuilder() + .set(limit: limit) + .set(uid: UID) + .build() messagesRequest.fetchPrevious(onSuccess: { (messages) in - - for message in messages!{ - - if let receivedMessage = (message as ? TextMessage) { + for message in messages! { + if let receivedMessage = (message as? TextMessage) { print("Message received successfully. " + receivedMessage.stringValue()) - } - else if let receivedMessage = (message as ? MediaMessage) { - print("Message received successfully. " + receivedMessage!.stringValue()) - } -} - -}) { (error) in - - print("Message receiving failed with error: " + error!.errorDescription); -} -``` - - - - -```objc -NSInteger limit = 50; - -MessagesRequest *messageRequest = [[[[MessageRequestBuilder alloc]init] setWithLimit:limit] build]; - -[messageRequest fetchPreviousOnSuccess:^(NSArray * messages) { - - for (BaseMessage *message in messages) { - - if ([message isKindOfClass:TextMessage.self]) { - - TextMessage *receivedMessage = (TextMessage *)message; - NSLog(@"TextMessage received successfully. %@",[receivedMessage stringValue]); - } - else if ([messages isKindOfClass:MediaMessage.self]) { - - MediaMessage *receivedMessage = (MediaMessage *)message; - NSLog(@"MediaMessage received successfully. %@",[receivedMessage stringValue]); - } - } - -} onError:^(CometChatException * error) { - - NSLog(@"Message receiving failed with error: %@",[error ErrorDescription]); - -}]; -``` - - - - - -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. - - - -```swift -let limit = 50; -let GUID = "cometchat-guid-1" - -let messagesRequest = MessagesRequest.MessageRequestBuilder().set(limit: limit).set(guid:GUID).build(); - -messagesRequest.fetchPrevious(onSuccess: { (messages) in - - for message in messages!{ - - if let receivedMessage = (message as ? TextMessage) { + } else if let receivedMessage = (message as? MediaMessage) { print("Message received successfully. " + receivedMessage.stringValue()) } - else if let receivedMessage = (message as ? MediaMessage) { - print("Message received successfully. " + receivedMessage!.stringValue()) } -} - }) { (error) in - print("Message receiving failed with error: " + error!.errorDescription); } ``` - - - -```objc -NSInteger limit = 50; - -MessagesRequest *messageRequest = [[[[MessageRequestBuilder alloc]init] setWithLimit:limit] build]; - -[messageRequest fetchPreviousOnSuccess:^(NSArray * messages) { - - for (BaseMessage *message in messages) { - - if ([message isKindOfClass:TextMessage.self]) { - - TextMessage *receivedMessage = (TextMessage *)message; - NSLog(@"TextMessage received successfully. %@",[receivedMessage stringValue]); - } - else if ([messages isKindOfClass:MediaMessage.self]) { - - MediaMessage *receivedMessage = (MediaMessage *)message; - NSLog(@"MediaMessage received successfully. %@",[receivedMessage stringValue]); - } - } - -} onError:^(CometChatException * error) { - - NSLog(@"Message receiving failed with error: %@",[error ErrorDescription]); - -}]; -``` - - - - - -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 - -In other words, as a logged-in user, how do I search a message? - -In order to do this, you can use the `set(searchKeyword: String)` method. This method accepts string as input. When set, the SDK will fetch messages which 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) - +The list of messages received is in the form of [`BaseMessage`](/sdk/reference/messages#basemessage) objects. A [`BaseMessage`](/sdk/reference/messages#basemessage) can be a [`TextMessage`](/sdk/reference/messages#textmessage), [`MediaMessage`](/sdk/reference/messages#mediamessage), or [`CustomMessage`](/sdk/reference/messages#custommessage). Use type casting to check the type. -| Feature | Basic Search | Advance Search | -| ---------------- | ------------ | -------------- | -| Text search | ✅ | ✅ | -| File name search | ❌ | ✅ | -| Mentions search | ❌ | ✅ | -| Mime type search | ❌ | ✅ | - -### Search Messages in a particular one-on-one conversation - - - -```swift -let limit = 50; -let UID = "cometchat-uid-2" - -let messagesRequest = MessagesRequest.MessageRequestBuilder().set(uid: UID).set(limit: limit).set(searchKeyword: "Hello").build(); - -messagesRequest.fetchPrevious(onSuccess: { (messages) in - - for message in messages!{ - - if let receivedMessage = (message as ? TextMessage) { - print("Message received successfully. " + receivedMessage.stringValue()) - } - else if let receivedMessage = (message as ? MediaMessage) { - print("Message received successfully. " + receivedMessage!.stringValue()) - } - } - -}) { (error) in - - print("Message receiving failed with error: " + error!.errorDescription); -} -``` - - - - -```objc -NSInteger limit = 50; -NSString *uid = "UID"; - -MessagesRequest *messageRequest = [[[[[[MessageRequestBuilder alloc] init] setWithUID: uid] setWithLimit:limit] setWithSearchKeyword: "String To be Searched"] build]; - -[messageRequest fetchPreviousOnSuccess:^(NSArray * messages) { - - for (BaseMessage *message in messages) { - - if ([message isKindOfClass:TextMessage.self]) { - - TextMessage *receivedMessage = (TextMessage *)message; - NSLog(@"TextMessage received successfully. %@",[receivedMessage stringValue]); - } - else if ([messages isKindOfClass:MediaMessage.self]) { - - MediaMessage *receivedMessage = (MediaMessage *)message; - NSLog(@"MediaMessage received successfully. %@",[receivedMessage stringValue]); - } - } - -} onError:^(CometChatException * error) { - - NSLog(@"Message receiving failed with error: %@",[error ErrorDescription]); - -}]; -``` - - - - - -### Search Messages in a particular group conversation - - - -```swift -let limit = 50; -let GUID = "cometchat-guid-1" - -let messagesRequest = MessagesRequest.MessageRequestBuilder().set(guid: GUID).set(limit: limit).set(searchKeyword: "Hello").build(); - -messagesRequest.fetchPrevious(onSuccess: { (messages) in - - for message in messages!{ - - if let receivedMessage = (message as ? TextMessage) { - print("Message received successfully. " + receivedMessage.stringValue()) - } - else if let receivedMessage = (message as ? MediaMessage) { - print("Message received successfully. " + receivedMessage!.stringValue()) - } - } - -}) { (error) in - - print("Message receiving failed with error: " + error!.errorDescription); -} -``` - - - - -```objc -NSInteger limit = 50; -NSString *uid = "UID"; - -MessagesRequest *messageRequest = [[[[[MessageRequestBuilder alloc] init] setWithUID: uid] setWithLimit:limit] build]; - -[messageRequest fetchPreviousOnSuccess:^(NSArray * messages) { - - for (BaseMessage *message in messages) { - - if ([message isKindOfClass:TextMessage.self]) { - - TextMessage *receivedMessage = (TextMessage *)message; - NSLog(@"TextMessage received successfully. %@",[receivedMessage stringValue]); - } - else if ([messages isKindOfClass:MediaMessage.self]) { - - MediaMessage *receivedMessage = (MediaMessage *)message; - NSLog(@"MediaMessage received successfully. %@",[receivedMessage stringValue]); - } - } - -} onError:^(CometChatException * error) { - - NSLog(@"Message receiving failed with error: %@",[error ErrorDescription]); - -}]; -``` - - - - - -## Unread Messages Count - -*In other words, as a logged-in user, 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?* - -In order to get the unread message count for a particular user (with respect to the logged-in user), you can use the `getUnreadMessageCountForUser()`. - -This method has the two variants: - - - -```swift -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: - - - -```swift -CometChat.getUnreadMessageCountForUser(UID, hideMessagesFromBlockedUsers:true) -``` - - - - - - - -```swift -let UID = "cometchat-uid-1" - -CometChat.getUnreadMessageCountForUser(UID, onSuccess: { (response) in - - print("Unread count for users: \(response)") - -}) { (error) in - - print("Error in unread count for users: \(error)") -} -``` - - - - - -In the `onSuccess()` callback, you will receive a dictionary that 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 - -In order to get the unread message count for a particular group, you can use the `getUnreadMessageCountForGroup()`. This method has the below two variants: - - - -```swift -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: - - - -```swift -CometChat.getUnreadMessageCountForGroup(GUID, hideMessagesFromBlockedUsers:true) -``` - - - - - - - -```swift -let GUID = "cometchat-guid-1" - -CometChat.getUnreadMessageCountForGroup(GUID, onSuccess: { (response) in - - print("Unread count for groups: \(response)") - -}) { (error) in - - print("Error in unread count for group: \(error.errorDescription)") -} -``` - - - - - -In the `onSuccess()` callback, you will receive a dictionary that 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 conversation - -*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 counts, you can use the `getUnreadMessageCount()` method. This method has two variants: - - - -```swift -CometChat.getUnreadMessageCount(callbacks) -``` - - - - - -If you wish to ignore the messages from blocked users you can use the below syntax setting the boolean parameter to true: - - - -```swift -CometChat.getUnreadMessageCount(hideMessagesFromBlockedUsers:true, callbacks) -``` - - - - - - - -```swift -CometChat.getUnreadMessageCount(onSuccess: { (response) in - - print("Unread message count: \(response)") - -}) { (error) in - - print("Error in fetching unread count: \(error)") -} -``` - - - - - -In the `onSuccess()` callback, you will receive a dictionary having two keys: - -1. user - The value for this key holds another dictionary that holds the UIDs of the users and their corresponding unread message counts -2. group - The value for this key holds another dictionary that holds the GUIDs of the groups and their corresponding unread message counts - -### Fetch Unread Message Count of all one-on-one conversation - -*In other words, 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. - -This method, just like others, has two variants: - - - -```swift -CometChat.getUnreadMessageCountForAllUsers(callbacks) -``` - - - - - -If you wish to ignore the messages from blocked users you can use the below syntax setting the boolean parameter to true: - - - -```swift -CometChat.getUnreadMessageCountForAllUsers(hideMessagesFromBlockedUsers:true, callbacks) -``` - - - - - - - -```swift -CometChat.getUnreadMessageCountForAllUsers(onSuccess: { response in - - print("Unread count for all users: \(response)") - -}) { (error) in - - print("Error in fetching unread count for all users: \(error?.errorDescription)") -} -``` - - - - - -In the `onSuccess()` callback, you will receive a dictionary that will contain the UIDs of the users as the key and the unread message counts as the values. - -### Fetch Unread Message Count of all group conversation - -*In other words, 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. - -This method has two variants: - - - -```swift -CometChat.getUnreadMessageCountForAllGroups(callbacks) -``` - - - - - -If you wish to ignore the messages from blocked users you can use the below syntax setting the boolean parameter to true: - - - -```swift -CometChat.getUnreadMessageCountForAllGroups(hideMessagesFromBlockedUsers:true, callbacks) -``` - - - - - - - -```swift -CometChat.getUnreadMessageCountForAllGroups(onSuccess: { response in - - print("Unread count for all groups: \(response)") - -}) { (error) in - - print("Error in fetching unread count for all groups: \(error.errorDescription)") -} -``` - - +--- - +## Next Steps -In the `onSuccess()` callback, you will receive a dictionary that will contain the GUIDs of the groups as the key and the unread message counts as the values. + + + Track when messages are delivered and read by recipients + + + Show real-time typing status in conversations + + diff --git a/sdk/ios/recording.mdx b/sdk/ios/recording.mdx index f1a5ab6e4..78cab15bf 100644 --- a/sdk/ios/recording.mdx +++ b/sdk/ios/recording.mdx @@ -1,9 +1,32 @@ --- title: "Recording" +sidebarTitle: "Recording" +description: "Implement call recording for voice and video calls using the CometChat iOS SDK, including start/stop controls and listeners." --- + +```swift +// Start recording +CometChatCalls.startRecording() + +// Stop recording +CometChatCalls.stopRecording() + +// Auto-start recording when call begins +let callSettings = CallSettings.CallSettingsBuilder(callView: callView, sessionId: sessionID) + .startRecordingOnCallStart(true) + .showCallRecordButton(true) + .build() + +// Listen for recording events (CallsEventsDelegate) +func onRecordingToggled(recordingInfo: RTCRecordingInfo) { + print("Recording: \(recordingInfo)") +} +``` +**Recordings are available on the [CometChat Dashboard](https://app.cometchat.com) under the Calls section.** + This section will guide you to implement call recording feature for the voice and video calls. ## Implementation @@ -23,52 +46,110 @@ let callToken = "" let callSettings = CallSettings.CallSettingsBuilder(callView: callView, sessionId:sessionID).setAudioOnlyCall(audioOnly: true).enableDefaultLayout(defaultLayout: true).build() - CometChatCalls.startSession(callToken: callToken, callSetting: callSettings, view: callView) { success in +CometChatCalls.startSession(callToken: callToken, callSetting: callSettings, view: callView) { success in print("CometChatCalls startSession success: \(success)") - } onError: { error in - print("CometChatCalls startSession error: \(String(describing: error?.errorDescription))") - } +} onError: { error in + print("CometChatCalls startSession error: \(String(describing: error?.errorDescription))") +} ``` -
-
## 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 customise the overall calling experience. The properties for the call/conference can be set using the `CallSettingsBuilder` class. This will eventually give 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: -| Setting | Description | -| -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `showCallRecordButton(boolean showCallRecordButton)` | 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(boolean startRecordingOnCallStart)` | 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** | +| Setting | Type | Default | Description | +| ------- | ---- | ------- | ----------- | +| `showCallRecordButton(_:)` | Bool | false | Show/hide recording button in UI | +| `startRecordingOnCallStart(_:)` | Bool | false | Auto-start recording when call starts | + +### Show Recording Button + + + +```swift +let callSettings = CallSettings.CallSettingsBuilder(callView: callView, sessionId: sessionID) + .setAudioOnlyCall(audioOnly: false) + .enableDefaultLayout(defaultLayout: true) + .showCallRecordButton(true) + .build() +``` + + + +### Auto-Start Recording + + + +```swift +let callSettings = CallSettings.CallSettingsBuilder(callView: callView, sessionId: sessionID) + .setAudioOnlyCall(audioOnly: false) + .enableDefaultLayout(defaultLayout: true) + .startRecordingOnCallStart(true) + .build() +``` + + ### Start Recording -You can use the startRecording() method to start call recording. +You can use the `startRecording()` method to start call recording manually during an active call. ```swift CallManager.startRecording() -``` +// Alternative using CometChatCalls directly: +CometChatCalls.startRecording() +``` - ### Stop Recording -You can use the stopRecording() method to stop call recording. +You can use the `stopRecording()` method to stop call recording. ```swift CallManager.stopRecording() -``` +// Alternative using CometChatCalls directly: +CometChatCalls.stopRecording() +``` + + +## Recording Listener + +Implement `CallsEventsDelegate` to receive recording state change notifications. All participants receive the `onRecordingToggled` callback when recording starts or stops. + + +```swift +extension ViewController: CallsEventsDelegate { + func onRecordingToggled(recordingInfo: RTCRecordingInfo) { + print("Recording state changed: \(recordingInfo)") + // Update UI based on recording state + } +} +``` + + +--- + +## Next Steps + + + + Implement ringing call flows with accept/reject functionality + + + Retrieve and display call history for users and groups + + diff --git a/sdk/ios/remove-delivered-notifications.mdx b/sdk/ios/remove-delivered-notifications.mdx index d3d291ee8..77af1355a 100644 --- a/sdk/ios/remove-delivered-notifications.mdx +++ b/sdk/ios/remove-delivered-notifications.mdx @@ -1,12 +1,21 @@ --- title: "Remove Delivered Notifications" +description: "Guide to removing delivered push notifications programmatically using Notification Service Extension." --- + +- **Requires:** UNNotificationServiceExtension target in your app +- **Remove specific:** `UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers:)` +- **Remove all:** `UNUserNotificationCenter.current().removeAllDeliveredNotifications()` +- **Use case:** Clear notifications when user reads message in-app +- **Related:** [Push Notifications](/sdk/ios/push-notification-overview) · [Increment Badge Count](/sdk/ios/increment-app-icon-badge-count) -This guide helps you to set up with which you can remove certainly delivered notifications using **Notification Service Extension**. + -For removing notifications you will need to add Notification Service in your project. Please follow the below step to add Notification Service Extension in your app. +This guide helps you remove delivered notifications using **Notification Service Extension**. + +For removing notifications you will need to add Notification Service in your project. *** @@ -14,16 +23,12 @@ For removing notifications you will need to add Notification Service in your pro This service grabs the data from the push notification payload, the user can modify its content and display the customized data on to the push notification. -In our case, we are modifying the data of the push notification and incrementing the badge count when a new push notification is received. - If you already have Notification Service Extension then you can skip Step1. -Let's begin to implement an incremented badge count for your app. - *** ### **Step 1: Add UNNotificationServiceExtension inside the app.** @@ -42,7 +47,7 @@ Let's begin to implement an incremented badge count for your app. ### **Step 2: Add CometChat SDK in your Notification Extension.** -Make sure you are adding the CometChat SDK in your Notification Extension. So in case if you are using pods then your pod file should contain the following: +Make sure you are adding the CometChat SDK in your Notification Extension. If you are using pods then your pod file should contain the following: @@ -65,7 +70,7 @@ end ### **Step 3: Add Code for removing Notifications.** -Once you have successfully configured the Notification Service then add the below code in `didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent)` method under `bestAttemptContent` condition. The below code shows how you can remove the notifications for `call` type messages since we need to show the latest call notification. +Once you have configured the Notification Service, add the below code in `didReceive(_:withContentHandler:)` method under `bestAttemptContent` condition. The below code shows how you can remove the notifications for `call` type messages since we need to show the latest call notification. @@ -129,9 +134,9 @@ override func didReceive(_ request: UNNotificationRequest, withContentHandler co -In the above code, we are trying to remove the previous notification of the call message when the end call or unanswered call notification appears. Since we always have to show the latest notification for calls. We are removing the previous call notifications based on the call `sessionID`. +In the above code, we are removing the previous notification of the call message when the end call or unanswered call notification appears. We are removing the previous call notifications based on the call `sessionID`. -You can change the implementation as per your service. Once you added the code the above code add the completion handler in the main thread like shown below: +You can change the implementation as per your service. Once you added the code, add the completion handler in the main thread: @@ -144,3 +149,22 @@ DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { + +--- + +## Next Steps + + + + Set up push notifications for your iOS app + + + Update app icon badge from push notifications + + + Mark messages as delivered via push notification + + + Keep real-time connection alive in background + + diff --git a/sdk/ios/resources-overview.mdx b/sdk/ios/resources-overview.mdx index 2ad1c8400..69583fb5b 100644 --- a/sdk/ios/resources-overview.mdx +++ b/sdk/ios/resources-overview.mdx @@ -3,7 +3,18 @@ title: "Resources" sidebarTitle: "Overview" --- - + + +Available iOS SDK resources: +- [Real-Time Delegates (Listeners)](/sdk/ios/all-real-time-delegates-listeners) — Live events for users, groups, messages, and calls +- [Publishing to App Store](/sdk/ios/publishing-app-on-appstore) — Strip simulator architectures for submission +- [Increment Badge Count](/sdk/ios/increment-app-icon-badge-count) — Update app icon badge on new messages +- [Upgrading from v1 to v2](/sdk/ios/upgrading-from-v2) — Migration guide for v1 users +- [Remove Delivered Notifications](/sdk/ios/remove-delivered-notifications) — Clear notifications after reading +- [Launch Call Screen from Push](/sdk/ios/launch-call-screen-on-tap-of-push-notification) — Handle incoming call notifications +- [Launch Chat from Push](/sdk/ios/launch-chat-window-on-tap-of-push-notification) — Handle message notifications +- [Background Updates](/sdk/ios/prepare-your-app-for-background-updates) — Configure background processing + We have a number of resources that will help you while integrating CometChat in your app. @@ -82,3 +93,22 @@ Learn [how to launch a chat window from the UI Kit library on receiving a new me Learn [how to prepare your app for background updates](/sdk/ios/prepare-your-app-for-background-updates) + +--- + +## Next Steps + + + + Handle live events for users, groups, messages, and calls + + + Prepare and submit your app to the App Store + + + Update app icon badge on new messages + + + Configure background processing for your app + + diff --git a/sdk/ios/retrieve-conversations.mdx b/sdk/ios/retrieve-conversations.mdx index 8d873f7f5..a79ef7097 100644 --- a/sdk/ios/retrieve-conversations.mdx +++ b/sdk/ios/retrieve-conversations.mdx @@ -1,229 +1,162 @@ --- title: "Retrieve Conversations" +sidebarTitle: "Retrieve Conversations" +description: "Fetch, filter, tag, and search conversations using the CometChat iOS SDK." --- + +```swift +// Fetch conversations list +let request = ConversationRequest.ConversationRequestBuilder(limit: 30).build() +request.fetchNext(onSuccess: { conversations in }, onError: { error in }) -CometChat Allows you to fetch the list of conversations the logged-in user is a part of. This list of conversations consists of both user and group conversations. +// Get a specific conversation +CometChat.getConversation(conversationWith: "UID", conversationType: .user, onSuccess: { conv in }, onError: { error in }) -## Retrieve List of Conversations +// Tag a conversation +CometChat.tagConversation(conversationWith: "UID", conversationType: .user, tags: ["archived"], onSuccess: { conv in }, onError: { error in }) + +// Convert message to conversation +let conv = CometChat.getConversationFromMessage(message) +``` + -*In other words, as a logged-in user, how do I retrieve the latest conversations that I've been a part of?* +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. -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. +## Retrieve List of Conversations -The `ConversationsRequestBuilder` class allows you to set the below parameters: +Use `ConversationsRequest` with `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. Maximum is 50. - - ```swift -var conversationRequest = ConversationRequest.ConversationRequestBuilder(limit: 30) - .build() +var conversationRequest = ConversationRequest.ConversationRequestBuilder(limit: 30).build() ``` - - - - - - -A Maximum of only 50 Conversations can be fetched at once. If you want to fetch more conversation, you can use the fetchNext() on the same conversationsRequest Object - - - ### 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: a. CometChat.conversationType.user(user) - Only fetches user conversation. b. CometChat.conversationType.group(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. ```swift -var conversationRequest = ConversationRequest.ConversationRequestBuilder(limit: 30) - .setConversationType(conversationType: .group) - .build(); +var conversationRequest = ConversationRequest.ConversationRequestBuilder(limit: 50) + .setConversationType(conversationType: .user) + .build() ``` - - ```swift -var conversationRequest = ConversationRequest.ConversationRequestBuilder(limit: 30) +var conversationRequest = ConversationRequest.ConversationRequestBuilder(limit: 50) .setConversationType(conversationType: .group) - .build(); + .build() ``` - - ### 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`. - - ```swift -var conversationRequest = ConversationRequest.ConversationRequestBuilder(limit: 30) +var conversationRequest = ConversationRequest.ConversationRequestBuilder(limit: 50) .withUserAndGroupTags(true) - .build(); + .build() ``` - - - - ### Set User Tags -This method fetches user conversations that have the specified tags. +Fetch user conversations where the user has specific tags. - - ```swift +let limit = 30 let userTags = ["tag1"] -let conversationRequest = ConversationRequest.ConversationRequestBuilder(limit: 30) +let conversationRequest = ConversationRequest.ConversationRequestBuilder(limit: limit) .setUserTags(userTags) - .build(); + .build() ``` - - - - ### Set Group Tags -This method fetches group conversations that have the specified tags. +Fetch group conversations where the group has specific tags. - - ```swift -let userTags = ["tag1"] -let conversationRequest = ConversationRequest.ConversationRequestBuilder(limit: 30) - .setGroupTags(userTags) - .build(); +let limit = 30 +let groupTags = ["tag1"] +let conversationRequest = ConversationRequest.ConversationRequestBuilder(limit: limit) + .setGroupTags(groupTags) + .build() ``` - - - - ### 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`. - - ```swift -var conversationRequest = ConversationRequest.ConversationRequestBuilder(limit: 30) +var conversationRequest = ConversationRequest.ConversationRequestBuilder(limit: 50) .withTags(true) - .build(); + .build() ``` - - - - ### Set Tags -This method helps you fetch the conversations based on the specified tags. +Fetch conversations that have specific tags. - - ```swift -let tags = ["pinned","archived"] -var conversationRequest = ConversationRequest.ConversationRequestBuilder(limit: 30) +let tags = ["pinned", "archived"] +var conversationRequest = ConversationRequest.ConversationRequestBuilder(limit: 50) .setTags(tags) - .build(); + .build() ``` - - - - ### Include Blocked Users -This method helps you fetch the conversations of users whom the logged-in user has blocked. - - - ```swift -var conversationRequest = ConversationRequest.ConversationRequestBuilder(limit: 30) - .include(blockedUsers: true) - .build(); +var conversationRequest = ConversationRequest.ConversationRequestBuilder(limit: 50) + .includeBlockedUsers(true) + .build() ``` - - - - ### With Blocked Info -This method can be used to fetch the blocked information of the blocked user in the ConversationWith object. - - - ```swift -var conversationRequest = ConversationRequest.ConversationRequestBuilder(limit: 30) - .with(blockedInfo: true) - .build(); +var conversationRequest = ConversationRequest.ConversationRequestBuilder(limit: 50) + .withBlockedInfo(true) + .build() ``` - - - - ### Search Conversations -This method helps you search a conversation based on User or Group name. +Search conversations by user or group name. - -This feature is only available with `Conversation & Advanced Search`. 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) - +`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. - - ```swift -var conversationRequest = ConversationRequest.ConversationRequestBuilder(limit: 30) - .set(searchKeyword: "Hiking") - .build(); +var conversationRequest = ConversationRequest.ConversationRequestBuilder(limit: 50) + .setSearchKeyword("Hiking") + .build() ``` - - - - ### Unread Conversations -This method helps you fetch unread conversations. - - -This feature is only available with `Conversation & Advanced Search`. 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) - +`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. - - ```swift -var conversationRequest = ConversationRequest.ConversationRequestBuilder(limit: 30) - .set(unread: true) - .build(); +var conversationRequest = ConversationRequest.ConversationRequestBuilder(limit: 50) + .setUnread(true) + .build() ``` - - - +### Fetch Conversations -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. +After configuring the builder, call `build()` to create the request, then `fetchNext()` to retrieve conversations. Call `fetchNext()` repeatedly on the same object to paginate. @@ -238,9 +171,7 @@ convRequest.fetchNext(onSuccess: { (conversationList) in print("here exception \(String(describing: exception?.errorDescription))") } ``` - - ```swift let convRequest = ConversationRequest.ConversationRequestBuilder(limit: 20) @@ -253,120 +184,96 @@ convRequest.fetchNext(onSuccess: { (conversationList) in print("here exception \(String(describing: exception?.errorDescription))") } ``` - - -The `Conversation` object consists of the below fields: +The [`Conversation`](/sdk/reference/entities#conversation) object consists of the following fields: -| Field | Information | -| ------------------- | ----------------------------------------------- | -| conversationId | id of the conversation | -| conversationType | type of conversation (user/group) | -| lastMessage | last message in the conversation | -| conversationWith | User or Group object containing the details | -| 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 | +| Field | Information | +|-------|-------------| +| conversationId | ID of the conversation | +| conversationType | Type of conversation (user/group) | +| lastMessage | Last message in the conversation | +| conversationWith | User or Group object containing the details | +| unreadMessageCount | Unread message count for the conversation | ## 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. +Use `tagConversation()` to add tags to a conversation. -2. `conversationType`: The `conversationType` variable can hold one of the below two values: +| Parameter | Description | +| --- | --- | +| `conversationWith` | UID or GUID of the user/group | +| `conversationType` | `.user` or `.group` | +| `tags` | Array of tags to add | - 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. - - - ```swift -let id = "cometchat-uid-1"; //id of the user/group -let tags = ["pinned"]; - -CometChat.tagConversation(conversationWith: id, conversationType: .user, tags: tags, - onSuccess: { conversation in - print("conversation", conversation) - }, - onError: { error in - print("error", error) - } -) +let id = "cometchat-uid-1" +let tags = ["pinned"] + +CometChat.tagConversation(conversationWith: id, conversationType: .user, tags: tags, onSuccess: { conversation in + print("conversation", conversation) +}, onError: { error in + print("error", error) +}) ``` - - - - - -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. - +Tags for conversations are one-way. If user A tags a conversation with user B, that tag applies only for user A. ## 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. - -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: - -* user - Only fetches user conversation. -* group - Only fetches group conversations. +Use `getConversation()` to fetch a specific conversation. ```swift -CometChat.getConversation(conversationWith: "conversationWith", conversationType: .user) { conversation in +CometChat.getConversation(conversationWith: "cometchat-uid-3", conversationType: .user, onSuccess: { conversation in print("success \(String(describing: conversation?.stringValue()))") -} onError: { error in +}) { error in print("error \(String(describing: error?.errorDescription))") } ``` - - ```swift -CometChat.getConversation( - conversationWith: "conversationWith", conversationType: .group, - onSuccess: { (conversation) in - print("success \(String(describing: conversation?.stringValue()))") - } -) { (error) in +CometChat.getConversation(conversationWith: "cometchat-guid-101", conversationType: .group, onSuccess: { conversation in + print("success \(String(describing: conversation?.stringValue()))") +}) { error in print("error \(String(describing: error?.errorDescription))") } ``` - - -## Get Conversation From Message +## Convert Messages to Conversations -For real-time events, 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 `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. - - ```swift let myConversation = CometChat.getConversationFromMessage(message) ``` - - - - +When converting a message to a conversation, `unreadMessageCount` and `tags` won't be available. Manage unread counts in your client-side code. + -While converting a `Message` object to a `Conversation` object, the `unreadMessageCount` will not be available in the `Conversation` object. As this is for real-time events, the unread message count needs to be managed in your client-side code. +--- - +## Next Steps + + + + Remove conversations from the logged-in user's list + + + Listen for incoming messages to update conversation lists in real time + + + Show real-time typing status in conversations + + + Track message delivery and read status per conversation + + diff --git a/sdk/ios/retrieve-group-members.mdx b/sdk/ios/retrieve-group-members.mdx index e96f3d0b0..15ae0fb43 100644 --- a/sdk/ios/retrieve-group-members.mdx +++ b/sdk/ios/retrieve-group-members.mdx @@ -1,110 +1,129 @@ --- title: "Retrieve Group Members" +sidebarTitle: "Retrieve Members" +description: "Fetch and filter group members by scope, status, and search keyword using the CometChat iOS SDK with pagination support." --- + +```swift +// Fetch group members +let request = GroupMembersRequest.GroupMembersRequestBuilder(guid: "GUID") + .set(limit: 30).build() +request.fetchNext(onSuccess: { members in }, onError: { error in }) + +// Filter by scope +let scopeRequest = GroupMembersRequest.GroupMembersRequestBuilder(guid: "GUID") + .set(limit: 30).set(scopes: ["admin", "moderator"]).build() + +// Search members +let searchRequest = GroupMembersRequest.GroupMembersRequestBuilder(guid: "GUID") + .set(limit: 30).set(searchKeyword: "john").build() +``` + -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. +Fetch the members of a group with filtering by scope 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. -The `GroupMembersRequestBuilder` class allows you to set the below parameters: +## Retrieve the List of Group Members -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. The GUID must be specified in the constructor. -1. `set(limit: Int)` - This method sets the limit i.e. the number of members that should be fetched in a single iteration. +### Set Limit + +Sets the number of members to fetch per request. ```swift -let groupMembersRequest = GroupMembersRequest.GroupMembersRequestBuilder(guid: guid) -.set(limit: 30) -.build(); +let groupMembersRequest = GroupMembersRequest.GroupMembersRequestBuilder(guid: "cometchat-guid-1") + .set(limit: 30) + .build() ``` - - -2. `set(searchKeyword: String)` - This method allows you to set the search string based on which the group members are to be fetched. +### Set Search Keyword + +Filters members by a search string. ```swift -let groupMembersRequest = GroupMembersRequest.GroupMembersRequestBuilder(GUID: guid) -.set(limit: 30) -.set(searchKeyword : "abc") -.build(); +let groupMembersRequest = GroupMembersRequest.GroupMembersRequestBuilder(guid: "cometchat-guid-1") + .set(limit: 30) + .set(searchKeyword: "abc") + .build() ``` - - -3. `set(scopes: [String])` - This method allows you to fetch group members based on multiple scopes. +### Set Scopes + +Filters members by one or more scopes (`.admin`, `.moderator`, `.participant`). ```swift -let groupMembersRequest = GroupMembersRequest.GroupMembersRequestBuilder(GUID: guid) -.set(limit: 30) -.set(scopes : ["admin","participant"]) -.build(); +let groupMembersRequest = GroupMembersRequest.GroupMembersRequestBuilder(guid: "cometchat-guid-1") + .set(limit: 30) + .set(scopes: ["admin", "participant"]) + .build() ``` - - -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. +### Fetch Group Members -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. +After configuring the builder, call `build()` to create the request, then `fetchNext()` to retrieve members. Call `fetchNext()` repeatedly on the same instance to paginate. ```swift -let limit = 10; -let guid = "cometchat-guid-11" +let limit = 30 +let guid = "cometchat-guid-1" -let groupMembersRequest = GroupMembersRequest.GroupMembersRequestBuilder(guid: guid).set(limit: limit).build(); +let groupMembersRequest = GroupMembersRequest.GroupMembersRequestBuilder(guid: guid) + .set(limit: limit) + .build() groupMembersRequest.fetchNext(onSuccess: { (groupMembers) in - - for member in groupMembers { - - print("Group Member fetched successfully. " + member.stringValue()) - } - -}) { (error) in - - print("Group Member list fetching failed with error:" + error!.errorDescription); -} + for member in groupMembers { + print("Member: \(member.stringValue())") + } +}, onError: { (error) in + print("Error: \(error?.errorDescription)") +}) ``` - - ```objc -NSString *guid = @"cometchat-guid-101"; +NSString *guid = @"cometchat-guid-1"; NSInteger limit = 30; + GroupMembersRequest *groupMemberRequest = [[[[GroupMembersRequestBuilder alloc]initWithGuid:guid] setLimitWithLimit:limit] build]; [groupMemberRequest fetchNextOnSuccess:^(NSArray * groupMembers) { - - // received group members list - for (GroupMember *member in groupMembers) { - - // member - NSLog(@"Group Member fetched successfully: %@",[member stringValue]); + NSLog(@"Member: %@", [member stringValue]); } - } onError:^(CometChatException * error) { - - // Error - NSLog(@"Group Member list fetching failed with exception: %@",[error ErrorDescription]); - + NSLog(@"Error: %@", [error errorDescription]); }]; ``` - - + +The `fetchNext()` method returns an array of [`GroupMember`](/sdk/reference/entities#groupmember) objects. [`GroupMember`](/sdk/reference/entities#groupmember) extends [`User`](/sdk/reference/entities#user) and adds group-specific fields like `scope` and `joinedAt`. + +--- + +## Next Steps + + + + Add users to a group programmatically + + + Remove or ban members from a group + + diff --git a/sdk/ios/retrieve-groups.mdx b/sdk/ios/retrieve-groups.mdx index 44a55457d..a5d9b4e1b 100644 --- a/sdk/ios/retrieve-groups.mdx +++ b/sdk/ios/retrieve-groups.mdx @@ -1,214 +1,216 @@ --- title: "Retrieve Groups" +sidebarTitle: "Retrieve Groups" +description: "Fetch, filter, and search groups using the CometChat iOS SDK. Includes pagination, tag-based filtering, joined-only groups, and online member counts." --- + +```swift +// Fetch groups list +let request = GroupsRequest.GroupsRequestBuilder() + .set(limit: 30).build() +request.fetchNext(onSuccess: { groups in }, onError: { error in }) -## Retrieve List of Groups +// Get specific group details +CometChat.getGroup(GUID: "GUID", onSuccess: { group in }, onError: { error in }) + +// Fetch only joined groups +let joinedRequest = GroupsRequest.GroupsRequestBuilder() + .set(limit: 30).set(joinedOnly: true).build() -*In other words, as a logged-in user, how do I retrieve the list of groups I've joined and groups that are available?* +// Get online member count +CometChat.getOnlineGroupMemberCount(["GUID"], + onSuccess: { countData in }, onError: { error in }) +``` + + +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. -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. +## Retrieve List of Groups -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. ```swift -let groupsRequest = GroupsRequest.GroupsRequestBuilder.set(limit: 30).build(); +let groupsRequest = GroupsRequest.GroupsRequestBuilder() + .set(limit: 30) + .build() ``` - - ### 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. ```swift -let groupsRequest = GroupsRequest.GroupsRequestBuilder -.set(searchKeyword : "abc") -.set(limit: 30) -.build(); +let groupsRequest = GroupsRequest.GroupsRequestBuilder() + .set(searchKeyword: "abc") + .set(limit: 30) + .build() ``` - - ### 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. ```swift -let groupsRequest = GroupsRequest.GroupsRequestBuilder -.set(joinedOnly: true) -.build(); +let groupsRequest = GroupsRequest.GroupsRequestBuilder() + .set(joinedOnly: true) + .set(limit: 30) + .build() ``` - - ### 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. ```swift -let groupRequest = GroupsRequest.GroupsRequestBuilder() -.set(limit: 30) -.set(tags: ["tag1", "tag2"]) -.build(); +let groupsRequest = GroupsRequest.GroupsRequestBuilder() + .set(limit: 30) + .set(tags: ["tag1", "tag2"]) + .build() ``` - - ### 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. ```swift -let groupRequest = GroupsRequest.GroupsRequestBuilder() -.set(limit: 30) -.withTags(true) -.build(); +let groupsRequest = GroupsRequest.GroupsRequestBuilder() + .set(limit: 30) + .withTags(true) + .build() ``` - - -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. + ```swift -let limit = 30 +let limit = 30 -let groupsRequest = GroupsRequest.GroupsRequestBuilder(limit: limit).build(); +let groupsRequest = GroupsRequest.GroupsRequestBuilder(limit: limit).build() groupsRequest.fetchNext(onSuccess: { (groups) in - - for group in groups { - - print("Groups list fetched successfully. " + group.stringValue()) - } - -}) { (error) in - - print("Groups list fetching failed with error:" + error!.errorDescription); -} + for group in groups { + print("Group: \(group.stringValue())") + } +}, onError: { (error) in + print("Error: \(error?.errorDescription)") +}) ``` - - ```objc -NSInteger limit = 30 ; +NSInteger limit = 30; -GroupsRequest *groupRequest = [[[GroupsRequestBuilder alloc]initWithLimit:limit] build]; +GroupsRequest *groupRequest = [[[GroupsRequestBuilder alloc]initWithLimit:limit] build]; [groupRequest fetchNextOnSuccess:^(NSArray * groups) { - for (Group *group in groups) { - NSLog(@"Groups list fetched successfully. %@",[group stringValue]); + NSLog(@"Group: %@", [group stringValue]); } - } onError:^(CometChatException * error) { - - NSLog(@"Groups list fetching failed with error: %@",[error errorDescription]); + NSLog(@"Error: %@", [error errorDescription]); }]; ``` - - ## 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. ```swift -let guid = "cometchat-guid-11" +let guid = "cometchat-guid-1" CometChat.getGroup(GUID: guid, onSuccess: { (group) in - - print("Group details fetched successfully. " + group!.stringValue()) - -}) { (error) in - - print("Group details fetching failed with error:" + error!.errorDescription); -} + print("Group: \(group.stringValue())") +}, onError: { (error) in + print("Error: \(error?.errorDescription)") +}) ``` - - ```objc -NSString *guid = @"cometchat-guid-101"; +NSString *guid = @"cometchat-guid-1"; [CometChat getGroupWithGUID:guid onSuccess:^(Group * group) { - - NSLog(@"Group details fetched successfully. %@",[group stringValue]); - + NSLog(@"Group: %@", [group stringValue]); } onError:^(CometChatException * error) { - - NSLog(@"Group details fetching failed with error: %@",[error errorDescription]); + NSLog(@"Error: %@", [error errorDescription]); }]; ``` - - -| 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 | -On success, the `Group` object containing the details of the group is returned. +The method returns a [`Group`](/sdk/reference/entities#group) object. -## 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. ```swift -let data = ["cometchat-guid-1","cometchat-guid-11"] -CometChat.getOnlineGroupMemberCount(data, onSuccess: { - countData in - print(countData) -}, onError: { - error in - print(error?.errorDescription) - }) -``` +let guids = ["cometchat-guid-1", "cometchat-guid-2"] +CometChat.getOnlineGroupMemberCount(guids, onSuccess: { countData in + // countData: [String: Int] - GUID as key, count as value + for (guid, count) in countData { + print("Group \(guid): \(count) online members") + } +}, onError: { error in + print("Error: \(error?.errorDescription)") +}) +``` - -This method returns a Dictionary\ with the GUID as the key and the online member count for that group as the value. +Returns a `[String: Int]` dictionary with GUIDs as keys and online member counts as values. + +--- + +## Next Steps + + + + Create public, private, or password-protected groups + + + Fetch and filter members of a specific group + + diff --git a/sdk/ios/retrieve-users.mdx b/sdk/ios/retrieve-users.mdx index 2f3579a12..a5b514a53 100644 --- a/sdk/ios/retrieve-users.mdx +++ b/sdk/ios/retrieve-users.mdx @@ -1,41 +1,53 @@ --- title: "Retrieve Users" +sidebarTitle: "Retrieve Users" +description: "Fetch, filter, search, and sort users using the CometChat iOS SDK. Includes pagination, role-based filtering, tag support, and online status filtering." --- + +```swift +// Fetch users list +let request = UsersRequest.UsersRequestBuilder() + .set(limit: 30).build() +request.fetchNext(onSuccess: { users in }, onError: { error in }) + +// Get specific user details +CometChat.getUser(UID: "UID", onSuccess: { user in }, onError: { error in }) + +// Get logged-in user +let me = CometChat.getLoggedInUser() +``` + + +The CometChat SDK provides methods to retrieve the logged-in user, fetch filtered user lists, and look up individual users by UID. All user methods return [`User`](/sdk/reference/entities#user) objects. -## Retrieve Logged In User Details +## Get the Logged-In User -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 `nil`, 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. Returns `nil` if no user is logged in. ```swift let user = CometChat.getLoggedInUser(); ``` - - ```objc User *user = [CometChat getLoggedInUser]; ``` - - -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 containing all the information related to the logged-in 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. - -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. @@ -44,14 +56,12 @@ let usersRequest = UsersRequest.UsersRequestBuilder() .set(limit: 30) .build() ``` - - ### 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. @@ -61,14 +71,12 @@ let usersRequest = UsersRequest.UsersRequestBuilder() .set(searchKeyword: "abc") .build() ``` - - ### 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 `set(searchKeyword:)`. By default, searches both UID and name. @@ -78,22 +86,20 @@ let searchIn = ["uid", "name"] let usersRequest = UsersRequest.UsersRequestBuilder() .set(limit: 30) .set(searchKeyword: searchKeyword) -..searchIn(searchIn) +.searchIn(searchIn) .build() ``` - - ### 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.UserStatus.online - will return the list of only online users. -* CometChat.UserStatus.offline - will return the list of only offline users. +- `CometChat.UserStatus.online` — Only online users +- `CometChat.UserStatus.offline` — Only offline users -If this parameter is not set, will return all the available users. +If not set, returns all users. @@ -103,14 +109,12 @@ let usersRequest = UsersRequest.UsersRequestBuilder() .set(status: .online) .build() ``` - - ### 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. @@ -120,14 +124,12 @@ let usersRequest = UsersRequest.UsersRequestBuilder() .hideBlockedUsers(true) .build() ``` - - ### Set Roles -This method allows you to fetch the users based on multiple roles. +Filters users by specified roles. @@ -137,14 +139,12 @@ let usersRequest = UsersRequest.UsersRequestBuilder() .set(roles : ["role1","role2"]) .build() ``` - - ### 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. @@ -154,14 +154,12 @@ let usersRequest = UsersRequest.UsersRequestBuilder() .friendsOnly(true) .build(); ``` - - ### 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. @@ -171,14 +169,12 @@ let usersRequest = UsersRequest.UsersRequestBuilder() .set(tags: ["tag1", "tag2"]) .build(); ``` - - ### 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. @@ -188,14 +184,12 @@ let usersRequest = UsersRequest.UsersRequestBuilder() .withTags(true) .build() ``` - - ### 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. @@ -207,14 +201,12 @@ let usersRequest = UsersRequest.UsersRequestBuilder() .setUIDs(UIDs) .build(); ``` - - ### 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`. @@ -226,16 +218,12 @@ let usersRequest = UsersRequest.UsersRequestBuilder() .sortBy(sortBy) .build(); ``` - - ### 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. Use `.desc` for descending. @@ -246,14 +234,10 @@ let usersRequest = UsersRequest.UsersRequestBuilder() .sortOrder(.desc) .build(); ``` - - -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. @@ -274,9 +258,7 @@ usersRequest.fetchNext(onSuccess: { (users) in print("User list fetching failed with error: " + error!.errorDescription); } ``` - - ```objc NSInteger limit = 30 ; @@ -296,14 +278,12 @@ UsersRequest *userRequest = [[[UsersRequestBuilder alloc]initWithLimit:limit] bu }]; ``` - - ## 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. @@ -319,9 +299,7 @@ CometChat.getUser(UID: uid, onSuccess: { (user) in print("User fetching failed with error: " + error.errorDescription); } ``` - - ```objc NSString *UID = @"cometchat-uid-1"; @@ -335,15 +313,30 @@ NSString *UID = @"cometchat-uid-1"; NSLog(@"User fetching failed with error: %@",[error errorDescription]); }]; ``` - - -The `getUser()` method takes the following parameters: - | Parameter | Description | | --------- | ------------------------------------------------------------- | | UID | The `UID` of the user for whom the details are to be fetched. | -On success, the You will receive a `User` objects. +It returns a [`User`](/sdk/reference/entities#user) object containing the details of the user. + +--- + +## Next Steps + + + + Track and subscribe to user online/offline status + + + Block and unblock users from your application + + + Create, update, and delete users programmatically + + + Fetch conversation lists for your chat UI + + diff --git a/sdk/ios/send-message.mdx b/sdk/ios/send-message.mdx index 8b8b6fa19..a743649eb 100644 --- a/sdk/ios/send-message.mdx +++ b/sdk/ios/send-message.mdx @@ -1,80 +1,37 @@ --- -title: "Send A Message" +title: "Send Messages" +sidebarTitle: "Send Messages" +description: "Send text, media, and custom messages to users and groups using the CometChat iOS SDK." --- + +| Field | Value | +| --- | --- | +| Key Classes | [`TextMessage`](/sdk/reference/messages#textmessage), [`MediaMessage`](/sdk/reference/messages#mediamessage), [`CustomMessage`](/sdk/reference/messages#custommessage) | +| Key Methods | `sendTextMessage()`, `sendMediaMessage()`, `sendCustomMessage()` | +| Receiver Types | `.user`, `.group` | +| Message Types | `.text`, `.image`, `.video`, `.audio`, `.file`, custom | +| Prerequisites | SDK initialized, user logged in | -Using CometChat, you can send three types of messages: + -1. A [text message](/sdk/ios/send-message#text-message), the most common and standard message type. -2. A [media message](/sdk/ios/send-message#media-message), for sending photos, videos and files. -3. A [custom message](/sdk/ios/send-message#custom-message), for sending completely custom data using JSON structures. -4. [A Interactive Messages](/sdk/ios/interactive-messages) , for sending end-user interactive messages of type form, card and custom Interactive +CometChat supports three types of messages: -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. +| Type | Method | Use Case | +| --- | --- | --- | +| [Text](#text-message) | `sendTextMessage()` | 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. ## Text Message -*In other words, as a sender, 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. - -## Add Metadata - -To send custom data along with a text message, you can use the metadata field provided in `TextMessage`. A metadata field is a [`dictionary`](https://docs.swift.org/swift-book/LanguageGuide/CollectionTypes.html) of type `[String: Any]` which will be received as it was sent without any processing from CometChat. It can be used to send any additional data that needs to be sent along with a message. +Send a text message using `CometChat.sendTextMessage()` with a [`TextMessage`](/sdk/reference/messages#textmessage) object. - -```swift - let metadata = ["latitude":"50.6192171633316","longitude":"-72.68182268750002"]; - -textMessage.metaData = metadata; -``` - - - - -```objc - NSDictionary * metadata = @{@"latitude":@"50.6192171633316",@"longitude":@"-72.68182268750002"}; - -[textMessage setMetaData:metadata]; -``` - - - - - -### Add Tags - -To add a tag to a message you can use [`Array`](https://docs.swift.org/swift-book/LanguageGuide/CollectionTypes.html) of strings that you need to set it to property `tags`. - - - -```swift -let tags = ["pinned"] - -textMessage.tags = tags; -``` - - - - -```objc -NSArray * tags = @[@"latitude"]; - -[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. - - - + ```swift let receiverID = "cometchat-uid-2" let text = "Hello" @@ -82,18 +39,13 @@ let text = "Hello" let textMessage = TextMessage(receiverUid: receiverID, text: text, receiverType: .user) CometChat.sendTextMessage(message: textMessage, onSuccess: { (message) in - print("TextMessage sent successfully. " + message.stringValue()) - }) { (error) in - print("TextMessage sending failed with error: " + error!.errorDescription); } ``` - - - + ```objc NSString *receiverID = @"cometchat-uid-1"; NSString *text = @"Hello"; @@ -101,18 +53,13 @@ NSString *text = @"Hello"; TextMessage *textMessage = [[TextMessage alloc]initWithReceiverUid:receiverID text:text receiverType:ReceiverTypeUser]; [CometChat sendTextMessageWithMessage:textMessage onSuccess:^(TextMessage * message) { - NSLog(@"TextMessage sent successfully. %@",[message stringValue]); - } onError:^(CometChatException * error) { - NSLog(@"TextMessage sending failed with error: %@",[error errorDescription]); }]; ``` - - - + ```swift let receiverID = "cometchat-guid-102" let text = "Hello" @@ -120,18 +67,13 @@ let text = "Hello" let textMessage = TextMessage(receiverUid: receiverID, text: text, receiverType: .group) CometChat.sendTextMessage(message: textMessage, onSuccess: { (message) in - print("TextMessage sent successfully. " + message.stringValue()) - }) { (error) in - print("TextMessage sending failed with error: " + error!.errorDescription); } ``` - - - + ```objc NSString *receiverID = @"cometchat-guid-101"; NSString *text = @"Hello"; @@ -139,675 +81,249 @@ NSString *text = @"Hello"; TextMessage *textMessage = [[TextMessage alloc]initWithReceiverUid:receiverID text:text receiverType:ReceiverTypeGroup]; [CometChat sendTextMessageWithMessage:textMessage onSuccess:^(TextMessage * message) { - NSLog(@"TextMessage sent successfully. %@",[message stringValue]); - } onError:^(CometChatException * error) { - NSLog(@"TextMessage sending failed with error: %@",[error errorDescription]); }]; ``` - - - - - -The `TextMessage` class constructor takes the following parameters: - -| Parameters | Information | -| ------------ | -------------------------------------------------------------------------------- | -| receiverID | The `UID` or `GUID` of the recipient | -| text | The text to be sent | -| receiverType | The type of the receiver to whom the message is to be sent i.e `user` or `group` | - -When a text message is sent successfully, the response will include a `TextMessage` object which includes all information related to the sent message. - -### Set Quoted Message - -To set a quoted message for a message, use the `quotedMessageId`. - - - -```swift -textMessage.quotedMessageId = 0 -textMessage.quotedMessage = // Pass base message object here that you want to quote. -``` - - - -Once the text message object is ready, you need to use the `sendMessage()` method to send the text message to the recipient. - - - -```swift -var textMessage = TextMessage(receiverUid: currentUser?.uid ?? "", text: message, receiverType: .user) -textMessage.quotedMessageId = swipedMessage.id - -CometChat.sendTextMessage(message: textMessage, onSuccess: { (message) in - print("success") -}) { (error) in - DispatchQueue.main.async { - if let error = error { - print(error.errorDescription) - } - } -} -``` -The `TextMessage` class constructor takes the following parameters: +The [`TextMessage`](/sdk/reference/messages#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- `CometChatConstants.RECEIVER_TYPE_USER` (user) or `CometChatConstants.RECEIVER_TYPE_GROUP` (group) | Required | +| Parameter | Description | Required | +| --- | --- | --- | +| `receiverID` | UID of the user or GUID of the group receiving the message | Yes | +| `text` | The text message content | Yes | +| `receiverType` | `.user` or `.group` | Yes | -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. +On success, `sendTextMessage()` returns a [`TextMessage`](/sdk/reference/messages#textmessage) object containing all information about the sent message. ### Add Metadata -To send custom data along with a media message, you can use the metadata field provided in `MediaMessage`. A metadata field is a [`dictionary`](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/collectiontypes/) of type `[String: Any]` which will be received as it was sent without any processing from CometChat. It can be used to send any additional data that needs to be sent along with a message. +Send custom data along with a text message using the `metaData` property: ```swift let metadata = ["latitude":"50.6192171633316","longitude":"-72.68182268750002"]; - -mediaMessage.metaData = metadata; +textMessage.metaData = metadata; ``` - - - + ```objc NSDictionary * metadata = @{@"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 `setCaption` method and pass text to it. - - - -```swift -mediaMessage.caption = "Message Caption" +[textMessage setMetaData:metadata]; ``` - - ### Add Tags -To add a tag to a message you can use [`Array`](https://docs.swift.org/swift-book/LanguageGuide/CollectionTypes.html) of strings that you need to set it to property `tags`. - - - ```swift let tags = ["pinned"] - -textMessage.tags = tags; +textMessage.tags = tags ``` - +### Quote a Message - -```objc -NSArray * tags = @[@"latitude"]; - -[textMessage setTags:tags]; +```swift +textMessage.quotedMessageId = 140 +textMessage.quotedMessage = // Pass the BaseMessage object you want to quote ``` - +## Media Message - +Send images, videos, audio, or files using `CometChat.sendMediaMessage()`. -There are 2 ways you can send Media Messages using the CometChat SDK: +There are two ways to send media messages: +1. **Upload a file** — Pass a file path and CometChat uploads it automatically +2. **Send a URL** — Provide a URL to media hosted on your server or cloud storage -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. +### Upload a File ```swift let receiverid = "cometchat-uid-2" +let mediaUrl = "file:///Library/Developer/CoreSimulator/.../image.jpg" -let mediaUrl = "file:___Library_Developer_CoreSimulator_Devices_(numbers and letters)_data_Containers_Data_Application_(numbers and letters)_Documents_image.jpg" - -let mediaMessage = MediaMessage(receiverUid: receiverid, fileurl:mediaUrl, messageType: .image, receiverType: .user); +let mediaMessage = MediaMessage(receiverUid: receiverid, fileurl: mediaUrl, messageType: .image, receiverType: .user) CometChat.sendMediaMessage(message: mediaMessage, onSuccess: { (message) in - print("MediaMessage sent successfully. " + message.stringValue()) - }) { (error) in - print("MediaMessage sending failed with error: " + error.errorDescription); } ``` - - - + ```objc NSString *receiverID = @"cometchat-uid-1"; +NSString *filePath = @"Library/Developer/CoreSimulator/.../image.jpg"; -NSString *filePath = @"Library_Developer_CoreSimulator_Devices_(numbers and letters)_data_Containers_Data_Application_(numbers and letters)_Documents_image.jpg"; - -MediaMessage *mediaMessage = [MediaMessage alloc]initWithReceiverUid:receiverID fileurl:filePath messageType:messageTypeImage receiverType:ReceiverTypeUser]; +MediaMessage *mediaMessage = [[MediaMessage alloc]initWithReceiverUid:receiverID fileurl:filePath messageType:messageTypeImage receiverType:ReceiverTypeUser]; [CometChat sendMediaMessageWithMessage:mediaMessage onSuccess:^(MediaMessage * message) { - NSLog(@"MediaMessage sent successfully. %@",[message stringValue]); - } onError:^(CometChatException * error) { - NSLog(@"MediaMessage sending failed with error: %@",[error errorDescription]); - }]; ``` - - - - +### Send a URL + +Use the [`Attachment`](/sdk/reference/auxiliary#attachment) class to send media hosted on your server or cloud storage: + ```swift let receiverid = "cometchat-uid-2" +let mediaUrl = "https://pngimg.com/uploads/mario/mario_PNG125.png" -let mediaUrl = "Library_Developer_CoreSimulator_Devices_(numbers and letters)_data_Containers_Data_Application_(numbers and letters)_Documents_image.jpg" - -let mediaMessage = MediaMessage(receiverUid: receiverid, fileurl:mediaUrl, messageType: .image, receiverType: .group); +let mediaMessage = MediaMessage(receiverUid: receiverid, fileurl: "", messageType: .image, receiverType: .user) +mediaMessage.attachment = Attachment(fileName: "FileName", fileExtension: "png", fileMimeType: "image/png", fileUrl: mediaUrl) CometChat.sendMediaMessage(message: mediaMessage, onSuccess: { (message) in - print("MediaMessage sent successfully. " + message.stringValue()) - }) { (error) in - print("MediaMessage sending failed with error: " + error.errorDescription); } ``` - - - -```objc -NSString *receiverID = @"cometchat-uid-1"; - -NSString *filePath = @"Library_Developer_CoreSimulator_Devices_(numbers and letters)_data_Containers_Data_Application_(numbers and letters)_Documents_image.jpg"; +The [`MediaMessage`](/sdk/reference/messages#mediamessage) class constructor takes the following parameters: -MediaMessage *mediaMessage = [MediaMessage alloc]initWithReceiverUid:receiverID fileurl:filePath messageType:messageTypeImage receiverType:ReceiverTypeGroup]; +| Parameter | Description | Required | +| --- | --- | --- | +| `receiverID` | UID of the user or GUID of the group | Yes | +| `fileurl` | File path or empty string if using URL | Yes | +| `messageType` | `.image`, `.video`, `.audio`, or `.file` | Yes | +| `receiverType` | `.user` or `.group` | Yes | -[CometChat sendMediaMessageWithMessage:mediaMessage onSuccess:^(MediaMessage * message) { +On success, `sendMediaMessage()` returns a [`MediaMessage`](/sdk/reference/messages#mediamessage) object. - NSLog(@"MediaMessage sent successfully. %@",[message stringValue]); +### Add Caption -} onError:^(CometChatException * error) { - - NSLog(@"MediaMessage sending failed with error: %@",[error errorDescription]); - -}]; +```swift +mediaMessage.caption = "Message Caption" ``` - - - +### Add Metadata and Tags -To send a media message you need to create an object of the `MediaMessage` class. The initialize method of the `MediaMessage` class takes the following mandatory parameters: +Same as text messages: -| Parameter | Description | | -| ------------ | ------------------------------------------------------------------------------------------------------- | -------- | -| receiverId | The UID or GUID of the recipient | Required | -| fileurl | The file path object to be sent | Required | -| messageType | The type of the message that needs to be sent which in this case can be: - image - video - audio - file | Required | -| receiverType | The type of the receiver to whom the message is to be sent - user - 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 that is available in the MediaMessage class. For more information, you can refer to the below code snippet: - - - ```swift -let receiverid = "cometchat-uid-2" - -let mediaUrl = "https:__pngimg.com_uploads_mario_mario_PNG125.png" - -let mediaMessage = MediaMessage(receiverUid: receiverid, fileurl:"", messageType: .image, receiverType: .user); - -mediaMessage.attachment = Attachment(fileName: "FileName", fileExtension: "png", fileMimeType: "image_png", fileUrl: mediaUrl); - -CometChat.sendMediaMessage(message: mediaMessage, onSuccess: { (message) in - - print("MediaMessage sent successfully. " + message.stringValue()) - -}) { (error) in - - print("MediaMessage sending failed with error: " + error.errorDescription); -} +mediaMessage.metaData = ["location": "Paris"] +mediaMessage.tags = ["vacation"] ``` - - - - -On success, you will receive an object of the `MediaMessage` class containing all the information related to the sent media 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`. - ## Multiple Attachments in a Media Message -Starting version 3.0.906 & 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: - -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. +Starting version 3.0.906 & above, the SDK supports sending multiple attachments in a single media message. - - ```swift -String receiverId = "cometchat-uid-1" +let receiverId = "cometchat-uid-1" -let data = try? Data(contentsOf: URL(string: " file:___private_var_mobile_Containers_Data_Application_B71B0A14_tmp_1111.jpeg") -let data1 = try? Data(contentsOf: URL(string: " file:___private_var_mobile_Containers_Data_Application_B71B0A14_tmp_2222.jpeg") -let data2 = try? Data(contentsOf: URL(string: " file:___private_var_mobile_Containers_Data_Application_B71B0A14_tmp_3333.jpeg") +let data = try? Data(contentsOf: URL(string: "file:///path/to/image1.jpeg")!) +let data1 = try? Data(contentsOf: URL(string: "file:///path/to/image2.jpeg")!) var files = [File]() -files.append(File(name: "FileName 1", data: data) -files.append(File(name: "FileName 2", data: data1) -files.append(File(name: "FileName 3", data: data2) +files.append(File(name: "FileName 1", data: data)) +files.append(File(name: "FileName 2", data: data1)) -mediaMessage = MediaMessage(receiverUid: self.currentUser?.uid ?? "", files: files, messageType: .file, receiverType: .user) +let mediaMessage = MediaMessage(receiverUid: receiverId, files: files, messageType: .file, receiverType: .user) CometChat.sendMediaMessage(message: mediaMessage, onSuccess: { (message) in - print("Message sent successfully") + print("Message sent successfully") }, onError: { (error) in - print("Message sending failed with exception : ", error?.errorDescription) -} -``` - - - - - - - -```swift -mediaMessage = MediaMessage(receiverUid: self.currentUser?.uid ?? "", files: withFileArray, messageType: .file, receiverType: .user) -``` - - - - - -The `MediaMessage` class constructor takes the following parameters: - -| Parameter | Description | -| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **receiverId** | The `UID` or `GUID` of the recipient. | -| **files** | An array of File object. File object is made of name and data of the file | -| **messageType** | The type of the message that needs to be sent which in this case can be:
1. `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` | - -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: - - - -```swift -let mediaMessage = MediaMessage(receiverUid: self.currentUser?.uid ?? "", files: [], messageType: .file, receiverType: .user) -var attachments = [Attachment]() -for i in 0..<5 { - let attachement = Attachment(fileName: "test", fileExtension: "png", fileMimeType: "img_png", fileUrl: "https:__pngimg.com_uploads_mario_mario_PNG125.png") - attachments.append(attachement) -} -mediaMessage.attachments = attachments -CometChat.sendMediaMessage(message: mediaMessage!, onSuccess: { (message) in - print("Message Sent Successfully" -}) { (error) in - print("Message Sending Failed with exception : ",error.errorDesciption) - } + print("Message sending failed: ", error?.errorDescription) +}) ``` - - - - -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 -CometChat SDK allows you to send a completely custom message across. You can use this feature to send messages that do not fit in any default categories provided. In order to send a custom message, you need to use the `sendCustomMessage()` method. - -The `sendCustomMessage()` methods takes an object of the `CustomMessage` which can be obtained using the below two constructor: - - - -```swift -let customMessage : CustomMessage = CustomMessage(receiverId: receiverId, receiverType: .user, customData : customData, type: "Custom Type") -``` - - - - - -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. type - custom message type that you need to set -4. customData - The data to be passed as the message in the form of a Dictionary object. - -You can also use the subType field of the `CustomMessage` class to set a specific type for the CustomeMessage. - -### Add Tags - -To add a tag to a message you can use [`Array`](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/collectiontypes/) of strings that you need to set it to property `tags`. - - - -```swift -let tags = ["pinned"] - -textMessage.tags = tags; -``` - - - - -```objc -NSArray * tags = @[@"latitude"]; - -[textMessage setTags:tags]; -``` - - - - - -Once the object of `CustomMessage` class is ready you can send the custom message using the `sendCustomMessage()` method. +Send structured data that doesn't fit text or media categories — like location coordinates, polls, or game moves. - + ```swift let receiverid = "cometchat-uid-2" +let customData: [String: Any] = ["customKey": "customData"] -let customData : [String : Any] = ["customKey" : "customData"] - -let customMessage = CustomMessage(receiverUid: receiverid, receiverType: .user, customData : customData, type: "Custom Type"); +let customMessage = CustomMessage(receiverUid: receiverid, receiverType: .user, customData: customData, type: "Custom Type") CometChat.sendCustomMessage(message: customMessage, onSuccess: { (message) in - print("CustomMessage sent successfully. " + message.stringValue()) - }) { (error) in - print("CustomMessage sending failed with error: " + error!.errorDescription); } ``` - - - -```objc -NSString *receiverID = @"cometchat-uid-1"; - -NSMutableDictionary *customData = [NSMutableDictionary new]; - [customData setObject:@"customData" forKey:@"customKey"]; - -CustomMessage *customMessage = [CustomMessage alloc]initWithReceiverUid:receiverID receiverType:ReceiverTypeUser customData: customData type:@"Custom Type"]; - -[CometChat sendCustomMessageWithMessage:customMessage onSuccess:^(CustomMessage * message) { - - NSLog(@"CustomMessage sent successfully. %@",[message stringValue]); - -} onError:^(CometChatException * error) { - - NSLog(@"CustomMessage sending failed with error: %@",[error errorDescription]); - -}]; -``` - - - - + ```swift -let receiverid = "cometchat-uid-2" - -let customData : [String : Any] = ["customKey" : "customData"] +let receiverid = "cometchat-guid-1" +let customData: [String: Any] = ["customKey": "customData"] -let customMessage = CustomMessage(receiverUid: receiverid, receiverType: .group, customData : customData, type: "Custom Type"); +let customMessage = CustomMessage(receiverUid: receiverid, receiverType: .group, customData: customData, type: "Custom Type") CometChat.sendCustomMessage(message: customMessage, onSuccess: { (message) in - print("CustomMessage sent successfully. " + message.stringValue()) - }) { (error) in - print("CustomMessage sending failed with error: " + error!.errorDescription); } ``` - - - -```objc -NSString *receiverID = @"cometchat-uid-1"; - -NSMutableDictionary *customData = [NSMutableDictionary new]; -[customData setObject:@"customData" forKey:@"customKey"]; - -CustomMessage *customMessage = [CustomMessage alloc]initWithReceiverUid:receiverID receiverType:ReceiverTypeGroup customData: customData type:@"Custom Type"]; - -[CometChat sendCustomMessageWithMessage:customMessage onSuccess:^(CustomMessage * message) { - - NSLog(@"CustomMessage sent successfully. %@",[message stringValue]); - -} onError:^(CometChatException * error) { - - NSLog(@"CustomMessage sending failed with error: %@",[error errorDescription]); - -}]; -``` - - - -The above sample explains how custom messages can be used to share the location with a user. The same can be achieved for groups. - -In success, you will receive an object of the `CustomMessage` class. - -### Update Conversation - -How can I decide whether the custom message should update last message of a conversation? - -By default, a custom message will update the last message of a conversation. If you wish to not update last message of conversation when a custom message is sent, please use updateConversation property of the Custom Message. - - - -```swift -let receiverid = "cometchat-uid-2" -let customData : [String : Any] = ["customKey" : "customData"] -let customMessage = CustomMessage(receiverUid: receiverid, receiverType: .user, customData : customData, type: "Custom Type"); - -customMessage.updateConversation = false //for not updating conversation - -CometChat.sendCustomMessage(message: customMessage, onSuccess: { (message) in - print("CustomMessage sent successfully. " + message.stringValue()) -}) { (error) in - print("CustomMessage sending failed with error: " + error!.errorDescription); -} -``` - - - - -```objc -NSString *receiverID = @"cometchat-uid-1"; -NSMutableDictionary *customData = [NSMutableDictionary new]; - [customData setObject:@"customData" forKey:@"customKey"]; +The [`CustomMessage`](/sdk/reference/messages#custommessage) class constructor takes the following parameters: -CustomMessage *customMessage = [CustomMessage alloc]initWithReceiverUid:receiverID receiverType:ReceiverTypeUser customData: customData type:@"Custom Type"]; +| Parameter | Description | Required | +| --- | --- | --- | +| `receiverID` | UID of the user or GUID of the group | Yes | +| `receiverType` | `.user` or `.group` | Yes | +| `customData` | Dictionary with your custom data | Yes | +| `type` | Your custom type string (e.g., `"location"`, `"poll"`) | Yes | -customMessage.updateConversation = NO; //for not updating conversation +On success, `sendCustomMessage()` returns a [`CustomMessage`](/sdk/reference/messages#custommessage) object. -[CometChat sendCustomMessageWithMessage:customMessage onSuccess:^(CustomMessage * message) { - NSLog(@"CustomMessage sent successfully. %@",[message stringValue]); -} onError:^(CometChatException * error) { - NSLog(@"CustomMessage sending failed with error: %@",[error errorDescription]); -}]; -``` - - +### Add Tags - ```swift -let receiverid = "cometchat-uid-2" -let customData : [String : Any] = ["customKey" : "customData"] -let customMessage = CustomMessage(receiverUid: receiverid, receiverType: .group, customData : customData, type: "Custom Type"); - -customMessage.updateConversation = false //for not updating conversation - -CometChat.sendCustomMessage(message: customMessage, onSuccess: { (message) in - - print("CustomMessage sent successfully. " + message.stringValue()) - -}) { (error) in - - print("CustomMessage sending failed with error: " + error!.errorDescription); -} +customMessage.tags = ["starredMessage"] ``` - - - -```objc -NSString *receiverID = @"cometchat-uid-1"; - -NSMutableDictionary *customData = [NSMutableDictionary new]; -[customData setObject:@"customData" forKey:@"customKey"]; - -CustomMessage *customMessage = [CustomMessage alloc]initWithReceiverUid:receiverID receiverType:ReceiverTypeGroup customData: customData type:@"Custom Type"]; - -[customMessage] +### Control Conversation Update -customMessage.updateConversation = NO; //for not updating conversation +By default, custom messages update the conversation's last message. To prevent this: -[CometChat sendCustomMessageWithMessage:customMessage onSuccess:^(CustomMessage * message) { - NSLog(@"CustomMessage sent successfully. %@",[message stringValue]); -} onError:^(CometChatException * error) { - NSLog(@"CustomMessage sending failed with error: %@",[error errorDescription]); -}]; -``` - - - - - -### Custom Notification Body - -*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 `conversationText` property of Custom Message class. - - - ```swift -let receiverid = "cometchat-uid-2" -let customData : [String : Any] = ["customKey" : "customData"] -let customMessage = CustomMessage(receiverUid: receiverid, receiverType: .user, customData : customData, type: "Custom Type"); - -customMessage.conversationText = "Custom notification body"; - -CometChat.sendCustomMessage(message: customMessage, onSuccess: { (message) in - print("CustomMessage sent successfully. " + message.stringValue()) -}) { (error) in - print("CustomMessage sending failed with error: " + error!.errorDescription); -} +customMessage.updateConversation = false ``` - - - -```objc -NSString *receiverID = @"cometchat-uid-1"; -NSMutableDictionary *customData = [NSMutableDictionary new]; - [customData setObject:@"customData" forKey:@"customKey"]; - -CustomMessage *customMessage = [CustomMessage alloc]initWithReceiverUid:receiverID receiverType:ReceiverTypeUser customData: customData type:@"Custom Type"]; +### Custom Notification Text -customMessage.conversationText = "Custom notification body"; +Set custom text for push, email, and SMS notifications: -[CometChat sendCustomMessageWithMessage:customMessage onSuccess:^(CustomMessage * message) { - NSLog(@"CustomMessage sent successfully. %@",[message stringValue]); -} onError:^(CometChatException * error) { - NSLog(@"CustomMessage sending failed with error: %@",[error errorDescription]); -}]; -``` - - - - ```swift -let receiverid = "cometchat-uid-2" -let customData : [String : Any] = ["customKey" : "customData"] -let customMessage = CustomMessage(receiverUid: receiverid, receiverType: .group, customData : customData, type: "Custom Type"); - -customMessage.conversationText = "Custom notification body"; - -CometChat.sendCustomMessage(message: customMessage, onSuccess: { (message) in - - print("CustomMessage sent successfully. " + message.stringValue()) - -}) { (error) in - - print("CustomMessage sending failed with error: " + error!.errorDescription); -} +customMessage.conversationText = "Shared a location" ``` - - - -```objc -NSString *receiverID = @"cometchat-uid-1"; - -NSMutableDictionary *customData = [NSMutableDictionary new]; -[customData setObject:@"customData" forKey:@"customKey"]; - -CustomMessage *customMessage = [CustomMessage alloc]initWithReceiverUid:receiverID receiverType:ReceiverTypeGroup customData: customData type:@"Custom Type"]; - -[customMessage] - -customMessage.conversationText = "Custom notification body"; - -[CometChat sendCustomMessageWithMessage:customMessage onSuccess:^(CustomMessage * message) { - NSLog(@"CustomMessage sent successfully. %@",[message stringValue]); -} onError:^(CometChatException * error) { - NSLog(@"CustomMessage sending failed with error: %@",[error errorDescription]); -}]; -``` - - - - - +It is also possible to send interactive messages from CometChat. To learn more, see [Interactive Messages](/sdk/ios/interactive-messages). + -It is also possible to send interactive messages from CometChat , to know more [click here](/sdk/ios/interactive-messages) +--- - +## Next Steps + + + + Listen for incoming messages in real-time + + + Edit previously sent messages + + + Delete sent messages + + diff --git a/sdk/ios/session-timeout.mdx b/sdk/ios/session-timeout.mdx index d6b297d8c..03c9e22e7 100644 --- a/sdk/ios/session-timeout.mdx +++ b/sdk/ios/session-timeout.mdx @@ -2,7 +2,20 @@ title: "Session Timeout Flow" --- + +```swift +// Set custom timeout in CallSettings +let callSettings = CometChatCalls.callSettingsBuilder + .setIdleTimeoutPeriod(300) // 5 minutes, in seconds + .setDelegate(self) + .build() +``` + +- Default idle timeout: 180 seconds (3 minutes) alone in a session +- Warning dialog appears 60 seconds before auto-termination +- Listen for `onSessionTimeout` via `CallsEventsDelegate` to handle auto-termination + Available since v4.1.1 @@ -32,3 +45,19 @@ 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 + + + Configure call settings including idle timeout + + + Implement calling without the Chat SDK + + diff --git a/sdk/ios/setup.mdx b/sdk/ios/setup.mdx index 29c70bb2b..8679c2ee4 100644 --- a/sdk/ios/setup.mdx +++ b/sdk/ios/setup.mdx @@ -1,53 +1,67 @@ --- title: "Setup" +sidebarTitle: "Setup" +description: "Install, configure, and initialize the CometChat iOS SDK in your application." --- +{/* TL;DR for Agents and Quick Reference */} + +```swift +// CocoaPods +pod 'CometChatSDK', '4.1.0' -## Get your Application Keys - -[Signup 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 +// Swift Package Manager +// https://github.com/cometchat/chat-sdk-ios.git +``` -1. Xcode 12 (or Higher) -2. iOS 11 or higher +```swift +import CometChatSDK - +let appSettings = AppSettings.AppSettingsBuilder() + .setRegion(region: "APP_REGION") + .subscribePresenceForAllUsers() + .autoEstablishSocketConnection(true) + .build() + +CometChat.init(appId: "APP_ID", appSettings: appSettings, onSuccess: { _ in + print("CometChat initialized") +}, onError: { error in + print("Init failed: \(error.errorDescription)") +}) +``` -*** +**Prerequisites:** Xcode 12+, iOS 11+, credentials from [CometChat Dashboard](https://app.cometchat.com) + -## Add the CometChat Dependency +## Prerequisites -### CocoaPods +| Requirement | Version | +|-------------|---------| +| Xcode | 12 or above | +| iOS | 11 or higher | -We recommend using [CocoaPods](https://cocoapods.org/), as they are the most advanced way of managing iOS project dependencies. Open a terminal window, move to your project directory, and then create a `Podfile` by running the following command. +Get your credentials from the [CometChat Dashboard](https://app.cometchat.com): +- App ID +- Region +- Auth Key (for development) +**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. + -1. CometChatSDK supports installation through Cocoapods only. Currently, we are supporting Xcode 11.4 and higher. -2. CometChatSDK includes video calling components. We suggest you run on physical devices to avoid errors. +## Installation - +### CocoaPods + +Create a `Podfile` in your project directory: - - ```bash $ pod init ``` - - - +Add the CometChat SDK to your Podfile: -Add the following lines to the Podfile. - - - ```ruby platform :ios, '11.0' use_frameworks! @@ -57,37 +71,23 @@ target 'MyApp' do end ``` - - - - -And then install the `CometChatSDK` framework through CocoaPods. +Install the dependency: - - ```bash $ pod install ``` - - - +To update to the latest version: -Always get the latest version of `CometChatSDK` by command - - - ```bash $ pod update CometChatSDK ``` - - - - -### Swift Packages + +CometChatSDK includes video calling components. We suggest you run on physical devices to avoid errors. + -To install **Swift Packages** you can use Xcode package manager\*\*.\*\* +### Swift Package Manager 1. Open **Xcode**, go to the project's **General** settings tab and select the project under **Project** in the left column. 2. Go to the **Swift packages** tab and click on the **+** button. @@ -96,13 +96,13 @@ To install **Swift Packages** you can use Xcode package manager\*\*.\*\* -3. Once the pop-up appears, enter the github repository address in the search bar [`https://github.com/cometchat/chat-sdk-ios.git`](https://github.com/cometchat/chat-sdk-ios.git) and set dependency rule to `Up to Next Major Version` and set version as `4.1.0` . Then click on the **Add Package** button. +3. Enter the repository URL [`https://github.com/cometchat/chat-sdk-ios.git`](https://github.com/cometchat/chat-sdk-ios.git), set dependency rule to `Up to Next Major Version` with version `4.1.0`, and click **Add Package**. -4. `CometChatSDK` must be checked in the **Package Product** column and click on the Add Package button. This will add **Package Dependencies** menu in Xcode. +4. Ensure `CometChatSDK` is checked in the **Package Product** column and click **Add Package**. @@ -110,35 +110,29 @@ To install **Swift Packages** you can use Xcode package manager\*\*.\*\* ### Request Authorization -Prepare your app for this requirement by providing justification strings. The justification string is a localizable message that you add to your app's `Info.plist` file to tell the user why your app needs access to the user's photo library, Camera, Microphone. Then, App prompts the user to grant permission for access, the alert displays the justification string you provided, in the language of the locale selected on the user's device. You can do this as follows: +Add justification strings to your app's `Info.plist` for camera, microphone, and photo library access: - - ```xml -NSAppTransportSecurity<_key> +NSAppTransportSecurity - NSAllowsArbitraryLoads<_key> - - <_dict> -NSCameraUsageDescription<_key> - $(PRODUCT_NAME) need access to the camera in order to update your avatar<_string> -NSPhotoLibraryUsageDescription<_key> - $(PRODUCT_NAME) need access to the Photo Library in order to send Media Messages<_string> -NSMicrophoneUsageDescription<_key> - $(PRODUCT_NAME) need access to the Microphone in order to connect Audio_Video call <_string> + NSAllowsArbitraryLoads + + +NSCameraUsageDescription + $(PRODUCT_NAME) need access to the camera in order to update your avatar +NSPhotoLibraryUsageDescription + $(PRODUCT_NAME) need access to the Photo Library in order to send Media Messages +NSMicrophoneUsageDescription + $(PRODUCT_NAME) need access to the Microphone in order to connect Audio/Video call ``` - - - - ### Setup Bitcode -You can set the Enable Bitcode setting to YES present in build settings in your XCode project. +Set **Enable Bitcode** to `YES` in your target's build settings. @@ -146,7 +140,7 @@ You can set the Enable Bitcode setting to YES present in build settings in your ### Swift Standard Libraries -`CometChatSDK`framework build on Swift, you have to ensure the required libraries are embedded. This can be done by setting the `“Always Embed Swift Standard Libraries”` checkbox in your target’s build settings to “Yes”: +Set `"Always Embed Swift Standard Libraries"` to `Yes` in your target's build settings: @@ -154,103 +148,148 @@ You can set the Enable Bitcode setting to YES present in build settings in your ### Set Header Search Path -Set the `Header Search Paths` to `$SDKROOT/usr/include/libxml2`. +Set `Header Search Paths` to `$SDKROOT/usr/include/libxml2`. -*** - -## Initialize CometChat - -The `init()` method initializes 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 three settings: +## Initialization -* **Region**: The region where you app was created. -* **[Presence Subscription](/sdk/ios/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/ios/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. - -We suggest you call the method on app startup preferably in the `didFinishLaunchingWithOptions:` method of the `AppDelegate` class. +The `init()` method initializes the SDK and must be called before any other CometChat method. Call it once at app startup, typically in `didFinishLaunchingWithOptions:` of your `AppDelegate`. ```swift import CometChatSDK -class AppDelegate: UIResponder, UIApplicationDelegate{ -{ - var window: UIWindow? - let appId: String = "ENTER APP ID" - let region: String = "ENTER REGION CODE" +class AppDelegate: UIResponder, UIApplicationDelegate { + + var window: UIWindow? + let appId: String = "APP_ID" + let region: String = "APP_REGION" -func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { -let mySettings = AppSettings.AppSettingsBuilder().subscribePresenceForAllUsers().setRegion(region: region).build() + let mySettings = AppSettings.AppSettingsBuilder() + .subscribePresenceForAllUsers() + .setRegion(region: region) + .autoEstablishSocketConnection(true) + .build() - CometChat.init(appId: appId ,appSettings: mySettings,onSuccess: { (isSuccess) in - if (isSuccess) { - print("CometChat SDK intialise successfully.") - } - }) { (error) in - print("CometChat SDK failed intialise with error: \\(error.errorDescription)") - } - return true + CometChat.init(appId: appId, appSettings: mySettings, onSuccess: { (isSuccess) in + if (isSuccess) { + print("CometChat SDK initialized successfully.") + } + }) { (error) in + print("CometChat SDK failed to initialize with error: \(error.errorDescription)") } + return true + } } ``` - - + ```objc #import -@interface AppDelegate () +@implementation AppDelegate + +- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { + + NSString *region = @"APP_REGION"; + NSString *appID = @"APP_ID"; + + AppSettingsBuilder *appSettingBuilder = [[AppSettingsBuilder alloc] init]; + AppSettings *appSettings = [[[appSettingBuilder subscribePresenceForAllUsers] setRegionWithRegion:region] build]; + + [[CometChat alloc] initWithAppId:appID appSettings:appSettings onSuccess:^(BOOL isSuccess) { + NSLog(isSuccess ? @"CometChat Initialize Success" : @"CometChat Initialize Failed"); + } onError:^(CometChatException * error) { + NSLog(@"Error %@", [error errorDescription]); + }]; + return YES; +} @end +``` + + -@implementation AppDelegate +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. + -- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { +### Parameters - NSString *region = @"REGION"; - NSString *appID = @"YOUR_APP_ID"; +| Parameter | Type | Description | +|-----------|------|-------------| +| appId | String | Your CometChat App ID | +| appSettings | AppSettings | Configuration object built with AppSettingsBuilder | - AppSettingsBuilder *appSettingBuilder = [[AppSettingsBuilder alloc]init]; - AppSettings *appSettings = [[[appSettingBuilder subscribePresenceForAllUsers]setRegionWithRegion:region]build]; +### AppSettings Options - [[CometChat alloc]initWithAppId: appID appSettings:appSettings onSuccess:^(BOOL isSuccess) { - NSLog(isSuccess ? @"CometChat Initialize Success:-YES" : @"CometChat Initialize Success:-NO"); - } onError:^(CometChatException * error) { - NSLog(@"Error %@",[error errorDescription]); - }]; - return YES; -} +| Method | Description | Default | +|--------|-------------|---------| +| `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 | — | +| `autoEstablishSocketConnection(_:)` | Let SDK manage WebSocket connections | `true` | +| `overrideAdminHost(adminHost:)` | Custom admin URL (dedicated deployment) | — | +| `overrideClientHost(clientHost:)` | Custom client URL (dedicated deployment) | — | + +### Presence Subscription + +Choose how to subscribe to user presence (online/offline status): + +```swift +// All users +AppSettings.AppSettingsBuilder() + .subscribePresenceForAllUsers() + .setRegion(region: region) + .build() + +// Specific roles +AppSettings.AppSettingsBuilder() + .subscribePresenceForRoles(roles: ["admin", "moderator"]) + .setRegion(region: region) + .build() + +// Friends only +AppSettings.AppSettingsBuilder() + .subscribePresenceForFriends() + .setRegion(region: region) + .build() ``` -
+See [User Presence](/sdk/ios/user-presence) for more details. -
+### WebSocket Connection -Make sure you replace the `appId` with your CometChat **App ID** in the above code. +By default, the SDK manages WebSocket connections automatically. To manage them manually: -| Parameter | Description | -| ---------- | ----------------------------------- | -| appID | CometChat App ID | -| appSetting | An object of the AppSettings class. | +```swift +let mySettings = AppSettings.AppSettingsBuilder() + .setRegion(region: region) + .autoEstablishSocketConnection(false) + .build() +``` -*** +See [Managing WebSocket Connections](/sdk/ios/managing-web-socket-connections-manually) for manual control. + +--- -## Publishing to App Store +## Next Steps -To publish your App on App Store please [follow this guide](/sdk/ios/publishing-app-on-appstore) + + + Log in users with Auth Key or Auth Token + + + Send your first message + + diff --git a/sdk/ios/standalone-calling.mdx b/sdk/ios/standalone-calling.mdx index 022ee552f..d4996c189 100644 --- a/sdk/ios/standalone-calling.mdx +++ b/sdk/ios/standalone-calling.mdx @@ -1,7 +1,31 @@ --- title: "Standalone Calling" +sidebarTitle: "Standalone Calling" +description: "Implement video and audio calling using only the CometChat Calls SDK without the Chat SDK for iOS." --- + + +```swift +let sessionId = "SESSION_ID" +let userAuthToken = "USER_AUTH_TOKEN" // From REST API + +// Generate call token (requires user auth token from REST API) +CometChatCalls.generateToken(authToken: userAuthToken as NSString, sessionID: sessionId) { token in + let callSettings = CometChatCalls.CallSettingsBuilder + .setDefaultLayout(true) + .setIsAudioOnly(false) + .setDelegate(self) + .build() + + // Start call session + CometChatCalls.startSession(callToken: token, callSetting: callSettings, view: callView) { _ in } onError: { _ in } +} onError: { error in } + +// 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. @@ -18,14 +42,54 @@ To start a call session, you need a user auth token. Since this implementation d To understand user authentication in CometChat, see the [User Auth](/fundamentals/user-auth) documentation. -You can obtain the auth token using one of these REST API endpoints: +### Option 1: Create Auth Token (REST API) -- [Create Auth Token](/rest-api/auth-tokens/create) — Creates a new auth token for a user -- [Get Auth Token](/rest-api/auth-tokens/get) — Retrieves an existing auth token +Creates a new auth token for a user. - -For testing or POC purposes, you can create an auth token directly from the [CometChat Dashboard](https://app.cometchat.com). Navigate to **Users & Groups → Users**, select a user, and click **+ Create Auth Token**. - +**Endpoint:** +``` +POST https://{appid}.api-{region}.cometchat.io/v3/users/{uid}/auth_tokens +``` + +**Request Headers:** + +| Property | Type | Value | +| -------- | ---- | ----- | +| apiKey | String | YOUR_API_KEY | +| Content-Type | String | application/json | + +**Success Response:** + +| Property | Type | Description | +| -------- | ---- | ----------- | +| data.uid | String | User's unique identifier | +| data.authToken | String | The auth token for API calls | +| data.createdAt | Double | Unix timestamp when created | + +### Option 2: Get Auth Token (REST API) + +Retrieves an existing auth token for a user. + +**Endpoint:** +``` +GET https://{appid}.api-{region}.cometchat.io/v3/users/{uid}/auth_tokens +``` + +**Request Headers:** + +| Property | Type | Value | +| -------- | ---- | ----- | +| apiKey | String | YOUR_API_KEY | + +### Option 3: Dashboard (Testing/POC) + +For testing or POC purposes: + +1. Go to [CometChat Dashboard](https://app.cometchat.com) +2. Navigate to **Users & Groups → Users** +3. Select a user +4. Click **+ Create Auth Token** +5. Copy the generated token Store the auth token securely in your application for use when generating call tokens. @@ -52,10 +116,25 @@ CometChatCalls.generateToken(authToken: userAuthToken as NSString, sessionID: se
-| Parameter | Description | -| --------- | ----------- | -| `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. | +**Request Parameters:** + +| Property | Type | Value | +| -------- | ---- | ----- | +| authToken | NSString | "user_auth_token_from_rest_api" | +| sessionID | NSString | "unique_session_id_123" | + +**Success Response:** + +| Property | Type | Value | +| -------- | ---- | ----- | +| token | String | "eyJhbGciOiJIUzI1NiIsInR5cCI6..." | + +**Error Response (CometChatCallException):** + +| Property | Type | Description | +| -------- | ---- | ----------- | +| errorCode | String | Error code identifier | +| errorDescription | String | Error description message | ## Start Call Session @@ -81,31 +160,52 @@ CometChatCalls.startSession(callToken: callToken, callSetting: callSettings, vie
-### Call Settings +**Request Parameters:** + +| Property | Type | Value | +| -------- | ---- | ----- | +| callToken | String | "eyJhbGciOiJIUzI1NiIsInR5cCI6..." | +| callSetting | CallSettings | Configured settings object | +| view | UIView | View to render call UI | + +**Success Response:** + +| Property | Type | Value | +| -------- | ---- | ----- | +| success | String/Bool | Success confirmation | + +**Error Response (CometChatCallException):** + +| Property | Type | Description | +| -------- | ---- | ----------- | +| errorCode | String | Error code identifier | +| errorDescription | String | Error description message | + +### Call Settings Builder Configure the call experience using the following `CallSettingsBuilder` methods: -| Method | Description | -| ------ | ----------- | -| `setDefaultLayout(Bool)` | Enables or disables the default call UI layout with built-in controls. `true` shows the default layout. Default: `true` | -| `setIsAudioOnly(Bool)` | Sets whether the call is audio-only or audio-video. `true` for audio-only. Default: `false` | -| `setIsSingleMode(Bool)` | Enables single participant mode. | -| `setShowSwitchToVideoCall(Bool)` | Shows or hides the switch to video call button. | -| `setEnableVideoTileClick(Bool)` | Enables or disables click interactions on video tiles. Default: `true` | -| `setEnableDraggableVideoTile(Bool)` | Enables or disables drag functionality for video tiles in Spotlight mode. Default: `true` | -| `setEndCallButtonDisable(Bool)` | Shows or hides the end call button. Default: `false` (shown) | -| `setShowRecordingButton(Bool)` | Shows or hides the recording button. Default: `false` | -| `setSwitchCameraButtonDisable(Bool)` | Shows or hides the switch camera button. Default: `false` (shown) | -| `setMuteAudioButtonDisable(Bool)` | Shows or hides the mute audio button. Default: `false` (shown) | -| `setPauseVideoButtonDisable(Bool)` | Shows or hides the pause video button. Default: `false` (shown) | -| `setAudioModeButtonDisable(Bool)` | Shows or hides the audio mode selection button. Default: `false` (shown) | -| `setStartAudioMuted(Bool)` | Starts the call with the microphone muted. Default: `false` | -| `setStartVideoMuted(Bool)` | Starts the call with the camera turned off. Default: `false` | -| `setMode(DisplayModes)` | Sets the call UI layout mode. Available: `.default`, `.single`, `.spotlight`. Default: `.default` | -| `setAvatarMode(AvatarMode)` | Sets avatar display mode. Available: `.circle`, `.square`, `.fullscreen`. Default: `.circle` | -| `setDefaultAudioMode(AudioMode)` | Sets the initial audio output device. Available: `SPEAKER`, `EARPIECE`, `BLUETOOTH`, `HEADPHONES` | -| `setIdleTimeoutPeriod(Int)` | Sets idle timeout in seconds. Warning appears 60 seconds before auto-termination. Default: `180`. *v4.1.1+* | -| `setDelegate(self)` | Sets the delegate to receive call events. | +| Property | Type | Default | Description | +| -------- | ---- | ------- | ----------- | +| defaultLayout | Bool | true | Enable default call UI | +| isAudioOnly | Bool | false | Audio-only or audio+video | +| isSingleMode | Bool | false | Single participant mode | +| showSwitchToVideo | Bool | false | Show switch to video button | +| enableVideoTileClick | Bool | true | Enable video tile clicks | +| enableDraggableTile | Bool | true | Enable draggable tiles | +| endCallButtonDisable | Bool | false | Hide end call button | +| showRecordingButton | Bool | false | Show recording button | +| switchCameraDisable | Bool | false | Hide switch camera button | +| muteAudioDisable | Bool | false | Hide mute audio button | +| pauseVideoDisable | Bool | false | Hide pause video button | +| audioModeDisable | Bool | false | Hide audio mode button | +| startAudioMuted | Bool | false | Start with mic muted | +| startVideoMuted | Bool | false | Start with camera off | +| mode | DisplayModes | .default | .default/.single/.spotlight | +| avatarMode | AvatarMode | .circle | .circle/.square/.fullscreen | +| defaultAudioMode | AudioMode | SPEAKER | SPEAKER/EARPIECE/BLUETOOTH | +| idleTimeoutPeriod | Int | 180 | Idle timeout in seconds | +| delegate | CallsEventsDelegate | nil | Event delegate | ## Call Listeners @@ -162,20 +262,97 @@ extension ViewController: CallsEventsDelegate {
-### Events - -| Event | Description | -| ----- | ----------- | -| `onCallEnded()` | Invoked when the call session terminates for a 1:1 call. Both participants receive this callback. | -| `onSessionTimeout()` | Invoked when the call is auto-terminated due to inactivity (default: 180 seconds). *v4.1.1+* | -| `onCallEndButtonPressed()` | Invoked when the local user taps the end call button. Call `CometChatCalls.endSession()` to leave the session. | -| `onUserJoined(rtcUser: RTCUser)` | Invoked when a remote participant joins. | -| `onUserLeft(rtcUser: RTCUser)` | Invoked when a remote participant leaves. | -| `onUserListChanged(rtcUsers: [RTCUser])` | Invoked whenever the participant list changes. | -| `onAudioModeChanged(mode: [AudioMode])` | Invoked when available audio devices change. | -| `onCallSwitchedToVideo(callSwitchedInfo: CallSwitchRequestInfo)` | Invoked when an audio call is upgraded to video. | -| `onUserMuted(rtcMutedUser: RTCMutedUser)` | Invoked when a participant's mute state changes. | -| `onRecordingToggled(recordingInfo: RTCRecordingInfo)` | Invoked when call recording starts or stops. | +### onCallEnded + +Invoked when the call session terminates for a 1:1 call. Both participants receive this callback. + +**Payload:** None + +**Action:** Close the calling screen + +### onSessionTimeout + +Invoked when the call is auto-terminated due to inactivity (default: 180 seconds). *v4.1.1+* + +**Payload:** None + +### onCallEndButtonPressed + +Invoked when the local user taps the end call button. + +**Payload:** None + +**Action:** Call `CometChatCalls.endSession()` and close screen + +### onUserJoined + +Invoked when a remote participant joins the call. + +**Payload (RTCUser):** + +| Property | Type | Description | +| -------- | ---- | ----------- | +| rtcUser | RTCUser | User object containing participant details | + +### onUserLeft + +Invoked when a remote participant leaves the call. + +**Payload (RTCUser):** + +| Property | Type | Description | +| -------- | ---- | ----------- | +| rtcUser | RTCUser | User object containing participant details | + +### onUserListChanged + +Invoked whenever the participant list changes. + +**Payload:** + +| Property | Type | Description | +| -------- | ---- | ----------- | +| rtcUsers | [RTCUser] | Array of RTCUser objects | + +### onAudioModeChanged + +Invoked when available audio devices change. + +**Payload:** + +| Property | Type | Description | +| -------- | ---- | ----------- | +| mode | [AudioMode] | Array of available modes: SPEAKER, EARPIECE, BLUETOOTH, HEADPHONES | + +### onCallSwitchedToVideo + +Invoked when an audio call is upgraded to video. + +**Payload (CallSwitchRequestInfo):** + +| Property | Type | Description | +| -------- | ---- | ----------- | +| callSwitchedInfo | CallSwitchRequestInfo | Call switch request information | + +### onUserMuted + +Invoked when a participant's mute state changes. + +**Payload (RTCMutedUser):** + +| Property | Type | Description | +| -------- | ---- | ----------- | +| rtcMutedUser | RTCMutedUser | Muted user information | + +### onRecordingToggled + +Invoked when call recording starts or stops. + +**Payload (RTCRecordingInfo):** + +| Property | Type | Description | +| -------- | ---- | ----------- | +| recordingInfo | RTCRecordingInfo | Recording state information | ## End Call Session @@ -192,6 +369,23 @@ func onCallEndButtonPressed() {
+**When to Call endSession():** + +| Scenario | Action | +| -------- | ------ | +| User taps end call button | Call in `onCallEndButtonPressed()` | +| Call ended by remote user | Called automatically (`onCallEnded`) | +| Session timeout | Called automatically (`onSessionTimeout`) | + +**Resources Released:** + +| Resource | Description | +| -------- | ----------- | +| Camera | Video capture stopped | +| Microphone | Audio capture stopped | +| Network | WebRTC connection closed | +| UI | Call view can be dismissed | + ## 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. @@ -284,6 +478,15 @@ CometChatCalls.setAudioMode(AudioMode(mode: "SPEAKER"))
+**Available Modes:** + +| Mode | Description | +| ---- | ----------- | +| SPEAKER | Phone speaker | +| EARPIECE | Phone earpiece | +| BLUETOOTH | Bluetooth device | +| HEADPHONES | Wired headphones | + ### Enter PIP Mode Enters Picture-in-Picture mode. @@ -369,7 +572,7 @@ CometChatCalls.stopRecording()
-### End Call +### End Session Terminates the current call session and releases all media resources. @@ -385,3 +588,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/ios/threaded-messages.mdx b/sdk/ios/threaded-messages.mdx index c75a4733c..c907e4143 100644 --- a/sdk/ios/threaded-messages.mdx +++ b/sdk/ios/threaded-messages.mdx @@ -1,154 +1,192 @@ --- title: "Threaded Messages" +sidebarTitle: "Threaded Messages" +description: "Send, receive, and fetch threaded messages using the CometChat iOS SDK." --- + +```swift +// Send message in a thread +let msg = TextMessage(receiverUid: "UID", text: "Reply", receiverType: .user) +msg.parentMessageId = 100 +CometChat.sendTextMessage(message: msg, onSuccess: { _ in }, onError: { _ in }) + +// Fetch thread messages +let threadRequest = MessagesRequest.MessageRequestBuilder() + .setParentMessageId(parentMessageId: 100).set(limit: 30).build() +threadRequest.fetchPrevious(onSuccess: { _ in }, onError: { _ in }) + +// Exclude thread replies from main conversation +let mainRequest = MessagesRequest.MessageRequestBuilder() + .set(uid: "UID").set(limit: 30).hideReplies(hide: 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. +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/ios/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`. +Any message type (Text, Media, or Custom) can be sent in a thread. Set the `parentMessageId` property to indicate which thread the message belongs to. -This can be achieved using the `parentMessageId` property provided by the object of the `TextMessage`, `MediaMessage`, and `CustomMessage` class. The id specified in the `parentMessageId` property maps the message sent to the particular thread. +### Send Text Message in Thread -**Example to Send a Text Message in a thread in a user conversation.** - - - ```swift let receiverID = "cometchat-uid-2" let text = "Hello" let textMessage = TextMessage(receiverUid: receiverID, text: text, receiverType: .user) -textMessage?.parentMessageId = 100 -CometChat.sendTextMessage(message: textMessage, onSuccess: { (message) in +textMessage.parentMessageId = 38208 +CometChat.sendTextMessage(message: textMessage, onSuccess: { (message) in print("TextMessage sent successfully. " + message.stringValue()) - }) { (error) in - print("TextMessage sending failed with error: " + error!.errorDescription); } ``` - +### Send Media Message in Thread - +```swift +let receiverID = "cometchat-uid-2" +let fileUrl = "https://data-us.cometchat.io/assets/images/avatars/ironman.png" -The above snippet shows how a message with the text "Hello" can be sent in the thread with `parentMessageId` 100. +let mediaMessage = MediaMessage(receiverUid: receiverID, fileurl: fileUrl, messageType: .image, receiverType: .user) +mediaMessage.parentMessageId = 38208 -Similarly, using the `parentMessageId` property, Media and Custom Messages can be sent in threads too. +CometChat.sendMediaMessage(message: mediaMessage, onSuccess: { (message) in + print("MediaMessage sent successfully. " + message.stringValue()) +}) { (error) in + print("MediaMessage sending failed with error: " + error!.errorDescription); +} +``` -### Receiving Real-Time Messages +### Send Custom Message in Thread -The procedure to receive real-time messages is exactly the same as mentioned in the [Receive Messages](/sdk/ios/receive-message). This can be achieved using the `CometChatMessageDelegate` class provided by the SDK. +```swift +let receiverID = "cometchat-uid-2" +let customData: [String: Any] = ["emoji": "👍", "replyType": "reaction"] -In order to receive incoming messages, you must add protocol conformance CometChatMessageDelegate as Shown in the below code example. 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. +let customMessage = CustomMessage(receiverUid: receiverID, receiverType: .user, customData: customData, type: "thread_reaction") +customMessage.parentMessageId = 38208 + +CometChat.sendCustomMessage(message: customMessage, onSuccess: { (message) in + print("CustomMessage sent successfully. " + message.stringValue()) +}) { (error) in + print("CustomMessage sending failed with error: " + error!.errorDescription); +} +``` + +## Receiving Real-Time Messages + +Use `CometChatMessageDelegate` to receive real-time thread messages. Check if the received message belongs to the active thread using `parentMessageId`. - - ```swift -var activeThreadId = 100; +var activeThreadId = 38208 extension ViewController: CometChatMessageDelegate { func onTextMessageReceived(textMessage: TextMessage) { - if textMessage.id == activeThreadId { - print("TextMessage received successfully: " + textMessage.stringValue()) + if textMessage.parentMessageId == activeThreadId { + print("TextMessage received in thread: " + textMessage.stringValue()) } } func onMediaMessageReceived(mediaMessage: MediaMessage) { - if textMessage.id == activeThreadId { - print("MediaMessage received successfully: " + mediaMessage.stringValue()) + if mediaMessage.parentMessageId == activeThreadId { + print("MediaMessage received in thread: " + mediaMessage.stringValue()) } } func onCustomMessageReceived(customMessage: CustomMessage) { - if textMessage.id == activeThreadId { - print("CustomMessage received successfully: " + customMessage.stringValue()) + if customMessage.parentMessageId == activeThreadId { + print("CustomMessage received in thread: " + customMessage.stringValue()) } } } ``` - - - +## Fetch all the messages for any particular thread -### Fetch all the messages for any particular thread. +Use `MessagesRequestBuilder` with `setParentMessageId()` to fetch messages belonging to a specific thread. The `fetchPrevious()` method returns an array of [`BaseMessage`](/sdk/reference/messages#basemessage) objects representing thread replies. -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. - - - ```swift -let limit = 50; - -let messagesRequest = MessageRequestBuilder().setParentMessageId(parentMessageId: 100).set(limit: limit).build() +let messagesRequest = MessagesRequest.MessageRequestBuilder() + .setParentMessageId(parentMessageId: 38208) + .set(limit: 50) + .build() messagesRequest.fetchPrevious(onSuccess: { (messages) in - - for message in messages!{ - - if let receivedMessage = (message as ? TextMessage) { - print("Text Messages for thread fetched successfully. " + receivedMessage.stringValue()) + for message in messages! { + if let textMessage = message as? TextMessage { + print("Text Message: " + textMessage.stringValue()) + } else if let mediaMessage = message as? MediaMessage { + print("Media Message: " + mediaMessage.stringValue()) + } else if let customMessage = message as? CustomMessage { + print("Custom Message: " + customMessage.stringValue()) } - else if let receivedMessage = (message as ? MediaMessage) { - print("Media Messages for thread fetched successfully. " + receivedMessage!.stringValue()) } -} - }) { (error) in - - print("Messages fetching failed with error: " + error!.errorDescription); + print("Messages fetching failed with error: " + error!.errorDescription) } ``` - - - - ## 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(hide: true)` to exclude threaded messages when fetching messages for a conversation. The response is an array of [`BaseMessage`](/sdk/reference/messages#basemessage) objects, excluding any messages that are replies within a thread. - + ```swift -let limit = 50; - -let messageRequest = MessagesRequest.MessageRequestBuilder().set(uid: "cometchat-uid-1").set(limit: limit).hideReplies(hide: true).build() +let messagesRequest = MessagesRequest.MessageRequestBuilder() + .set(uid: "cometchat-uid-2") + .set(limit: 50) + .hideReplies(hide: true) + .build() messagesRequest.fetchPrevious(onSuccess: { (messages) in - - for message in messages!{ - - if let receivedMessage = (message as ? TextMessage) { - print("Text Messages for thread fetched successfully. " + receivedMessage.stringValue()) - } - else if let receivedMessage = (message as ? MediaMessage) { - print("Media Messages for thread fetched successfully. " + receivedMessage!.stringValue()) + for message in messages! { + print("Message ID: \(message.id), parentMessageId: \(message.parentMessageId)") } +}) { (error) in + print("Messages fetching failed with error: " + error!.errorDescription) } +``` + + +```swift +let messagesRequest = MessagesRequest.MessageRequestBuilder() + .set(guid: "cometchat-guid-1") + .set(limit: 50) + .hideReplies(hide: true) + .build() +messagesRequest.fetchPrevious(onSuccess: { (messages) in + for message in messages! { + print("Message ID: \(message.id), parentMessageId: \(message.parentMessageId)") + } }) { (error) in - - print("Messages fetching failed with error: " + error!.errorDescription); + print("Messages fetching failed with error: " + error!.errorDescription) } ``` - - -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 + + + Add emoji reactions to messages + + + Advanced message filtering with RequestBuilder + + diff --git a/sdk/ios/transfer-group-ownership.mdx b/sdk/ios/transfer-group-ownership.mdx index 6d818fffa..dd5cd50d1 100644 --- a/sdk/ios/transfer-group-ownership.mdx +++ b/sdk/ios/transfer-group-ownership.mdx @@ -1,31 +1,94 @@ --- title: "Transfer Group Ownership" +sidebarTitle: "Transfer Ownership" +description: "Transfer ownership of a CometChat group to another member using the iOS SDK." --- + +```swift +// Transfer group ownership +CometChat.transferGroupOwnership(UID: "NEW_OWNER_UID", GUID: "GUID", onSuccess: { success in }, onError: { error in }) +``` + +**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? +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/ios/leave-group). -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. +## Transfer Ownership -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 group member. + +| Parameter | Description | +|-----------|-------------| +| `UID` | The UID of the member to become the new owner | +| `GUID` | The GUID of the group | ```swift -var UID = "cometchat-uid-2" -var GUID = "cometchat-guid-1" +let uid = "cometchat-uid-2" +let guid = "cometchat-guid-1" -CometChat.transferGroupOwnership(UID: UID, GUID: GUID) { (success) in - - print("Transfer Group Ownership Successfully") +CometChat.transferGroupOwnership(UID: uid, GUID: guid, onSuccess: { (success) in + print("Ownership transferred: \(success)") +}, onError: { (error) in + print("Error: \(error?.errorDescription)") +}) +``` + + + +On success, the new owner gets admin scope and the previous owner becomes a participant. + +## Real-Time Ownership Changed Events -} onError: { (error) in +Implement `onOwnershipChanged()` in `CometChatGroupDelegate` to receive real-time notifications when group ownership changes. - print("Transfer Group Ownership failed with error \(error?.errorDescription)") + + +```swift +class ViewController: UIViewController, CometChatGroupDelegate { + + override func viewDidLoad() { + super.viewDidLoad() + CometChat.groupdelegate = self + } + + func onOwnershipChanged(group: Group, newOwner: GroupMember) { + print("Ownership changed in group: \(group.name ?? "")") + print("New owner: \(newOwner.name ?? "")") + } } ``` - - + + +Set delegate in `viewDidLoad()`: `CometChat.groupdelegate = self`. Remove delegate when view is dismissed to avoid memory leaks. + + +## Missed Ownership Changed Events + +When fetching previous messages, ownership transfers appear as [`Action`](/sdk/reference/messages#action) messages (a subclass of [`BaseMessage`](/sdk/reference/messages#basemessage)). + +| Field | Value/Type | Description | +|-------|------------|-------------| +| `action` | `"ownershipChanged"` | The action type | +| `actionOn` | [`User`](/sdk/reference/entities#user) | The new owner | +| `actionBy` | [`User`](/sdk/reference/entities#user) | The previous owner who transferred | +| `actionFor` | [`Group`](/sdk/reference/entities#group) | The group where change occurred | + +--- + +## Next Steps + + + + Leave a group after transferring ownership + + + Promote or demote group members + + diff --git a/sdk/ios/transient-messages.mdx b/sdk/ios/transient-messages.mdx index 6f1da0964..b56944750 100644 --- a/sdk/ios/transient-messages.mdx +++ b/sdk/ios/transient-messages.mdx @@ -1,72 +1,210 @@ --- title: "Transient Messages" +sidebarTitle: "Transient Messages" +description: "Send and receive ephemeral real-time messages that are not stored on the server using the CometChat iOS SDK." --- + +```swift +// Send transient message to user +let data: [String: Any] = ["LIVE_REACTION": "heart"] +let msg = TransientMessage(receiverID: "UID", receiverType: .user, data: data) +CometChat.sendTransientMessage(message: msg) + +// Listen for transient messages (CometChatMessageDelegate) +func onTransisentMessageReceived(_ message: TransientMessage) { + print("Transient:", message.data) +} +``` + +## Key Characteristics + +| Characteristic | Description | +|----------------|-------------| +| Fire-and-forget | No success/failure callbacks | +| NOT persisted | Cannot be retrieved from history | +| Real-time only | Receiver must be online | +| No receipts | No delivery/read receipts | -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. +--- + +## Use Cases -## Send a Transient Message +| Use Case | Description | +|----------|-------------| +| Live reactions | Heart, thumbs up, emoji animations | +| Live location | Real-time location sharing | +| Ephemeral indicators | Temporary status updates | +| Custom real-time data | Any data that doesn't need persistence | + +--- -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. +## Send Transient Message (User) ```swift -let receiverId = "cometchat-uid-2"; -let data = ["LIVE_REACTION","heart"] -let transientMessage = TransientMessage(receiverID: receiverId, receiverType: .user, data: data) +let data: [String: Any] = ["LIVE_REACTION": "heart", "timestamp": Date().timeIntervalSince1970] +let transientMessage = TransientMessage(receiverID: "cometchat-uid-2", receiverType: .user, data: data) CometChat.sendTransientMessage(message: transientMessage) -``` +// Note: Fire-and-forget - no success/failure callback +// Message is NOT persisted - receiver must be online +``` - ```objc -NSString *receiverId = @"cometchat-uid-2"; -NSArray *arr = [[NSArray arrayWithObjects: @"LIVE_REACTION",@"heart"]; -let transientMessage = TransientMessage(receiverID: receiverId, receiverType: .user, data: data) +NSDictionary *data = @{@"LIVE_REACTION": @"heart"}; +TransientMessage *transientMessage = [[TransientMessage alloc] initWithReceiverID:@"cometchat-uid-2" receiverType:ReceiverTypeUser data:data]; +[CometChat sendTransientMessageWithMessage:transientMessage]; +``` + + + +--- + +## Send Transient Message (Group) + + + +```swift +let data: [String: Any] = ["LIVE_REACTION": "thumbsup", "timestamp": Date().timeIntervalSince1970] +let transientMessage = TransientMessage(receiverID: "cometchat-guid-1", receiverType: .group, data: data) CometChat.sendTransientMessage(message: transientMessage) ``` + + +--- + +## Send Live Reaction + + + +```swift +let data = ["LIVE_REACTION": "heart", "type": "live_reaction"] +let transientMessage = TransientMessage(receiverID: "cometchat-uid-2", receiverType: .user, data: data) +CometChat.sendTransientMessage(message: transientMessage) +``` + + +### Common Live Reactions + +| Reaction | Value | +|----------|-------| +| Heart | `"heart"` | +| Thumbs Up | `"thumbsup"` | +| Thumbs Down | `"thumbsdown"` | +| Laugh | `"laugh"` | +| Wow | `"wow"` | +| Sad | `"sad"` | +| Angry | `"angry"` | +--- + +## Send Live Location + + + +```swift +let data: [String: Any] = [ + "type": "live_location", + "latitude": 37.7749, + "longitude": -122.4194, + "accuracy": 10.0, + "timestamp": Date().timeIntervalSince1970 +] +let transientMessage = TransientMessage(receiverID: "cometchat-uid-2", receiverType: .user, data: data) +CometChat.sendTransientMessage(message: transientMessage) +``` + -## Real-time Transient Messages +### Live Location Data Properties + +| Property | Type | Description | +|----------|------|-------------| +| type | `String` | `"live_location"` | +| latitude | `Double` | Latitude coordinate | +| longitude | `Double` | Longitude coordinate | +| accuracy | `Double` | Location accuracy in meters | +| timestamp | `Double` | Unix timestamp | -*In other words, as a recipient, how do I know when someone sends a transient message?* +--- -In order to receive incoming transient messages, you must add protocol conformance `CometChatMessageDelegate` as Shown Below : +## Real-time Transient Message Events + +To receive transient messages, implement `CometChatMessageDelegate`: ```swift -extension ViewController: CometChatMessageDelegate { - public func onTransisentMessageReceived(_ message: TransientMessage) { - print("TransientMessage received successfully: " + message.stringValue()) +extension YourViewController: CometChatMessageDelegate { + + func onTransisentMessageReceived(_ message: TransientMessage) { + print("Transient message received") + print("Sender UID: \(message.sender?.uid ?? "")") + print("Sender Name: \(message.sender?.name ?? "")") + print("Receiver ID: \(message.receiverID)") + print("Receiver Type: \(message.receiverType)") + print("Data: \(message.data)") + + // Handle specific data types + if let reaction = message.data["LIVE_REACTION"] as? String { + print("Live Reaction: \(reaction)") + // Show reaction animation + } + + if let type = message.data["type"] as? String, type == "live_location" { + let lat = message.data["latitude"] as? Double ?? 0 + let lon = message.data["longitude"] as? Double ?? 0 + print("Live Location: \(lat), \(lon)") + // Update map marker + } } } -``` +// Register the delegate: +CometChat.messagedelegate = self +``` - ```objc --(void)onTransisentMessageReceived:(TransientMessage *)message { - NSlog(@"TransientMessage received successfully:%@", [message stringValue]); +- (void)onTransisentMessageReceived:(TransientMessage *)message { + NSLog(@"TransientMessage received: %@", [message stringValue]); } ``` - - -The `TransientMessage` class consists of the below parameters: +--- + +The received object is a [`TransientMessage`](/sdk/reference/auxiliary#transientmessage). + +## TransientMessage Object Properties + +| Property | Type | Description | +|----------|------|-------------| +| `sender` | `User?` | User who sent the transient message | +| `receiverID` | `String` | UID of user or GUID of group | +| `receiverType` | `ReceiverType` | `.user` or `.group` | +| `data` | `[String: Any]` | Custom data dictionary | + + +Transient messages are NOT persisted and cannot be retrieved later. The receiver must be online to receive them. There are no delivery/read receipts for transient messages. + + +--- + +## Next Steps -| 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** | This parameter indicates if the transient message is to be sent to a user or a group. The possible values are: 1. `.user` 2.`.group` | -| **data** | A Dictionary to provide data. | + + + Show real-time typing status in conversations + + + Send text, media, and custom messages + + diff --git a/sdk/ios/typing-indicators.mdx b/sdk/ios/typing-indicators.mdx index 08fdd6514..2be8252a2 100644 --- a/sdk/ios/typing-indicators.mdx +++ b/sdk/ios/typing-indicators.mdx @@ -1,107 +1,123 @@ --- title: "Typing Indicators" +sidebarTitle: "Typing Indicators" +description: "Send and receive real-time typing indicators using the CometChat iOS SDK." --- + +```swift +// Start typing indicator +let typing = TypingIndicator(receiverID: "UID", receiverType: .user) +CometChat.startTyping(indicator: typing) -## Send a Typing Indicator +// Stop typing indicator +CometChat.endTyping(indicator: typing) -*In other words, as a sender, how do I let the recipient(s) know that I'm typing?* +// Listen for typing events +extension VC: CometChatMessageDelegate { + func onTypingStarted(_ typingDetails: TypingIndicator) { } + func onTypingEnded(_ typingDetails: TypingIndicator) { } +} +``` + + +## Send a Typing Indicator ### 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 `CometChatMessageDelegate` protocol conformance. In order to send the typing indicator, you need to use the `TypingIndicator` class. +Use `startTyping()` with a [`TypingIndicator`](/sdk/reference/auxiliary#typingindicator) object to notify the receiver that you're typing. - + ```swift -let typingIndicator = TypingIndicator(receiverID: "receiverUID", receiverType: .user) - +let typingIndicator = TypingIndicator(receiverID: "cometchat-uid-2", receiverType: .user) CometChat.startTyping(indicator: typingIndicator) ``` - - - + ```objc -TypingIndicator *typingIndicator = [[TypingIndicator alloc]initWithReceiverID:@"receiverID" receiverType: ReceiverTypeUser metadata:nil]; - +TypingIndicator *typingIndicator = [[TypingIndicator alloc]initWithReceiverID:@"cometchat-uid-2" receiverType:ReceiverTypeUser metadata:nil]; [CometChat startTypingWithIndicator:typingIndicator]; ``` - - + +```swift +let typingIndicator = TypingIndicator(receiverID: "group-guid-1", receiverType: .group) +CometChat.startTyping(indicator: typingIndicator) +``` + +`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 `CometChatMessageDelegate` protocol conformance. 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. - + ```swift -let typingIndicator = TypingIndicator(receiverID: "receiverUID", receiverType: .user) - +let typingIndicator = TypingIndicator(receiverID: "cometchat-uid-2", receiverType: .user) CometChat.endTyping(indicator: typingIndicator) ``` - - - + ```objc -TypingIndicator *typingIndicator = [[TypingIndicator alloc]initWithReceiverID:@"receiverID" receiverType: ReceiverTypeUser metadata:nil]; - +TypingIndicator *typingIndicator = [[TypingIndicator alloc]initWithReceiverID:@"cometchat-uid-2" receiverType:ReceiverTypeUser metadata:nil]; [CometChat endTypingWithIndicator:typingIndicator]; ``` - - + +```swift +let typingIndicator = TypingIndicator(receiverID: "group-guid-1", receiverType: .group) +CometChat.endTyping(indicator: typingIndicator) +``` + - -Custom Data - -You can use the `metaData` field of the `TypingIndicator` class to pass additional data along with the typing indicators. A metaData field is a dictionary and this property can be set from `TypingIndicator` class. This data will be received at the receiver end and can be obtained using the `metaData` property. +`endTyping()` returns `void` — the typing indicator is sent as a fire-and-forget operation. + +Use the `metadata` property of [`TypingIndicator`](/sdk/reference/auxiliary#typingindicator) to pass additional custom data. Retrieve it with `metadata` on the receiver side. ## Real-time Typing Indicators -*In other words, as a recipient, how do I know when someone is typing?* - -You will receive the typing indicators in the `onTypingStarted()` and the `onTypingEnded()` method of the `CometChatMessageDelegate`. In order to receive typing indicators, you must add protocol conformance `CometChatMessageDelegate`. +Use `onTypingStarted` and `onTypingEnded` in `CometChatMessageDelegate` to receive typing events. ```swift -extension ViewController: CometChatMessageDelegate { - - func onTypingStarted(_ typingDetails : TypingIndicator) { - - print("Typing started received successfully") - } - - func onTypingEnded(_ typingDetails : TypingIndicator) { - - print("Typing ended received successfully") - } +extension YourViewController: CometChatMessageDelegate { + + func onTypingStarted(_ typingDetails: TypingIndicator) { + print("User started typing") + print("Sender: \(typingDetails.sender?.name ?? "")") + print("Receiver ID: \(typingDetails.receiverID)") + print("Receiver Type: \(typingDetails.receiverType)") + } + + func onTypingEnded(_ typingDetails: TypingIndicator) { + print("User stopped typing") + print("Sender: \(typingDetails.sender?.name ?? "")") + } } -``` +// Register the delegate: +CometChat.messagedelegate = self +``` - - + ```objc @interface ViewController () - @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; - - CometChat.messagedelegate = self ; + CometChat.messagedelegate = self; } - (void)onTypingStarted:(TypingIndicator *)typingDetails { @@ -114,16 +130,31 @@ extension ViewController: CometChatMessageDelegate { @end ``` - - -The `TypingIndicator` class consists of the below parameters: +The received [`TypingIndicator`](/sdk/reference/auxiliary#typingindicator) object contains: + +| Property | Type | Description | +|----------|------|-------------| +| `sender` | [`User`](/sdk/reference/entities#user)? | User object of the person typing | +| `receiverID` | `String` | UID of user or GUID of group | +| `receiverType` | `ReceiverType` | `.user` or `.group` | +| `metadata` | `[String: Any]?` | Custom data sent with indicator | + + +Typing indicators are transient and not persisted. The receiver must be online to receive them. + + +--- + +## Next Steps -| 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.ReceiverType.user` 2. `CometChat.ReceiverType.group` | -| metaData | A Dictionary to provide additional data | + + + Track when messages are delivered and read + + + Send ephemeral real-time messages like live reactions + + diff --git a/sdk/ios/update-group.mdx b/sdk/ios/update-group.mdx index 8b69733f5..32baa7ff4 100644 --- a/sdk/ios/update-group.mdx +++ b/sdk/ios/update-group.mdx @@ -1,14 +1,24 @@ --- title: "Update A Group" +sidebarTitle: "Update Group" +description: "Update group details such as name, type, icon, and description using the CometChat iOS SDK." --- + +```swift +// Update group details +let group = Group(guid: "GUID", name: "New Name", groupType: .public, password: nil) +CometChat.updateGroup(group: group, + onSuccess: { group in }, onError: { error in }) +``` + -## Update 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/ios/create-group#group-class) reference for all editable fields. -*In other words, as a group owner, how can I update the group details?* +## Update Group -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. @@ -54,14 +64,38 @@ Group *groupToBeUpdated = [[Group alloc]initWithGuid:guid name:name groupType:gr -This method takes an instance of the `Group` class as a parameter that should contain the data that you wish to update. +| Parameter | Description | +| --------- | ----------- | +| `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. + +## Real-time Events + +When a group is updated, all members receive the `onGroupUpdated` event via `CometChatGroupDelegate`: + + + +```swift +extension YourClass: CometChatGroupDelegate { + func onGroupUpdated(action: ActionMessage, updatedGroup: Group, updatedBy: User) { + print("Group updated: \(updatedGroup.name ?? "")") + print("Updated by: \(updatedBy.name ?? "")") + } +} +``` + + -| Parameter | Description | -| --------- | ---------------------------- | -| group | an instance of class `Group` | +--- -After a successful update of the group, you will receive an instance of the `Group` class containing update information of the group. +## Next Steps - -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. - + + + Permanently delete a group + + + Fetch and filter groups with pagination + + diff --git a/sdk/ios/upgrading-from-v3-to-v4.mdx b/sdk/ios/upgrading-from-v3-to-v4.mdx index 05d06336e..78802effb 100644 --- a/sdk/ios/upgrading-from-v3-to-v4.mdx +++ b/sdk/ios/upgrading-from-v3-to-v4.mdx @@ -2,7 +2,15 @@ title: "Upgrading From V3" --- + +Key changes from v3 to v4: +- Chat SDK: `pod 'CometChatSDK'` (was `CometChatPro`) +- Calls SDK: `pod 'CometChatCallsSDK'` (was `CometChatCalls`) +- Import: `import CometChatSDK` (was `import CometChatPro`) +- Import Calls: `import CometChatCallsSDK` (was `import CometChatCalls`) +- Class access: `CometChatSDK.` (was `CometChatPro.`) + Upgrading from v3 to v4 is fairly simple. Below are the major changes that are released as a part of CometChat v4. We have renamed our SDK from CometChatPro to CometChatSDK and CometChatCalls to CometChatCallsSDK for Chat and Calls SDK receptively. Note only import name is changed all class name inside the SDKs are same as it is before. There will only be few changes required for v4 migration. Let's start! @@ -79,3 +87,16 @@ For this as well do a find and replace all over the project for exact statement All Done! now just do pod install, build you project and enjoy all the new features from v4. *** + +--- + +## Next Steps + + + + Install and configure the CometChat iOS SDK + + + Learn the core concepts behind CometChat v4 + + diff --git a/sdk/ios/user-management.mdx b/sdk/ios/user-management.mdx index bdd886bd2..8c55302d4 100644 --- a/sdk/ios/user-management.mdx +++ b/sdk/ios/user-management.mdx @@ -1,28 +1,49 @@ --- title: "User Management" +sidebarTitle: "User Management" +description: "Create, update, and manage CometChat users programmatically using the iOS SDK. Includes user creation, profile updates, and the User class reference." --- + +```swift +// Create a user +let user = User(uid: "user1", name: "Kevin") +CometChat.createUser(user: user, apiKey: "AUTH_KEY", + onSuccess: { user in }, onError: { error in }) + +// Update a user +let updateUser = User(uid: "user1", name: "Kevin Fernandez") +CometChat.updateUser(user: updateUser, apiKey: "AUTH_KEY", + onSuccess: { user in }, onError: { error in }) + +// Update logged-in user (no auth key needed) +CometChat.updateCurrentUserDetails(user: currentUser, + onSuccess: { user in }, onError: { error in }) +``` -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. - -Summing up- +**Note:** User creation/deletion should ideally happen on your backend via the [REST API](https://api-explorer.cometchat.com). + -**When a user registers in your app** +Users must exist in CometChat before they can log in. This page covers creating, updating, and deleting users. -1. You add the user details in your database -2. You create a user in CometChat +The typical flow: +1. User registers in your app → Create user in CometChat +2. User logs into your app → [Log user into CometChat](/sdk/ios/authentication-overview) -**When a user logs into your app** + +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. + -1. You log in the user to your app -2. You [log in the user to CometChat](/sdk/ios/authentication-overview) (programmatically) +## Creating a User -## Creating a user +User creation should ideally happen on your backend via the [REST API](https://api-explorer.cometchat.com/reference/creates-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. + +**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()`: @@ -35,20 +56,18 @@ CometChat.createUser(user: newUser, apiKey: authKey, onSuccess: { (User) in print("The error is \(String(describing: error?.description))") } ``` - - - UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. - -## Updating a user +## 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 Auth Key as inputs and returns the updated `User` object on successful execution of the request. +Like creation, user updates should ideally happen on your backend via the [REST API](https://api-explorer.cometchat.com/reference/update-user). + +For client-side updates (development only), use `updateUser()`: @@ -61,16 +80,14 @@ CometChat.updateUser(user: newUser1, apiKey: authKey, onSuccess: { (User) in print("The error is \(String(describing: error?.description))") } ``` - - -Please make sure the `User` object provided to the `updateUser()` method has the `UID` of the user to be updated set. +Ensure the [`User`](/sdk/reference/entities#user) object has the correct `UID` set. -## 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. @@ -82,16 +99,14 @@ CometChat.updateCurrentUserDetails(user: currentUser, onSuccess: { user in print("Update user failed with error: \(error?.errorDescription)") }) ``` - - -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 updates the logged-in user irrespective of the UID passed. -## 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 @@ -107,5 +122,24 @@ Deleting a user can only be achieved via the Restful APIs. For more information | statusMessage | Yes | Any custom status message that needs to be set for a user | | lastActiveAt | No | The Unix timestamp of the time the user was last active. | | 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 | +| 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 and filter user lists with pagination. + + + Monitor real-time online/offline status. + + + Block and unblock users. + + + Log users into CometChat. + + diff --git a/sdk/ios/user-presence.mdx b/sdk/ios/user-presence.mdx index 3fd1c1ae5..4c56bc6b9 100644 --- a/sdk/ios/user-presence.mdx +++ b/sdk/ios/user-presence.mdx @@ -1,44 +1,117 @@ --- title: "User Presence" +sidebarTitle: "User Presence" +description: "Track real-time user online/offline status and configure presence subscriptions using the CometChat iOS SDK." --- + +```swift +// Subscribe to presence during init +let appSettings = AppSettings.AppSettingsBuilder() + .subscribePresenceForAllUsers() // or .subscribePresenceForFriends() / .subscribePresenceForRoles(_:) + .setRegion(region: "us") + .build() + +// Listen for presence changes via CometChatUserDelegate +func onUserOnline(user: User) { } +func onUserOffline(user: User) { } + +// Stop listening +CometChat.userdelegate = nil +``` + -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: + +| Method | Description | +| ------ | ----------- | +| `subscribePresenceForAllUsers()` | Receive presence updates for all users | +| `subscribePresenceForRoles(_:)` | Receive presence updates only for users with specified roles | +| `subscribePresenceForFriends()` | Receive presence updates only for friends | + +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/ios/setup) for details. + + +## Presence Subscription + + + +```swift +// Subscribe to ALL Users +let appSettings = AppSettings.AppSettingsBuilder() + .subscribePresenceForAllUsers() + .setRegion(region: "us") + .build() + +CometChat.init(appId: APP_ID, appSettings: appSettings, onSuccess: { success in + print("CometChat initialized with presence for all users") +}, onError: { error in + print("Error: \(error.errorDescription)") +}) +``` + + + +### Subscribe to Friends Only + + + +```swift +let appSettings = AppSettings.AppSettingsBuilder() + .subscribePresenceForFriends() + .setRegion(region: "us") + .build() +``` + + -Based on the settings provided in the AppSettings class while initializing the SDK using the init() method, the logged-in user will receive the presence for the other users in the app. In the AppSettings class, you can set the type of Presence you wish to receive for that particular session of the app. +### Subscribe to Specific Roles -For presence subscription, the AppSettingsBuilder provides 3 methods : + + +```swift +let appSettings = AppSettings.AppSettingsBuilder() + .subscribePresenceForRoles(roles: ["admin", "moderator"]) + .setRegion(region: "us") + .build() +``` + + -* subscribePresenceForAllUsers() - this will inform the logged-in user when any user in the app comes online or goes offline -* subscribePresenceForRoles(roles : \[String]) - 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. +## CometChatUserDelegate -To get the real-time updates of users you must add protocol conformance `CometChatUserDelegate` as Shown Below : +Register a `CometChatUserDelegate` to receive real-time presence events: ```swift -extension ViewController : CometChatUserDelegate { +class ViewController: UIViewController, CometChatUserDelegate { - func onUserOnline(user: User) { - - print(user.stringValue() + " status becomes online.") - } + override func viewDidLoad() { + super.viewDidLoad() + CometChat.userdelegate = self + } - func onUserOffline(user: User) { - - print(user.stringValue() + " status becomes offline.") - } + // Called when a user comes online + func onUserOnline(user: User) { + print("\(user.name ?? "") is now online") + } + + // Called when a user goes offline + func onUserOffline(user: User) { + print("\(user.name ?? "") is now offline") + } } ``` - - ```objc @interface ViewController () @@ -63,22 +136,46 @@ extension ViewController : CometChatUserDelegate { NSLog(@"%@ status becomes online.",[user stringValue]); } ``` - - -Do not forget to set your view controller as a CometChat delegate probably in `viewDidLoad()` as `CometChat.userdelegate = self` +| Method | Parameter | Description | +|--------|-----------|-------------| +| `onUserOnline(user:)` | [`User`](/sdk/reference/entities#user) | Called when a subscribed user comes online | +| `onUserOffline(user:)` | [`User`](/sdk/reference/entities#user) | Called when a subscribed user goes offline | -## User List Presence + +Always remove your delegate when the view is dismissed to prevent memory leaks and duplicate event handling. -*In other words, as a logged-in user, when I retrieve the user list, how do I know if a user is online/offline?* +```swift +CometChat.userdelegate = nil +``` + + +## User List Presence -When you [fetch the list of users](/sdk/ios/retrieve-users#retrieve-list-of-users), in the `User` object, you will receive 2 fields +When fetching users via `UsersRequest`, each [`User`](/sdk/reference/entities#user) object includes presence fields: -1. status - This will hold either of the two values : +| Field | Description | +| ----- | ----------- | +| `status` | `.online` or `.offline` | +| `lastActiveAt` | Timestamp of last activity (useful for "Last seen" display) | -* 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. +--- -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 + + + + Fetch user lists with filtering and pagination. + + + Create and update users programmatically. + + + Monitor SDK connection to CometChat servers. + + + Overview of all available real-time listeners. + + diff --git a/sdk/ios/users-overview.mdx b/sdk/ios/users-overview.mdx index fe7c61592..3a10a3ea6 100644 --- a/sdk/ios/users-overview.mdx +++ b/sdk/ios/users-overview.mdx @@ -1,10 +1,37 @@ --- title: "Users" sidebarTitle: "Overview" +description: "Overview of CometChat iOS SDK user functionality including user management, retrieval, and presence tracking." --- + +- [User Management](/sdk/ios/user-management) — Create and update users +- [Retrieve Users](/sdk/ios/retrieve-users) — Fetch and filter user lists +- [User Presence](/sdk/ios/user-presence) — Track online/offline status +- [Block Users](/sdk/ios/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. +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. -You can begin with [user management](/sdk/ios/user-management) to sync your users to CometChat. Once that is done, you can [retrieve users](/sdk/ios/retrieve-users) and display them in your app. +- [User Management](/sdk/ios/user-management) — Create users when they sign up, update profiles, and delete accounts +- [Retrieve Users](/sdk/ios/retrieve-users) — Fetch and filter user lists with pagination, search, and role-based filtering +- [User Presence](/sdk/ios/user-presence) — Monitor real-time online/offline status and subscribe to presence changes +- [Block Users](/sdk/ios/block-users) — Block and unblock users to prevent all communication + +## Next Steps + + + + Create, update, and delete users in CometChat. + + + Fetch user lists with filtering, sorting, and pagination. + + + Monitor real-time online/offline status of users. + + + Block and unblock users to control communication. + + diff --git a/sdk/ios/video-view-customisation.mdx b/sdk/ios/video-view-customisation.mdx index 59b394618..3586e8a9b 100644 --- a/sdk/ios/video-view-customisation.mdx +++ b/sdk/ios/video-view-customisation.mdx @@ -2,7 +2,14 @@ title: "Video View Customisation" --- + +- **Class:** `MainVideoContainerSetting` +- **Apply via:** `CallSettingsBuilder.setMainVideoContainerSetting(videoSettings)` +- **Customizable elements:** Aspect ratio, full screen button, name label, zoom button, user list button +- **Position constants:** `CallSettings.Position.TOP_LEFT`, `TOP_RIGHT`, `BOTTOM_LEFT`, `BOTTOM_RIGHT` +- **Requires:** [Default Calling](/sdk/ios/default-calling) or [Direct Calling](/sdk/ios/direct-calling) setup + This section will guide you to customise the main video container. @@ -40,3 +47,22 @@ videoSettings.setUserListButtonParams(true,.BOTTOM_RIGHT)
+ +--- + +## Next Steps + + + + Implement default audio/video calling + + + Implement direct calling without call events + + + Enable screen sharing and presenter layouts + + + Record calls for playback + + diff --git a/sdk/ios/web-socket-connection-behaviour.mdx b/sdk/ios/web-socket-connection-behaviour.mdx index f8b050621..f2c96d97b 100644 --- a/sdk/ios/web-socket-connection-behaviour.mdx +++ b/sdk/ios/web-socket-connection-behaviour.mdx @@ -1,8 +1,17 @@ --- title: "Connection Behaviour" +description: "Understanding the default WebSocket connection behavior of the CometChat iOS SDK during login and app lifecycle." --- + +- **On login:** SDK automatically creates WebSocket connection +- **On logout:** SDK disconnects WebSocket +- **Background:** Connection maintained based on app settings +- **Reconnection:** Automatic reconnection on network recovery +- **Related:** [Connection Status](/sdk/ios/connection-status) · [Managing WebSocket Manually](/sdk/ios/managing-web-socket-connections-manually) · [Setup](/sdk/ios/setup) + + ### Default SDK behaviour @@ -12,19 +21,19 @@ When the login method of the SDK is called, the SDK performs the below operation 2. Saves the details of the logged in user locally. 3. Creates a web-socket 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 makes sure that the logged in user starts receiving real-time messages as soon as he logs 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 web-socket connection to the server is established automatically. -And as soon as the app gets into background, web sockets will get disconnected. It will get reconnected when the app comes on foreground from the background. +As soon as the app gets into background, web sockets will get disconnected. It will get reconnected when the app comes on foreground from the background. -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. +If you wish to take control of the web-socket connection manually, refer to the [Managing Web-socket Connection](/sdk/ios/managing-web-socket-connections-manually) 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 default connection behaviour is auto mode. The SDK automatically establishes and maintains the WebSocket connection. -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 AppSettings builder class to `true`. If you do not set this, the SDK will automatically apply auto mode as the default behaviour. @@ -41,17 +50,15 @@ If the app is in the foreground and there is no internet connection, the SDK wil ## Manual Mode SDK behaviour -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. - -Manual mode provides an advantage of being connected to the web-sockets even if the app is in background. But this needs to be handled by the user according to there need with the help of **ping()** function. +In manual mode, you explicitly establish and disconnect the WebSocket connection. Set `autoEstablishSocketConnection()` to `false` and then call `CometChat.connect()` to establish the connection and `CometChat.disconnect()` 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. +Manual mode provides an advantage of being connected to the web-sockets even if the app is in background. This needs to be handled by the user with the help of the **ping()** function. -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. +By default, if manual mode is activated, the SDK will disconnect the WebSocket connection after 30 seconds if the app goes into the background. -You have to continue calling CometChat.ping() function every 30 seconds till the time you need your web-sockets to be connected. +To keep the WebSocket connection alive in the background, call the `CometChat.ping()` method from your app within 30 seconds. Continue calling `CometChat.ping()` every 30 seconds as long as you need the web-sockets connected. -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 `CometChat.ping()` within 30 seconds, the SDK will disconnect the WebSocket connection. @@ -64,29 +71,27 @@ 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: - ### 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 the app startup, use the `autoEstablishSocketConnection()` method provided by the `AppSettingsBuilder` class. If set to `true`, the SDK manages the web-socket connection internally. If set to `false`, you handle it manually: ```swift -let appId = "your_App_ID" +let appId = "your_App_ID" let region = "us" - + let mySettings = AppSettings.AppSettingsBuilder() .subscribePresenceForAllUsers() .setRegion(region: region) - .autoEstablishSocketConnection(false) //call this function + .autoEstablishSocketConnection(false) //call this function .build() CometChat.init(appId: appID ,appSettings: mySettings,onSuccess: { (isSuccess) in }) { - print("CometChatSDK intialise success") -}) { (error) in - print("CometChatSDK intialise failed with error: \(error.errorDescription)") + print("CometChatSDK initialise success") +}) { (error) in + print("CometChatSDK initialise failed with error: \(error.errorDescription)") } ``` @@ -94,11 +99,11 @@ CometChat.init(appId: appID ,appSettings: mySettings,onSuccess: { (isSuccess) in -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 web-socket server using the `connect()`, `disconnect()` and `ping()` methods provided by the SDK. ### Connect to the web-socket 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. Make sure the user is logged in before calling this method (`CometChat.getLoggedInUser()`). Once connected, you will start receiving all real-time events. @@ -116,7 +121,7 @@ CometChat.connect { ### Disconnect from the web-socket 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 to break the established connection. Once disconnected, you will stop receiving all real-time events. @@ -134,13 +139,7 @@ CometChat.disconnect { ### 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. - - - -You can maintain a long-standing background connection event when your app is in the background, call the `CometChat.ping()` method every 30 seconds of your app entering the background or after the previous ping() call. +You can maintain a long-standing background connection by calling the `CometChat.ping()` method every 30 seconds after your app enters the background or after the previous ping() call. @@ -158,4 +157,35 @@ CometChat.ping { ## 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. +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 `CometChat.connect()` to create a new WebSocket connection. + +--- + +## Common Error Codes + +| Error Code | Description | Resolution | +|------------|-------------|------------| +| ERROR_WEBSOCKETS_ALLREADY_IN_CONNECTED_STATE | WebSocket already connected | No action needed, connection exists | +| ERROR_PING_NOT_AVAILABLE | Ping called in auto mode | Enable manual mode with `autoEstablishSocketConnection(false)` | +| ERR_NOT_LOGGED_IN | No user is logged in | Call `CometChat.login()` first | +| ERR_WEBSOCKET_ERROR | WebSocket connection error | Check network connectivity | +| ERR_NO_INTERNET | No internet connection | Wait for network recovery or retry | + +--- + +## Next Steps + + + + Monitor the SDK connection state in real time + + + Take full control of WebSocket connections + + + Complete reference for all SDK event delegates + + + Keep real-time connection alive in background + + diff --git a/sdk/react-native/additional-message-filtering.mdx b/sdk/react-native/additional-message-filtering.mdx index f5e825e32..74ce76e6e 100644 --- a/sdk/react-native/additional-message-filtering.mdx +++ b/sdk/react-native/additional-message-filtering.mdx @@ -1,62 +1,75 @@ --- -title: "Additional Message Filtering" -description: "Learn how to use MessagesRequestBuilder to filter and fetch messages by conversation, type, category, tags, timestamps, and more in the CometChat React Native SDK." +title: "Message Filtering" +sidebarTitle: "Message Filtering" +description: "Advanced filtering options for fetching messages using MessagesRequestBuilder in the CometChat React Native SDK." --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript -// Fetch messages for a user conversation -let request = new CometChat.MessagesRequestBuilder().setUID("UID").setLimit(50).build(); +let parentId = 100; -// Fetch messages for a group conversation -let request = new CometChat.MessagesRequestBuilder().setGUID("GUID").setLimit(50).build(); +// Filter by category and type +let mediaRequest = new CometChat.MessagesRequestBuilder() + .setUID("UID") + .setCategories(["message"]) + .setTypes(["image", "video", "audio", "file"]) + .setLimit(50) + .build(); -// Fetch only unread messages -let request = new CometChat.MessagesRequestBuilder().setUID("UID").setUnread(true).setLimit(30).build(); +// Unread messages only +let unreadRequest = new CometChat.MessagesRequestBuilder() + .setUID("UID") + .setUnread(true) + .setLimit(50) + .build(); -// Fetch only media messages -let request = new CometChat.MessagesRequestBuilder().setUID("UID").setCategories(["message"]).setTypes(["image", "video", "audio", "file"]).setLimit(30).build(); +// Threaded messages +let threadRequest = new CometChat.MessagesRequestBuilder() + .setUID("UID") + .setParentMessageId(parentId) + .setLimit(50) + .build(); -// Fetch messages, then paginate -let messages = await request.fetchPrevious(); +// Fetch with pagination +mediaRequest.fetchPrevious().then(messages => { }); +mediaRequest.fetchNext().then(messages => { }); ``` - - -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. - -**Available via:** [SDK](/sdk/react-native/additional-message-filtering) | [REST API](/rest-api/messages/list-messages) | [UI Kits](/ui-kit/react/message-list#filters) - - -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: +**Key methods:** `setUID()`, `setGUID()`, `setLimit()`, `setCategories()`, `setTypes()`, `setTags()`, `setUnread()`, `setParentMessageId()`, `setMessageId()`, `setTimestamp()`, `hideReplies()`, `hideDeletedMessages()` + -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. +The `MessagesRequest` class fetches messages based on various parameters. It uses the Builder design pattern via `MessagesRequestBuilder`. -Once you have an object of the `MessagesRequest` class, you can call either the `fetchNext()` method or the `fetchPrevious()` method using the object. +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 -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. +| Method | Description | +| --- | --- | +| `fetchNext()` | Returns messages after the specified parameters | +| `fetchPrevious()` | Returns 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. +Messages are paginated with a maximum of 100 per request. Call `fetchPrevious()`/`fetchNext()` repeatedly on the same object to get subsequent pages. -Now that you are clear how to use the `MessagesRequest` class, below are the various options available: +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 -*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. + +```typescript +let messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder().setLimit(50).build(); +``` + + + ```javascript let messagesRequest = new CometChat.MessagesRequestBuilder() @@ -66,3889 +79,827 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() + + +## Messages for a user conversation + +Use `setUID()` to fetch messages between the logged-in user and a specific user. + + ```typescript +let UID: string = "UID"; let messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder().setLimit(50).build(); + new CometChat.MessagesRequestBuilder().setUID(UID).setLimit(50).build(); ``` - - - -**On Success** — `fetchPrevious()` returns an array of `Message` objects: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25234"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `receiverId` | string | Receiver's UID or GUID | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Nice"` | -| `sentAt` | number | Unix timestamp when sent | `1771398092` | -| `deliveredAt` | number | Unix timestamp when delivered | `1771398092` | -| `readAt` | number | Unix timestamp when read | `1771404705` | -| `updatedAt` | number | Unix timestamp when updated | `1771404705` | -| `sender` | object | Sender user details | [See below ↓](#filter-limit-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#filter-limit-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#filter-limit-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#filter-limit-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771397739` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771397762` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Nice"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `entities` | object | Sender and receiver entities | [See below ↓](#filter-limit-data-entities-object) | -| `metadata` | object | Injected metadata | [See below ↓](#filter-limit-data-metadata-object) | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#filter-limit-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#filter-limit-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#filter-limit-data-entities-sender-entity-object) | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771397739` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#filter-limit-data-entities-receiver-entity-object) | - ---- + +```javascript +let UID = "UID"; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setLimit(50) + .build(); +``` - + -**`data.entities.receiver.entity` Object:** + -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771397762` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `tags` | array | User tags | `[]` | +When messages are fetched successfully, the response includes an array of message objects. ---- +## Messages for a group conversation - +Use `setGUID()` to fetch messages from a group. The logged-in user must be a member of the group. -**`data.metadata` Object:** + + +```typescript +let GUID: string = "GUID"; +let messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder().setGUID(GUID).setLimit(50).build(); +``` -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#filter-limit-data-metadata-injected-object) | + ---- + +```javascript +let GUID = "GUID"; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setLimit(50) + .build(); +``` - + -**`data.metadata.@injected` Object:** + -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#filter-limit-data-metadata-extensions-object) | +When messages are fetched successfully, the response includes an array of message objects. ---- +## Messages before/after a message - +Use `setMessageId()` to fetch messages before or after a specific message ID. Use `fetchNext()` to get messages after, or `fetchPrevious()` to get messages before. -**`data.metadata.@injected.extensions` Object:** + + +```typescript +let UID: string = "UID", + messageId: number = 1, + limit: number = 30, + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setMessageId(messageId) + .setLimit(limit) + .build(); +``` -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension data | [See below ↓](#filter-limit-data-metadata-linkpreview-object) | + ---- + +```javascript +let UID = "UID"; +let messageId = 1; +let limit = 30; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setMessageId(messageId) + .setLimit(limit) + .build(); +``` - + -**`data.metadata.@injected.extensions.link-preview` Object:** + +```typescript +let GUID: string = "GUID", + messageId: number = 1, + limit: number = 30, + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setMessageId(messageId) + .setLimit(limit) + .build(); +``` -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Array of link previews | `[]` | + ---- + +```javascript +let GUID = "GUID"; +let messageId = 1; +let limit = 30; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setMessageId(messageId) + .setLimit(limit) + .build(); +``` - + -**`metadata` Object:** + -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#filter-limit-metadata-injected-object) | +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 - +Use `setTimestamp()` with a Unix timestamp to fetch messages before or after a specific time. -**`metadata.@injected` Object:** + + +```typescript +let UID: string = "UID", + timestamp: number = 1602221371, + limit: number = 30, + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setTimestamp(timestamp) + .setLimit(limit) + .build(); +``` -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#filter-limit-metadata-extensions-object) | + ---- + +```javascript +let UID = "UID"; +let timestamp = 1602221371; +let limit = 30; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setTimestamp(timestamp) + .setLimit(limit) + .build(); +``` - + -**`metadata.@injected.extensions` Object:** + +```typescript +let GUID: string = "GUID", + timestamp: number = 1602221371, + limit: number = 30, + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setTimestamp(timestamp) + .setLimit(limit) + .build(); +``` -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension data | [See below ↓](#filter-limit-metadata-linkpreview-object) | + ---- + +```javascript +let GUID = "GUID"; +let timestamp = 1602221371; +let limit = 30; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setTimestamp(timestamp) + .setLimit(limit) + .build(); +``` - + -**`metadata.@injected.extensions.link-preview` Object:** + -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Array of link previews | `[]` | +This method can be combined with `setUID()` or `setGUID()` to fetch messages around a specific time in a conversation. - +## Unread messages -## Messages for a user conversation +Use `setUnread(true)` to fetch only unread messages. -*In other words, how do I fetch messages between me and any user* + + +```typescript +let UID: string = "UID", + limit: number = 30, + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setUnread(true) + .setLimit(limit) + .build(); +``` -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. + - - + ```javascript let UID = "UID"; +let limit = 30; let messagesRequest = new CometChat.MessagesRequestBuilder() .setUID(UID) - .setLimit(50) + .setUnread(true) + .setLimit(limit) .build(); ``` - + ```typescript -let UID: string = "UID", +let GUID: string = "GUID", + limit: number = 30, messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder().setUID(UID).setLimit(50).build(); + new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setUnread(true) + .setLimit(limit) + .build(); ``` - - - -**On Success** — `fetchPrevious()` returns an array of `Message` objects: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25234"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Nice"` | -| `sentAt` | number | Unix timestamp when sent | `1771398092` | -| `deliveredAt` | number | Unix timestamp when delivered | `1771398092` | -| `readAt` | number | Unix timestamp when read | `1771404705` | -| `updatedAt` | number | Unix timestamp when updated | `1771404705` | -| `sender` | object | Sender user details | [See below ↓](#filter-uid-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#filter-uid-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#filter-uid-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#filter-uid-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771397739` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | + +```javascript +let GUID = "GUID"; +let limit = 30; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setUnread(true) + .setLimit(limit) + .build(); +``` ---- + - + -**`receiver` Object:** +Combine with `setGUID()` or `setUID()` to fetch unread messages for a specific conversation. -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771397762` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | +## Exclude messages from blocked users ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Nice"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `entities` | object | Sender and receiver entities | [See below ↓](#filter-uid-data-entities-object) | -| `metadata` | object | Injected metadata | [See below ↓](#filter-uid-data-metadata-object) | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#filter-uid-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#filter-uid-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#filter-uid-data-entities-sender-entity-object) | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771397739` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#filter-uid-data-entities-receiver-entity-object) | - ---- - - - -**`data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771397762` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#filter-uid-data-metadata-injected-object) | - ---- - - - -**`data.metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#filter-uid-data-metadata-extensions-object) | - ---- - - - -**`data.metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#filter-uid-data-metadata-linkpreview-object) | - ---- - - - -**`data.metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#filter-uid-metadata-injected-object) | - ---- - - - -**`metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#filter-uid-metadata-extensions-object) | - ---- - - - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#filter-uid-metadata-linkpreview-object) | - ---- - - - -**`metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - - - -## Messages for a group conversation - -*In other words, 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. - - - -```javascript -let GUID = "GUID"; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setLimit(50) - .build(); -``` - - - - -```typescript -let GUID: string = "GUID", - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder().setGUID(GUID).setLimit(50).build(); -``` - - - - - - -**On Success** — `fetchPrevious()` returns an array of `Message` objects for the group: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25237"` | -| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | -| `receiverId` | string | Group's GUID | `"group_1748415903905"` | -| `receiverType` | string | Type of receiver | `"group"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Nice"` | -| `sentAt` | number | Unix timestamp when sent | `1771400683` | -| `updatedAt` | number | Unix timestamp when updated | `1771400683` | -| `sender` | object | Sender user details | [See below ↓](#filter-guid-sender-object) | -| `receiver` | object | Receiver group details | [See below ↓](#filter-guid-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#filter-guid-data-object) | -| `metadata` | object | Message metadata | Contains `@injected.extensions.link-preview` | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771397739` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object (Group):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `guid` | string | Group's unique identifier | `"group_1748415903905"` | -| `name` | string | Group's display name | `"3 People Group"` | -| `type` | string | Group type | `"public"` | -| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | -| `owner` | string | Group owner's UID | `"123456"` | -| `scope` | string | Current user's scope in group | `"admin"` | -| `membersCount` | number | Total members in group | `12` | -| `onlineMembersCount` | number | Online members count | `2` | -| `hasJoined` | boolean | Whether current user has joined | `true` | -| `isBanned` | boolean | Whether current user is banned | `false` | -| `joinedAt` | number | Timestamp when user joined | `1749203133` | -| `createdAt` | number | Group creation timestamp | `1748415957` | -| `updatedAt` | number | Group update timestamp | `1771245340` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Nice"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `entities` | object | Sender and receiver entities | [See below ↓](#filter-guid-data-entities-object) | -| `metadata` | object | Injected metadata | Contains `@injected.extensions.link-preview` | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#filter-guid-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#filter-guid-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | Contains `uid`, `name`, `avatar`, `status`, `role`, `lastActiveAt`, `tags` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"group"` | -| `entity` | object | Group entity details | [See below ↓](#filter-guid-data-entities-receiver-entity-object) | - ---- - - - -**`data.entities.receiver.entity` Object (Group):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `guid` | string | Group's unique identifier | `"group_1748415903905"` | -| `name` | string | Group's display name | `"3 People Group"` | -| `type` | string | Group type | `"public"` | -| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | -| `owner` | string | Group owner's UID | `"123456"` | -| `scope` | string | Current user's scope in group | `"admin"` | -| `membersCount` | number | Total members in group | `12` | -| `onlineMembersCount` | number | Online members count | `2` | -| `hasJoined` | boolean | Whether current user has joined | `true` | -| `joinedAt` | number | Timestamp when user joined | `1749203133` | -| `createdAt` | number | Group creation timestamp | `1748415957` | -| `updatedAt` | number | Group update timestamp | `1771245340` | - - - - -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. - - - - -## 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 `hideMessagesFromBlockedUsers(true)` to exclude messages from users you've blocked. Default is `false`. - -```javascript -let UID = "UID"; -let messageId = 1; -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setMessageId(messageId) - .setLimit(limit) - .build(); -``` - - - - -```javascript -let UID = "UID"; -let messageId = 1; -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setMessageId(messageId) - .setLimit(limit) - .build(); -``` - - - ```typescript let UID: string = "UID", - messageId: number = 1, - limit: number = 30, - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setMessageId(messageId) - .setLimit(limit) - .build(); -``` - - - - -```typescript -let UID: string = "UID", - messageId: number = 1, limit: number = 30, messagesRequest: CometChat.MessagesRequest = new CometChat.MessagesRequestBuilder() .setUID(UID) - .setMessageId(messageId) + .hideMessagesFromBlockedUsers(true) .setLimit(limit) .build(); ``` - - - - - -**On Success** — `fetchPrevious()` returns messages before the specified message ID: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25233"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"UnreadHey"` | -| `sentAt` | number | Unix timestamp when sent | `1771398088` | -| `deliveredAt` | number | Unix timestamp when delivered | `1771398088` | -| `readAt` | number | Unix timestamp when read | `1771404705` | -| `updatedAt` | number | Unix timestamp when updated | `1771398088` | -| `sender` | object | Sender user details | [See below ↓](#filter-msgid-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#filter-msgid-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#filter-msgid-data-object) | -| `metadata` | object | Message metadata | Contains `@injected.extensions.link-preview` | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771397739` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771397762` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"UnreadHey"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `entities` | object | Sender and receiver entities | Contains `sender` and `receiver` wrappers | -| `metadata` | object | Injected metadata | Contains `@injected.extensions.link-preview` | - - - -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. - -## 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. - - - -```javascript -let UID = "UID"; -let timestamp = 1602221371; -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setTimestamp(timestamp) - .setLimit(limit) - .build(); -``` - - - - -```javascript -let UID = "UID"; -let timestamp = 1602221371; -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setTimestamp(timestamp) - .setLimit(limit) - .build(); -``` - - - - -```typescript -let UID = "UID"; -let timestamp = 1602221371; -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setTimestamp(timestamp) - .setLimit(limit) - .build(); -``` - - - - -```typescript -let UID = "UID"; -let timestamp = 1602221371; -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setTimestamp(timestamp) - .setLimit(limit) - .build(); -``` - - - - - - -**On Success** — `fetchPrevious()` returns messages before the specified timestamp (includes custom message types): - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25191"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"test-custom"` | -| `category` | string | Message category | `"custom"` | -| `customData` | object | Custom message data | [See below ↓](#filter-timestamp-customdata-object) | -| `sentAt` | number | Unix timestamp when sent | `1771324025` | -| `deliveredAt` | number | Unix timestamp when delivered | `1771328175` | -| `readAt` | number | Unix timestamp when read | `1771328175` | -| `updatedAt` | number | Unix timestamp when updated | `1771328175` | -| `sender` | object | Sender user details | [See below ↓](#filter-timestamp-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#filter-timestamp-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#filter-timestamp-data-object) | -| `metadata` | object | Message metadata | Contains `@injected.extensions.link-preview` | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`customData` Object (for custom messages):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `greeting` | string | Custom greeting text | `"Hello from custom message!"` | -| `timestamp` | number | Custom timestamp | `1771324022864` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771323567` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771323089` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `customData` | object | Custom message data | Same as top-level `customData` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `entities` | object | Sender and receiver entities | Contains `sender` and `receiver` wrappers | -| `metadata` | object | Injected metadata | Contains `@injected.extensions.link-preview` | - - - -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. - -## 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. - - - -```javascript -let UID = "UID"; -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setUnread(true) - .setLimit(limit) - .build(); -``` - - - - -```javascript -let UID = "UID"; -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setUnread(true) - .setLimit(limit) - .build(); -``` - - - - -```typescript -let UID: string = "UID"; -let limit: number = 30; -let messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setUnread(true) - .setLimit(limit) - .build(); -``` - - - - -```typescript -let GUID: string = "GUID", - limit: number = 30, - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setUnread(true) - .setLimit(limit) - .build(); -``` - - - - - - -**On Success** — `fetchPrevious()` returns only unread messages: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25241"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"You there?"` | -| `sentAt` | number | Unix timestamp when sent | `1771413707` | -| `deliveredAt` | number | Unix timestamp when delivered | `1771413707` | -| `updatedAt` | number | Unix timestamp when updated | `1771413707` | -| `sender` | object | Sender user details | [See below ↓](#filter-unread-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#filter-unread-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#filter-unread-data-object) | -| `metadata` | object | Message metadata | Contains `@injected.extensions.link-preview` | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771413285` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771413280` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"You there?"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `entities` | object | Sender and receiver entities | Contains `sender` and `receiver` wrappers | -| `metadata` | object | Injected metadata | Contains `@injected.extensions.link-preview` | - - - -This method along with `setGUID()` or `setUID()` can be used to fetch unread messages for a particular group or user conversation respectively. - -## 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. - - - -```javascript -let UID = "UID"; -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .hideMessagesFromBlockedUsers(true) - .setLimit(limit) - .build(); -``` - - - - -```javascript -let GUID = "GUID"; -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .hideMessagesFromBlockedUsers(true) - .setLimit(limit) - .build(); -``` - - - - -```typescript -let UID: string = "UID", - limit: number = 30, - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setUID(UID) - .hideMessagesFromBlockedUsers(true) - .setLimit(limit) - .build(); -``` - - - - -```typescript -let GUID: string = "GUID", - limit: number = 30, - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .hideMessagesFromBlockedUsers(true) - .setLimit(limit) - .build(); -``` - - - - - - -**On Success** — `fetchPrevious()` returns messages excluding those from blocked users (includes group-call custom messages): - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25239"` | -| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | -| `receiverId` | string | Group's GUID | `"group_1748415903905"` | -| `receiverType` | string | Type of receiver | `"group"` | -| `type` | string | Message type | `"group-call"` | -| `category` | string | Message category | `"custom"` | -| `customData` | object | Custom message data | [See below ↓](#filter-blocked-customdata-object) | -| `sentAt` | number | Unix timestamp when sent | `1771413265` | -| `updatedAt` | number | Unix timestamp when updated | `1771413265` | -| `sender` | object | Sender user details | [See below ↓](#filter-blocked-sender-object) | -| `receiver` | object | Receiver group details | [See below ↓](#filter-blocked-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#filter-blocked-data-object) | -| `metadata` | object | Message metadata | Contains `@injected.extensions.link-preview` | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`customData` Object (for group-call):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `callType` | string | Type of call | `"audio"` | -| `isCaller` | boolean | Whether current user initiated call | `true` | -| `sessionId` | string | Call session identifier | `"v1.in.2748663902141719..."` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771412068` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object (Group):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `guid` | string | Group's unique identifier | `"group_1748415903905"` | -| `name` | string | Group's display name | `"3 People Group"` | -| `type` | string | Group type | `"public"` | -| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | -| `owner` | string | Group owner's UID | `"123456"` | -| `scope` | string | Current user's scope in group | `"admin"` | -| `membersCount` | number | Total members in group | `12` | -| `onlineMembersCount` | number | Online members count | `1` | -| `hasJoined` | boolean | Whether current user has joined | `true` | -| `isBanned` | boolean | Whether current user is banned | `false` | -| `joinedAt` | number | Timestamp when user joined | `1748437105` | -| `createdAt` | number | Group creation timestamp | `1748415957` | -| `updatedAt` | number | Group update timestamp | `1771245340` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `customData` | object | Custom message data | Same as top-level `customData` | -| `text` | string | Display text | `"Group video call started. Tap to join!"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `entities` | object | Sender and receiver entities | Contains `sender` and `receiver` wrappers | -| `metadata` | object | Injected metadata | Contains `@injected.extensions.link-preview` | -| `moderation` | object | Moderation status | [See below ↓](#filter-blocked-data-moderation-object) | - ---- - - - -**`data.moderation` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `status` | string | Moderation status | `"approved"` | - - - -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 - -*In other words, 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. - - - -```javascript -let UID = "UID"; -let limit = 30; -let timestamp = 1602221371; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setUpdatedAfter(timestamp) - .setLimit(limit) - .build(); -``` - - - - -```javascript -let UID = "UID"; -let limit = 30; -let timestamp = 1602221371; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setUpdatedAfter(timestamp) - .setLimit(limit) - .build(); -``` - - - - -```typescript -let UID = "UID"; -let limit = 30; -let timestamp = 1602221371; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setUpdatedAfter(timestamp) - .setLimit(limit) - .build(); -``` - - - - -```typescript -let GUID: string = "GUID", - limit: number = 30, - timestamp: string = "1602221371", - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setUpdatedAfter(timestamp) - .setLimit(limit) - .build(); -``` - - - - - - -**On Success** — `fetchNext()` returns messages received or updated after the specified timestamp: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25234"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Nice"` | -| `sentAt` | number | Unix timestamp when sent | `1771398092` | -| `deliveredAt` | number | Unix timestamp when delivered | `1771398092` | -| `readAt` | number | Unix timestamp when read | `1771404705` | -| `updatedAt` | number | Unix timestamp when updated | `1771404705` | -| `sender` | object | Sender user details | [See below ↓](#filter-updatedafter-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#filter-updatedafter-receiver-object) | -| `data` | object | Additional message data | Contains `text`, `resource`, `entities`, `metadata` | -| `metadata` | object | Message metadata | Contains `@injected.extensions.link-preview` | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771397739` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771397762` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - - - -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. - -## 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 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. - - - -```javascript -let UID = "UID"; -let limit = 30; -let timestamp = 1602221371; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setUpdatedAfter(timestamp) - .updatesOnly(true) - .setLimit(limit) - .build(); -``` - - - - -```javascript -let GUID = "GUID"; -let limit = 30; -let timestamp = 1602221371; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setUpdatedAfter(timestamp) - .updatesOnly(true) - .setLimit(limit) - .build(); -``` - - - - -```typescript -let UID: string = "UID", - limit: number = 30, - timestamp: string = "1602221371", - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setUpdatedAfter(timestamp) - .updatesOnly(true) - .setLimit(limit) - .build(); -``` - - - - -```typescript -let GUID: string = "GUID", - limit: number = 30, - timestamp: string = "1602221371", - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setUpdatedAfter(timestamp) - .updatesOnly(true) - .setLimit(limit) - .build(); -``` - - - - - - -**On Success** — `fetchNext()` returns only updated messages (e.g., read receipt changes, edits, deletions): - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25189"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-3"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"image"` | -| `category` | string | Message category | `"message"` | -| `sentAt` | number | Unix timestamp when sent | `1771323061` | -| `deliveredAt` | number | Unix timestamp when delivered | `1771323062` | -| `readAt` | number | Unix timestamp when read | `1771323227` | -| `updatedAt` | number | Unix timestamp when updated | `1771323227` | -| `sender` | object | Sender user details | [See below ↓](#filter-updatesonly-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#filter-updatesonly-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#filter-updatesonly-data-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771323060` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771322968` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object (for image message):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `type` | string | Media type | `"image"` | -| `category` | string | Message category | `"message"` | -| `url` | string | Media URL | `"https://data-in.cometchat.io/..."` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `attachments` | array | File attachments | [See below ↓](#filter-updatesonly-data-attachments-array) | -| `entities` | object | Sender and receiver entities | Contains `sender` and `receiver` wrappers | -| `moderation` | object | Moderation status | Contains `status: "approved"` | - ---- - - - -**`data.attachments` Array (per item):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extension` | string | File extension | `"png"` | -| `mimeType` | string | MIME type | `"image/png"` | -| `name` | string | File name | `"photo.png"` | -| `size` | number | File size in bytes | `2295572` | -| `url` | string | File URL | `"https://data-in.cometchat.io/..."` | - - - -## Messages for multiple categories - -*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/react-native/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. - - - -```javascript -let UID = "UID"; -let limit = 30; -let categories = ["message", "custom"]; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setCategories(categories) - .setLimit(limit) - .build(); -``` - - - - -```javascript -let GUID = "GUID"; -let limit = 30; -let categories = ["message", "custom"]; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setCategories(categories) - .setLimit(limit) - .build(); -``` - - - - -```typescript -let UID: string = "UID", - limit: number = 30, - categories: Array = ["message", "custom"], - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setCategories(categories) - .setLimit(limit) - .build(); -``` - - - - -```typescript -let GUID: string = "GUID", - limit: number = 30, - categories: Array = ["message", "custom"], - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setCategories(categories) - .setLimit(limit) - .build(); -``` - - - - - - -**On Success** — `fetchPrevious()` returns messages from the specified categories (includes both `custom` and `message` categories): - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25251"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"extension_poll"` or `"text"` | -| `category` | string | Message category | `"custom"` or `"message"` | -| `customData` | object | Custom message data (for custom category) | [See below ↓](#filter-categories-customdata-object) | -| `text` | string | Message text (for text type) | `"Hello Message"` | -| `sentAt` | number | Unix timestamp when sent | `1771474256` | -| `deliveredAt` | number | Unix timestamp when delivered | `1771474256` | -| `readAt` | number | Unix timestamp when read | `1771474256` | -| `updatedAt` | number | Unix timestamp when updated | `1771474256` | -| `sender` | object | Sender user details | [See below ↓](#filter-categories-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#filter-categories-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#filter-categories-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#filter-categories-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`customData` Object (for poll extension):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Poll unique identifier | `"fde49a5e-baa8-4e04-95e9-c2c09557caa0"` | -| `question` | string | Poll question | `"Custom"` | -| `options` | object | Poll options | `{"1": "Yes", "2": "No"}` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771474104` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771474191` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Display text | `"Custom"` or `"Hello Message"` | -| `customData` | object | Custom data (for custom messages) | Same as top-level `customData` | -| `updateConversation` | boolean | Whether to update conversation | `true` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `entities` | object | Sender and receiver entities | Contains `sender` and `receiver` wrappers | -| `metadata` | object | Injected metadata | Contains extensions data | - ---- - - - -**`metadata` Object (for poll extension):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#filter-categories-metadata-injected-object) | -| `incrementUnreadCount` | boolean | Whether to increment unread count | `true` | -| `pushNotification` | string | Push notification text | `"Poll: Custom"` | - ---- - - - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview data | `{"links": []}` | -| `polls` | object | Poll extension data | [See below ↓](#filter-categories-metadata-polls-object) | - ---- - - - -**`metadata.@injected.extensions.polls` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Poll unique identifier | `"fde49a5e-baa8-4e04-95e9-c2c09557caa0"` | -| `question` | string | Poll question | `"Custom"` | -| `options` | object | Poll options | `{"1": "Yes", "2": "No"}` | -| `results` | object | Poll results | Contains `options` and `total` | - - - -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. - -## 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/react-native/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 -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 -let GUID: string = "GUID", - limit: number = 30, - categories: Array = ["message", "custom"], - types: Array = ["image", "video", "audio", "file"], - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setCategories(categories) - .setTypes(types) - .setLimit(limit) - .build(); -``` - - - - - - -**On Success** — `fetchPrevious()` returns only media messages (image, video, audio, file types): - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25253"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"image"` or `"audio"` | -| `category` | string | Message category | `"message"` | -| `sentAt` | number | Unix timestamp when sent | `1771474540` | -| `deliveredAt` | number | Unix timestamp when delivered | `1771474540` | -| `readAt` | number | Unix timestamp when read | `1771474540` | -| `updatedAt` | number | Unix timestamp when updated | `1771474540` | -| `sender` | object | Sender user details | [See below ↓](#filter-types-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#filter-types-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#filter-types-data-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771474535` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771474191` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object (for media messages):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `type` | string | Media type | `"image"` or `"audio"` | -| `category` | string | Message category | `"message"` | -| `url` | string | Media URL | `"https://data-in.cometchat.io/..."` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `attachments` | array | File attachments | [See below ↓](#filter-types-data-attachments-array) | -| `entities` | object | Sender and receiver entities | Contains `sender` and `receiver` wrappers | - ---- - - - -**`data.attachments` Array (per item):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extension` | string | File extension | `"jpg"` or `"ogg"` | -| `mimeType` | string | MIME type | `"image/jpeg"` or `"application/ogg"` | -| `name` | string | File name | `"photo.jpg"` or `"audio.ogg"` | -| `size` | number | File size in bytes | `142099` | -| `url` | string | File URL | `"https://data-in.cometchat.io/..."` | - - - -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. - -## 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 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. - - - -```javascript -let UID = "UID"; -let messageId = 1; // Use msg.getId() on a message where msg.getReplyCount() > 0 -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setLimit(limit) - .setParentMessageId(messageId) - .build(); -``` - - - - -```javascript -let GUID = "GUID"; -let messageId = 1; // Use msg.getId() on a message where msg.getReplyCount() > 0 -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setLimit(limit) - .setParentMessageId(messageId) - .build(); -``` - - - - -```typescript -let UID: string = "UID", - limit: number = 30, - messageId: number = 1, // Use msg.getId() on a message where msg.getReplyCount() > 0 - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setLimit(limit) - .setParentMessageId(messageId) - .build(); -``` - - - - -```typescript -let GUID: string = "GUID", - limit: number = 30, - messageId: number = 1, // Use msg.getId() on a message where msg.getReplyCount() > 0 - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setLimit(limit) - .setParentMessageId(messageId) - .build(); -``` - - - - - - -**On Success** — `fetchPrevious()` returns messages belonging to the specified thread: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25257"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Thread Message"` | -| `parentMessageId` | string | Parent message ID (thread root) | `"25256"` | -| `sentAt` | number | Unix timestamp when sent | `1771476403` | -| `deliveredAt` | number | Unix timestamp when delivered | `1771476404` | -| `readAt` | number | Unix timestamp when read | `1771476404` | -| `updatedAt` | number | Unix timestamp when updated | `1771476404` | -| `sender` | object | Sender user details | [See below ↓](#filter-thread-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#filter-thread-receiver-object) | -| `data` | object | Additional message data | Contains `text`, `resource`, `entities`, `metadata` | -| `metadata` | object | Message metadata | Contains `@injected.extensions.link-preview` | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771475038` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771475047` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - - - -The above code snippet returns the messages that belong to the thread with parent id 100. - - -## Hide threaded messages in user/group conversations - -*In other words, 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. - - - -```javascript -let UID = "UID"; -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setLimit(limit) - .hideReplies(true) - .build(); -``` - - - - -```javascript -let GUID = "GUID"; -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setLimit(limit) - .hideReplies(true) - .build(); -``` - - - - -```typescript -let UID: string = "UID", - limit: number = 30, - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setLimit(limit) - .hideReplies(true) - .build(); -``` - - - - -```typescript -let GUID: string = "GUID", - limit: number = 30, - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setLimit(limit) - .hideReplies(true) - .build(); -``` - - - - - - -**On Success** — `fetchPrevious()` returns messages excluding threaded replies (parent messages with threads still appear): - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25256"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` or `"audio"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"New Message for Thread"` | -| `replyCount` | number | Number of replies (for parent messages) | `1` | -| `sentAt` | number | Unix timestamp when sent | `1771476391` | -| `deliveredAt` | number | Unix timestamp when delivered | `1771476392` | -| `readAt` | number | Unix timestamp when read | `1771476392` | -| `updatedAt` | number | Unix timestamp when updated | `1771476392` | -| `sender` | object | Sender user details | [See below ↓](#filter-hidereplies-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#filter-hidereplies-receiver-object) | -| `data` | object | Additional message data | Contains `text`, `resource`, `entities`, `metadata` or `attachments` | -| `metadata` | object | Message metadata | Contains `@injected.extensions.link-preview` | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771475038` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771475047` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - - - -## Hide deleted messages in user/group conversations - -*In other words, 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. - - - -```javascript -let UID = "UID"; -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setLimit(limit) - .hideDeletedMessages(true) - .build(); -``` - - - - -```javascript -let GUID = "GUID"; -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setLimit(limit) - .hideDeletedMessages(true) - .build(); -``` - - - - -```typescript -let UID: string = "UID", - limit: number = 30, - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setLimit(limit) - .hideDeletedMessages(true) - .build(); -``` - - - - -```typescript -let GUID: string = "GUID", - limit: number = 30, - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setLimit(limit) - .hideDeletedMessages(true) - .build(); -``` - - - - - - -**On Success** — `fetchPrevious()` returns messages excluding deleted messages: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25256"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"New Message for Thread"` | -| `replyCount` | number | Number of replies (if parent message) | `1` | -| `parentMessageId` | string | Parent message ID (if threaded reply) | `"25256"` | -| `sentAt` | number | Unix timestamp when sent | `1771476391` | -| `deliveredAt` | number | Unix timestamp when delivered | `1771476392` | -| `readAt` | number | Unix timestamp when read | `1771476392` | -| `updatedAt` | number | Unix timestamp when updated | `1771476392` | -| `sender` | object | Sender user details | [See below ↓](#filter-hidedeleted-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#filter-hidedeleted-receiver-object) | -| `data` | object | Additional message data | Contains `text`, `resource`, `entities`, `metadata` | -| `metadata` | object | Message metadata | Contains `@injected.extensions.link-preview` | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771475038` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771475047` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - - - -## 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. - - - -```javascript -let UID = "UID"; -let limit = 30; -let tags = ["starredMessage"]; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setLimit(limit) - .setTags(tags) - .build(); -``` - - - - -```javascript -let GUID = "GUID"; -let limit = 30; -let tags = ["starredMessage"]; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setLimit(limit) - .setTags(tags) - .build(); -``` - - - - -```typescript -let UID: string = "UID", - limit: number = 30, - tags: Array = ["starredMessage"], - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setLimit(limit) - .setTags(tags) - .build(); -``` - - - - -```typescript -let GUID: string = "GUID", - limit: number = 30, - tags: Array = ["starredMessage"], - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setLimit(limit) - .setTags(tags) - .build(); -``` - - - - - - -**On Success** — `fetchPrevious()` returns only messages matching the specified tags: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25259"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Tagged message for docs"` | -| `sentAt` | number | Unix timestamp when sent | `1771478898` | -| `deliveredAt` | number | Unix timestamp when delivered | `1771478900` | -| `readAt` | number | Unix timestamp when read | `1771478900` | -| `updatedAt` | number | Unix timestamp when updated | `1771478900` | -| `sender` | object | Sender user details | [See below ↓](#filter-settags-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#filter-settags-receiver-object) | -| `data` | object | Additional message data | Contains `text`, `resource`, `entities`, `metadata` | -| `metadata` | object | Message metadata | Contains `@injected.extensions.link-preview` | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771478591` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771477541` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - - - -## 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` . - - - -```javascript -let UID = "UID"; -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setLimit(limit) - .withTags(true) - .build(); -``` - - - - -```javascript -let GUID = "GUID"; -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setLimit(limit) - .withTags(tags) - .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** — `fetchPrevious()` returns messages with the `tags` field included: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25265"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-3"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Tagged message for docs"` | -| `tags` | array | Message tags | `["starredMessage"]` | -| `sentAt` | number | Unix timestamp when sent | `1771481257` | -| `updatedAt` | number | Unix timestamp when updated | `1771481257` | -| `sender` | object | Sender user details | [See below ↓](#filter-withtags-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#filter-withtags-receiver-object) | -| `data` | object | Additional message data | Contains `text`, `resource`, `entities`, `metadata`, `moderation` | -| `metadata` | object | Message metadata | Contains `@injected.extensions.link-preview` | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771480243` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771480251` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - - - -## Messages with links - -*In other words, as a logged-in user, how do I fetch messages that contain 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`. - - - -This feature is only available with `Conversation & Advanced Search`. 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) - - - - - -```javascript -let UID = "UID"; -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setLimit(limit) - .hasLinks(true) - .build(); -``` - - - - -```javascript -let GUID = "GUID"; -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setLimit(limit) - .hasLinks(true) - .build(); -``` - - - - -```typescript -let UID: string = "UID", - limit: number = 30, - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setGUID(UID) - .setLimit(limit) - .hasLinks(true) - .build(); -``` - - - - -```typescript -let GUID: string = "GUID", - limit: number = 30, - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setLimit(limit) - .hasLinks(true) - .build(); -``` - - - - - - -**On Success** — `fetchPrevious()` returns an array of `Message` objects containing links: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25269"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Please checkout our website https://cometchat.com"` | -| `sentAt` | number | Unix timestamp when sent | `1771481824` | -| `deliveredAt` | number | Unix timestamp when delivered | `1771481825` | -| `readAt` | number | Unix timestamp when read | `1771481825` | -| `updatedAt` | number | Unix timestamp when updated | `1771481825` | -| `sender` | object | Sender user details | [See below ↓](#filter-haslinks-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#filter-haslinks-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#filter-haslinks-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#filter-haslinks-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771480251` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771480243` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Please checkout our website https://cometchat.com"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `entities` | object | Sender and receiver entities | [See below ↓](#filter-haslinks-data-entities-object) | -| `metadata` | object | Injected metadata | [See below ↓](#filter-haslinks-data-metadata-object) | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#filter-haslinks-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#filter-haslinks-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#filter-haslinks-data-entities-sender-entity-object) | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771480251` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#filter-haslinks-data-entities-receiver-entity-object) | - ---- - - - -**`data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771480243` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#filter-haslinks-data-metadata-injected-object) | - ---- - - - -**`data.metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#filter-haslinks-data-metadata-extensions-object) | - ---- - - - -**`data.metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension data | [See below ↓](#filter-haslinks-data-metadata-linkpreview-object) | - ---- - - - -**`data.metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Array of link previews | [See below ↓](#filter-haslinks-data-metadata-links-array) | - ---- - - - -**`data.metadata.@injected.extensions.link-preview.links` Array (per item):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `url` | string | The URL found in the message | `"https://cometchat.com"` | -| `title` | string | Page title | `"In-app Chat SDK & API For Messaging And Calling - CometChat"` | -| `description` | string | Page description | `"Build real time chat, voice and video calling experience..."` | -| `favicon` | string | URL to site favicon | `"https://cometchat.com/_static/favicon.png"` | -| `image` | string | URL to preview image | `"https://a.storyblok.com/f/231922/1200x630/d639d0748b/open-graph-image.png/m/1200x630/"` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#filter-haslinks-metadata-injected-object) | - ---- - - - -**`metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#filter-haslinks-metadata-extensions-object) | - ---- - - - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#filter-haslinks-metadata-linkpreview-object) | - ---- - - - -**`metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Array of link previews | [See below ↓](#filter-haslinks-metadata-links-array) | - ---- - - - -**`metadata.@injected.extensions.link-preview.links` Array (per item):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `url` | string | The URL found in the message | `"https://cometchat.com"` | -| `title` | string | Page title | `"In-app Chat SDK & API For Messaging And Calling - CometChat"` | -| `description` | string | Page description | `"Build real time chat, voice and video calling experience..."` | -| `favicon` | string | URL to site favicon | `"https://cometchat.com/_static/favicon.png"` | -| `image` | string | URL to preview image | `"https://a.storyblok.com/f/231922/1200x630/d639d0748b/open-graph-image.png/m/1200x630/"` | - - - -## Messages with attachments - -*In other words, as a logged-in user, how do I fetch messages that contain 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`. - - - -This feature is only available with `Conversation & Advanced Search`. 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) - - + - - + ```javascript let UID = "UID"; let limit = 30; let messagesRequest = new CometChat.MessagesRequestBuilder() .setUID(UID) + .hideMessagesFromBlockedUsers(true) .setLimit(limit) - .hasAttachments(true) .build(); ``` - + +```typescript +let GUID: string = "GUID", + limit: number = 30, + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .hideMessagesFromBlockedUsers(true) + .setLimit(limit) + .build(); +``` + + + + ```javascript let GUID = "GUID"; let limit = 30; let messagesRequest = new CometChat.MessagesRequestBuilder() .setGUID(GUID) + .hideMessagesFromBlockedUsers(true) .setLimit(limit) - .hasAttachments(true) .build(); ``` + + +This also works in group conversations where both users are members. + +## Updated and received messages + +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. + + ```typescript let UID: string = "UID", limit: number = 30, + timestamp: string = "1602221371", messagesRequest: CometChat.MessagesRequest = new CometChat.MessagesRequestBuilder() - .setGUID(UID) + .setUID(UID) + .setUpdatedAfter(timestamp) .setLimit(limit) - .hasAttachments(true) .build(); ``` + +```javascript +let UID = "UID"; +let limit = 30; +let timestamp = 1602221371; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setUpdatedAfter(timestamp) + .setLimit(limit) + .build(); +``` + + + ```typescript let GUID: string = "GUID", limit: number = 30, + timestamp: string = "1602221371", messagesRequest: CometChat.MessagesRequest = new CometChat.MessagesRequestBuilder() .setGUID(GUID) + .setUpdatedAfter(timestamp) .setLimit(limit) - .hasAttachments(true) .build(); ``` - - - -**On Success** — `fetchPrevious()` returns an array of `Message` objects with attachments: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25253"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"image"` | -| `category` | string | Message category | `"message"` | -| `sentAt` | number | Unix timestamp when sent | `1771474540` | -| `deliveredAt` | number | Unix timestamp when delivered | `1771474540` | -| `readAt` | number | Unix timestamp when read | `1771474540` | -| `updatedAt` | number | Unix timestamp when updated | `1771474540` | -| `sender` | object | Sender user details | [See below ↓](#filter-attachments-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#filter-attachments-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#filter-attachments-data-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771474535` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771474191` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `type` | string | Attachment type | `"image"` | -| `category` | string | Message category | `"message"` | -| `url` | string | URL to the attachment | `"https://data-in.cometchat.io/2748663902141719/media/..."` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `attachments` | array | Array of attachment objects | [See below ↓](#filter-attachments-data-attachments-array) | -| `entities` | object | Sender and receiver entities | [See below ↓](#filter-attachments-data-entities-object) | - ---- - - - -**`data.attachments` Array (per item):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extension` | string | File extension | `"jpg"` | -| `mimeType` | string | MIME type of the file | `"image/jpeg"` | -| `name` | string | File name | `"IMG_20260217_150412.jpg"` | -| `size` | number | File size in bytes | `142099` | -| `url` | string | URL to the attachment | `"https://data-in.cometchat.io/2748663902141719/media/..."` | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#filter-attachments-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#filter-attachments-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#filter-attachments-data-entities-sender-entity-object) | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771474535` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#filter-attachments-data-entities-receiver-entity-object) | - ---- - - - -**`data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771474191` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `tags` | array | User tags | `[]` | - - - -## Messages with reactions - -*In other words, as a logged-in user, how do I fetch messages that contain 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`. - - - -This feature is only available with `Conversation & Advanced Search`. 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) - - - - - -```javascript -let UID = "UID"; -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setLimit(limit) - .hasReactions(true) - .build(); -``` - - - - + ```javascript let GUID = "GUID"; let limit = 30; +let timestamp = 1602221371; let messagesRequest = new CometChat.MessagesRequestBuilder() .setGUID(GUID) + .setUpdatedAfter(timestamp) .setLimit(limit) - .hasReactions(true) .build(); ``` + + +Useful for syncing messages with a local database — fetch only what's changed since your last sync. + +## Updated messages only + +Use `updatesOnly(true)` with `setUpdatedAfter()` to fetch only updated messages (not newly received ones). This method must be used together with `setUpdatedAfter()`. + + ```typescript let UID: string = "UID", limit: number = 30, + timestamp: string = "1602221371", messagesRequest: CometChat.MessagesRequest = new CometChat.MessagesRequestBuilder() - .setGUID(UID) + .setUID(UID) + .setUpdatedAfter(timestamp) + .updatesOnly(true) .setLimit(limit) - .hasReactions(true) .build(); ``` + +```javascript +let UID = "UID"; +let limit = 30; +let timestamp = 1602221371; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setUpdatedAfter(timestamp) + .updatesOnly(true) + .setLimit(limit) + .build(); +``` + + + ```typescript let GUID: string = "GUID", limit: number = 30, + timestamp: string = "1602221371", messagesRequest: CometChat.MessagesRequest = new CometChat.MessagesRequestBuilder() .setGUID(GUID) + .setUpdatedAfter(timestamp) + .updatesOnly(true) .setLimit(limit) - .hasReactions(true) .build(); ``` - - - -**On Success** — `fetchPrevious()` returns an array of `Message` objects with reactions: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25275"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Message with reactions"` | -| `sentAt` | number | Unix timestamp when sent | `1771495045` | -| `deliveredAt` | number | Unix timestamp when delivered | `1771495045` | -| `readAt` | number | Unix timestamp when read | `1771495045` | -| `updatedAt` | number | Unix timestamp when updated | `1771495045` | -| `sender` | object | Sender user details | [See below ↓](#filter-reactions-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#filter-reactions-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#filter-reactions-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#filter-reactions-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771495034` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771494233` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Message with reactions"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `reactions` | array | Reactions on the message | [See below ↓](#filter-reactions-data-reactions-array) | -| `entities` | object | Sender and receiver entities | [See below ↓](#filter-reactions-data-entities-object) | -| `metadata` | object | Injected metadata | [See below ↓](#filter-reactions-data-metadata-object) | - ---- - - - -**`data.reactions` Array (per item):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `reaction` | string | The reaction emoji | `"❤️"` | -| `count` | number | Number of users who reacted | `1` | -| `reactedByMe` | boolean | Whether current user reacted (optional) | `true` | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#filter-reactions-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#filter-reactions-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#filter-reactions-data-entities-sender-entity-object) | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771495034` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#filter-reactions-data-entities-receiver-entity-object) | - ---- - - - -**`data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771494233` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#filter-reactions-data-metadata-injected-object) | - ---- - - - -**`data.metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#filter-reactions-data-metadata-extensions-object) | - ---- - - - -**`data.metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension data | [See below ↓](#filter-reactions-data-metadata-linkpreview-object) | - ---- - - - -**`data.metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#filter-reactions-metadata-injected-object) | - ---- - - - -**`metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#filter-reactions-metadata-extensions-object) | - ---- - - - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension data | [See below ↓](#filter-reactions-metadata-linkpreview-object) | - ---- - - - -**`metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - - - -## Messages with mentions + +```javascript +let GUID = "GUID"; +let limit = 30; +let timestamp = 1602221371; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setUpdatedAfter(timestamp) + .updatesOnly(true) + .setLimit(limit) + .build(); +``` -*In other words, as a logged-in user, how do I fetch messages that contain 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`. + - +When messages are fetched successfully, the response includes only messages that have been updated (edited, deleted, read/delivered status changed) after the specified timestamp. -This feature is only available with `Conversation & Advanced Search`. 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) +## Messages for multiple categories - +Use `setCategories()` with an array of category names to filter by message category. See [Message structure and hierarchy](/sdk/react-native/message-structure-and-hierarchy) for available categories. - + +```typescript +let UID: string = "UID", + limit: number = 30, + categories: Array = ["message", "custom"], + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setCategories(categories) + .setLimit(limit) + .build(); +``` + + + + ```javascript let UID = "UID"; let limit = 30; +let categories = ["message", "custom"]; let messagesRequest = new CometChat.MessagesRequestBuilder() .setUID(UID) + .setCategories(categories) .setLimit(limit) - .hasMentions(true) .build(); ``` - + +```typescript +let GUID: string = "GUID", + limit: number = 30, + categories: Array = ["message", "custom"], + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setCategories(categories) + .setLimit(limit) + .build(); +``` + + + + ```javascript let GUID = "GUID"; let limit = 30; +let categories = ["message", "custom"]; let messagesRequest = new CometChat.MessagesRequestBuilder() .setGUID(GUID) + .setCategories(categories) .setLimit(limit) - .hasMentions(true) .build(); ``` + + +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 + +Use `setTypes()` with an array of type names to filter by message type. See [Message structure and hierarchy](/sdk/react-native/message-structure-and-hierarchy) for available types. + + ```typescript let UID: string = "UID", limit: number = 30, + categories: Array = ["message", "custom"], + types: Array = ["image", "video", "audio", "file"], messagesRequest: CometChat.MessagesRequest = new CometChat.MessagesRequestBuilder() - .setGUID(UID) + .setUID(UID) + .setCategories(categories) + .setTypes(types) .setLimit(limit) - .hasMentions(true) .build(); ``` + +```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(); +``` + + + ```typescript let GUID: string = "GUID", limit: number = 30, + categories: Array = ["message", "custom"], + types: Array = ["image", "video", "audio", "file"], messagesRequest: CometChat.MessagesRequest = new CometChat.MessagesRequestBuilder() .setGUID(GUID) + .setCategories(categories) + .setTypes(types) .setLimit(limit) - .hasMentions(true) .build(); ``` - - - -**On Success** — `fetchPrevious()` returns an array of `Message` objects containing mentions: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25271"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"<@uid:cometchat-uid-2> Hello"` | -| `sentAt` | number | Unix timestamp when sent | `1771482742` | -| `deliveredAt` | number | Unix timestamp when delivered | `1771482743` | -| `readAt` | number | Unix timestamp when read | `1771482743` | -| `updatedAt` | number | Unix timestamp when updated | `1771482743` | -| `sender` | object | Sender user details | [See below ↓](#filter-mentions-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#filter-mentions-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#filter-mentions-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#filter-mentions-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | [See below ↓](#filter-mentions-mentionedusers-array) | -| `mentionedMe` | boolean | Whether current user is mentioned | `true` | - ---- - - - -**`mentionedUsers` Array (per item):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771494233` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771482552` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771482544` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"<@uid:cometchat-uid-2> Hello"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `mentions` | object | Map of mentioned users by UID | [See below ↓](#filter-mentions-data-mentions-object) | -| `entities` | object | Sender and receiver entities | [See below ↓](#filter-mentions-data-entities-object) | -| `metadata` | object | Injected metadata | [See below ↓](#filter-mentions-data-metadata-object) | - ---- - - - -**`data.mentions` Object (keyed by UID):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771494233` | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#filter-mentions-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#filter-mentions-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#filter-mentions-data-entities-sender-entity-object) | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771482552` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#filter-mentions-data-entities-receiver-entity-object) | - ---- - - - -**`data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771482544` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#filter-mentions-data-metadata-injected-object) | - ---- - - - -**`data.metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#filter-mentions-data-metadata-extensions-object) | - ---- + +```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(); +``` - + -**`data.metadata.@injected.extensions` Object:** + -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#filter-mentions-data-metadata-linkpreview-object) | +The above snippet fetches all media messages (image, video, audio, file). ---- +## Messages for a specific thread - +Use `setParentMessageId()` to fetch messages belonging to a specific thread. -**`data.metadata.@injected.extensions.link-preview` Object:** + + +```typescript +let UID: string = "UID", + limit: number = 30, + messageId: number = 1, + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setLimit(limit) + .setParentMessageId(messageId) + .build(); +``` -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | + ---- + +```javascript +let UID = "UID"; +let messageId = 1; +let limit = 30; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setLimit(limit) + .setParentMessageId(messageId) + .build(); +``` - + -**`metadata` Object:** + +```typescript +let GUID: string = "GUID", + limit: number = 30, + messageId: number = 1, + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setLimit(limit) + .setParentMessageId(messageId) + .build(); +``` -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#filter-mentions-metadata-injected-object) | + ---- + +```javascript +let GUID = "GUID"; +let messageId = 1; +let limit = 30; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setLimit(limit) + .setParentMessageId(messageId) + .build(); +``` - + -**`metadata.@injected` Object:** + -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#filter-mentions-metadata-extensions-object) | +The above code returns messages belonging to the thread with the specified parent message ID. ---- +## Hide threaded messages in user/group conversations - +Use `hideReplies(true)` to exclude threaded messages from the main conversation. Default is `false`. -**`metadata.@injected.extensions` Object:** + + +```typescript +let UID: string = "UID", + limit: number = 30, + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setLimit(limit) + .hideReplies(true) + .build(); +``` -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#filter-mentions-metadata-linkpreview-object) | + ---- + +```javascript +let UID = "UID"; +let limit = 30; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setLimit(limit) + .hideReplies(true) + .build(); +``` - + -**`metadata.@injected.extensions.link-preview` Object:** + +```typescript +let GUID: string = "GUID", + limit: number = 30, + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setLimit(limit) + .hideReplies(true) + .build(); +``` -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | + - + +```javascript +let GUID = "GUID"; +let limit = 30; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setLimit(limit) + .hideReplies(true) + .build(); +``` -## Messages with particular user mentions + -*In other words, as a logged-in user, how do I fetch messages that mention 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. +## Hide deleted messages in user/group conversations - +Use `hideDeletedMessages(true)` to exclude deleted messages. Default is `false`. -This feature is only available with `Conversation & Advanced Search`. 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) + + +```typescript +let UID: string = "UID", + limit: number = 30, + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setLimit(limit) + .hideDeletedMessages(true) + .build(); +``` - +
- - + ```javascript let UID = "UID"; let limit = 30; let messagesRequest = new CometChat.MessagesRequestBuilder() .setUID(UID) .setLimit(limit) - .setMentionedUIDs(["UID"]) + .hideDeletedMessages(true) .build(); ``` - + +```typescript +let GUID: string = "GUID", + limit: number = 30, + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setLimit(limit) + .hideDeletedMessages(true) + .build(); +``` + + + + ```javascript let GUID = "GUID"; let limit = 30; let messagesRequest = new CometChat.MessagesRequestBuilder() .setGUID(GUID) .setLimit(limit) - .setMentionedUIDs(["UID"]) + .hideDeletedMessages(true) .build(); ``` + + +## Hide quoted messages in user/group conversations + +Use `hideQuotedMessages(true)` to exclude quoted messages. Default is `false`. + + ```typescript let UID: string = "UID", limit: number = 30, messagesRequest: CometChat.MessagesRequest = new CometChat.MessagesRequestBuilder() - .setGUID(UID) + .setUID(UID) .setLimit(limit) - .setMentionedUIDs(["UID"]) + .hideQuotedMessages(true) .build(); ``` + +```javascript +let UID = "UID"; +let limit = 30; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setLimit(limit) + .hideQuotedMessages(true) + .build(); +``` + + + ```typescript let GUID: string = "GUID", @@ -3957,280 +908,229 @@ let GUID: string = "GUID", new CometChat.MessagesRequestBuilder() .setGUID(GUID) .setLimit(limit) - .setMentionedUIDs(["UID"]) + .hideQuotedMessages(true) .build(); ``` - - - -**On Success** — `fetchPrevious()` returns an array of `Message` objects mentioning the specified UIDs: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25271"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"<@uid:cometchat-uid-2> Hello"` | -| `sentAt` | number | Unix timestamp when sent | `1771482742` | -| `deliveredAt` | number | Unix timestamp when delivered | `1771482743` | -| `readAt` | number | Unix timestamp when read | `1771482743` | -| `updatedAt` | number | Unix timestamp when updated | `1771482743` | -| `sender` | object | Sender user details | [See below ↓](#filter-mentioneduid-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#filter-mentioneduid-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#filter-mentioneduid-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#filter-mentioneduid-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | [See below ↓](#filter-mentioneduid-mentionedusers-array) | -| `mentionedMe` | boolean | Whether current user is mentioned | `true` | - ---- - - - -**`mentionedUsers` Array (per item):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771494233` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771482552` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771482544` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"<@uid:cometchat-uid-2> Hello"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `mentions` | object | Map of mentioned users by UID | [See below ↓](#filter-mentioneduid-data-mentions-object) | -| `entities` | object | Sender and receiver entities | [See below ↓](#filter-mentioneduid-data-entities-object) | -| `metadata` | object | Injected metadata | [See below ↓](#filter-mentioneduid-data-metadata-object) | - ---- - - - -**`data.mentions` Object (keyed by UID):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771494233` | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#filter-mentioneduid-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#filter-mentioneduid-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#filter-mentioneduid-data-entities-sender-entity-object) | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771482552` | -| `tags` | array | User tags | `[]` | - ---- - - + +```javascript +let GUID = "GUID"; +let limit = 30; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setLimit(limit) + .hideQuotedMessages(true) + .build(); +``` -**`data.entities.receiver` Object:** + -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#filter-mentioneduid-data-entities-receiver-entity-object) | +
---- +## Messages by tags - +Use `setTags()` with an array of tag names to fetch only messages with those tags. -**`data.entities.receiver.entity` Object:** + + +```typescript +let UID: string = "UID", + limit: number = 30, + tags: Array = ["starredMessage"], + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setLimit(limit) + .setTags(tags) + .build(); +``` -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771482544` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `tags` | array | User tags | `[]` | + ---- + +```javascript +let UID = "UID"; +let limit = 30; +let tags = ["starredMessage"]; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setLimit(limit) + .setTags(tags) + .build(); +``` - + -**`data.metadata` Object:** + +```typescript +let GUID: string = "GUID", + limit: number = 30, + tags: Array = ["starredMessage"], + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setLimit(limit) + .setTags(tags) + .build(); +``` -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#filter-mentioneduid-data-metadata-injected-object) | + ---- + +```javascript +let GUID = "GUID"; +let limit = 30; +let tags = ["starredMessage"]; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setLimit(limit) + .setTags(tags) + .build(); +``` - + -**`data.metadata.@injected` Object:** + -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#filter-mentioneduid-data-metadata-extensions-object) | +## Messages with tags ---- +Use `withTags(true)` to include tag information in the response. Default is `false`. - + + +```typescript +let UID: string = "UID", + limit: number = 30, + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setLimit(limit) + .withTags(true) + .build(); +``` -**`data.metadata.@injected.extensions` Object:** + -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#filter-mentioneduid-data-metadata-linkpreview-object) | + +```javascript +let UID = "UID"; +let limit = 30; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setUID(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(); +``` -**`data.metadata.@injected.extensions.link-preview` Object:** + -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | + +```javascript +let GUID = "GUID"; +let limit = 30; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setLimit(limit) + .withTags(true) + .build(); +``` ---- + - + -**`metadata` Object:** +When `withTags(true)` is set, each message's `tags` field will be populated. Access tags using `getTags()`. -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#filter-mentioneduid-metadata-injected-object) | +| Additional Field | Getter | Return Type | Description | +| --- | --- | --- | --- | +| tags | `getTags()` | `string[]` | Tags associated with the message | ---- +## Messages with links - +Use `hasLinks(true)` to fetch only messages containing links. Default is `false`. -**`metadata.@injected` Object:** + -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#filter-mentioneduid-metadata-extensions-object) | +This feature is only available with `Conversation & Advanced Search`. 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) ---- + - + + +```typescript +let UID: string = "UID", + limit: number = 30, + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setLimit(limit) + .hasLinks(true) + .build(); +``` -**`metadata.@injected.extensions` Object:** + -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#filter-mentioneduid-metadata-linkpreview-object) | + +```javascript +let UID = "UID"; +let limit = 30; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setLimit(limit) + .hasLinks(true) + .build(); +``` ---- + - + +```typescript +let GUID: string = "GUID", + limit: number = 30, + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setLimit(limit) + .hasLinks(true) + .build(); +``` -**`metadata.@injected.extensions.link-preview` Object:** + -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | + +```javascript +let GUID = "GUID"; +let limit = 30; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setLimit(limit) + .hasLinks(true) + .build(); +``` - + -## Messages with specific attachment types + -*In other words, as a logged-in user, how do I fetch messages that contain specific types of attachments?* +## Messages with 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 `hasAttachments(true)` to fetch only messages with attachments (image, audio, video, or file). Default is `false`. @@ -4239,46 +1139,102 @@ This feature is only available with `Conversation & Advanced Search`. The `Conve - + +```typescript +let UID: string = "UID", + limit: number = 30, + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setLimit(limit) + .hasAttachments(true) + .build(); +``` + + + + ```javascript let UID = "UID"; let limit = 30; let messagesRequest = new CometChat.MessagesRequestBuilder() .setUID(UID) .setLimit(limit) - .setAttachmentTypes([CometChat.AttachmentType.IMAGE, CometChat.AttachmentType.VIDEO]) + .hasAttachments(true) .build(); ``` - + +```typescript +let GUID: string = "GUID", + limit: number = 30, + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setLimit(limit) + .hasAttachments(true) + .build(); +``` + + + + ```javascript let GUID = "GUID"; let limit = 30; let messagesRequest = new CometChat.MessagesRequestBuilder() .setGUID(GUID) .setLimit(limit) - .setAttachmentTypes([CometChat.AttachmentType.IMAGE, CometChat.AttachmentType.VIDEO]) + .hasAttachments(true) .build(); ``` + + +The response contains media message objects with attachment details including file metadata and thumbnail URLs. + +## Messages with reactions + +Use `hasReactions(true)` to fetch only messages that have reactions. Default is `false`. + + + +This feature is only available with `Conversation & Advanced Search`. 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) + + + + ```typescript let UID: string = "UID", limit: number = 30, messagesRequest: CometChat.MessagesRequest = new CometChat.MessagesRequestBuilder() - .setGUID(UID) + .setUID(UID) .setLimit(limit) - .setAttachmentTypes([CometChat.AttachmentType.IMAGE, CometChat.AttachmentType.VIDEO]) + .hasReactions(true) .build(); ``` + +```javascript +let UID = "UID"; +let limit = 30; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setLimit(limit) + .hasReactions(true) + .build(); +``` + + + ```typescript let GUID: string = "GUID", @@ -4287,218 +1243,251 @@ let GUID: string = "GUID", new CometChat.MessagesRequestBuilder() .setGUID(GUID) .setLimit(limit) - .setAttachmentTypes([CometChat.AttachmentType.IMAGE, CometChat.AttachmentType.VIDEO]) + .hasReactions(true) .build(); ``` + +```javascript +let GUID = "GUID"; +let limit = 30; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setLimit(limit) + .hasReactions(true) + .build(); +``` + + + - -**On Success** — `fetchPrevious()` returns an array of `Message` objects with the specified attachment types: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25196"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"image"` | -| `category` | string | Message category | `"message"` | -| `sentAt` | number | Unix timestamp when sent | `1771386517` | -| `deliveredAt` | number | Unix timestamp when delivered | `1771386517` | -| `readAt` | number | Unix timestamp when read | `1771483750` | -| `updatedAt` | number | Unix timestamp when updated | `1771483750` | -| `sender` | object | Sender user details | [See below ↓](#filter-attachmenttypes-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#filter-attachmenttypes-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#filter-attachmenttypes-data-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | +The response contains message objects with reactions. Each message's `data` object includes a `reactions` array. ---- +## Messages with mentions + +Use `hasMentions(true)` to fetch only messages that contain mentions. Default is `false`. - + -**`sender` Object:** +This feature is only available with `Conversation & Advanced Search`. 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) -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771386507` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | + ---- + + +```typescript +let UID: string = "UID", + limit: number = 30, + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setLimit(limit) + .hasMentions(true) + .build(); +``` - + -**`receiver` Object:** + +```javascript +let UID = "UID"; +let limit = 30; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setLimit(limit) + .hasMentions(true) + .build(); +``` -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771386436` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | + ---- + +```typescript +let GUID: string = "GUID", + limit: number = 30, + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setLimit(limit) + .hasMentions(true) + .build(); +``` - + -**`data` Object:** + +```javascript +let GUID = "GUID"; +let limit = 30; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setLimit(limit) + .hasMentions(true) + .build(); +``` -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `type` | string | Attachment type | `"image"` | -| `category` | string | Message category | `"message"` | -| `url` | string | URL to the attachment | `"https://data-in.cometchat.io/2748663902141719/media/..."` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `attachments` | array | Array of attachment objects | [See below ↓](#filter-attachmenttypes-data-attachments-array) | -| `entities` | object | Sender and receiver entities | [See below ↓](#filter-attachmenttypes-data-entities-object) | + ---- + - +The response contains text message objects with mentions. Each message has a `mentionedUsers` array, a `mentionedMe` boolean, and a `data.mentions` object. -**`data.attachments` Array (per item):** +## Messages with particular user mentions -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extension` | string | File extension | `"jpg"` | -| `mimeType` | string | MIME type of the file | `"image/jpeg"` | -| `name` | string | File name | `"IMG_20260217_150412.jpg"` | -| `size` | number | File size in bytes | `142099` | -| `url` | string | URL to the attachment | `"https://data-in.cometchat.io/2748663902141719/media/..."` | +Use `setMentionedUIDs()` with an array of UIDs to fetch messages that mention specific users. ---- + + +This feature is only available with `Conversation & Advanced Search`. 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) - + -**`data.entities` Object:** + + +```typescript +let UID: string = "UID", + limit: number = 30, + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setLimit(limit) + .setMentionedUIDs(["UID"]) + .build(); +``` -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#filter-attachmenttypes-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#filter-attachmenttypes-data-entities-receiver-object) | + ---- + +```javascript +let UID = "UID"; +let limit = 30; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setLimit(limit) + .setMentionedUIDs(["UID"]) + .build(); +``` - + -**`data.entities.sender` Object:** + +```typescript +let GUID: string = "GUID", + limit: number = 30, + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setLimit(limit) + .setMentionedUIDs(["UID"]) + .build(); +``` -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#filter-attachmenttypes-data-entities-sender-entity-object) | + ---- + +```javascript +let GUID = "GUID"; +let limit = 30; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setLimit(limit) + .setMentionedUIDs(["UID"]) + .build(); +``` - + -**`data.entities.sender.entity` Object:** + -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771386507` | -| `tags` | array | User tags | `[]` | +The response contains text message objects that mention the specified users. ---- +## Messages with specific attachment types - +Use `setAttachmentTypes()` with an array of `CometChat.AttachmentType` values to fetch messages with specific attachment types. -**`data.entities.receiver` Object:** + -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#filter-attachmenttypes-data-entities-receiver-entity-object) | +This feature is only available with `Conversation & Advanced Search`. 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) ---- + - + + +```typescript +let UID: string = "UID", + limit: number = 30, + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setLimit(limit) + .setAttachmentTypes([CometChat.AttachmentType.IMAGE, CometChat.AttachmentType.VIDEO]) + .build(); +``` -**`data.entities.receiver.entity` Object:** + -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771386436` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `tags` | array | User tags | `[]` | + +```javascript +let UID = "UID"; +let limit = 30; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setLimit(limit) + .setAttachmentTypes([CometChat.AttachmentType.IMAGE, CometChat.AttachmentType.VIDEO]) + .build(); +``` - +
-## Best Practices & Troubleshooting + +```typescript +let GUID: string = "GUID", + limit: number = 30, + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setLimit(limit) + .setAttachmentTypes([CometChat.AttachmentType.IMAGE, CometChat.AttachmentType.VIDEO]) + .build(); +``` - - - Always call `fetchNext()` or `fetchPrevious()` on the same `MessagesRequest` object to paginate through results. Creating a new `MessagesRequest` object will reset pagination and start from the beginning. - + - - You can chain multiple builder methods together (e.g., `setCategories()` + `setTypes()` + `setUID()`) to narrow down results. This is more efficient than fetching all messages and filtering client-side. - + +```javascript +let GUID = "GUID"; +let limit = 30; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setLimit(limit) + .setAttachmentTypes([CometChat.AttachmentType.IMAGE, CometChat.AttachmentType.VIDEO]) + .build(); +``` - - If you store messages locally, use `setUpdatedAfter()` with the timestamp of your last synced message to fetch only new or updated messages. Combine with `updatesOnly(true)` if you only need edits, deletions, and read/delivery status changes. - + - - The maximum limit per fetch is `100`. For most UI use cases, a limit of `30–50` provides a good balance between performance and user experience. Smaller limits mean faster responses and less memory usage. - +
- - If `fetchNext()` or `fetchPrevious()` returns an empty array, verify that: the logged-in user is a member of the group (for group conversations), the UID/GUID is correct, and the applied filters aren't too restrictive. Try removing filters one at a time to isolate the issue. - +The response contains media message objects filtered to the specified attachment types. - - Methods like `hasLinks()`, `hasAttachments()`, `hasReactions()`, `hasMentions()`, `setMentionedUIDs()`, and `setAttachmentTypes()` require the Conversation & Advanced Search feature to be enabled. Ensure you are on an Advanced or Custom [plan](https://www.cometchat.com/pricing) and have enabled the feature from the [CometChat Dashboard](https://app.cometchat.com) (Chats → Settings → General Configuration). - - ---- ## Next Steps - - Listen for and handle incoming real-time messages - - Send text, media, and custom messages to users and groups + Send text, media, and custom messages + + + Listen for incoming messages in real-time - - Understand message categories, types, and structure + + Understand message categories, types, and hierarchy - - Fetch and display conversation lists with latest messages + + Work with threaded conversations diff --git a/sdk/react-native/ai-agents.mdx b/sdk/react-native/ai-agents.mdx index f6d1464ad..05f8e5bde 100644 --- a/sdk/react-native/ai-agents.mdx +++ b/sdk/react-native/ai-agents.mdx @@ -1,68 +1,102 @@ --- title: "AI Agents" -description: "Learn how to integrate AI Agents in your React Native app using the CometChat SDK, including real-time event streaming and agentic message handling." +sidebarTitle: "AI Agents" +description: "Integrate AI Agents into your React Native app using the CometChat SDK, including real-time event streaming and agentic message handling." --- - -**Quick Reference** + + +| Feature | Description | +| --- | --- | +| [AI Agents](#agent-run-lifecycle-and-message-flow) | Intelligent automated conversations with real-time streaming | +| [AI Moderation](/sdk/react-native/ai-moderation) | Automatic content moderation with `PENDING` → `APPROVED` / `DISAPPROVED` flow | + ```javascript -// Listen for real-time AI Agent events -CometChat.addAIAssistantListener("listenerId", { - onAIAssistantEventReceived: (event) => {} +// 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("listenerId", { - onAIAssistantMessageReceived: (message) => {}, - onAIToolResultReceived: (message) => {}, - onAIToolArgumentsReceived: (message) => {} -}); +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"); +CometChat.removeMessageListener("LISTENER_ID"); ``` - -## Overview +**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 + -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). -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 are received via the **`onAIAssistantEventReceived`** method of the **`AIAssistantListener`** class as [`AIAssistantBaseEvent`](/sdk/reference/messages#aiassistantbaseevent) objects, in this general order: + +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 — 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 | - - ```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); } }); @@ -70,14 +104,15 @@ Notes: // Removing the AIAssistantListener 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); } }); @@ -85,7 +120,8 @@ Notes: // Removing the AIAssistantListener CometChat.removeAIAssistantListener(listnerId); ``` - + + @@ -95,41 +131,60 @@ CometChat.removeAIAssistantListener("unique_listener_id"); ``` -#### Event Descriptions - -| Event | Description | -|-------|-------------| -| 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 | +#### 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 | + +Each message type extends [`BaseMessage`](/sdk/reference/messages#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 | - - ```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); }, }); @@ -138,20 +193,19 @@ These events are received via the **`MessageListener`** after the run completes. 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); }, }); @@ -163,36 +217,21 @@ These events are received via the **`MessageListener`** after the run completes. -Always remove message listeners when the component unmounts to prevent memory leaks. -```javascript -CometChat.removeMessageListener("unique_listener_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. - - -- Register both `AIAssistantListener` (for real-time streaming) and `MessageListener` (for persisted messages) to get the complete agent interaction flow -- Use `Text Message Content` events for progressive rendering of the agent's reply as it streams in -- Handle `Tool Call` events to show tool execution status in your UI (e.g., loading indicators) -- Always remove both listeners on component unmount to avoid memory leaks -- Since agents only respond to text messages, validate the message type before sending to an agent - - - -- **No events received**: Ensure you registered the `AIAssistantListener` with a unique listener ID before sending a message to the agent. -- **Missing agentic messages**: Agentic messages arrive via `MessageListener` after the run completes. Make sure you have both listeners registered. -- **Duplicate events**: Verify you are not registering the same listener ID multiple times without removing the previous one. -- **Tool call events not appearing**: Tool call events only fire when the agent invokes a tool. Not all runs include tool calls. - - +--- ## Next Steps - -Explore the full AI Agents platform documentation - - -Automatically moderate messages using AI - + + Explore the full AI Agents platform documentation + + + Automatically moderate messages using AI + + + Send text messages that trigger AI Agent responses + diff --git a/sdk/react-native/ai-chatbots-overview.mdx b/sdk/react-native/ai-chatbots-overview.mdx index 7bbac1856..7a460169b 100644 --- a/sdk/react-native/ai-chatbots-overview.mdx +++ b/sdk/react-native/ai-chatbots-overview.mdx @@ -1,4 +1,4 @@ --- title: "Bots" -url: "/ai-chatbots-overview" ---- \ No newline at end of file +url: "/ai-chatbots/overview" +--- diff --git a/sdk/react-native/ai-moderation.mdx b/sdk/react-native/ai-moderation.mdx index fcaa57fd8..7d1139da8 100644 --- a/sdk/react-native/ai-moderation.mdx +++ b/sdk/react-native/ai-moderation.mdx @@ -1,41 +1,46 @@ --- title: "AI Moderation" -description: "Learn how to use AI-powered message moderation in your React Native app using the CometChat SDK, including real-time moderation events and handling disapproved messages." +sidebarTitle: "AI Moderation" +description: "Automatically moderate chat messages using AI to detect and block inappropriate content in real-time." --- - -**Quick Reference** + + ```javascript -// Send a message and check moderation status -CometChat.sendMessage(textMessage).then((message) => { +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(); // CometChat.ModerationStatus.PENDING | APPROVED | DISAPPROVED }); // Listen for moderation results -CometChat.addMessageListener("listenerId", new CometChat.MessageListener({ +CometChat.addMessageListener("MOD_LISTENER", new CometChat.MessageListener({ onMessageModerated: (message) => { const status = message.getModerationStatus(); + // Handle APPROVED or DISAPPROVED } })); ``` - -## Overview +**Supported types:** Text, Image, Video messages only +**Statuses:** `PENDING` → `APPROVED` or `DISAPPROVED` + + +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. -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. +`getModerationStatus()` is available on [`TextMessage`](/sdk/reference/messages#textmessage) and [`MediaMessage`](/sdk/reference/messages#mediamessage) objects. Custom messages are not subject to moderation. -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 -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 a 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 @@ -84,6 +89,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 @@ -92,8 +98,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?", @@ -101,23 +107,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?", @@ -125,16 +131,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); } ); @@ -144,23 +150,23 @@ 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: - - ```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: @@ -183,20 +189,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: @@ -221,16 +227,9 @@ Register a message listener to receive moderation results in real-time: - -Always remove message listeners when the component unmounts to prevent memory leaks. -```javascript -CometChat.removeMessageListener("MODERATION_LISTENER"); -``` - - ### Step 3: Handle Disapproved Messages -When a message is disapproved, handle it appropriately in your UI: +When a message is disapproved, you should handle it appropriately in your UI: ```javascript function handleDisapprovedMessage(message) { @@ -249,30 +248,171 @@ function handleDisapprovedMessage(message) { } ``` - - -- Always check `getModerationStatus()` after sending a message to show appropriate UI indicators (e.g., a pending badge) -- Register the `onMessageModerated` listener early in your app lifecycle so you don't miss moderation results -- Provide clear feedback to users when their message is disapproved — avoid silently hiding content without explanation -- Custom and Action messages are not moderated — if you need moderation on custom message types, implement your own server-side checks -- Consider caching moderation status locally to avoid re-checking on message list re-renders - +## Complete Example - -- **Moderation status always PENDING**: Ensure moderation rules are configured in the CometChat Dashboard under **Moderation > Rules**. -- **`onMessageModerated` not firing**: Verify you registered a `MessageListener` with the correct listener ID and that moderation is enabled for your app. -- **Custom messages not being moderated**: This is expected — AI Moderation only applies to text, image, and video messages. -- **Disapproved messages still visible**: Make sure your `onMessageModerated` handler updates the UI when a message status changes to `DISAPPROVED`. - - +Here's a complete implementation showing the full moderation flow: + + + +```typescript + class ModerationHandler { + constructor() { + this.pendingMessages = new Map(); + this.setupListener(); + } + + setupListener() { + CometChat.addMessageListener( + "MODERATION_LISTENER", + new CometChat.MessageListener({ + onMessageModerated: (message) => this.onModerated(message) + }) + ); + } + + async sendMessage(receiverUID, text) { + const textMessage = new CometChat.TextMessage( + receiverUID, + text, + CometChat.RECEIVER_TYPE.USER + ); + + try { + const message = await CometChat.sendMessage(textMessage); + const status = message.getModerationStatus(); + + if (status === CometChat.ModerationStatus.PENDING) { + // Track pending message + this.pendingMessages.set(message.getId(), message); + return { success: true, pending: true, message }; + } + + return { success: true, pending: false, message }; + } catch (error) { + return { success: false, error }; + } + } + + onModerated(message) { + const messageId = message.getId(); + const status = message.getModerationStatus(); + + // Remove from pending + this.pendingMessages.delete(messageId); + + // Emit event for UI update + this.emit("moderationResult", { + messageId, + status, + approved: status === CometChat.ModerationStatus.APPROVED, + message + }); + } + + cleanup() { + CometChat.removeMessageListener("MODERATION_LISTENER"); + } + } + + // Usage + const handler = new ModerationHandler(); + const result = await handler.sendMessage("user123", "Hello!"); + + if (result.pending) { + console.log("Message pending moderation..."); + } + ``` + + + +```javascript + class ModerationHandler { + constructor() { + this.pendingMessages = new Map(); + this.setupListener(); + } + + setupListener() { + CometChat.addMessageListener( + "MODERATION_LISTENER", + new CometChat.MessageListener({ + onMessageModerated: (message) => this.onModerated(message) + }) + ); + } + + async sendMessage(receiverUID, text) { + const textMessage = new CometChat.TextMessage( + receiverUID, + text, + CometChat.RECEIVER_TYPE.USER + ); + + try { + const message = await CometChat.sendMessage(textMessage); + const status = message.getModerationStatus(); + + if (status === CometChat.ModerationStatus.PENDING) { + // Track pending message + this.pendingMessages.set(message.getId(), message); + return { success: true, pending: true, message }; + } + + return { success: true, pending: false, message }; + } catch (error) { + return { success: false, error }; + } + } + + onModerated(message) { + const messageId = message.getId(); + const status = message.getModerationStatus(); + + // Remove from pending + this.pendingMessages.delete(messageId); + + // Emit event for UI update + this.emit("moderationResult", { + messageId, + status, + approved: status === CometChat.ModerationStatus.APPROVED, + message + }); + } + + cleanup() { + CometChat.removeMessageListener("MODERATION_LISTENER"); + } + } + + // Usage + const handler = new ModerationHandler(); + const result = await handler.sendMessage("user123", "Hello!"); + + if (result.pending) { + console.log("Message pending moderation..."); + } + ``` + + + + + +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 - -Allow users to report inappropriate messages - - -Add intelligent AI agent interactions - + + Allow users to report inappropriate messages manually + + + Build intelligent automated conversations with AI Agents + + + Send text, media, and custom messages + diff --git a/sdk/react-native/authentication-overview.mdx b/sdk/react-native/authentication-overview.mdx index 2afe70562..eaad222a0 100644 --- a/sdk/react-native/authentication-overview.mdx +++ b/sdk/react-native/authentication-overview.mdx @@ -1,283 +1,332 @@ --- title: "Authentication" -sidebarTitle: "Overview" -description: "Learn how to create users, log in with Auth Key or Auth Token, and manage user sessions in CometChat React Native SDK." +sidebarTitle: "Authentication" +description: "Create users, log in with Auth Key or Auth Token, check login status, and log out using the CometChat React Native SDK." --- - -**Quick Reference** - Login with Auth Key (dev) or Auth Token (production): +{/* TL;DR for Agents and Quick Reference */} + ```javascript -// Auth Key login (development only) -const user = await CometChat.login("USER_UID", "AUTH_KEY"); +// Check existing session +const user = await CometChat.getLoggedinUser(); -// Auth Token login (recommended for production) -const user = await CometChat.login("AUTH_TOKEN"); +// Login with Auth Key (development only) +CometChat.login("cometchat-uid-1", "AUTH_KEY").then(user => console.log("Logged in:", user)); -// Check existing session -const loggedInUser = await CometChat.getLoggedinUser(); +// 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 User +**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` + -Before you log in a user, you must add the user to CometChat. +After [initializing](/sdk/react-native/setup-sdk) 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. + +### How It Works + +```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) +``` + +## 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:** 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`. - +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. +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); + } +); +``` + + -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. +`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/react-native/user-management) for full details. -## Login using Auth Key +### 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. + +```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 with Auth Key + +Auth Key login is the simplest way to get started. Pass a UID and your Auth Key directly from the client. -**Security Warning:** This straightforward authentication method is ideal for proof-of-concept (POC) development or during the early stages of application development. For production environments, we strongly recommend using an [Auth Token](#login-using-auth-token) instead of an Auth Key to ensure enhanced security. +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. - - ```javascript - var UID = "UID"; - var authKey = "AUTH_KEY"; - - // Check if user is already logged in before calling login - 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("Something went wrong", error); - } - ); - ``` - - - ```typescript - var UID: string = "cometchat-uid-1", - authKey: string = "AUTH_KEY"; - - // Check if user is already logged in before calling login - 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); - } - ); + +```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); - } - ); - ``` - - - -| Parameter | Description | -| --------- | ------------------------------------------------ | -| UID | The UID of the user that you would like to login | -| authKey | CometChat Auth Key | + ); + } + }, + (error: CometChat.CometChatException) => { + console.log("Some Error Occurred", { error }); + } +); +``` + -After the user logs in, their information is returned in the `User` object on `Promise` resolved. + +```javascript +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 Occurred", { error }); + } +); +``` - -**On Success** — Returns a User object: +Alternatively, you can use the `async/await` syntax: - +```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 }); +} +``` + -**User Object:** + -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"cometchat-uid-2"` | -| `name` | string | Display name of the user | `"George Alan"` | -| `authToken` | string | Authentication token for the session | `"cometchat-uid-2_17713124898af10df254d51ef6ffc14e79955ac0"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | Current online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771311515` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Unix timestamp if user is deactivated (0 if active) | `0` | -| `tags` | array | Tags associated with the user | `[]` | +| Parameter | Description | +| --------- | ----------- | +| UID | The UID of the user to log in | +| authKey | Your CometChat Auth Key | - +On success, the `Promise` resolves with a [`User`](/sdk/reference/entities#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. - - - [Create a User](https://api-explorer.cometchat.com/reference/creates-user) via the CometChat API when the user signs up in your app. - - - [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. - - - 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()`. - - ```javascript - var authToken = "AUTH_TOKEN"; - - // Check if user is already logged in before calling login - CometChat.getLoggedinUser().then( - (user) => { - if (!user) { - CometChat.login(authToken).then( - (user) => { - console.log("Login Successful:", user); - }, - (error) => { - console.log("Login failed with exception:", error); - } - ); + +```typescript +const authToken: string = "AUTH_TOKEN"; + +CometChat.getLoggedinUser().then( + (user: CometChat.User) => { + if (!user) { + CometChat.login(authToken).then( + (user: CometChat.User) => { + console.log("Login Successful:", { user }); + }, + (error: CometChat.CometChatException) => { + console.log("Login failed with exception:", { error }); } - }, - (error) => { - console.log("Something went wrong", error); - } - ); - ``` - - - ```typescript - var authToken: string = "AUTH_TOKEN"; - - // Check if user is already logged in before calling login - CometChat.getLoggedinUser().then( - (user: CometChat.User) => { - if (!user) { - CometChat.login(authToken).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); - } - ); - ``` - - - -| Parameter | Description | -| --------- | ---------------------------------------------- | -| authToken | Auth Token of the user you would like to login | + ); + } + }, + (error: CometChat.CometChatException) => { + console.log("Some Error Occurred", { error }); + } +); +``` +
-After the user logs in, their information is returned in the `User` object on the `Promise` resolved. + +```javascript +const authToken = "AUTH_TOKEN"; + +CometChat.getLoggedinUser().then( + (user) => { + if (!user) { + CometChat.login(authToken).then( + (user) => { + console.log("Login Successful:", { user }); + }, + (error) => { + console.log("Login failed with exception:", { error }); + } + ); + } + }, + (error) => { + console.log("Some Error Occurred", { error }); + } +); +``` - -**On Success** — Returns a User object: +Alternatively, you can use the `async/await` syntax: - +```javascript +const 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 }); +} +``` + -**User Object:** +
-| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"cometchat-uid-2"` | -| `name` | string | Display name of the user | `"George Alan"` | -| `authToken` | string | Authentication token for the session | `"cometchat-uid-2_17713124898af10df254d51ef6ffc14e79955ac0"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | Current online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771311515` | -| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | -| `blockedByMe` | boolean | Whether logged-in user has blocked this user | `false` | -| `deactivatedAt` | number | Unix timestamp if user is deactivated (0 if active) | `0` | -| `tags` | array | Tags associated with the user | `[]` | +| Parameter | Description | +| --------- | ----------- | +| authToken | Auth Token generated on your server for the user | - +On success, the `Promise` resolves with a [`User`](/sdk/reference/entities#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. - - ```javascript - CometChat.logout().then( - () => { - console.log("Logout completed successfully"); - }, - (error) => { - console.log("Logout failed with exception:", error); - } - ); - ``` - - - ```typescript - CometChat.logout().then( - (loggedOut: Object) => { - console.log("Logout completed successfully"); - }, - (error: CometChat.CometChatException) => { - console.log("Logout failed with exception:", error); - } - ); - ``` - - + +```typescript +CometChat.logout().then( + (loggedOut: Object) => { + console.log("Logout completed successfully"); + }, + (error: CometChat.CometChatException) => { + console.log("Logout failed with exception:", { error }); + } +); +``` + + + +```javascript +CometChat.logout().then( + () => { + console.log("Logout completed successfully"); + }, + (error) => { + console.log("Logout failed with exception:", { error }); + } +); +``` - -**On Success** — Returns a success message: +Alternatively, you can use the `async/await` syntax: -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `message` | string | Logout confirmation | `"Logout completed successfully"` | +```javascript +try { + await CometChat.logout(); + console.log("Logout completed successfully"); +} catch (error) { + console.log("Logout failed with exception:", { error }); +} +``` + - + - - - - Always check for an existing session with `getLoggedinUser()` before calling `login()` - - Use Auth Token (not Auth Key) in production environments - - Generate Auth Tokens server-side and never expose your REST API Key in client code - - Call `logout()` when the user logs out of your app to clean up the CometChat session - - Handle login errors gracefully and provide user-friendly error messages - - - - **Login fails with "UID not found":** Ensure the user has been created in CometChat before attempting login - - **Auth Token expired:** Generate a new Auth Token from your server and retry login - - **Session persists after logout:** Ensure `logout()` completes successfully before redirecting - - **Multiple login calls:** Use `getLoggedinUser()` to prevent redundant login attempts - - +--- ## Next Steps @@ -285,13 +334,13 @@ You can use the `logout()` method to log out the user from CometChat. We suggest Listen for real-time login and logout events - - Start sending text, media, and custom messages + + Send your first text, media, or custom message - - Track real-time online/offline status of users + + Create, update, and delete users programmatically - - Add pre-built UI components to your app + + Complete reference for all SDK event listeners diff --git a/sdk/react-native/block-users.mdx b/sdk/react-native/block-users.mdx index 1b3528b24..33a1bc088 100644 --- a/sdk/react-native/block-users.mdx +++ b/sdk/react-native/block-users.mdx @@ -1,10 +1,10 @@ --- title: "Block Users" -description: "Block and unblock users, and retrieve blocked user lists using the CometChat React Native SDK." +sidebarTitle: "Block Users" +description: "Block and unblock users, and retrieve the list of blocked users using the CometChat React Native SDK." --- - -**Quick Reference** - Block and unblock users: + ```javascript // Block users @@ -13,40 +13,24 @@ await CometChat.blockUsers(["UID1", "UID2"]); // Unblock users await CometChat.unblockUsers(["UID1", "UID2"]); -// Fetch blocked users -const request = new CometChat.BlockedUsersRequestBuilder().setLimit(30).build(); -const blockedUsers = await request.fetchNext(); +// Get blocked users list +let request = new CometChat.BlockedUsersRequestBuilder().setLimit(30).build(); +let blockedUsers = await request.fetchNext(); ``` - - -**Available via:** [SDK](/sdk/react-native/block-users) | [REST API](/rest-api/blocked-users/block-user) - +**Directions:** `BLOCKED_BY_ME` | `HAS_BLOCKED_ME` | `BOTH` (default) + -## Block Users +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. -*In other words, as a logged-in user, how do I block a user from sending me messages?* +## 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. +Block users to prevent all communication with them. Use `blockUsers()` with an array of UIDs. - -```javascript -var 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 -var usersList: String[] = ["UID1", "UID2", "UID3"]; +const usersList: String[] = ["UID1", "UID2", "UID3"]; CometChat.blockUsers(usersList).then( (list: Object) => { @@ -56,39 +40,61 @@ CometChat.blockUsers(usersList).then( } ); ``` - - + +```javascript +const usersList = ["UID1", "UID2", "UID3"]; - -**On Success** — `blockUsers()` returns an object with each UID as key and result object as value: +CometChat.blockUsers(usersList).then( +list => { + console.log("users list blocked", { list }); +}, error => { + console.log("Blocking user fails with error", error); +} +); +``` -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `[UID]` | object | Result object for each blocked UID | See below | +Alternatively, you can use the `async/await` syntax: -**Result Object (per UID):** +```javascript +const usersList = ["UID1", "UID2", "UID3"]; -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `success` | boolean | Whether the block operation succeeded | `true` | -| `message` | string | Descriptive message about the operation | `"The user with UID cometchat-uid-7 has blocked user with UID cometchat-uid-2 successfully."` | +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. +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 -*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. + +```typescript +const usersList: String[] = ["UID1", "UID2", "UID3"]; + +CometChat.unblockUsers(usersList).then( + (list: Object) => { + console.log("users list unblocked", { list }); + }, (error: CometChat.CometChatException) => { + console.log("Unblocking user fails with error", error); + } +); +``` + + ```javascript -var usersList = ["UID1", "UID2", "UID3"]; +const usersList = ["UID1", "UID2", "UID3"]; CometChat.unblockUsers(usersList).then( list => { @@ -99,66 +105,33 @@ list => { ); ``` - +Alternatively, you can use the `async/await` syntax: - -```typescript -var usersList: String[] = ["UID1", "UID2", "UID3"]; +```javascript +const usersList = ["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); - } -); +try { + const list = await CometChat.unblockUsers(usersList); + console.log("users list unblocked", { list }); +} catch (error) { + console.log("unblocking user fails with error", error); +} ``` - - -**On Success** — `unblockUsers()` returns an object with each UID as key and result object as value: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `[UID]` | object | Result object for each unblocked UID | See below | - -**Result Object (per UID):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `success` | boolean | Whether the unblock operation succeeded | `true` | -| `message` | string | Descriptive message about the operation | `"The user with UID cometchat-uid-7 has unblocked user with UID cometchat-uid-2 successfully."` | - - - -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. Each [`User`](/sdk/reference/entities#user) in the request is processed independently. ## 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. - -```javascript -let limit = 30; -let blockedUsersRequest = new BlockedUsersRequest.BlockedUsersRequestBuilder() - .setLimit(limit) - .build(); -``` - - - ```typescript let limit: number = 30; @@ -169,25 +142,23 @@ 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. - - ```javascript let limit = 30; -let searchKeyword = "super"; -let blockedUsersRequest = new BlockedUsersRequest.BlockedUsersRequestBuilder() +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; @@ -200,46 +171,29 @@ let blockedUsersRequest: CometChat.BlockedUsersRequest = new CometChat.BlockedUs - - - -**On Success** — `fetchNext()` with search filter returns an array of blocked `User` objects matching the search: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"cometchat-uid-2"` | -| `name` | string | Display name of the user | `"George Alan"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1772104172` | -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `true` | -| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | -| `blockedByMeAt` | number | Timestamp when blocked by current user | `1772173462` | -| `blockedAt` | number | Timestamp of block action | `1772173462` | -| `conversationId` | string | Conversation ID between this user and logged-in user | `"cometchat-uid-2_user_cometchat-uid-6"` | - - - -### 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. - - ```javascript let limit = 30; -let blockedUsersRequest = new BlockedUsersRequest.BlockedUsersRequestBuilder() +let searchKeyword = "super"; +let blockedUsersRequest = new CometChat.BlockedUsersRequestBuilder() .setLimit(limit) - .setDirection(CometChat.BlockedUsersRequest.directions.BLOCKED_BY_ME) + .setSearchKeyword(searchKeyword) .build(); ``` + + +### Set Direction + +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) + + ```typescript let limit: number = 30; @@ -248,78 +202,23 @@ let blockedUsersRequest: CometChat.BlockedUsersRequest = new CometChat.BlockedUs .setDirection(CometChat.BlockedUsersRequest.directions.BLOCKED_BY_ME) .build(); ``` - - - - -**On Success** — `fetchNext()` with `BLOCKED_BY_ME` direction returns users blocked by the logged-in user: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"cometchat-uid-2"` | -| `name` | string | Display name of the user | `"George Alan"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1772104172` | -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `true` | -| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | -| `blockedByMeAt` | number | Timestamp when blocked by current user | `1772173462` | -| `blockedAt` | number | Timestamp of block action | `1772173462` | -| `conversationId` | string | Conversation ID between this user and logged-in user | `"cometchat-uid-2_user_cometchat-uid-6"` | - - - - -**On Success** — `fetchNext()` with `HAS_BLOCKED_ME` direction returns users who have blocked the logged-in user. Returns an empty array if no users have blocked you. - - - - -**On Success** — `fetchNext()` with `BOTH` direction returns all blocked users (both directions): - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"cometchat-uid-2"` | -| `name` | string | Display name of the user | `"George Alan"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1772104172` | -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `true` | -| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | -| `blockedByMeAt` | number | Timestamp when blocked by current user | `1772173462` | -| `blockedAt` | number | Timestamp of block action | `1772173462` | -| `conversationId` | string | Conversation ID between this user and logged-in user | `"cometchat-uid-2_user_cometchat-uid-6"` | - - - -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. - - ```javascript -var limit = 30; -var 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); -} -); +let limit = 30; +let blockedUsersRequest = new CometChat.BlockedUsersRequestBuilder() + .setLimit(limit) + .setDirection(CometChat.BlockedUsersRequest.directions.BLOCKED_BY_ME) + .build(); ``` - + + +After configuring the builder, call `build()` to get the `BlockedUsersRequest` object, then call `fetchNext()` to retrieve blocked users. + + ```typescript let limit: number = 30; @@ -333,55 +232,38 @@ blockedUsersRequest.fetchNext().then( }, (error: CometChat.CometChatException) => { console.log("Blocked user list fetching failed with error:", error); } -); +); ``` - - - -**On Success** — `fetchNext()` returns an array of blocked `User` objects: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"123456"` | -| `name` | string | Display name of the user | `"Farhan Ahmed"` | -| `avatar` | string | URL to user's avatar image | `"https://st2.depositphotos.com/38197074/46684/v/450/depositphotos_466848082-stock-illustration-initial-letter-vector-logo.jpg"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"extrarole"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1768988601` | -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `true` | -| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | -| `metadata` | object | Custom metadata attached to the user | `{"meta": "anyValue"}` | -| `blockedByMeAt` | number | Timestamp when blocked by current user | `1772164515` | -| `blockedAt` | number | Timestamp of block action | `1772164515` | -| `conversationId` | string | Conversation ID between this user and logged-in user | `"123456_user_cometchat-uid-7"` | + +```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); +} +); +``` - + -## Best Practices + - - - When displaying user lists in your app, use `hideBlockedUsers(true)` in the `UsersRequestBuilder` to automatically exclude blocked users from the results. - - - The `blockUsers()` and `unblockUsers()` methods return a map with each UID's result ("success" or "fail"). Check individual results rather than assuming all operations succeeded. - - +The `fetchNext()` method returns an array of [`User`](/sdk/reference/entities#user) objects representing blocked users. -## Troubleshooting +Relevant fields to access on returned users: - - - Blocking is enforced server-side. If a blocked user's messages still appear, verify the block operation returned "success" for that UID. Also ensure you're not using a cached conversation list — refresh after blocking. - - - Check the `setDirection` filter. If set to `BLOCKED_BY_ME`, only users you blocked are returned. If set to `HAS_BLOCKED_ME`, only users who blocked you are returned. Use `BOTH` to see all. - - +| 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 | --- @@ -389,15 +271,15 @@ blockedUsersRequest.fetchNext().then( - Fetch user lists with filtering and pagination - - - Create, update, and delete users in CometChat + Fetch and filter user lists - Track online/offline status of users in real time + Track online/offline status of users + + + Create, update, and delete users - - Send text, media, and custom messages to users and groups + + Report inappropriate messages from users - \ No newline at end of file + diff --git a/sdk/react-native/call-logs.mdx b/sdk/react-native/call-logs.mdx index 413411612..67ca132be 100644 --- a/sdk/react-native/call-logs.mdx +++ b/sdk/react-native/call-logs.mdx @@ -1,49 +1,61 @@ --- title: "Call Logs" -description: "Fetch, filter, and display call history in your React Native app using CometChat Calls SDK — including call duration, participants, direction, and recording status." +sidebarTitle: "Call Logs" +description: "Fetch, filter, and retrieve call history including duration, participants, and recording status using the CometChat Calls SDK." --- - -**Quick Reference** - Fetch call logs: + ```javascript -const loggedInUser = await CometChat.getLoggedinUser(); +let loggedInUser = await CometChat.getLoggedinUser(); +let authToken = loggedInUser.getAuthToken(); -let callLogRequest = new CometChatCalls.CallLogRequestBuilder() +// Fetch call logs +let request = new CometChatCalls.CallLogRequestBuilder() .setLimit(30) - .setAuthToken(loggedInUser.getAuthToken()) + .setAuthToken(authToken) .setCallCategory("call") .build(); -const callLogs = await callLogRequest.fetchNext(); -``` - - - -**Available via:** [SDK](/sdk/react-native/call-logs) | [REST API](/rest-api/list-calls) | [UI Kits](/ui-kit/react/call-features#call-logs) - +let logs = await request.fetchNext(); -## Overview +// Get details for a specific call session +let details = await CometChatCalls.getCallDetails("SESSION_ID", authToken); +``` -CometChat's React Native 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. +**Filters:** `setCallType()`, `setCallStatus()`, `setCallCategory()`, `setCallDirection()`, `setHasRecording()`, `setUid()`, `setGuid()` + -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. +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. -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 React Native application. +Before you begin, make sure you've completed the [Calls SDK Setup](/sdk/react-native/calling-setup). -## Fetching Call Logs +## Fetch Call Logs -To fetch all call logs in your React Native application, you should use the `CallLogRequestBuilder`, This builder allows you to customize the call logs fetching process according to your needs. +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. + + +```typescript +let callLogRequestBuilder: any = new CometChatCalls.CallLogRequestBuilder() + .setLimit(30) + .setAuthToken(loggedInUser.getAuthToken()) + .setCallCategory("call") + .build(); +``` + + ```javascript let callLogRequestBuilder = new CometChatCalls.CallLogRequestBuilder() - .setLimit(30) - .setAuthToken(loggedInUser.getAuthToken()) - .setCallCategory("call") - .build() + .setLimit(30) + .setAuthToken(loggedInUser.getAuthToken()) + .setCallCategory("call") + .build(); ``` + + -`CallLogRequestBuilder` has the following settings available. +### Builder Settings | Setting | Description | | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ | @@ -59,248 +71,140 @@ let callLogRequestBuilder = new CometChatCalls.CallLogRequestBuilder() ### Fetch Next -The `fetchNext()` method retrieves the next set of call logs. +Retrieves the next set of call logs: + + + +```typescript +let callLogRequestBuilder: any = new CometChatCalls.CallLogRequestBuilder() + .setLimit(30) + .setAuthToken(loggedInUser.getAuthToken()) + .setCallCategory("call") + .build(); +callLogRequestBuilder.fetchNext().then( + (callLogHistory: any[]) => { + console.log(callLogHistory); + }, + (err: any) => { + console.log(err); + } +); +``` + + ```javascript let callLogRequestBuilder = new CometChatCalls.CallLogRequestBuilder() - .setLimit(30) - .setAuthToken(loggedInUser.getAuthToken()) - .setCallCategory("call") - .build() + .setLimit(30) + .setAuthToken(loggedInUser.getAuthToken()) + .setCallCategory("call") + .build(); -callLogRequestBuilder.fetchNext() - .then(callLogHistory => { +callLogRequestBuilder.fetchNext().then( + (callLogHistory) => { console.log(callLogHistory); - }) - .catch(err => { - console.log(err); - }); + }, + (err) => { + console.log(err); + } +); ``` - - -**On Success** — `fetchNext()` returns an array of `CallLog` objects: - - - -**CallLog Array:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| (array) | array | Array of call log objects | [See below ↓](#call-log-object) | - - - -**CallLog Object (each item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sessionId` | string | Unique session identifier | `"v1.in.2748663902141719.1772100619..."` | -| `totalAudioMinutes` | number | Total audio duration in minutes | `7.65` | -| `totalVideoMinutes` | number | Total video duration in minutes | `0` | -| `totalDuration` | string | Formatted total duration | `"00:07:39"` | -| `totalDurationInMinutes` | number | Total duration in minutes | `7.65` | -| `hasRecording` | boolean | Whether call has recordings | `true` | -| `initiatedAt` | number | Unix timestamp when call was initiated | `1772100619` | -| `startedAt` | number | Unix timestamp when call started | `1772100622` | -| `endedAt` | number | Unix timestamp when call ended | `1772101081` | -| `initiator` | object | User who initiated the call | [See below ↓](#call-log-initiator-object) | -| `receiver` | object | User who received the call | [See below ↓](#call-log-receiver-object) | -| `mode` | string | Call mode | `"call"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `status` | string | Call status | `"ended"` | -| `totalParticipants` | number | Total number of participants | `2` | -| `type` | string | Type of call | `"audio"` | -| `mid` | string | Message ID | `"21d6e797-1b44-4a70-be73-d915dba206c7"` | -| `participants` | array | List of call participants | [See below ↓](#call-log-participants-array) | -| `recordings` | array | List of recordings | [See below ↓](#call-log-recordings-array) | -| `data` | object | Additional call data | [See below ↓](#call-log-data-object) | - ---- - - - -**`initiator` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user identifier | `"cometchat-uid-7"` | -| `name` | string | Display name of the user | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user identifier | `"cometchat-uid-6"` | -| `name` | string | Display name of the user | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | - ---- - - - -**`participants` Array:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| (array) | array | Array of participant objects | [See below ↓](#call-log-participant-object) | - - - -**Participant Object (each item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user identifier | `"cometchat-uid-6"` | -| `name` | string | Display name of the user | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `totalAudioMinutes` | number | User's audio duration in minutes | `7.65` | -| `totalVideoMinutes` | number | User's video duration in minutes | `0` | -| `totalDurationInMinutes` | number | User's total duration in minutes | `7.65` | -| `isJoined` | boolean | Whether user joined the call | `true` | -| `state` | string | Participant state | `"ended"` | -| `deviceId` | string | Device identifier | `"2b1d0b90-b6b9-4c1c-9899-9bf4effe549f@..."` | -| `joinedAt` | number | Unix timestamp when user joined | `1772100622` | -| `leftAt` | number | Unix timestamp when user left | `1772101081` | -| `mid` | string | Message ID | `"21d6e797-1b44-4a70-be73-d915dba206c7"` | - ---- - - - -**`recordings` Array:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| (array) | array | Array of recording objects | [See below ↓](#call-log-recording-object) | - - - -**Recording Object (each item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `rid` | string | Recording ID | `"noujausedimwfhwl"` | -| `recording_url` | string | URL to download the recording | `"https://recordings-in.cometchat.io/..."` | -| `duration` | number | Recording duration in minutes | `1.045` | -| `startTime` | number | Unix timestamp when recording started | `1772100632` | -| `endTime` | number | Unix timestamp when recording ended | `1772100634` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entities` | object | Entity details for the call | [See below ↓](#call-log-data-entities-object) | - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `initiator` | object | Initiator entity wrapper | [See below ↓](#call-log-data-entities-initiator) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#call-log-data-entities-receiver) | - - - -**`data.entities.initiator` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entity` | object | User entity details | `{"uid": "cometchat-uid-7", "name": "Henry Marino", "avatar": "..."}` | - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entity` | object | User entity details | `{"uid": "cometchat-uid-6", "name": "Ronald Jerry", "avatar": "..."}` | - - + + ### Fetch Previous -The `fetchPrevious()` method retrieves the previous set of call logs. +Retrieves the previous set of call logs: + + +```typescript +let callLogRequestBuilder: any = new CometChatCalls.CallLogRequestBuilder() + .setLimit(30) + .setAuthToken(loggedInUser.getAuthToken()) + .setCallCategory("call") + .build(); + +callLogRequestBuilder.fetchPrevious().then( + (callLogHistory: any[]) => { + console.log(callLogHistory); + }, + (err: any) => { + console.log(err); + } +); +``` + + ```javascript let callLogRequestBuilder = new CometChatCalls.CallLogRequestBuilder() - .setLimit(30) - .setAuthToken(loggedInUser.getAuthToken()) - .setCallCategory("call") - .build() + .setLimit(30) + .setAuthToken(loggedInUser.getAuthToken()) + .setCallCategory("call") + .build(); -callLogRequestBuilder.fetchPrevious() - .then(callLogHistory => { +callLogRequestBuilder.fetchPrevious().then( + (callLogHistory) => { console.log(callLogHistory); - }) - .catch(err => { - console.log(err); - }); + }, + (err) => { + console.log(err); + } +); ``` + + - -**On Success** — `fetchPrevious()` returns an array of `CallLog` objects with the same structure as `fetchNext()`. See [fetchNext Response](#call-log-array) for the complete object structure. - +The `fetchNext()` and `fetchPrevious()` methods return an array of [`CallLog`](/sdk/reference/calls#calllog) objects. ## 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()`: + + + +```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 -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); + } +); ``` - -**On Success** — `getCallDetails()` returns an array of `CallLog` objects with the same structure as `fetchNext()`. See [fetchNext Response](#call-log-array) for the complete object structure. - +Alternatively, you can use the `async/await` syntax: + +```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); +} +``` + - -Replace `"SESSION_ID"` with the ID of the session you are interested in. - - -## Best Practices - - - - Always use `fetchNext()` with a reasonable `setLimit()` value (e.g., 20-30) rather than fetching all logs at once. This improves performance and reduces memory usage, especially for users with extensive call histories. - - - Use the builder's filter methods (`setCallType`, `setCallStatus`, `setCallDirection`) to fetch only the logs relevant to your current UI view. For example, show only missed calls in a "Missed" tab rather than filtering client-side. - - - Consider caching fetched call logs locally to reduce API calls and improve load times. Use `fetchNext()` to load newer logs and `fetchPrevious()` for older ones as the user scrolls. - - - -## Troubleshooting - - - - Verify that the `authToken` passed to `setAuthToken()` is valid and belongs to the logged-in user. Also check that calls have actually been made — call logs are only generated after a call session completes. - - - Ensure you're reusing the same `callLogRequestBuilder` instance for pagination. Creating a new builder resets the cursor, causing the same page to be fetched repeatedly. - - - Confirm the `sessionID` is correct and corresponds to a completed call. Active or in-progress calls may not have full details available yet. - - + + +Note: Replace `"SESSION_ID"` with the ID of the session you are interested in. --- @@ -308,15 +212,15 @@ Replace `"SESSION_ID"` with the ID of the session you are interested in. - Implement a complete calling experience with incoming and outgoing call UI - - - Start and manage call sessions with full configuration options + Implement the complete ringing call flow - Record call sessions for playback and compliance + Record audio and video calls + + + Start call sessions without the ringing flow - - Implement calling without the Chat SDK + + Install and initialize the Calls SDK - \ No newline at end of file + diff --git a/sdk/react-native/calling-overview.mdx b/sdk/react-native/calling-overview.mdx index 12683a7c5..1dd5d537b 100644 --- a/sdk/react-native/calling-overview.mdx +++ b/sdk/react-native/calling-overview.mdx @@ -1,35 +1,29 @@ --- title: "Calling" sidebarTitle: "Overview" -description: "Add voice and video calling to your React Native app with CometChat. Choose between Ringing, Call Session, or Standalone implementations." +description: "Overview of CometChat voice and video calling capabilities including ringing, direct call sessions, and standalone calling." --- - -**Quick Reference** - Install the Calls SDK and initialize: + -```javascript -npm install @cometchat/calls-sdk-react-native +Choose your calling approach: +- **Ringing** → [Default Call](/sdk/react-native/default-call) — Full call flow with notifications, accept/reject +- **Call Session** → [Direct Call](/sdk/react-native/direct-call) — Session-based calling with custom UI +- **Standalone** → [Standalone Calling](/sdk/react-native/standalone-calling) — Calls SDK only, no Chat SDK needed -// Initialize CometChatCalls -const callAppSettings = new CometChatCalls.CallAppSettingsBuilder() - .setAppId("APP_ID") - .setRegion("REGION") - .build(); -await CometChatCalls.init(callAppSettings); +```bash +# Install Calls SDK +npm install @cometchat/calls-sdk-react-native ``` - - -Available via: [SDK](/sdk/react-native/calling-overview) | [REST API](/rest-api/calls) | [UI Kits](/ui-kit/react-native/call-features) - +**Features:** Recording, Video View Customization, Presenter Mode, Call Logs, Session Timeout + -## Overview - -CometChat provides voice and video calling capabilities for your React Native 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 React Native 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/react-native/setup-sdk) guide. +1. CometChat Chat SDK installed and configured. See the [Setup](/sdk/react-native/setup-sdk) guide. 2. CometChat Calls SDK added to your project: ```bash @@ -38,58 +32,53 @@ npm install @cometchat/calls-sdk-react-native For detailed setup instructions, see the [Calls SDK Setup](/sdk/react-native/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/react-native/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/react-native/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/react-native/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. @@ -108,36 +97,21 @@ Use this when you want: - - - - Initialize `CometChatCalls` on app startup, right after `CometChat.init()` - - Use the Ringing flow for user-to-user calls where you need push notification support - - Use Call Session when building custom call UIs or conference-style experiences - - Always request camera and microphone permissions before initiating a call - - Handle call errors gracefully and provide user-friendly feedback - - - - **Calls not connecting:** Verify the Calls SDK is initialized after the Chat SDK and that both use the same App ID and Region - - **No audio/video:** Check that camera and microphone permissions are granted on both Android and iOS - - **Push notifications not arriving:** Ensure push notification setup is complete — see the [Push Notifications](/sdk/react-native/push-notification) guide - - **iOS build fails:** Run `pod install` in the `ios` directory after adding the Calls SDK dependency - - **Android minSdkVersion error:** Set `minSdkVersion` to 24 or higher in your `build.gradle` - - +--- ## Next Steps - Install dependencies, configure permissions, and initialize the Calls SDK. + Install and initialize the CometChat Calls SDK - - Implement the complete incoming/outgoing call experience. + + Implement the complete ringing call flow - Manage call sessions with custom initiation logic. + Start and manage call sessions directly - - Retrieve and display call history for your users. + + Use calling without the Chat SDK diff --git a/sdk/react-native/calling-setup.mdx b/sdk/react-native/calling-setup.mdx index bd2de66f1..40c7506c2 100644 --- a/sdk/react-native/calling-setup.mdx +++ b/sdk/react-native/calling-setup.mdx @@ -1,86 +1,86 @@ --- -title: "Setup" -description: "Install and configure the CometChat Calls SDK for React Native, including dependencies, platform permissions, and initialization." +title: "Calls SDK Setup" +sidebarTitle: "Setup" +description: "Install and initialize the CometChat Calls SDK for React Native to enable voice and video calling in your application." --- - -**Quick Reference** - Install and initialize the Calls SDK: + -```javascript +```bash npm install @cometchat/calls-sdk-react-native +``` -// Initialize on app startup +```javascript import { CometChatCalls } from "@cometchat/calls-sdk-react-native"; -const callAppSettings = new CometChatCalls.CallAppSettingsBuilder() + +const callAppSetting = new CometChatCalls.CallAppSettingsBuilder() .setAppId("APP_ID") .setRegion("REGION") .build(); -await CometChatCalls.init(callAppSettings); + +CometChatCalls.init(callAppSetting).then(() => console.log("Calls SDK ready")); ``` - -## Get your Application Keys +**Required:** App ID, Region from [CometChat Dashboard](https://app.cometchat.com) + -[Signup for CometChat](https://app.cometchat.com) and then: +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. -1. Create a new app -2. Head over to the **API & Auth Keys** section and note the **Auth Key**, **App ID** & **Region** +## Prerequisites -## Add the CometChatCalls Dependency +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. -Install the package as NPM module: +If you're using the Chat SDK alongside (i.e., not [Standalone Calling](/sdk/react-native/standalone-calling)), make sure `CometChat.init()` completes before calling `CometChatCalls.init()`. + +## Installation ```bash npm install @cometchat/calls-sdk-react-native ``` - ```bash yarn add @cometchat/calls-sdk-react-native ``` - - -The CometChat Calls SDK also requires the below dependencies to be installed. +The CometChat Calls SDK also requires the following peer dependencies: - - ```json { "@cometchat/chat-sdk-react-native": "^4.0.18", "@react-native-async-storage/async-storage": "^1.23.1", - "@react-native-community/netinfo": "^11.3.1", // for react-native 0.63 & above. - "@react-native-community/netinfo": "6.1.0", // for react-native below 0.63 + "@react-native-community/netinfo": "^11.3.1", "react-native-background-timer": "^2.4.1", "react-native-callstats": "^3.73.7", "react-native-webrtc": "^1.106.1" } ``` - + +For React Native below 0.63, use `@react-native-community/netinfo` version `6.1.0` instead. + - +Then import wherever needed: + +```javascript +import { CometChatCalls } from "@cometchat/calls-sdk-react-native"; +``` ## Permissions - -If you're using Expo, please refer to the [Expo Integration Guide](/sdk/react-native/expo-integration-guide) for setting up permissions. - +If you're using Expo, refer to the [Expo Integration Guide](/sdk/react-native/expo-integration-guide) for setting up permissions. ### Android -You need to add the below in your App's `AndroidManifest.xml` file. +Add the following to your `AndroidManifest.xml`: - - ```xml @@ -89,14 +89,8 @@ You need to add the below in your App's `AndroidManifest.xml` file. ``` - +Set `minSdkVersion` to 24 or higher in your `build.gradle`: - - -Also in the same file in `buildscript` section in `ext` block make sure you have set **minSdkVersion** to **24.** - - - ```gradle buildscript { ext { @@ -108,16 +102,10 @@ buildscript { } ``` - - - - ### iOS -You need to add the below in your App's `Info.plist` file. +Add the following to your `Info.plist`: - - ```xml NSCameraUsageDescription This is for Camera permission @@ -125,63 +113,45 @@ You need to add the below in your App's `Info.plist` file. This is for Mic permission ``` - - - - -Also, update the minimum target version in the Podfile. Goto `./ios` folder and open the `Podfile`. In the Podfile update the platform version to `12.0.` +Update the minimum platform version in your `Podfile` (located in `./ios`): - - ``` platform :ios, '12.0' ``` - - - - -Open the `ios/App` folder and run `pod install` this will create an `App.xcworkspace` open this and run the app. - -## Initialize CometChatCalls +Then run `pod install` in the `ios` directory and open the generated `.xcworkspace` file. -The init() method initialises the settings required for CometChatCalls. The init() method takes a single paramater, that is the instance of CallAppSettingsBuilder class. +## Initialization -The `CallAppSettings` class allows you to configure three settings: - -* **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. - -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 `App.tsx` file. +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`. - -```javascript + +```typescript import { CometChatCalls } from "@cometchat/calls-sdk-react-native"; -let appID = "APP_ID"; -let region = "REGION"; +let appID: string = "APP_ID"; +let region: string = "REGION"; -const callAppSettings = new CometChatCalls.CallAppSettingsBuilder() - .setAppId(appID) - .setRegion(region) - .build(); +const callAppSetting: CometChatCalls.CallAppSettings = + new CometChatCalls.CallAppSettingsBuilder() + .setAppId(appID) + .setRegion(region) + .build(); -CometChatCalls.init(callAppSettings).then( +CometChatCalls.init(callAppSetting).then( () => { console.log("CometChatCalls initialization completed successfully"); }, - (error) => { + (error: unknown) => { console.log("CometChatCalls initialization failed with error:", error); } ); ``` - - -```typescript + +```javascript import { CometChatCalls } from "@cometchat/calls-sdk-react-native"; let appID = "APP_ID"; @@ -201,49 +171,79 @@ CometChatCalls.init(callAppSetting).then( } ); ``` - - +Replace `APP_ID` and `REGION` with your credentials from the [Dashboard](https://app.cometchat.com). + -Make sure you replace the `APP_ID` with your CometChat `AppID` and `REGION` with your **App Region** in the above code. +`CometChatCalls.init()` must be called before any other Calls SDK method. Calling `generateToken()`, `startSession()`, or registering listeners before `init()` will fail. -| Parameter | Description | -| ----------------- | ---------------------------------------- | -| `callAppSettings` | An object of the `CallAppSettings` class | - - - - - Initialize `CometChatCalls` right after `CometChat.init()` on app startup - - Always call `CometChatCalls.init()` before using any calling methods - - Request camera and microphone permissions at runtime before initiating calls - - Use the correct `netinfo` version based on your React Native version (0.63+ vs below) - - Run `pod install` after adding dependencies to ensure iOS native modules are linked - - - - **Initialization fails:** Verify your App ID and Region match the values in your CometChat Dashboard - - **Android build fails:** Ensure `minSdkVersion` is set to 24 or higher in `build.gradle` - - **iOS build fails:** Run `pod install` in the `ios` directory and open the `.xcworkspace` file (not `.xcodeproj`) - - **Permission denied errors:** Confirm camera and microphone permissions are declared in `AndroidManifest.xml` and `Info.plist` - - **Module not found:** Make sure all required peer dependencies are installed — check the dependency list above - - +### 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: + + + +```typescript +// 1. Chat SDK first +await CometChat.init(appID, appSettings); + +// 2. Then Calls SDK +const callAppSetting: CometChatCalls.CallAppSettings = new CometChatCalls.CallAppSettingsBuilder() + .setAppId(appID) + .setRegion(region) + .build(); + +await CometChatCalls.init(callAppSetting); + +// 3. Now both SDKs are ready +``` + + +```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 +``` + + + +For [Standalone Calling](/sdk/react-native/standalone-calling), you only need `CometChatCalls.init()` — no Chat SDK required. + +--- ## Next Steps - - Choose the right calling implementation for your use case. - - - Implement the complete incoming/outgoing call experience. + + Implement the complete ringing call flow - Manage call sessions with custom initiation logic. + Start and manage call sessions + + + Use Calls SDK without the Chat SDK - - Record audio and video calls for playback or compliance. + + Compare calling approaches and features diff --git a/sdk/react-native/connection-status.mdx b/sdk/react-native/connection-status.mdx index d6dc91ab0..0135d7ec5 100644 --- a/sdk/react-native/connection-status.mdx +++ b/sdk/react-native/connection-status.mdx @@ -1,42 +1,68 @@ --- title: "Connection Status" -description: "Learn how to monitor the real-time WebSocket connection status using the CometChat React Native SDK, including connecting, connected, and disconnected states." +description: "Monitor real-time WebSocket connection status and respond to connectivity changes using the CometChat React Native SDK." --- - -**Quick Reference** + + ```javascript -// Listen for connection status changes -CometChat.addConnectionListener("listenerId", new CometChat.ConnectionListener({ - onConnected: () => {}, - inConnecting: () => {}, - onDisconnected: () => {} +// Get current status: "connecting" | "connected" | "disconnected" +const 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") })); -// Get current connection status -var status = CometChat.getConnectionStatus(); -// Returns: "connecting" | "connected" | "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. +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"` | `onFeatureThrottled()` | 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 -var listenerID = "UNIQUE_LISTENER_ID"; +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 (e.g., in `App.tsx`) after `CometChat.init()` completes. + + + +```typescript +let listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addConnectionListener( listenerID, new CometChat.ConnectionListener({ @@ -61,9 +87,9 @@ CometChat.addConnectionListener( - -```typescript -let listenerID: string = "UNIQUE_LISTENER_ID"; + +```javascript +let listenerID = "UNIQUE_LISTENER_ID"; CometChat.addConnectionListener( listenerID, new CometChat.ConnectionListener({ @@ -76,6 +102,12 @@ CometChat.addConnectionListener( onDisconnected: () => { console.log("ConnectionListener => On Disconnected"); }, + onFeatureThrottled: () => { + console.log("ConnectionListener => On Feature Throttled"); + }, + onConnectionError: () => { + console.log("ConnectionListener => On Connection Error"); + }, }) ); ``` @@ -85,64 +117,24 @@ CometChat.addConnectionListener( -Always remove connection listeners when the component unmounts to prevent memory leaks. -```javascript -CometChat.removeConnectionListener("UNIQUE_LISTENER_ID"); -``` +Always remove connection listeners when they're no longer needed (e.g., on component unmount). Failing to remove listeners can cause memory leaks and duplicate event handling. - -We recommend you to add the Connection Listener in your method on app startup, preferably in the App.tsx file. Once you have successfully initialized CometChat. - - -You can also get the current connection status by using `getConnectionStatus` property provided by CometChat SDK - - - -```javascript -var connectionStatus = CometChat.getConnectionStatus(); -``` - - - - -```typescript -var connectionStatus: string = CometChat.getConnectionStatus(); -``` - - - - - -The `CometChat.getConnectionStatus` method will return either of the below 3 values: - -1. `connecting` -2. `connected` -3. `disconnected` - - - -- Register the connection listener early in your app lifecycle (after `CometChat.init()`) to catch connection state changes from the start -- Use connection status to show a connectivity indicator in your UI (e.g., a banner when disconnected) -- When the status changes to `connected` after a `disconnected` state, consider refreshing your message list to fetch any messages missed during the disconnection -- Avoid making SDK calls (sending messages, fetching data) while the status is `disconnected` — queue them and retry once `connected` - - - -- **Listener not firing**: Ensure you registered the `ConnectionListener` with a unique listener ID after calling `CometChat.init()`. -- **Stuck in connecting state**: Check your network connection and verify that the App ID and region are correct in your `AppSettings`. -- **Frequent disconnections**: This is typically caused by network instability. The SDK handles reconnection automatically in auto mode. -- **`onFeatureThrottled` firing**: This indicates your app is hitting rate limits. Reduce the frequency of API calls. - - +--- ## Next Steps - -Take full control of WebSocket connections - - -Register listeners for users, groups, messages, and calls - + + Manually manage WebSocket connections + + + Complete reference for all SDK listeners + + + Install and initialize the CometChat SDK + + + Review the fundamental building blocks of CometChat + diff --git a/sdk/react-native/create-group.mdx b/sdk/react-native/create-group.mdx index 8b12fea86..5b7c622d6 100644 --- a/sdk/react-native/create-group.mdx +++ b/sdk/react-native/create-group.mdx @@ -1,54 +1,65 @@ --- title: "Create A Group" -description: "Create public, private, or password-protected groups in CometChat React Native SDK, with optional member and ban lists at creation time." +sidebarTitle: "Create Group" +description: "Create public, private, or password-protected groups and optionally add members during creation using the CometChat React Native SDK." --- - -**Quick Reference** - Create a group: + ```javascript -// Create a public group -const group = new CometChat.Group("GUID", "Hello Group!", CometChat.GROUP_TYPE.PUBLIC, ""); -await CometChat.createGroup(group); +// Create a group +let group = new CometChat.Group("GUID", "Group Name", CometChat.GROUP_TYPE.PUBLIC, ""); +let createdGroup = await CometChat.createGroup(group); -// Create with members -const members = [new CometChat.GroupMember("UID", CometChat.GROUP_MEMBER_SCOPE.PARTICIPANT)]; -await CometChat.createGroupWithMembers(group, members, []); +// Create group with members +let members = [new CometChat.GroupMember("UID", CometChat.GROUP_MEMBER_SCOPE.PARTICIPANT)]; +let result = await CometChat.createGroupWithMembers(group, members, []); ``` - - -**Available via:** [SDK](/sdk/react-native/create-group) | [REST API](/rest-api/groups/create) | [UI Kits](/ui-kit/react-native/groups) - - -## Create a Group - -*In other words, as a logged-in user, how do I create a public, private or password-protected group?* +**Group types:** `PUBLIC` | `PASSWORD` | `PRIVATE` +**Member scopes:** `ADMIN` | `MODERATOR` | `PARTICIPANT` + -You can create a group using `createGroup()` method. This method takes a `Group` object as input. +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. -To create an object of `Group` class, you can use either of the below two constructors: +## Create a Group -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)` +Use `createGroup()` to create a new group. Pass a [`Group`](/sdk/reference/entities#group) object with the group details. -The `groupType` needs to be either of the below 3 values: +| 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 | -1.`CometChat.GROUP_TYPE.PUBLIC` + + +```typescript +const GUID: string = "GUID"; +const groupName: string = "Hello Group!"; +const groupType: string = CometChat.GROUP_TYPE.PUBLIC; +const password: string = ""; -2.`CometChat.GROUP_TYPE.PASSWORD` +const group: CometChat.Group = new CometChat.Group(GUID, groupName, groupType, password); -3.`CometChat.GROUP_TYPE.PRIVATE` +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 -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 => { @@ -59,87 +70,74 @@ CometChat.createGroup(group).then( ); ``` - - - -```typescript -var GUID: string = "GUID"; -var groupName: string = "Hello Group!"; -var groupType: string = CometChat.GROUP_TYPE.PUBLIC; -var password: string = ""; - -var group: CometChat.Group = new CometChat.Group(GUID, groupName, groupType, password); +Alternatively, you can use the `async/await` syntax: -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"; +const groupName = "Hello Group!"; +const groupType = CometChat.GROUP_TYPE.PUBLIC; +const password = ""; + +const 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); +} ``` - - -**On Success** — `createGroup()` returns the created Group object: - - - -**Group Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `guid` | string | Unique group identifier | `"group_1772435275327"` | -| `name` | string | Group name | `"Creation"` | -| `type` | string | Group type | `"public"` | -| `owner` | string | UID of the group owner | `"cometchat-uid-7"` | -| `scope` | string | Logged-in user's scope in the group | `"admin"` | -| `membersCount` | number | Number of members in the group | `1` | -| `hasJoined` | boolean | Whether logged-in user has joined | `true` | -| `isBanned` | boolean | Whether logged-in user is banned | `false` | -| `joinedAt` | number | Unix timestamp when user joined | `1772435275` | -| `createdAt` | number | Unix timestamp when group was created | `1772435275` | -| `conversationId` | string | Conversation identifier for the group | `"group_group_1772435275327"` | +| Parameter | Description | +| --------- | ----------- | +| `group` | An instance of [`Group`](/sdk/reference/entities#group) class | - - -The createGroup() method takes the following parameters: - -| 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. -GUID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. CometChat automatically converts any uppercase characters in the GUID to lowercase. +GUID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. -## Add members while creating a group +## 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. +Use `createGroupWithMembers()` to create a group and add members in one operation. -To create an object of `Group` class, you can use either of the below two constructors: +Parameters: +- `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) -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)` +Create a [`GroupMember`](/sdk/reference/entities#groupmember) with: `new CometChat.GroupMember(UID, scope)` -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` + + +```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; -To create an object of `Group Member` class, you can use the below constructor: +let group: CometChat.Group = new CometChat.Group(GUID, groupName, groupType); +let members: Array = [ +new CometChat.GroupMember(UID, CometChat.GROUP_MEMBER_SCOPE.PARTICIPANT) +]; +let banMembers: Array = ["cometchat-uid-2"]; -* new CometChat.GroupMember(String UID, String scope) +CometChat.createGroupWithMembers(group, members, banMembers).then( + (response: Object) => { + console.log("Group created successfully", response); + }, (error: CometChat.CometChatException) => { + console.log("Some error occured while creating group", error) + } +); +``` + - ```javascript let GUID = "cometchat-guid-11"; @@ -162,86 +160,39 @@ CometChat.createGroupWithMembers(group, members, banMembers).then( ); ``` - +Alternatively, you can use the `async/await` syntax: - -```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; +```javascript +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 = [ -new CometChat.GroupMember(UID, CometChat.GROUP_MEMBER_SCOPE.PARTICIPANT) +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) => { - console.log("Group created successfully", response); - }, (error: CometChat.CometChatException) => { - console.log("Some error occured while creating group", error) - } -); +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); +} ``` - - -**On Success** — `createGroupWithMembers()` returns an object with `group` and `members` keys: - - - -**Response Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `group` | object | The created Group object | [See below ↓](#create-group-with-members-group-object) | -| `members` | object | Per-UID results for member additions | [See below ↓](#create-group-with-members-members-object) | - ---- - - - -**`group` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `guid` | string | Unique group identifier | `"group_with_members_1772435203225"` | -| `name` | string | Group name | `"Test Group With Members"` | -| `type` | string | Group type | `"public"` | -| `owner` | string | UID of the group owner | `"cometchat-uid-7"` | -| `scope` | string | Logged-in user's scope in the group | `"admin"` | -| `membersCount` | number | Number of members in the group | `4` | -| `hasJoined` | boolean | Whether logged-in user has joined | `true` | -| `isBanned` | boolean | Whether logged-in user is banned | `false` | -| `joinedAt` | number | Unix timestamp when user joined | `1772435203` | -| `createdAt` | number | Unix timestamp when group was created | `1772435203` | -| `conversationId` | string | Conversation identifier for the group | `"group_group_with_members_1772435203225"` | - ---- - - - -**`members` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `cometchat-uid-1` | string | Result for this UID | `"success"` | -| `cometchat-uid-2` | string | Result for this UID | `"success"` | -| `cometchat-uid-3` | string | Result for this UID | `"success"` | - -Each key is a UID, and the value is either `"success"` or an error message describing why the operation failed. - - - -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 +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 | @@ -260,49 +211,22 @@ This method returns an Object which has two keys: `group` & `members` . The grou | membersCount | No | The number of members in the groups | | tags | Yes | A list of tags to identify specific groups. | -## Best Practices - - - - If you know the initial members at creation time, use `createGroupWithMembers()` instead of creating the group first and then adding members separately. This reduces API calls and ensures atomic group setup. - - - Use the same group identifier from your backend as the CometChat GUID. This simplifies mapping between your system and CometChat. - - - The `createGroupWithMembers()` response includes per-UID results ("success" or error). Check each result rather than assuming all members were added successfully. - - - -## Troubleshooting - - - - Each GUID must be unique across your CometChat app. If the group already exists, use a different GUID or retrieve the existing group with `getGroup()`. - - - GUIDs can only contain alphanumeric characters, underscores, and hyphens. Spaces, punctuation, and other special characters are not allowed. Uppercase characters are automatically converted to lowercase. - - - Check the `members` key in the response object for per-UID error messages. Common causes include invalid UIDs or users that don't exist in your CometChat app. - - --- ## Next Steps - - Fetch group lists, search groups, and get group details - - Join public or password-protected groups + Join public, private, or password-protected groups + + + Add users to an existing group - - Manage members, roles, and permissions within groups + + Fetch and filter group lists - - Send text, media, and custom messages to groups + + Overview of all group management features - \ No newline at end of file + diff --git a/sdk/react-native/default-call.mdx b/sdk/react-native/default-call.mdx index 6ff56e10f..686e25e4a 100644 --- a/sdk/react-native/default-call.mdx +++ b/sdk/react-native/default-call.mdx @@ -1,30 +1,35 @@ --- title: "Ringing" -description: "Implement a complete calling workflow with ringing, incoming/outgoing call UI, accept, reject, and cancel functionality in CometChat React Native SDK." +sidebarTitle: "Ringing" +description: "Implement a complete calling workflow with ringing, incoming/outgoing call UI, accept/reject/cancel functionality, and call session management." --- - -**Quick Reference** - Initiate a call and listen for events: +{/* TL;DR for Agents and Quick Reference */} + ```javascript -// Initiate a video call (default 45s no-answer timeout) -const call = new CometChat.Call("RECEIVER_ID", CometChat.CALL_TYPE.VIDEO, CometChat.RECEIVER_TYPE.USER); +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); -// Initiate with custom timeout (60 seconds) -await CometChat.initiateCall(call, 60); +// 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 an incoming call +// Accept / Reject / Cancel await CometChat.acceptCall(sessionId); - -// Reject or cancel await CometChat.rejectCall(sessionId, CometChat.CALL_STATUS.REJECTED); +await CometChat.rejectCall(sessionId, CometChat.CALL_STATUS.CANCELLED); ``` - - -Available via: [SDK](/sdk/react-native/default-call) | [REST API](/rest-api/calls) | [UI Kits](/ui-kit/react-native/call-features) - +**Flow:** Initiate → Receiver notified → Accept/Reject → Start session + ## Overview @@ -49,31 +54,29 @@ After the call is accepted, you need to start the call session. See the [Call Se The `initiateCall()` method sends a call request to a user or a group. On success, the receiver gets an `onIncomingCallReceived()` callback. - -```javascript -const receiverID = "UID"; -const callType = CometChat.CALL_TYPE.VIDEO; -const receiverType = CometChat.RECEIVER_TYPE.USER; + +```typescript +const receiverID: string = "UID"; +const callType: string = CometChat.CALL_TYPE.VIDEO; +const receiverType: string = CometChat.RECEIVER_TYPE.USER; -const call = new CometChat.Call(receiverID, callType, receiverType); +const call: CometChat.Call = new CometChat.Call(receiverID, callType, receiverType); CometChat.initiateCall(call).then( - (outgoingCall) => { + (outgoingCall: CometChat.Call) => { console.log("Call initiated:", outgoingCall); - // Show outgoing call UI - // Store outgoingCall.getSessionId() for later use }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Call initiation failed:", error); } ); ``` - + ```javascript -const receiverID = "GUID"; +const receiverID = "UID"; const callType = CometChat.CALL_TYPE.VIDEO; -const receiverType = CometChat.RECEIVER_TYPE.GROUP; +const receiverType = CometChat.RECEIVER_TYPE.USER; const call = new CometChat.Call(receiverID, callType, receiverType); @@ -81,6 +84,7 @@ CometChat.initiateCall(call).then( (outgoingCall) => { console.log("Call initiated:", outgoingCall); // Show outgoing call UI + // Store outgoingCall.getSessionId() for later use }, (error) => { console.log("Call initiation failed:", error); @@ -88,11 +92,11 @@ CometChat.initiateCall(call).then( ); ``` - + ```typescript -const receiverID: string = "UID"; +const receiverID: string = "GUID"; const callType: string = CometChat.CALL_TYPE.VIDEO; -const receiverType: string = CometChat.RECEIVER_TYPE.USER; +const receiverType: string = CometChat.RECEIVER_TYPE.GROUP; const call: CometChat.Call = new CometChat.Call(receiverID, callType, receiverType); @@ -106,19 +110,20 @@ CometChat.initiateCall(call).then( ); ``` - -```typescript -const receiverID: string = "GUID"; -const callType: string = CometChat.CALL_TYPE.VIDEO; -const receiverType: string = CometChat.RECEIVER_TYPE.GROUP; + +```javascript +const receiverID = "GUID"; +const callType = CometChat.CALL_TYPE.VIDEO; +const receiverType = CometChat.RECEIVER_TYPE.GROUP; -const call: CometChat.Call = new CometChat.Call(receiverID, callType, receiverType); +const call = new CometChat.Call(receiverID, callType, receiverType); CometChat.initiateCall(call).then( - (outgoingCall: CometChat.Call) => { + (outgoingCall) => { console.log("Call initiated:", outgoingCall); + // Show outgoing call UI }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Call initiation failed:", error); } ); @@ -132,35 +137,35 @@ 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. By default, an unanswered call automatically cancels after 45 seconds. You can customize this duration by passing an optional `timeout` parameter (in seconds) as the second argument to `initiateCall()`. - -```javascript -const receiverID = "UID"; -const callType = CometChat.CALL_TYPE.VIDEO; -const receiverType = CometChat.RECEIVER_TYPE.USER; + +```typescript +const receiverID: string = "UID"; +const callType: string = CometChat.CALL_TYPE.VIDEO; +const receiverType: string = CometChat.RECEIVER_TYPE.USER; -const call = new CometChat.Call(receiverID, callType, receiverType); +const call: CometChat.Call = new CometChat.Call(receiverID, callType, receiverType); // Set a custom timeout of 60 seconds CometChat.initiateCall(call, 60).then( - (outgoingCall) => { + (outgoingCall: CometChat.Call) => { console.log("Call initiated with 60s timeout:", outgoingCall); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Call initiation failed:", error); } ); ``` - + ```javascript -const receiverID = "GUID"; +const receiverID = "UID"; const callType = CometChat.CALL_TYPE.VIDEO; -const receiverType = CometChat.RECEIVER_TYPE.GROUP; +const receiverType = CometChat.RECEIVER_TYPE.USER; const call = new CometChat.Call(receiverID, callType, receiverType); @@ -175,11 +180,11 @@ CometChat.initiateCall(call, 60).then( ); ``` - + ```typescript -const receiverID: string = "UID"; +const receiverID: string = "GUID"; const callType: string = CometChat.CALL_TYPE.VIDEO; -const receiverType: string = CometChat.RECEIVER_TYPE.USER; +const receiverType: string = CometChat.RECEIVER_TYPE.GROUP; const call: CometChat.Call = new CometChat.Call(receiverID, callType, receiverType); @@ -194,20 +199,20 @@ CometChat.initiateCall(call, 60).then( ); ``` - -```typescript -const receiverID: string = "GUID"; -const callType: string = CometChat.CALL_TYPE.VIDEO; -const receiverType: string = CometChat.RECEIVER_TYPE.GROUP; + +```javascript +const receiverID = "GUID"; +const callType = CometChat.CALL_TYPE.VIDEO; +const receiverType = CometChat.RECEIVER_TYPE.GROUP; -const call: CometChat.Call = new CometChat.Call(receiverID, callType, receiverType); +const call = new CometChat.Call(receiverID, callType, receiverType); // Set a custom timeout of 60 seconds CometChat.initiateCall(call, 60).then( - (outgoingCall: CometChat.Call) => { + (outgoingCall) => { console.log("Call initiated with 60s timeout:", outgoingCall); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Call initiation failed:", error); } ); @@ -220,73 +225,33 @@ CometChat.initiateCall(call, 60).then( | `call` | `Call` | The call object created with receiver ID, call type, and receiver type. | | `timeout` | `number` | Optional. The ringing duration in seconds before an unanswered call is automatically cancelled. Default: `45`. | - -**On Success** — `initiateCall()` returns a `Call` object with session details: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `receiverId` | string | UID of the call recipient | `"cometchat-uid-7"` | -| `type` | string | Type of call | `"audio"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `category` | string | Message category | `"call"` | -| `action` | string | Current call action | `"initiated"` | -| `sessionId` | string | Unique session identifier for the call | `"v1.in.2748663902141719.1772009087929026e8ed35bb3c1f9b4aea3d6fe52b63eaa060"` | -| `status` | string | Current call status | `"initiated"` | -| `initiatedAt` | number | Unix timestamp when call was initiated | `1772009087` | -| `joinedAt` | number | Unix timestamp when user joined | `1772009087` | -| `id` | string | Unique message ID | `"25329"` | -| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `sender` | object | User who initiated the call | See User Object below | -| `receiver` | object | User receiving the call | See User Object below | -| `callInitiator` | object | User who started the call | See User Object below | -| `callReceiver` | object | Intended call recipient | See User Object below | -| `sentAt` | number | Unix timestamp when call was sent | `1772009087` | -| `updatedAt` | number | Unix timestamp of last update | `1772009087` | - -**User Object Structure:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user identifier | `"cometchat-uid-6"` | -| `name` | string | Display name of the user | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | - - - ## 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. - -```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 } }) ); @@ -295,31 +260,31 @@ 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 } @@ -346,142 +311,38 @@ Always remove call listeners when the component unmounts using `CometChat.remove | `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. | - -**On Event** — `onIncomingCallReceived` returns a `Call` object (same structure as `initiateCall` response): - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `receiverId` | string | UID of the call recipient | `"cometchat-uid-7"` | -| `type` | string | Type of call | `"audio"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `category` | string | Message category | `"call"` | -| `action` | string | Current call action | `"initiated"` | -| `sessionId` | string | Unique session identifier for the call | `"v1.in.2748663902141719.1772009087929026e8ed35bb3c1f9b4aea3d6fe52b63eaa060"` | -| `status` | string | Current call status | `"initiated"` | -| `initiatedAt` | number | Unix timestamp when call was initiated | `1772009087` | -| `joinedAt` | number | Unix timestamp when user joined | `1772009087` | -| `id` | string | Unique message ID | `"25329"` | -| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `sender` | object | User who initiated the call | See User Object below | -| `receiver` | object | User receiving the call | See User Object below | -| `callInitiator` | object | User who started the call | See User Object below | -| `callReceiver` | object | Intended call recipient | See User Object below | -| `sentAt` | number | Unix timestamp when call was sent | `1772009087` | -| `updatedAt` | number | Unix timestamp of last update | `1772009087` | - ---- - -**On Event** — `onOutgoingCallRejected` / `onIncomingCallCancelled` returns a `Call` object with `status: "unanswered"`: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `receiverId` | string | UID of the call recipient | `"cometchat-uid-7"` | -| `type` | string | Type of call | `"audio"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `category` | string | Message category | `"call"` | -| `action` | string | Current call action | `"unanswered"` | -| `sessionId` | string | Unique session identifier for the call | `"v1.in.2748663902141719.1772009087929026e8ed35bb3c1f9b4aea3d6fe52b63eaa060"` | -| `status` | string | Current call status | `"unanswered"` | -| `initiatedAt` | number | Unix timestamp when call was initiated | `1772009087` | -| `id` | string | Unique message ID | `"25330"` | -| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `sender` | object | User who initiated the call | See User Object below | -| `receiver` | object | User receiving the call | See User Object below | -| `callInitiator` | object | User who started the call | See User Object below | -| `callReceiver` | object | Intended call recipient | See User Object below | -| `sentAt` | number | Unix timestamp when call was sent | `1772009132` | -| `updatedAt` | number | Unix timestamp of last update | `1772009132` | - ---- - -**On Event** — `onOutgoingCallAccepted` returns a `Call` object with `status: "ongoing"`: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `receiverId` | string | UID of the call recipient | `"cometchat-uid-6"` | -| `type` | string | Type of call | `"audio"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `category` | string | Message category | `"call"` | -| `action` | string | Current call action | `"ongoing"` | -| `sessionId` | string | Unique session identifier for the call | `"v1.in.2748663902141719.1772009341a5f92ad7d21eba0bf840bb6950c7000eb9d5863b"` | -| `status` | string | Current call status | `"ongoing"` | -| `initiatedAt` | number | Unix timestamp when call was initiated | `1772009341` | -| `joinedAt` | number | Unix timestamp when user joined | `1772009347` | -| `id` | string | Unique message ID | `"25332"` | -| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `sender` | object | User who accepted the call | See User Object below | -| `receiver` | object | User receiving the acceptance | See User Object below | -| `callInitiator` | object | User who started the call | See User Object below | -| `callReceiver` | object | Intended call recipient | See User Object below | -| `sentAt` | number | Unix timestamp when call was sent | `1772009347` | -| `updatedAt` | number | Unix timestamp of last update | `1772009347` | - ---- - -**On Event** — `onCallEndedMessageReceived` returns a `Call` object with `status: "ended"`: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `receiverId` | string | UID of the call recipient | `"cometchat-uid-6"` | -| `type` | string | Type of call | `"audio"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `category` | string | Message category | `"call"` | -| `action` | string | Current call action | `"ended"` | -| `sessionId` | string | Unique session identifier for the call | `"v1.in.2748663902141719.1772009341a5f92ad7d21eba0bf840bb6950c7000eb9d5863b"` | -| `status` | string | Current call status | `"ended"` | -| `initiatedAt` | number | Unix timestamp when call was initiated | `1772009341` | -| `id` | string | Unique message ID | `"25333"` | -| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `sender` | object | User who ended the call | See User Object below | -| `receiver` | object | Other participant | See User Object below | -| `callInitiator` | object | User who started the call | See User Object below | -| `callReceiver` | object | Intended call recipient | See User Object below | -| `sentAt` | number | Unix timestamp when call ended | `1772009475` | -| `updatedAt` | number | Unix timestamp of last update | `1772009475` | - -**User Object Structure:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user identifier | `"cometchat-uid-6"` | -| `name` | string | Display name of the user | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | - - +All call listener callbacks receive a [`Call`](/sdk/reference/messages#call) object. ## Accept Call When an incoming call is received via `onIncomingCallReceived()`, use `acceptCall()` to accept it. On success, start the call session. - -```javascript -const sessionId = call.getSessionId(); // From onIncomingCallReceived + +```typescript +const sessionId: string = call.getSessionId(); // From onIncomingCallReceived CometChat.acceptCall(sessionId).then( - (call) => { + (call: CometChat.Call) => { console.log("Call accepted:", call); - // Call accepted, now start the call session - // Generate token and render CometChatCalls.Component }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Accept call failed:", error); } ); ``` - -```typescript -const sessionId: string = call.getSessionId(); // From onIncomingCallReceived + +```javascript +const sessionId = call.getSessionId(); // From onIncomingCallReceived CometChat.acceptCall(sessionId).then( - (call: CometChat.Call) => { + (call) => { console.log("Call accepted:", call); // Call accepted, now start the call session + // Generate token and render CometChatCalls.Component }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Accept call failed:", error); } ); @@ -489,45 +350,26 @@ CometChat.acceptCall(sessionId).then( - -**On Success** — `acceptCall()` returns a `Call` object with `status: "ongoing"`: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `receiverId` | string | UID of the call recipient | `"cometchat-uid-6"` | -| `type` | string | Type of call | `"audio"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `category` | string | Message category | `"call"` | -| `action` | string | Current call action | `"ongoing"` | -| `sessionId` | string | Unique session identifier for the call | `"v1.in.2748663902141719.1772009341a5f92ad7d21eba0bf840bb6950c7000eb9d5863b"` | -| `status` | string | Current call status | `"ongoing"` | -| `initiatedAt` | number | Unix timestamp when call was initiated | `1772009341` | -| `joinedAt` | number | Unix timestamp when user joined | `1772009347` | -| `id` | string | Unique message ID | `"25332"` | -| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `sender` | object | User who accepted the call | See User Object below | -| `receiver` | object | User receiving the acceptance | See User Object below | -| `callInitiator` | object | User who started the call | See User Object below | -| `callReceiver` | object | Intended call recipient | See User Object below | -| `sentAt` | number | Unix timestamp when call was sent | `1772009347` | -| `updatedAt` | number | Unix timestamp of last update | `1772009347` | - -**User Object Structure:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user identifier | `"cometchat-uid-7"` | -| `name` | string | Display name of the user | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | - - ## 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; + +CometChat.rejectCall(sessionId, status).then( + (call: CometChat.Call) => { + console.log("Call rejected:", call); + }, + (error: CometChat.CometChatException) => { + console.log("Reject call failed:", error); + } +); +``` + ```javascript const sessionId = call.getSessionId(); @@ -544,61 +386,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); } ); ``` - - - -**On Success** — `rejectCall()` with `REJECTED` status returns a `Call` object: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `receiverId` | string | UID of the call recipient | `"cometchat-uid-6"` | -| `type` | string | Type of call | `"audio"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `category` | string | Message category | `"call"` | -| `action` | string | Current call action | `"rejected"` | -| `sessionId` | string | Unique session identifier for the call | `"v1.in.2748663902141719.1772011647d5c89acf4865fd17a9e7195bae5cee3e15d0dc34"` | -| `status` | string | Current call status | `"rejected"` | -| `initiatedAt` | number | Unix timestamp when call was initiated | `1772011647` | -| `id` | string | Unique message ID | `"25361"` | -| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `sender` | object | User who rejected the call | See User Object below | -| `receiver` | object | User receiving the rejection | See User Object below | -| `callInitiator` | object | User who started the call | See User Object below | -| `callReceiver` | object | Intended call recipient | See User Object below | -| `sentAt` | number | Unix timestamp when rejection was sent | `1772011654` | -| `updatedAt` | number | Unix timestamp of last update | `1772011654` | - -**User Object Structure:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user identifier | `"cometchat-uid-7"` | -| `name` | string | Display name of the user | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | - - -## 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(); @@ -615,57 +424,8 @@ 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); - } -); -``` - - -**On Success** — `rejectCall()` with `CANCELLED` status returns a `Call` object: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `receiverId` | string | UID of the call recipient | `"cometchat-uid-7"` | -| `type` | string | Type of call | `"audio"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `category` | string | Message category | `"call"` | -| `action` | string | Current call action | `"cancelled"` | -| `sessionId` | string | Unique session identifier for the call | `"v1.in.2748663902141719.1772009850a11d03ce320d8df8fde2ac7b43a0c30009b954f5"` | -| `status` | string | Current call status | `"cancelled"` | -| `initiatedAt` | number | Unix timestamp when call was initiated | `1772009850` | -| `id` | string | Unique message ID | `"25338"` | -| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `sender` | object | User who cancelled the call | See User Object below | -| `receiver` | object | User who was being called | See User Object below | -| `callInitiator` | object | User who started the call | See User Object below | -| `callReceiver` | object | Intended call recipient | See User Object below | -| `sentAt` | number | Unix timestamp when cancellation was sent | `1772009856` | -| `updatedAt` | number | Unix timestamp of last update | `1772009856` | - -**User Object Structure:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user identifier | `"cometchat-uid-6"` | -| `name` | string | Display name of the user | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | - - - ## Start Call Session Once the call is accepted, both participants need to start the call session. @@ -675,15 +435,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 userAuthToken = loggedInUser.getAuthToken(); +const userAuthToken: string = loggedInUser.getAuthToken(); // Step 1: Generate call token CometChatCalls.generateToken(sessionId, userAuthToken).then( - (callToken) => { + (callToken: GenerateToken) => { // Step 2: Configure call settings const callListener = new CometChatCalls.OngoingCallListener({ onCallEnded: () => { @@ -698,12 +458,12 @@ CometChatCalls.generateToken(sessionId, userAuthToken).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: CometChat.User) => console.log("User joined:", user), + onUserLeft: (user: CometChat.User) => console.log("User left:", user), + onError: (error: CometChat.CometChatException) => console.log("Call error:", error) }); const callSettings = new CometChatCalls.CallSettingsBuilder() @@ -715,21 +475,21 @@ CometChatCalls.generateToken(sessionId, userAuthToken).then( // Step 3: Render call component // }, - (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 userAuthToken: string = loggedInUser.getAuthToken(); +const userAuthToken = loggedInUser.getAuthToken(); // Step 1: Generate call token CometChatCalls.generateToken(sessionId, userAuthToken).then( - (callToken: GenerateToken) => { + (callToken) => { // Step 2: Configure call settings const callListener = new CometChatCalls.OngoingCallListener({ onCallEnded: () => { @@ -744,12 +504,12 @@ CometChatCalls.generateToken(sessionId, userAuthToken).then( CometChatCalls.endSession(); // Close calling screen }, - (error: CometChat.CometChatException) => console.log("End call failed:", error) + (error) => console.log("End call failed:", error) ); }, - onUserJoined: (user: CometChat.User) => console.log("User joined:", user), - onUserLeft: (user: CometChat.User) => console.log("User left:", user), - onError: (error: CometChat.CometChatException) => 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() @@ -761,7 +521,7 @@ CometChatCalls.generateToken(sessionId, userAuthToken).then( // Step 3: Render call component // }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Token generation failed:", error); } ); @@ -769,63 +529,8 @@ CometChatCalls.generateToken(sessionId, userAuthToken).then( - -**On Success** — `generateToken()` returns an object with session and token: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sessionId` | string | Unique session identifier for the call | `"v1.in.2748663902141719.1772009341a5f92ad7d21eba0bf840bb6950c7000eb9d5863b"` | -| `token` | string | JWT token for authenticating the call session | `"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6ImNjcHJvX2p3dF9yczI1Nl9rZXkxIn0..."` | - ---- - -**On Event** — `onUserJoined` returns user info when a participant joins: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user identifier | `"cometchat-uid-7"` | -| `name` | string | Display name of the user | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `isVideoMuted` | boolean | Whether user's video is muted | `true` | -| `isAudioMuted` | boolean | Whether user's audio is muted | `false` | -| `isLocalUser` | boolean | Whether this is the local user | `false` | -| `id` | string | Internal participant ID | `"03dcf87d"` | -| `joinedAt` | string | Unix timestamp (ms) when user joined | `"1772009349593"` | - ---- - -**On Event** — `onUserListUpdated` returns the current list of participants: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| (array) | array | Array of participant objects | See below | - -Each participant object: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user identifier | `"cometchat-uid-6"` | -| `name` | string | Display name of the user | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | - ---- - -**On Event** — `onUserLeft` returns user info when a participant leaves: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user identifier | `"cometchat-uid-7"` | -| `name` | string | Display name of the user | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `id` | string | Internal participant ID | `"07ba41cd"` | -| `joinedAt` | string | Unix timestamp (ms) when user joined | `"1772010034825"` | -| `isAudioMuted` | boolean | Whether user's audio was muted | `false` | -| `isVideoMuted` | boolean | Whether user's video was muted | `true` | - - For more details on call settings and customization, see the [Call Session](/sdk/react-native/direct-call#start-call-session) guide. - ## End Call To end an active call in the ringing flow, the process differs based on who ends the call. @@ -835,34 +540,34 @@ To end an active call in the ringing flow, the process differs based on who ends When the user presses 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); } ); @@ -874,8 +579,8 @@ onCallEndButtonPressed: () => { **Remote participant** (receives `onCallEnded()` callback): - -```javascript + +```typescript onCallEnded: () => { CometChat.clearActiveCall(); CometChatCalls.endSession(); @@ -883,8 +588,8 @@ onCallEnded: () => { } ``` - -```typescript + +```javascript onCallEnded: () => { CometChat.clearActiveCall(); CometChatCalls.endSession(); @@ -894,40 +599,6 @@ onCallEnded: () => { - -**On Success** — `endCall()` returns a `Call` object with `status: "ended"`: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `receiverId` | string | UID of the call recipient | `"cometchat-uid-6"` | -| `type` | string | Type of call | `"audio"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `category` | string | Message category | `"call"` | -| `action` | string | Current call action | `"ongoing"` | -| `sessionId` | string | Unique session identifier for the call | `"v1.in.2748663902141719.17720117078263785b8e96c36c6a586d6bb3a60e0a6c16d018"` | -| `status` | string | Current call status | `"ended"` | -| `initiatedAt` | number | Unix timestamp when call was initiated | `1772011707` | -| `joinedAt` | number | Unix timestamp when user joined | `1772011711` | -| `id` | string | Unique message ID | `"25363"` | -| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `sender` | object | User who ended the call | See User Object below | -| `receiver` | object | Other participant | See User Object below | -| `callInitiator` | object | User who started the call | See User Object below | -| `callReceiver` | object | Intended call recipient | See User Object below | -| `sentAt` | number | Unix timestamp when call ended | `1772011711` | -| `updatedAt` | number | Unix timestamp of last update | `1772011711` | - -**User Object Structure:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user identifier | `"cometchat-uid-7"` | -| `name` | string | Display name of the user | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | - - For more details, see the [End Call Session](/sdk/react-native/direct-call#end-call-session) guide. ## Busy Call Handling @@ -935,31 +606,31 @@ For more details, see the [End Call Session](/sdk/react-native/direct-call#end-c 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); } ); @@ -967,95 +638,25 @@ CometChat.rejectCall(sessionId, status).then( - -**On Success** — `rejectCall()` with `BUSY` status returns a `Call` object: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `receiverId` | string | UID of the call recipient | `"cometchat-uid-6"` | -| `type` | string | Type of call | `"audio"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `category` | string | Message category | `"call"` | -| `action` | string | Current call action | `"busy"` | -| `sessionId` | string | Unique session identifier for the call | `"v1.in.2748663902141719.1772011351c36eb867b604d0a861952ea718d3d8eaf1c89ec0"` | -| `status` | string | Current call status | `"busy"` | -| `initiatedAt` | number | Unix timestamp when call was initiated | `1772011351` | -| `id` | string | Unique message ID | `"25359"` | -| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `sender` | object | User who sent busy status | See User Object below | -| `receiver` | object | User receiving the busy status | See User Object below | -| `callInitiator` | object | User who started the call | See User Object below | -| `callReceiver` | object | Intended call recipient | See User Object below | -| `sentAt` | number | Unix timestamp when busy status was sent | `1772011351` | -| `updatedAt` | number | Unix timestamp of last update | `1772011351` | + +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. + --- -**On Event** — The caller receives `onOutgoingCallRejected` with `status: "busy"`: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `receiverId` | string | UID of the call recipient | `"cometchat-uid-6"` | -| `type` | string | Type of call | `"audio"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `category` | string | Message category | `"call"` | -| `action` | string | Current call action | `"busy"` | -| `sessionId` | string | Unique session identifier for the call | `"v1.in.2748663902141719.1772011351c36eb867b604d0a861952ea718d3d8eaf1c89ec0"` | -| `status` | string | Current call status | `"busy"` | -| `initiatedAt` | number | Unix timestamp when call was initiated | `1772011351` | -| `id` | string | Unique message ID | `"25359"` | -| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `sender` | object | User who sent busy status | See User Object below | -| `receiver` | object | User receiving the busy status | See User Object below | -| `callInitiator` | object | User who started the call | See User Object below | -| `callReceiver` | object | Intended call recipient | See User Object below | -| `sentAt` | number | Unix timestamp when busy status was sent | `1772011351` | -| `updatedAt` | number | Unix timestamp of last update | `1772011351` | - -**User Object Structure:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user identifier | `"cometchat-uid-7"` | -| `name` | string | Display name of the user | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | - - - - - - - Always remove call listeners on component unmount to prevent memory leaks and duplicate events - - Store the `sessionId` from `initiateCall()` or `onIncomingCallReceived()` — you'll need it for accept, reject, cancel, and starting the session - - Handle the `CALL_STATUS_BUSY` case when the receiver is already on another call - - Call `CometChat.clearActiveCall()` and `CometChatCalls.endSession()` together when a call ends to properly release all resources - - Request camera and microphone permissions before initiating or accepting a call - - Show appropriate UI feedback (spinner, ringing animation) while waiting for the receiver to respond - - - - **`onIncomingCallReceived` not firing:** Ensure `CometChat.addCallListener()` is registered before the call is initiated and that the listener ID is unique - - **Call accepted but no audio/video:** After `acceptCall()`, you must start the call session by generating a token and rendering `CometChatCalls.Component` — see the Start Call Session section above - - **Duplicate call events:** You may have registered the same listener multiple times — always call `CometChat.removeCallListener(listenerId)` on unmount - - **`initiateCall` fails with error:** Verify the receiver UID/GUID exists and that the logged-in user has an active session - - **Call ends immediately after accept:** Make sure both caller and receiver generate a call token and render `CometChatCalls.Component` — if only one side renders the component, the call will appear to drop - - **Busy status not working:** Ensure you're using `CometChat.CALL_STATUS.BUSY` (not `REJECTED`) when the receiver is already on a call - - - ## Next Steps - Start and manage the actual call session after the ringing flow completes. + Manage call sessions, tokens, and settings - - Install dependencies, configure permissions, and initialize the Calls SDK. + + Retrieve and display call history - Record audio and video calls for playback or compliance. + Record audio and video calls - - Retrieve and display call history including duration and participants. + + Install and initialize the Calls SDK diff --git a/sdk/react-native/delete-conversation.mdx b/sdk/react-native/delete-conversation.mdx index 0e0eecfac..6b970ac19 100644 --- a/sdk/react-native/delete-conversation.mdx +++ b/sdk/react-native/delete-conversation.mdx @@ -1,67 +1,65 @@ --- -title: "Delete A Conversation" -description: "Learn how to delete user and group conversations for the logged-in user using the CometChat React Native SDK." +title: "Delete Conversation" +sidebarTitle: "Delete Conversation" +description: "Delete user or group conversations using the CometChat React Native SDK." --- - -**Quick Reference** +{/* TL;DR for Agents and Quick Reference */} + + ```javascript -// Delete a user conversation -CometChat.deleteConversation("UID", "user"); +// Delete user conversation +await CometChat.deleteConversation("UID", "user"); -// Delete a group conversation -CometChat.deleteConversation("GUID", "group"); +// Delete group conversation +await CometChat.deleteConversation("GUID", "group"); ``` - - - -**Available via:** [SDK](/sdk/react-native/delete-conversation) | [REST API](/rest-api/conversations/reset-user-conversation) | [UI Kits](/ui-kit/react-native/overview) - - -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, and the type (`user`/`group`) of conversation to be deleted. +**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. + -Deleting a conversation is an irreversible operation for the logged-in user. Once deleted, the conversation and its associated data cannot be recovered for that user. +This operation is irreversible. Deleted conversations cannot be recovered for the logged-in user. +Use `deleteConversation()` to delete a conversation for the logged-in user. + - -```javascript -let UID = "UID"; -let type = "user"; + +```typescript +let UID: string = "UID"; +let type: string = "user"; CometChat.deleteConversation(UID, type).then( - deletedConversation => { + (deletedConversation: string) => { console.log(deletedConversation); - }, error => { + }, (error: CometChat.CometChatException) => { console.log('error while deleting a conversation', error); } -); +); ``` - + ```javascript -let GUID = "GUID"; -let type = "group"; -CometChat.deleteConversation(GUID, type).then( +let UID = "UID"; +let type = "user"; +CometChat.deleteConversation(UID, type).then( deletedConversation => { console.log(deletedConversation); }, error => { console.log('error while deleting a conversation', error); } -); +); ``` - + ```typescript -let UID: string = "UID"; -let type: string = "user"; -CometChat.deleteConversation(UID, type).then( +let GUID: string = "GUID"; +let type: string = "group"; +CometChat.deleteConversation(GUID, type).then( (deletedConversation: string) => { console.log(deletedConversation); }, (error: CometChat.CometChatException) => { @@ -72,14 +70,14 @@ CometChat.deleteConversation(UID, type).then( - -```typescript -let GUID: string = "GUID"; -let type: string = "group"; + +```javascript +let GUID = "GUID"; +let type = "group"; CometChat.deleteConversation(GUID, type).then( - (deletedConversation: string) => { + deletedConversation => { console.log(deletedConversation); - }, (error: CometChat.CometChatException) => { + }, error => { console.log('error while deleting a conversation', error); } ); @@ -89,50 +87,30 @@ CometChat.deleteConversation(GUID, type).then( - -**On Success** — `deleteConversation()` returns a success message: +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 | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `message` | string | Confirmation message | `"Conversation deleted successfully."` | +| Parameter | Description | Required | +| --- | --- | --- | +| conversationWith | UID or GUID of the conversation to delete | Yes | +| conversationType | `user` or `group` | Yes | - - -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: +On success, returns a confirmation message string. -| 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 | - - - - - Always confirm with the user before deleting a conversation, as this action is irreversible for the logged-in user. - - Handle the error callback gracefully to inform users if the deletion fails (e.g., due to network issues or invalid IDs). - - After a successful deletion, update your local conversation list by refreshing it using `ConversationsRequest`. - - - - **Conversation not found**: Ensure the `UID` or `GUID` you are passing is correct and that a conversation with that user or group exists. - - **Permission denied**: Verify that the logged-in user has the appropriate permissions and that the SDK is initialized and the user is logged in. - - **Type mismatch**: Make sure the `conversationType` parameter matches the ID you are passing — use `"user"` with a `UID` and `"group"` with a `GUID`. - - +--- ## Next Steps - - Fetch and display the list of conversations for the logged-in user. + + Fetch and filter conversation lists - - Remove individual messages from a conversation. + + Delete individual messages from conversations - - Listen for and handle incoming real-time messages. + + Show when users are typing in conversations - - Explore the full set of messaging capabilities available in the SDK. + + Track message delivery and read status diff --git a/sdk/react-native/delete-group.mdx b/sdk/react-native/delete-group.mdx index fb205d5c9..5c63cf888 100644 --- a/sdk/react-native/delete-group.mdx +++ b/sdk/react-native/delete-group.mdx @@ -1,28 +1,47 @@ --- title: "Delete A Group" -description: "Delete groups using the CometChat React Native SDK — requires Admin scope on the group." +sidebarTitle: "Delete Group" +description: "Delete a group permanently using the CometChat React Native SDK. Only group admins can perform this operation." --- - -**Quick Reference** - Delete a group: + ```javascript +// Delete a group (owner only) await CometChat.deleteGroup("GUID"); ``` - - -**Available via:** [SDK](/sdk/react-native/delete-group) | [REST API](/rest-api/delete-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 -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()` with the group's GUID. + +```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 -var GUID = "GUID"; +const GUID = "GUID"; CometChat.deleteGroup(GUID).then( response => { @@ -30,64 +49,33 @@ response => { }, error => { console.log("Group delete failed with exception:", error); } -); +); ``` - +Alternatively, you can use the `async/await` syntax: - -```typescript -var GUID: string = "GUID"; +```javascript +const GUID = "GUID"; -CometChat.deleteGroup(GUID).then( - (response: boolean) => { - console.log("Group deleted successfully:", response); - }, (error: CometChat.CometChatException) => { - console.log("Group delete failed with exception:", error); - } -); +try { + const response = await CometChat.deleteGroup(GUID); + console.log("Group deleted successfully:", response); +} catch (error) { + console.log("Group delete failed with exception:", error); +} ``` - - -**On Success** — `deleteGroup()` returns a boolean: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `response` | boolean | Indicates successful deletion | `true` | - - - The `deleteGroup()` method takes the following parameters: | Parameter | Description | | --------- | ---------------------------------------------- | | `GUID` | The GUID of the group you would like to delete | -## Best Practices - - - - Deleting a group is irreversible — all messages, members, and metadata are permanently removed. Always prompt the user for confirmation before calling `deleteGroup()`. - - - The logged-in user must have Admin scope on the group. Verify the user's scope using `getGroup()` before attempting deletion to provide a better UX. - - - -## Troubleshooting +On success, the method resolves with `true` (boolean). - - - Verify the logged-in user is an Admin of the group. Owners and Moderators may not have delete permissions depending on your app configuration. - - - Ensure the `deleteGroup()` promise resolved successfully. If using cached data, refresh your group list after deletion to remove stale entries. - - --- @@ -106,4 +94,4 @@ The `deleteGroup()` method takes the following parameters: Transfer group ownership before leaving - \ No newline at end of file + diff --git a/sdk/react-native/delete-message.mdx b/sdk/react-native/delete-message.mdx index 197fff172..91acb54d6 100644 --- a/sdk/react-native/delete-message.mdx +++ b/sdk/react-native/delete-message.mdx @@ -1,62 +1,44 @@ --- -title: "Delete A Message" -description: "Learn how to delete messages, listen for real-time message delete events, and retrieve missed message deletions using the CometChat React Native SDK." +title: "Delete Message" +sidebarTitle: "Delete Message" +description: "Delete messages using the CometChat React Native SDK." --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript -// Delete a message by ID let messageId = "MESSAGE_ID"; -CometChat.deleteMessage(messageId).then( - (message) => console.log("Message deleted", message), - (error) => console.log("Delete failed:", error) -); -// Listen for real-time message deletes -CometChat.addMessageListener("LISTENER_ID", new CometChat.MessageListener({ - onMessageDeleted: (message) => console.log("Deleted:", message) +// 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()); + } })); ``` - -While [deleting a message](/sdk/react-native/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/react-native/delete-message#real-time-message-delete-events) when your app is running. -2. Calling a method to retrieve [missed message deletes](/sdk/react-native/delete-message#missed-message-delete-events) when your app was not running. - - -**Available via:** [SDK](/sdk/react-native/delete-message) | [REST API](/rest-api/messages/delete-message) | [UI Kits](/ui-kit/react-native/overview) - - -## Delete a Message - -*In other words, as a sender, 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. +**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. - - -```javascript -let messageId = "ID_OF_THE_MESSAGE_YOU_WANT_TO_DELETE"; +Deleting a message is straightforward. Receiving delete events has two parts: -CometChat.deleteMessage(messageId).then( -message => { - console.log("Message deleted", message); -}, error => { - console.log("Message delete failed with error:", error); -} -); -``` +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 + +Use `deleteMessage()` with the message ID. + ```typescript let messageId: number = 1; @@ -69,160 +51,51 @@ CometChat.deleteMessage(messageId).then( } ); ``` - - - - -**On Success** — `deleteMessage()` returns the deleted message object with `deletedAt` and `deletedBy` fields set: - - - -**Message Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25305"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-6"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `sentAt` | number | Unix timestamp when originally sent | `1771996215` | -| `deliveredAt` | number | Unix timestamp when delivered | `1771996215` | -| `readAt` | number | Unix timestamp when read | `1771996215` | -| `deletedAt` | number | Unix timestamp when deleted | `1771996222` | -| `deletedBy` | string | UID of user who deleted the message | `"cometchat-uid-7"` | -| `updatedAt` | number | Unix timestamp when updated | `1771996222` | -| `sender` | object | Sender user details | [See below ↓](#delete-message-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#delete-message-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#delete-message-data-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771993054` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771994056` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entities` | object | Sender and receiver entities | [See below ↓](#delete-message-data-entities-object) | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#delete-message-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#delete-message-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#delete-message-data-entities-sender-entity-object) | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"offline"` | -| `lastActiveAt` | number | Last active timestamp | `1771993054` | -| `tags` | array | User tags | `[]` | - ---- + +```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); +} +); +``` -**`data.entities.receiver` Object:** +Alternatively, you can use the `async/await` syntax: -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#delete-message-data-entities-receiver-entity-object) | +```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); +} +``` + - + -**`data.entities.receiver.entity` Object:** +The deleted message object is returned with `deletedAt` (timestamp) and `deletedBy` (UID of deleter) fields set. -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"offline"` | -| `lastActiveAt` | number | Last active timestamp | `1771994056` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `tags` | array | User tags | `[]` | +The `deleteMessage()` method returns a [`BaseMessage`](/sdk/reference/messages#basemessage) object. - +Relevant fields to access on the returned 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. +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| 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. +Message deletion in CometChat is controlled by - -| User Role | Conversation Type | Deletion Capabilities | +| User | Conversation Type | Deletion Capabilities | | --------------- | ----------------------- | ------------------------------ | | Message Sender | One-on-One Conversation | Messages they have sent. | | Message Sender | Group Conversation | Messages they have sent. | @@ -231,27 +104,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?* - -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. - -```javascript -var listenerID = "UNIQUE_LISTENER_ID"; - -CometChat.addMessageListener( -listenerID, -new CometChat.MessageListener({ - onMessageDeleted: message => { - console.log("Deleted Message", message); - } -}) -); -``` - - - ```typescript let listenerID: string = "UNIQUE_LISTENER_ID"; @@ -268,341 +123,50 @@ CometChat.addMessageListener( - - - -**On Event** — `onMessageDeleted` callback receives the deleted message object: - - - -**Message Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25301"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-7"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `sentAt` | number | Unix timestamp when originally sent | `1771996032` | -| `deliveredAt` | number | Unix timestamp when delivered | `1771996033` | -| `readAt` | number | Unix timestamp when read | `1771996033` | -| `deletedAt` | number | Unix timestamp when deleted | `1771996040` | -| `deletedBy` | string | UID of user who deleted the message | `"cometchat-uid-6"` | -| `updatedAt` | number | Unix timestamp when updated | `1771996040` | -| `sender` | object | Sender user details | [See below ↓](#on-message-deleted-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#on-message-deleted-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#on-message-deleted-data-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771994056` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771993054` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entities` | object | Sender and receiver entities | [See below ↓](#on-message-deleted-data-entities-object) | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#on-message-deleted-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#on-message-deleted-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#on-message-deleted-data-entities-sender-entity-object) | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"offline"` | -| `lastActiveAt` | number | Last active timestamp | `1771994056` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#on-message-deleted-data-entities-receiver-entity-object) | - ---- - - - -**`data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"offline"` | -| `lastActiveAt` | number | Last active timestamp | `1771993054` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `tags` | array | User tags | `[]` | - - - - -Always remove listeners when they are no longer needed (e.g., on component unmount or screen navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. - + ```javascript -CometChat.removeMessageListener("UNIQUE_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?* - -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 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: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25301"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-7"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `sentAt` | number | Unix timestamp when originally sent | `1771996032` | -| `deliveredAt` | number | Unix timestamp when delivered | `1771996033` | -| `readAt` | number | Unix timestamp when read | `1771996033` | -| `deletedAt` | number | Unix timestamp when deleted | `1771996040` | -| `deletedBy` | string | UID of user who deleted the message | `"cometchat-uid-6"` | -| `updatedAt` | number | Unix timestamp when updated | `1771996040` | -| `sender` | object | Sender user details | [See below ↓](#missed-delete-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#missed-delete-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#missed-delete-data-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- +let listenerID = "UNIQUE_LISTENER_ID"; - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771994056` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771993054` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entities` | object | Sender and receiver entities | [See below ↓](#missed-delete-data-entities-object) | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#missed-delete-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#missed-delete-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#missed-delete-data-entities-sender-entity-object) | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"offline"` | -| `lastActiveAt` | number | Last active timestamp | `1771994056` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#missed-delete-data-entities-receiver-entity-object) | +CometChat.addMessageListener( +listenerID, +new CometChat.MessageListener({ + onMessageDeleted: message => { + console.log("Deleted Message", message); + } +}) +); +``` ---- + - + -**`data.entities.receiver.entity` Object:** +The `onMessageDeleted` callback receives a [`BaseMessage`](/sdk/reference/messages#basemessage) object with the `deletedAt` and `deletedBy` fields set. -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"offline"` | -| `lastActiveAt` | number | Last active timestamp | `1771993054` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `tags` | array | User tags | `[]` | +Relevant fields to access on the returned message: - +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| deletedAt | `getDeletedAt()` | `number` | Timestamp when the message was deleted | +| deletedBy | `getDeletedBy()` | `string` | UID of the user who deleted the message | -For the message deleted event, in the `Action` object received, the following fields can help you get the relevant information- +## Missed Message Delete Events -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. +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. - -When fetching message history, deleted messages include `deletedAt` and `deletedBy` fields. You can check if `deletedAt` is set to identify deleted messages. Additionally, an Action message with `action: "deleted"` is added to the message list for audit/timeline purposes. - +The [`Action`](/sdk/reference/messages#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. - - - - **Check `deletedAt` when rendering messages.** Before displaying a message, check if `deletedAt` is set. If it is, show a "This message was deleted" placeholder instead of the original content. - - **Use unique listener IDs.** Use a unique identifier per screen or component (e.g., `"ChatScreen_DeleteListener"`) to avoid conflicts with other listeners. - - **Always clean up listeners.** Remove message listeners in your component's cleanup or unmount lifecycle to prevent memory leaks. - - **Handle permissions gracefully.** If a user attempts to delete a message they don't have permission to delete, handle the error callback and inform the user. - - - - **"Message delete failed" error:** Verify that the message ID is valid and that the current user has permission to delete the message (sender, group admin, or group moderator). - - **`onMessageDeleted` not firing:** Ensure you have registered the `MessageListener` with `CometChat.addMessageListener()` before the delete event occurs, and that the listener ID is unique. - - **Deleted messages still showing in the UI:** Make sure you are checking the `deletedAt` field on each message when rendering your message list, and updating your local state when `onMessageDeleted` fires. - - **Duplicate delete events:** This usually happens when multiple listeners are registered with the same or different IDs without being removed. Ensure you remove listeners on component unmount. - - + +Always remove message listeners when they're no longer needed to prevent memory leaks. + --- @@ -610,15 +174,15 @@ In order to edit or delete a message, you need to be either the sender of the me - Modify the content of a sent message + Edit sent messages in conversations Send text, media, and custom messages - Listen for and retrieve incoming messages + Listen for incoming messages in real-time - Report inappropriate or unwanted messages + Report inappropriate messages diff --git a/sdk/react-native/delivery-read-receipts.mdx b/sdk/react-native/delivery-read-receipts.mdx index 854168bc1..46f544d97 100644 --- a/sdk/react-native/delivery-read-receipts.mdx +++ b/sdk/react-native/delivery-read-receipts.mdx @@ -1,1026 +1,624 @@ --- title: "Delivery & Read Receipts" -description: "Learn how to mark messages as delivered, read, or unread and listen for real-time receipt events using the CometChat React Native SDK." +sidebarTitle: "Delivery & Read Receipts" +description: "Mark messages as delivered, read, or unread and receive real-time receipt events using the CometChat React Native SDK." --- - -**Quick Reference** - Mark messages and listen for receipts: + + +| 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 | ```javascript -// Mark as delivered +// Mark as delivered/read (pass message object) CometChat.markAsDelivered(message); - -// Mark as read CometChat.markAsRead(message); -// Listen for receipts +// Mark entire conversation +CometChat.markConversationAsRead("UID", "user"); + +// Listen for receipt events CometChat.addMessageListener("LISTENER_ID", new CometChat.MessageListener({ - onMessagesDelivered: (receipt) => console.log("Delivered", receipt), - onMessagesRead: (receipt) => console.log("Read", receipt), + onMessagesDelivered: (receipt) => { }, + onMessagesRead: (receipt) => { }, + onMessagesDeliveredToAll: (receipt) => { }, // Groups only + onMessagesReadByAll: (receipt) => { } // Groups only })); ``` - - - -**Available via:** [SDK](/sdk/react-native/delivery-read-receipts) | [REST API](/rest-api/conversations/mark-user-conversation-as-delivered) | [UI Kits](/ui-kit/react-native/overview) - - -## Mark Messages as Delivered - -*In other words, as a recipient, how do I inform the sender that I've received a message?* - -{/* Mark all messages up to a specified message ID as delivered. Two ways to use markAsDelivered: - 1. Pass the message object directly — CometChat.markAsDelivered(message) - 2. Pass individual params — CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId) */} - -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 -var messageId = "MESSAGE_ID"; -var receiverId = "MESSAGE_RECEIVER_UID"; -var receiverType = "user"; -var senderId = "MESSAGE_SENDER_UID"; -CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId); -``` - - - - -```javascript -var messageId = "MESSAGE_ID"; -var receiverId = "MESSAGE_RECEIVER_GUID"; -var receiverType = "group"; -var senderId = "MESSAGE_SENDER_UID"; -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"; -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); + } +); ``` - - - -```typescript -var messageId: string = "MESSAGE_ID"; -var receiverId: string = "MESSAGE_RECEIVER_GUID"; -var receiverType: string = "group"; -var senderId: string = "MESSAGE_SENDER_UID"; -CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId); + +```javascript +CometChat.markAsDelivered(message).then( + () => { + console.log("Marked as delivered successfully"); + }, + (error) => { + 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( + +```typescript +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) => { - console.log( - "An error occurred when marking the message as delivered.", - error - ); + (error: CometChat.CometChatException) => { + console.log("Error marking as delivered:", error); } ); ``` - - + ```javascript -CometChat.markAsDelivered( - message.getId(), - message.getReceiverUid(), - "group", - 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); } ); ``` - - + ```typescript -var messageId: string = "MESSAGE_ID"; -var receiverId: string = "MESSAGE_SENDER_UID"; -var receiverType: string = "user"; -var senderId: string = "MESSAGE_SENDER_UID"; +let messageId: string = "MESSAGE_ID"; +let receiverId: string = "GROUP_GUID"; +let receiverType: string = "group"; +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); } ); ``` - - -```typescript -var messageId: string = "MESSAGE_ID"; -var receiverId: string = "MESSAGE_RECEIVER_GUID"; -var receiverType: string = "group"; -var senderId: string = "MESSAGE_SENDER_UID"; + +```javascript +let messageId = "MESSAGE_ID"; +let receiverId = "GROUP_GUID"; +let receiverType = "group"; +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: CometChat.CometChatException) => { - console.log( - "An error occurred when marking the message as delivered.", - error - ); + (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. +## Mark Conversation as Delivered - - -```javascript -CometChat.markAsDelivered(message); -``` +Use `markConversationAsDelivered()` to mark all messages in a conversation as delivered. - +`markConversationAsDelivered()` resolves with a `string` on success. - + + ```typescript -let message: CometChat.BaseMessage; -CometChat.markAsDelivered(message); -``` +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:", error); + } +); +``` - - -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.markAsDelivered(message).then( - () => { - console.log("mark as delivered success."); +let conversationWith = "USER_UID"; +let conversationType = "user"; + +CometChat.markConversationAsDelivered(conversationWith, conversationType).then( + (response) => { + console.log("Conversation marked as delivered", response); }, (error) => { - console.log( - "An error occurred when marking the message as delivered.", - error - ); + console.log("Error:", error); } ); ``` - - + ```typescript -let message: CometChat.BaseMessage; -CometChat.markAsDelivered(message).then( - () => { - console.log("mark as delivered success."); +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( - "An error occurred when marking the message as delivered.", - error - ); + console.log("Error:", error); } ); ``` - - - - -**On Success** — `markAsDelivered()` returns a confirmation object: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `messageId` | string | ID of the message marked as delivered | `"25323"` | -| `type` | string | Message type | `"text"` | - - - -## Mark Messages as Read - -*In other words, as a recipient, how do I inform the sender I've read a message?* - -{/* Mark all messages up to a specified message ID as read. Two ways to use markAsRead: - 1. Pass the message object directly — CometChat.markAsRead(message) - 2. Pass individual params — CometChat.markAsRead(messageId, receiverId, receiverType, senderId) */} - -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. | - -Messages for both user and group conversations can be marked as read using this method. - -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 - - - -``` -var messageId = "MESSAGE_ID"; -var receiverId = "MESSAGE_SENDER_UID"; -var receiverType = "user"; -var senderId = "MESSAGE_SENDER_UID"; -CometChat.markAsRead(messageId, receiverId, receiverType, senderId); -``` - - - - -``` -var messageId = "MESSAGE_ID"; -var receiverId = "MESSAGE_RECEIVER_GUID"; -var receiverType = "group"; -var senderId = "MESSAGE_SENDER_UID"; -CometChat.markAsRead(messageId, receiverId, receiverType, senderId); -``` - - + +```javascript +let conversationWith = "GROUP_GUID"; +let conversationType = "group"; - -``` -var messageId: string = "MESSAGE_ID"; -var receiverId: string = "MESSAGE_SENDER_UID"; -var receiverType: string = "user"; -var senderId: string = "MESSAGE_SENDER_UID"; -CometChat.markAsRead(messageId, receiverId, receiverType, senderId); +CometChat.markConversationAsDelivered(conversationWith, conversationType).then( + (response) => { + console.log("Conversation marked as delivered", response); + }, + (error) => { + console.log("Error:", error); + } +); ``` - - -``` -var messageId: string = "MESSAGE_ID"; -var receiverId: string = "MESSAGE_RECEIVER_GUID"; -var receiverType: string = "group"; -var senderId: string = "MESSAGE_SENDER_UID"; -CometChat.markAsRead(messageId, receiverId, receiverType, senderId); -``` + - - +## Mark as Read -This method will mark all the messages before the messageId specified, for the conversation with receiverId and receiverType(user/group) as read. +Use `markAsRead()` to mark messages as read. You can pass either a message object or individual 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. +### Using Message Object - -```javascript -CometChat.markAsRead( - message.getId(), - message.getSender().getUid(), - "user", - message.getSender().getUid() -).then( + +```typescript +CometChat.markAsRead(message).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); + (error: CometChat.CometChatException) => { + console.log("Error marking as read:", error); } ); ``` - - - + ```javascript -CometChat.markAsRead( - message.getId(), - message.getReceiverUid(), - "group", - message.getSender().getUid() -).then( +CometChat.markAsRead(message).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); } ); ``` - + + +### Using Parameters + ```typescript -var messageId: string = "MESSAGE_ID"; -var receiverId: string = "MESSAGE_SENDER_UID"; -var receiverType: string = "user"; -var 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); } ); ``` - - -```typescript -var messageId: string = "MESSAGE_ID"; -var receiverId: string = "MESSAGE_RECEIVER_GUID"; -var receiverType: string = "group"; -var senderId: string = "MESSAGE_SENDER_UID"; + +```javascript +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: CometChat.CometChatException) => { - console.log("An error occurred when marking the message as read.", error); + (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.If the message object is the last message, the entire conversation will be marked as read. - - - -```javascript -CometChat.markAsRead(message); -``` - - + ```typescript -let message: CometChat.BaseMessage; -CometChat.markAsRead(message); -``` - - +let messageId: string = "MESSAGE_ID"; +let receiverId: string = "GROUP_GUID"; +let receiverType: string = "group"; +let senderId: string = "MESSAGE_SENDER_UID"; - - -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( +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); + (error: CometChat.CometChatException) => { + console.log("Error marking as read:", error); } ); ``` - - -```typescript -let message: CometChat.BaseMessage; -CometChat.markAsRead(message).then( + +```javascript +let messageId = "MESSAGE_ID"; +let receiverId = "GROUP_GUID"; +let receiverType = "group"; +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: CometChat.CometChatException) => { - console.log("An error occurred when marking the message as read.", error); + (error) => { + console.log("Error marking as read:", error); } ); ``` - - -**On Success** — `markAsRead()` returns a confirmation object: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `messageId` | string | ID of the message marked as read | `"25323"` | -| `type` | string | Message type | `"text"` | - - - -## Mark Messages as Unread - -{/* Mark a message as unread — CometChat.markMessageAsUnread(message) - Only works for messages received from other users. Returns updated Conversation object. */} +## Mark Conversation as Read -The Mark 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? - -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 | -| --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| 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. | - - -You cannot mark your own messages as unread. This method only works for messages received from other users. - +Use `markConversationAsRead()` to mark all messages in a conversation as read. - -```javascript -CometChat.markMessageAsUnread(message); -``` - - - - + ```typescript -let message: CometChat.BaseMessage; -CometChat.markMessageAsUnread(message); -``` +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:", error); + } +); +``` - - -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. - - - + ```javascript -CometChat.markMessageAsUnread(message).then( - (conversation) => { - console.log("mark messages as unread success.", conversation); - console.log("Unread message count:", conversation.getUnreadMessageCount()); +let conversationWith = "USER_UID"; +let conversationType = "user"; + +CometChat.markConversationAsRead(conversationWith, conversationType).then( + (response) => { + console.log("Conversation marked as read", response); }, (error) => { - console.log("An error occurred when marking the message as unread.", error); + console.log("Error:", 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()); +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("An error occurred when marking the message as unread.", error); + console.log("Error:", error); } ); ``` - - - - -**On Success** — `markMessageAsUnread()` returns the updated `Conversation` object with the new unread count: - - - -**Conversation Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `conversationType` | string | Type of conversation | `"user"` | -| `unreadMessageCount` | number | Number of unread messages | `1` | -| `unreadMentionsCount` | number | Number of unread mentions | `0` | -| `lastReadMessageId` | string | ID of last read message | `"25323"` | -| `latestMessageId` | string | ID of latest message | `""` | -| `lastMessage` | object | Last message in conversation | [See below ↓](#mark-unread-lastmessage-object) | -| `conversationWith` | object | User or group the conversation is with | [See below ↓](#mark-unread-conversationwith-object) | - ---- - - - -**`lastMessage` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25326"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-7"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Hello <@uid:cometchat-uid-7>, this is a test mention!"` | -| `sentAt` | number | Unix timestamp when sent | `1772006074` | -| `deliveredAt` | number | Unix timestamp when delivered | `1772006158` | -| `readAt` | number | Unix timestamp when read | `1772006158` | -| `updatedAt` | number | Unix timestamp when updated | `1772006158` | -| `mentionedMe` | boolean | Whether current user is mentioned | `true` | -| `mentionedUsers` | array | Users mentioned in message | [See below ↓](#mark-unread-mentionedusers-array) | -| `sender` | object | Sender user details | [See below ↓](#mark-unread-lastmessage-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#mark-unread-lastmessage-receiver-object) | -| `reactions` | array | Message reactions | `[]` | - ---- - - - -**`lastMessage.mentionedUsers` Array (per item):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1772005334` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`lastMessage.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1772004288` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`lastMessage.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1772005334` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`conversationWith` Object:** + +```javascript +let conversationWith = "GROUP_GUID"; +let conversationType = "group"; -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1772004288` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +CometChat.markConversationAsRead(conversationWith, conversationType).then( + (response) => { + console.log("Conversation marked as read", response); + }, + (error) => { + console.log("Error:", error); + } +); +``` + - + -## 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?* +## Real-Time Receipt Events -### Real-time events +Register a `MessageListener` to receive delivery and read 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. +| 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"; + +```typescript +let listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener( - "listenerId", + listenerID, new CometChat.MessageListener({ - onMessagesDelivered: (messageReceipt) => { - console.log("Message is delivered to a user: ", { messageReceipt }); - }, - onMessagesRead: (messageReceipt) => { - console.log("Message is read by a user: ", { messageReceipt }); + onMessagesDelivered: (messageReceipt: CometChat.MessageReceipt) => { + console.log("Message delivered:", messageReceipt); }, - /** This event is only for Group Conversation. */ - onMessagesDeliveredToAll: (messageReceipt) => { - console.log("Message delivered to all members of group: ", { - messageReceipt, - }); + onMessagesRead: (messageReceipt: CometChat.MessageReceipt) => { + console.log("Message read:", messageReceipt); }, - /** This event is only for Group Conversation. */ - onMessagesReadByAll: (messageReceipt) => { - console.log("Message read by all members of group: ", { messageReceipt }); + onMessagesDeliveredToAll: (messageReceipt: CometChat.MessageReceipt) => { + console.log("Message delivered to all group members:", 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, + listenerID, new CometChat.MessageListener({ - onMessagesDelivered: (messageReceipt: CometChat.MessageReceipt) => { - console.log("Message is delivered to a user: ", { messageReceipt }); - }, - onMessagesRead: (messageReceipt: CometChat.MessageReceipt) => { - console.log("Message is read by a user: ", { messageReceipt }); + onMessagesDelivered: (messageReceipt) => { + console.log("Message delivered:", messageReceipt); }, - /** This event is only for Group Conversation. */ - onMessagesDeliveredToAll: (messageReceipt: CometChat.MessageReceipt) => { - console.log("Message delivered to all members of group: ", { - messageReceipt, - }); + onMessagesRead: (messageReceipt) => { + console.log("Message read:", messageReceipt); }, - /** This event is only for Group Conversation. */ - onMessagesReadByAll: (messageReceipt: CometChat.MessageReceipt) => { - console.log("Message read by all members of group: ", { messageReceipt }); + onMessagesDeliveredToAll: (messageReceipt) => { + console.log("Message delivered to all group members:", messageReceipt); }, + onMessagesReadByAll: (messageReceipt) => { + console.log("Message read by all group members:", messageReceipt); + } }) ); ``` - - -**On Event** — `onMessagesDelivered` returns a `MessageReceipt` object for user conversations: - - - -**MessageReceipt Object (onMessagesDelivered):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `receiptType` | string | Type of receipt | `"delivery"` | -| `messageId` | string | ID of the message | `"25323"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `receiver` | string | Receiver's UID | `"cometchat-uid-6"` | -| `deliveredAt` | number | Unix timestamp when delivered | `1772005348` | -| `timestamp` | number | Event timestamp | `1772005348` | -| `sender` | object | User who triggered the receipt | [See below ↓](#on-delivered-sender-object) | - ---- - - +You will receive events in the form of [`MessageReceipt`](/sdk/reference/auxiliary#messagereceipt) objects containing the following parameters: -**`sender` Object (onMessagesDelivered):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771853565` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - -**On Event** — `onMessagesRead` returns a `MessageReceipt` object for user conversations: - - - -**MessageReceipt Object (onMessagesRead):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `receiptType` | string | Type of receipt | `"read"` | -| `messageId` | string | ID of the message | `"25323"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `receiver` | string | Receiver's UID | `"cometchat-uid-6"` | -| `readAt` | number | Unix timestamp when read | `1772005377` | -| `timestamp` | number | Event timestamp | `1772005377` | -| `sender` | object | User who triggered the receipt | [See below ↓](#on-read-sender-object) | - ---- - - - -**`sender` Object (onMessagesRead):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771853565` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - -**On Event** — `onMessagesDeliveredToAll` returns a `MessageReceipt` object for group conversations (sender is System): - - - -**MessageReceipt Object (onMessagesDeliveredToAll):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `receiptType` | string | Type of receipt | `"deliveredToAll"` | -| `messageId` | string | ID of the message | `"25325"` | -| `receiverType` | string | Type of receiver | `"group"` | -| `receiver` | string | Group GUID | `"tg1"` | -| `deliveredAt` | number | Unix timestamp when delivered to all | `1772005516` | -| `timestamp` | number | Event timestamp | `1772005516` | -| `sender` | object | System user object | [See below ↓](#on-delivered-all-sender-object) | - ---- - - - -**`sender` Object (onMessagesDeliveredToAll):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | System user identifier | `"app_system"` | -| `name` | string | System user name | `"System"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - -**On Event** — `onMessagesReadByAll` returns a `MessageReceipt` object for group conversations (sender is System): - - - -**MessageReceipt Object (onMessagesReadByAll):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `receiptType` | string | Type of receipt | `"readByAll"` | -| `messageId` | string | ID of the message | `"25325"` | -| `receiverType` | string | Type of receiver | `"group"` | -| `receiver` | string | Group GUID | `"tg1"` | -| `readAt` | number | Unix timestamp when read by all | `1772005546` | -| `timestamp` | number | Event timestamp | `1772005546` | -| `sender` | object | System user object | [See below ↓](#on-read-all-sender-object) | - ---- +| 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](/sdk/reference/entities#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. Only present if the receiptType is delivered. | +| `readAt` | The timestamp of the time when the message was read. Only present when the receiptType is read. | - +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. -**`sender` Object (onMessagesReadByAll):** + -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | System user identifier | `"app_system"` | -| `name` | string | System user name | `"System"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +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 - + -**Listener Cleanup Required** — Always remove your message listener when the component unmounts or the listener is no longer needed to avoid memory leaks and duplicate event handling: +Always remove listeners when no longer needed to prevent memory leaks. In React Native, place this in a cleanup function inside `useEffect` or in `componentWillUnmount`. ```javascript CometChat.removeMessageListener("UNIQUE_LISTENER_ID"); ``` - -In React Native, place this in a cleanup function inside `useEffect` or in `componentWillUnmount`. -You will receive events in the form of `MessageReceipt` objects. The message receipt contains the below parameters: - -| 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. | - -### Missed Receipts +### MessageReceipt Object -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. +The listener callbacks receive a [`MessageReceipt`](/sdk/reference/auxiliary#messagereceipt) object: -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. +| Field | Getter | Return Type | Description | +| --- | --- | --- | --- | +| messageId | `getMessageId()` | `string` | ID of the message | +| sender | `getSender()` | [`User`](/sdk/reference/entities#user) | User who triggered the receipt | +| 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 | -### Receipt History for a Single Message +## Get Receipt History -{/* Fetch delivery & read receipts for a specific message — CometChat.getMessageReceipts(messageId) - Returns a list of MessageReceipt objects with per-user delivery/read status. */} - -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; + +```typescript +let messageId: number = 123; + CometChat.getMessageReceipts(messageId).then( - (receipts) => { - console.log("Message details fetched:", receipts); + (receipts: CometChat.MessageReceipt[]) => { + console.log("Message receipts:", receipts); }, - (error) => { - console.log("Error in getting messag details ", error); + (error: CometChat.CometChatException) => { + console.log("Error fetching receipts:", error); } ); ``` - + +```javascript +let messageId = 123; - -```typescript -let messageId: number = 1; CometChat.getMessageReceipts(messageId).then( - (receipts: CometChat.MessageReceipt[]) => { - console.log("Message details fetched:", receipts); + (receipts) => { + console.log("Message receipts:", receipts); }, - (error: CometChat.CometChatException) => { - console.log("Error in getting messag details ", error); + (error) => { + console.log("Error fetching receipts:", error); } ); ``` - - -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. +Returns an array of [`MessageReceipt`](/sdk/reference/auxiliary#messagereceipt) objects. -* `onMessagesDeliveredToAll` event, -* `onMessagesReadByAll` event, -* `deliveredAt` field in a group message, -* `readAt` field in a group message. -* `markMessageAsUnread` method. - - +## Missed Receipts -## Best Practices +When fetching messages, each message object includes `deliveredAt` and `readAt` timestamps indicating when the message was delivered and read. - - - Mark messages as **delivered** as soon as they are received by the device — typically when fetching messages or receiving a real-time message while the app is open. Mark messages as **read** only when the user actually views the conversation or message. This distinction gives senders accurate insight into whether their message reached the device versus was actually seen. - - - - Rather than calling `markAsDelivered()` for every individual message, pass the **last message** in a fetched list. The SDK marks all prior messages in that conversation as delivered automatically, reducing unnecessary API calls. - - - - Remove message listeners when a component unmounts using `CometChat.removeMessageListener(listenerId)`. Failing to do so can cause memory leaks, duplicate callbacks, and unexpected behavior — especially in React Native navigation flows where screens may mount and unmount frequently. - +```javascript +let deliveredAt = message.getDeliveredAt(); +let readAt = message.getReadAt(); +``` - - Prefer passing the full `BaseMessage` object to `markAsDelivered()` and `markAsRead()` instead of individual parameters. This is simpler, less error-prone, and ensures the SDK has all the context it needs. - - +## Mark as Unread -## Troubleshooting +Use `markMessageAsUnread()` to mark a message as unread. This is useful for "mark as unread" functionality in conversation lists. - - - Ensure you have registered a `MessageListener` with `CometChat.addMessageListener()` **before** the receipt events are dispatched. Verify the listener ID is unique and that you haven't accidentally removed the listener elsewhere. Also confirm the user is logged in and the WebSocket connection is active. - + +You cannot mark your own messages as unread. This method only works for messages received from other users. + - - Check that you are passing valid parameters — `messageId`, `receiverId`, `receiverType`, and `senderId` must all be correct. For group messages, `receiverId` should be the group GUID, not a user UID. Use the `.then()` error callback to inspect the `CometChatException` for details. - + + +```typescript +CometChat.markMessageAsUnread(message).then( + (conversation: CometChat.Conversation) => { + console.log("Message marked as unread:", conversation); + console.log("Unread message count:", conversation.getUnreadMessageCount()); + }, + (error: CometChat.CometChatException) => { + console.log("Error marking as unread:", error); + } +); +``` + + +```javascript +CometChat.markMessageAsUnread(message).then( + (conversation) => { + console.log("Message marked as unread:", conversation); + console.log("Unread message count:", conversation.getUnreadMessageCount()); + }, + (error) => { + console.log("Error marking as unread:", error); + } +); +``` + + - - These events require the **Enhanced Messaging Status** feature to be enabled for your app in the [CometChat Dashboard](https://app.cometchat.com). Verify this setting is turned on if you rely on group-level delivery and read tracking. - +| Parameter | Type | Description | +|-----------|------|-------------| +| `message` | [`BaseMessage`](/sdk/reference/messages#basemessage) | The message object to mark as unread | - - You cannot mark your own messages as unread — this method only works for messages received from other users. Additionally, the `markMessageAsUnread` method requires the **Enhanced Messaging Status** feature to be enabled. - - +--- ## Next Steps - - Learn how to send text, media, and custom messages to users and groups. + + Show real-time typing status in conversations - - Set up real-time message listeners and fetch missed messages. + + Listen for incoming messages in real time - Fetch and display the user's conversation list with unread counts. + Fetch conversation list with unread counts - - Show real-time typing status in one-on-one and group chats. + + Complete reference for all SDK event listeners diff --git a/sdk/react-native/direct-call.mdx b/sdk/react-native/direct-call.mdx index 0ae7b7815..9ad2f0bbb 100644 --- a/sdk/react-native/direct-call.mdx +++ b/sdk/react-native/direct-call.mdx @@ -1,41 +1,41 @@ --- title: "Call Session" -description: "Start and manage call sessions in your React Native app using the CometChat Calls SDK, including token generation, call settings, listeners, and session control." +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 React Native Calls SDK." --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference** - Generate token and start a call session: + ```javascript +let sessionId = "SESSION_ID"; +let userAuthToken = "AUTH_TOKEN"; +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, userAuthToken); -// Configure and render +// Build call settings const callSettings = new CometChatCalls.CallSettingsBuilder() .enableDefaultLayout(true) .setIsAudioOnlyCall(false) + .setCallEventListener(callListener) .build(); +// Render call component // -``` - - -## Overview - -This section demonstrates how to start a call session in a React Native application. Previously known as **Direct Calling**. - - -**Available via:** SDK | UI Kits - -Before you begin, we strongly recommend you read the [calling setup guide](/sdk/react-native/calling-setup). - - +// End call session +CometChatCalls.endSession(); +``` + -If you want to implement a complete calling experience with ringing functionality (incoming/outgoing call UI), follow the [Ringing](/sdk/react-native/default-call) guide first. Once the call is accepted, return here to start the call session. +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/react-native/default-call), your own custom UI, or [Standalone Calling](/sdk/react-native/standalone-calling), this page covers how to manage the session itself. - +Before you begin, make sure you've completed the [Calls SDK Setup](/sdk/react-native/calling-setup). ## Generate Call Token @@ -43,105 +43,87 @@ 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. - -```javascript + +```typescript const loggedInUser = await CometChat.getLoggedinUser(); const userAuthToken = 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, userAuthToken).then( - (callToken) => { + (callToken: GenerateToken) => { 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 userAuthToken = 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, userAuthToken).then( - (callToken: GenerateToken) => { + (callToken) => { console.log("Call token generated:", callToken.token); // Use callToken to start the session }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Token generation failed:", error); } ); ``` - - | 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. | -| `userAuthToken` | The user auth token is the logged-in user auth token which you can get by calling CometChat Chat SDK method `CometChat.getLoggedinUser().getAuthToken()` | - - -**On Success** — `generateToken()` returns a `GenerateToken` object containing the session ID and JWT token: - - +| `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. | +| `userAuthToken` | The user auth token is the logged-in user auth token which you can get by calling `CometChat.getLoggedinUser().getAuthToken()` | -**GenerateToken Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sessionId` | string | Unique identifier for the call session | `"v1.in.2748663902141719.1772095292a49c6a5198e07f9096447749e87124204d95cfc8"` | -| `token` | string | JWT token for authenticating the call session | `"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6ImNjcHJvX2p3dF9yczI1Nl9rZXkxIn0..."` | - - +The `Promise` resolves with an object containing a `token` property (string) that you pass to the `CometChatCalls.Component`. ## Start Call Session Use the `CometChatCalls.Component` to render the call UI. This component requires a call token (generated in the previous step) and a `CallSettings` object that configures the call UI and behavior. -The `CallSettings` class configures the call UI and behavior. Use `CallSettingsBuilder` to create a `CallSettings` instance. - - -```javascript + +```typescript const callListener = new CometChatCalls.OngoingCallListener({ - onUserJoined: (user) => { + onUserJoined: (user: CometChat.User) => { console.log("User joined:", user); }, - onUserLeft: (user) => { + onUserLeft: (user: CometChat.User) => { console.log("User left:", user); }, - onUserListUpdated: (userList) => { + onUserListUpdated: (userList: CometChat.User[]) => { console.log("User list updated:", userList); }, onCallEnded: () => { console.log("Call ended"); - // Clear Active Call and End Session - see End Call Session section }, onCallEndButtonPressed: () => { console.log("End call button pressed"); // Handle end call - see End Call Session section }, - onError: (error) => { + onError: (error: CometChat.CometChatException) => { console.log("Call error:", error); }, - onAudioModesUpdated: (audioModes) => { + onAudioModesUpdated: (audioModes: string[]) => { console.log("Audio modes updated:", audioModes); }, - onCallSwitchedToVideo: (event) => { + onCallSwitchedToVideo: (event: any) => { console.log("Call switched to video:", event); }, - onUserMuted: (event) => { + onUserMuted: (event: any) => { console.log("User muted:", event); }, onSessionTimeout: () => { @@ -162,39 +144,36 @@ return ( ); ``` - - - -```typescript + +```javascript const callListener = new CometChatCalls.OngoingCallListener({ - onUserJoined: (user: CometChat.User) => { + onUserJoined: (user) => { console.log("User joined:", user); }, - onUserLeft: (user: CometChat.User) => { + onUserLeft: (user) => { console.log("User left:", user); }, - onUserListUpdated: (userList: CometChat.User[]) => { + onUserListUpdated: (userList) => { console.log("User list updated:", userList); }, onCallEnded: () => { console.log("Call ended"); - // Clear Active Call and End Session - see End Call Session section }, onCallEndButtonPressed: () => { console.log("End call button pressed"); // Handle end call - see End Call Session section }, - onError: (error: CometChat.CometChatException) => { + onError: (error) => { console.log("Call error:", error); }, - onAudioModesUpdated: (audioModes: string[]) => { + onAudioModesUpdated: (audioModes) => { console.log("Audio modes updated:", audioModes); }, - onCallSwitchedToVideo: (event: any) => { + onCallSwitchedToVideo: (event) => { console.log("Call switched to video:", event); }, - onUserMuted: (event: any) => { + onUserMuted: (event) => { console.log("User muted:", event); }, onSessionTimeout: () => { @@ -215,9 +194,7 @@ return ( ); ``` - - | Parameter | Description | @@ -225,16 +202,15 @@ return ( | `callToken` | The `GenerateToken` object received from `generateToken()` onSuccess | | `callSettings` | Object of `CallSettings` class configured via `CallSettingsBuilder` | - ### Call Settings Configure the call experience using the following `CallSettingsBuilder` methods: | Method | Description | | ------ | ----------- | -| `enableDefaultLayout(boolean)` | Enables or disables the default call UI layout with built-in controls. `true` shows the default layout with end call, mute, video toggle buttons. `false` hides the button layout. Default: `true` | +| `enableDefaultLayout(boolean)` | Enables or disables the default call UI layout with built-in controls. `true` shows the default layout. `false` hides the button layout. Default: `true` | | `setIsAudioOnlyCall(boolean)` | Sets whether the call is audio-only or audio-video. `true` for audio-only, `false` for audio-video. Default: `false` | -| `setCallEventListener(OngoingCallListener)` | Sets the listener to receive call events. See [Call Listeners](#call-listeners) for available callbacks. | +| `setCallEventListener(OngoingCallListener)` | Sets the listener to receive call events. See [Call Listeners](#call-listeners). | | `setMode(string)` | Sets the call UI layout mode. Available: `CometChat.CALL_MODE.DEFAULT` (grid), `CometChat.CALL_MODE.SPOTLIGHT` (active speaker), `CometChat.CALL_MODE.SINGLE` (one participant). Default: `DEFAULT` | | `setAvatarMode(string)` | Sets how avatars are displayed when video is off. Available: `circle`, `square`, `fullscreen`. Default: `circle` | | `setDefaultAudioMode(string)` | Sets the initial audio output device. Available: `SPEAKER`, `EARPIECE`, `BLUETOOTH`, `HEADPHONES` | @@ -251,6 +227,111 @@ Configure the call experience using the following `CallSettingsBuilder` methods: | `enableVideoTileDrag(boolean)` | Enables or disables drag functionality for video tiles in Spotlight mode. Default: `true` | | `setIdleTimeoutPeriod(number)` | Sets idle timeout in seconds. Warning appears 60 seconds before auto-termination. Default: `180` seconds. *v4.2.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/react-native/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 presses 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. @@ -265,19 +346,19 @@ Each listener requires a unique `listenerId` string. This ID is used to: - **Enable targeted removal** — Remove specific listeners without affecting others - -```javascript + +```typescript useEffect(() => { - const listenerId = "UNIQUE_LISTENER_ID"; + const listenerId: string = "UNIQUE_LISTENER_ID"; CometChatCalls.addCallEventListener(listenerId, { - onUserJoined: (user) => { + onUserJoined: (user: CometChat.User) => { console.log("User joined:", user); }, - onUserLeft: (user) => { + onUserLeft: (user: CometChat.User) => { console.log("User left:", user); }, - onUserListUpdated: (userList) => { + onUserListUpdated: (userList: CometChat.User[]) => { console.log("User list updated:", userList); }, onCallEnded: () => { @@ -286,16 +367,16 @@ useEffect(() => { onCallEndButtonPressed: () => { console.log("End call button pressed"); }, - onError: (error) => { + onError: (error: CometChat.CometChatException) => { console.log("Call error:", error); }, - onAudioModesUpdated: (audioModes) => { + onAudioModesUpdated: (audioModes: string[]) => { console.log("Audio modes updated:", audioModes); }, - onCallSwitchedToVideo: (event) => { + onCallSwitchedToVideo: (event: any) => { console.log("Call switched to video:", event); }, - onUserMuted: (event) => { + onUserMuted: (event: any) => { console.log("User muted:", event); }, onSessionTimeout: () => { @@ -307,22 +388,20 @@ useEffect(() => { return () => CometChatCalls.removeCallEventListener(listenerId); }, []); ``` - - - -```typescript + +```javascript useEffect(() => { - const listenerId: string = "UNIQUE_LISTENER_ID"; + const listenerId = "UNIQUE_LISTENER_ID"; CometChatCalls.addCallEventListener(listenerId, { - onUserJoined: (user: CometChat.User) => { + onUserJoined: (user) => { console.log("User joined:", user); }, - onUserLeft: (user: CometChat.User) => { + onUserLeft: (user) => { console.log("User left:", user); }, - onUserListUpdated: (userList: CometChat.User[]) => { + onUserListUpdated: (userList) => { console.log("User list updated:", userList); }, onCallEnded: () => { @@ -331,16 +410,16 @@ useEffect(() => { onCallEndButtonPressed: () => { console.log("End call button pressed"); }, - onError: (error: CometChat.CometChatException) => { + onError: (error) => { console.log("Call error:", error); }, - onAudioModesUpdated: (audioModes: string[]) => { + onAudioModesUpdated: (audioModes) => { console.log("Audio modes updated:", audioModes); }, - onCallSwitchedToVideo: (event: any) => { + onCallSwitchedToVideo: (event) => { console.log("Call switched to video:", event); }, - onUserMuted: (event: any) => { + onUserMuted: (event) => { console.log("User muted:", event); }, onSessionTimeout: () => { @@ -352,18 +431,21 @@ useEffect(() => { return () => CometChatCalls.removeCallEventListener(listenerId); }, []); ``` - - Always remove call event listeners when the component unmounts using `CometChatCalls.removeCallEventListener(listenerId)`. Failing to remove listeners can cause memory leaks and duplicate event handling. - +```javascript +CometChatCalls.removeCallEventListener("UNIQUE_LISTENER_ID"); +``` + ### Events +For the full list of callbacks, their descriptions, and parameter shapes, see the [`OngoingCallListener`](/sdk/react-native/all-real-time-listeners#ongoing-call-listener-calls-sdk) reference. + | 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. | @@ -379,450 +461,32 @@ Always remove call event listeners when the component unmounts using `CometChatC | `onScreenShareStopped()` | Invoked when the local user stops sharing a screen. | | `onError(error)` | Invoked when an error occurs during the call session. | - -**On Event** — `onUserJoined` returns a user object when a participant joins the call: +The ringing flow methods (`initiateCall()`, `acceptCall()`, `rejectCall()`, `endCall()`) return [`Call`](/sdk/reference/messages#call) objects. - +## In-Call Methods -**User Object:** +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. -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"cometchat-uid-6"` | -| `name` | string | Display name of the user | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `id` | string | Internal session participant ID | `"cd530243"` | -| `joinedAt` | string | Unix timestamp when user joined (as string) | `"1772095303043"` | -| `isVideoMuted` | boolean | Whether user's video is muted | `true` | -| `isAudioMuted` | boolean | Whether user's audio is muted | `false` | -| `isLocalUser` | boolean | Whether this is the local user | `false` | + +These methods can only be called when a call session is active. + - +### Switch Camera - -**On Event** — `onUserLeft` returns a user object when a participant leaves the call: +Toggles between the front and rear camera during a video call. - - -**User Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"cometchat-uid-6"` | -| `name` | string | Display name of the user | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `id` | string | Internal session participant ID | `"cd530243"` | -| `joinedAt` | string | Unix timestamp when user joined (as string) | `"1772095303043"` | -| `isVideoMuted` | boolean | Whether user's video was muted | `true` | -| `isAudioMuted` | boolean | Whether user's audio was muted | `false` | - - - - -**On Event** — `onUserListUpdated` returns an array of all current participants in the call: - - - -**User Array:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| (array) | array | Array of user objects | [See below ↓](#on-user-list-updated-user-object) | - - - -**User Object (each item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"cometchat-uid-7"` | -| `name` | string | Display name of the user | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | - - - - -**On Event** — `onAudioModesUpdated` returns an array of available audio output modes: - - - -**Audio Modes Array:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| (array) | array | Array of audio mode objects | [See below ↓](#on-audio-modes-updated-mode-object) | - - - -**Audio Mode Object (each item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `type` | string | Type of audio output device | `"SPEAKER"` | -| `selected` | boolean | Whether this mode is currently selected | `true` | - - - - -**On Event** — `onCallSwitchedToVideo` is invoked when an audio call is upgraded to video. This event may not include additional data. - - -## 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/react-native/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 presses 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 -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); - } - ); -} -``` - - - - -```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); - } - ); -} -``` - - - - - - -**On Success** — `CometChat.endCall()` returns a `Call` object with the final call status: - - - -**Call Object (Root Level):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `reactions` | array | List of reactions on the call | `[]` | -| `mentionedUsers` | array | List of mentioned users | `[]` | -| `mentionedMe` | boolean | Whether current user was mentioned | `false` | -| `receiverId` | string | UID of the call receiver | `"cometchat-uid-6"` | -| `type` | string | Type of call | `"audio"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `category` | string | Message category | `"call"` | -| `action` | string | Call action | `"ended"` | -| `sessionId` | string | Unique session identifier | `"v1.in.2748663902141719.1772095292a49c6a5198e07f9096447749e87124204d95cfc8"` | -| `status` | string | Current call status | `"ended"` | -| `metadata` | object | Custom metadata attached to the call | `{"new": "metajson"}` | -| `initiatedAt` | number | Unix timestamp when call was initiated | `1772095292` | -| `id` | string | Unique message ID | `"25424"` | -| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `sender` | object | User who initiated the call | [See below ↓](#end-call-sender-object) | -| `receiver` | object | User receiving the call | [See below ↓](#end-call-receiver-object) | -| `data` | object | Additional call data | [See below ↓](#end-call-data-object) | -| `sentAt` | number | Unix timestamp when call message was sent | `1772095553` | -| `updatedAt` | number | Unix timestamp of last update | `1772095553` | -| `callInitiator` | object | User who initiated the call | [See below ↓](#end-call-initiator-object) | -| `callReceiver` | object | User receiving the call | [See below ↓](#end-call-call-receiver-object) | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | -| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | -| `uid` | string | Unique user identifier | `"cometchat-uid-7"` | -| `name` | string | Display name of the user | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1772094890` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `tags` | array | Tags associated with the user | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | -| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | -| `uid` | string | Unique user identifier | `"cometchat-uid-6"` | -| `name` | string | Display name of the user | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1772094886` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `tags` | array | Tags associated with the user | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `action` | string | Call action type | `"ended"` | -| `entities` | object | Entity details for the call | [See below ↓](#end-call-data-entities-object) | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-3e152d60-8e2b-435b-86cd-0c0fe3bbc6e1-1772094888945"` | - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `by` | object | User who performed the action | [See below ↓](#end-call-data-entities-by-object) | -| `for` | object | User the action was performed for | [See below ↓](#end-call-data-entities-for-object) | -| `on` | object | The call entity | [See below ↓](#end-call-data-entities-on-object) | - - - -**`data.entities.by` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entity` | object | User entity details | [See below ↓](#end-call-data-entities-by-entity-object) | -| `entityType` | string | Type of entity | `"user"` | - - - -**`data.entities.by.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user identifier | `"cometchat-uid-7"` | -| `name` | string | Display name of the user | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1772094890` | -| `tags` | array | Tags associated with the user | `[]` | - - - -**`data.entities.for` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entity` | object | User entity details | [See below ↓](#end-call-data-entities-for-entity-object) | -| `entityType` | string | Type of entity | `"user"` | - - - -**`data.entities.for.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique user identifier | `"cometchat-uid-6"` | -| `name` | string | Display name of the user | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1772094886` | -| `conversationId` | string | Conversation ID for this user | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `tags` | array | Tags associated with the user | `[]` | - - - -**`data.entities.on` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entity` | object | Call entity details | [See below ↓](#end-call-data-entities-on-entity-object) | -| `entityType` | string | Type of entity | `"call"` | - - - -**`data.entities.on.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sessionid` | string | Unique session identifier | `"v1.in.2748663902141719.1772095292a49c6a5198e07f9096447749e87124204d95cfc8"` | -| `conversationId` | string | Conversation ID | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `sender` | string | UID of the call sender | `"cometchat-uid-7"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `receiver` | string | UID of the call receiver | `"cometchat-uid-6"` | -| `status` | string | Call status | `"ended"` | -| `type` | string | Type of call | `"audio"` | -| `data` | object | Nested call data | `{...}` | -| `initiatedAt` | number | Unix timestamp when call was initiated | `1772095292` | -| `startedAt` | number | Unix timestamp when call started | `1772095302` | -| `endedAt` | number | Unix timestamp when call ended | `1772095553` | -| `duration` | number | Call duration in seconds | `251` | - ---- - - - -**`callInitiator` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | -| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | -| `uid` | string | Unique user identifier | `"cometchat-uid-7"` | -| `name` | string | Display name of the user | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1772094890` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `tags` | array | Tags associated with the user | `[]` | - ---- - - - -**`callReceiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | -| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | -| `uid` | string | Unique user identifier | `"cometchat-uid-6"` | -| `name` | string | Display name of the user | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1772094886` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `tags` | array | Tags associated with the user | `[]` | - - - -**Remote participant** (receives the `onCallEnded()` callback): - -Call `CometChat.clearActiveCall()` to clear the local call state, then call `CometChatCalls.endSession()` to release media resources. - - - -```javascript -onCallEnded: () => { - CometChat.clearActiveCall(); - CometChatCalls.endSession(); - // Close the calling screen -} -``` - - - - -```typescript -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. - - - -```javascript -onCallEndButtonPressed: () => { - CometChatCalls.endSession(); - // Close the calling screen -} -``` - - - - -```typescript -onCallEndButtonPressed: () => { - CometChatCalls.endSession(); - // Close the calling screen -} -``` - - - - - - -## 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. - - -These methods can only be called when a call session is active. - - -### Switch Camera - -Toggles between the front and rear camera during a video call. Useful for allowing users to switch their camera view without leaving the call. - - - -```javascript -CometChatCalls.switchCamera(); -``` - - - - -```typescript -CometChatCalls.switchCamera(); -``` - - - - + + +```typescript +CometChatCalls.switchCamera(); +``` + + +```javascript +CometChatCalls.switchCamera(); +``` + + ### Mute Audio @@ -832,20 +496,16 @@ 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); ``` - - ### Pause Video @@ -856,20 +516,16 @@ 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); ``` - - ### Set Audio Mode @@ -883,41 +539,16 @@ Routes the audio output to a specific device. Use this to let users choose betwe - `CometChat.AUDIO_MODE.HEADPHONES` — Wired headphones - -```javascript -CometChatCalls.setAudioMode(CometChat.AUDIO_MODE.EARPIECE); -``` - - - ```typescript CometChatCalls.setAudioMode(CometChat.AUDIO_MODE.EARPIECE); ``` - - - - -### 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. - - ```javascript -CometChatCalls.switchToVideoCall(); -``` - - - - -```typescript -CometChatCalls.switchToVideoCall(); +CometChatCalls.setAudioMode(CometChat.AUDIO_MODE.EARPIECE); ``` - - ### Get Audio Output Modes @@ -925,137 +556,160 @@ CometChatCalls.switchToVideoCall(); Returns the list of available audio output devices. Use this to display audio options to the user and then set the selected mode using `setAudioMode()`. - -```javascript + +```typescript CometChatCalls.getAudioOutputModes().then( - (modes) => { + (modes: CometChat.AudioMode[]) => { console.log("Available audio modes:", modes); - // Each mode has: mode (string) and isSelected (boolean) }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Failed to get audio modes:", error); } ); ``` - - - -```typescript + +```javascript CometChatCalls.getAudioOutputModes().then( - (modes: CometChat.AudioMode[]) => { + (modes) => { console.log("Available audio modes:", modes); - // Each mode has: mode (string) and isSelected (boolean) }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Failed to get audio modes:", error); } ); ``` - - - -**On Success** — `getAudioOutputModes()` returns an object containing an array of available audio modes: - - +### Switch To Video Call -**Response Object:** +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. -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `modes` | array | Array of available audio output modes | [See below ↓](#get-audio-modes-mode-object) | + + +```typescript +CometChatCalls.switchToVideoCall(); +``` + + +```javascript +CometChatCalls.switchToVideoCall(); +``` + + - +### End Call -**Mode Object (each item in `modes` array):** +Terminates the current call session and releases all media resources (camera, microphone, network connections). After calling this method, the call view should be closed. -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `type` | string | Type of audio output device | `"SPEAKER"` | -| `selected` | boolean | Whether this mode is currently selected | `true` | + + +```javascript +CometChatCalls.endSession(); +``` + + - +## Utility Methods -### End Call +### Get Active Call -Terminates the current call session and releases all media resources (camera, microphone, network connections). After calling this method, the call view should be closed. +Returns the current active [`Call`](/sdk/reference/messages#call) object, or `undefined` if no call is in progress. + +```typescript +const activeCall: CometChat.Call | undefined = CometChat.getActiveCall(); +if (activeCall) { + console.log("Active call session:", activeCall.getSessionId()); +} +``` + ```javascript -CometChatCalls.endSession(); +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. + + ```typescript -CometChatCalls.endSession(); +CometChat.clearActiveCall(); +``` + + +```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); + } +); +``` + - -## Best Practices - - - - Call tokens are session-specific and time-limited. Generate them right before starting the call session rather than caching them for extended periods. This ensures the token is fresh and reduces the chance of token expiry errors. - - - When using the Ringing flow, remember to call both `CometChat.endCall()` and `CometChatCalls.endSession()`. Missing either call can leave the session in an inconsistent state — the Chat SDK may still show the call as active, or media resources may not be released properly. - - - Always remove call event listeners in your component's cleanup function (e.g., the return function of `useEffect`). Orphaned listeners can cause memory leaks, duplicate event handling, and unexpected behavior when navigating between screens. - - - The `CometChatCalls.Component` should be rendered inside a `View` with `height: '100%'`, `width: '100%'`, and `position: 'relative'`. This ensures the call UI fills the screen correctly and overlays render in the right position. - - - When registering call event listeners with `addCallEventListener`, use a unique `listenerId` per component instance. This prevents one component from accidentally overwriting another component's listener, especially in navigation stacks where multiple screens may be mounted simultaneously. - - - -## Troubleshooting - - - - Ensure the user is logged in and the auth token is valid. Call `CometChat.getLoggedinUser()` to verify the user session is active. If the auth token has expired, re-authenticate the user before generating a call token. - - - Verify that the `CometChatCalls.Component` is wrapped in a `View` with explicit dimensions (`height: '100%'`, `width: '100%'`). The component requires a sized container to render. Also confirm that both `callSettings` and `callToken` props are provided and not `null` or `undefined`. - - - Check that the listener is registered before the call session starts. If using `addCallEventListener`, ensure the `listenerId` is unique and hasn't been overwritten by another registration. Also verify that the Calls SDK has been initialized via `CometChatCalls.init()`. - - - The `onCallEnded` callback only fires for 1:1 calls (exactly 2 participants). For group calls, use `onUserLeft` and `onUserListUpdated` to track when participants leave, and handle session cleanup based on your app's logic. - - - Check device permissions for camera and microphone. On React Native, you need to request `CAMERA` and `RECORD_AUDIO` permissions on Android, and add `NSCameraUsageDescription` and `NSMicrophoneUsageDescription` to `Info.plist` on iOS. Also verify that `setIsAudioOnlyCall` matches your intended call type. - - +| Parameter | Type | Description | +|-----------|------|-------------| +| `sessionId` | `string` | The call session ID | +| `type` | `string` | Call type: `"direct"` or `"default"` | --- ## Next Steps - - Implement a complete calling experience with incoming and outgoing call UI + + Implement calls with incoming/outgoing ringing UI - Record call sessions for playback and compliance + Record call sessions for playback - - Customize the main video container and participant tiles + + Customize the video layout and main video container - - Enable screen sharing and presenter layouts in calls + + Retrieve and display call history - \ No newline at end of file + diff --git a/sdk/react-native/edit-message.mdx b/sdk/react-native/edit-message.mdx index 863aaf2b4..e5f36e650 100644 --- a/sdk/react-native/edit-message.mdx +++ b/sdk/react-native/edit-message.mdx @@ -1,102 +1,84 @@ --- -title: "Edit A Message" -description: "Edit text and custom messages, listen for real-time edit events, and retrieve missed edits using the CometChat React Native SDK." +title: "Edit Message" +sidebarTitle: "Edit Message" +description: "Edit text and custom messages using the CometChat React Native SDK." --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference** - Edit a text message: + ```javascript -let receiverID = "RECEIVER_UID"; -let messageText = "Updated message text"; +let receiverID = "UID"; let receiverType = CometChat.RECEIVER_TYPE.USER; -let textMessage = new CometChat.TextMessage(receiverID, messageText, receiverType); -textMessage.setId(MESSAGE_ID); +let messageId = "MESSAGE_ID"; -CometChat.editMessage(textMessage).then( - message => console.log("Message Edited", message), - error => console.log("Edit failed:", error) -); -``` - +// Edit a text message +const textMessage = new CometChat.TextMessage(receiverID, "Updated text", receiverType); +textMessage.setId(messageId); +await CometChat.editMessage(textMessage); - -**Available via:** [SDK](/sdk/react-native/edit-message) | [REST API](/rest-api/messages/update-message) | [UI Kits](/ui-kits/react-native/overview) - +// Listen for real-time edits +CometChat.addMessageListener("edits", new CometChat.MessageListener({ + onMessageEdited: (message) => console.log("Edited:", message) +})); +``` + -While [editing a message](/sdk/react-native/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/react-native/edit-message#real-time-message-edit-events) when your app is running. -2. Calling a method to retrieve [missed message edits](/sdk/react-native/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?* - -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`](/sdk/reference/messages#textmessage) or [`CustomMessage`](/sdk/reference/messages#custommessage) object. Set the message ID using `setId()`. ### Add/Update Tags -While editing a message, you can update the tags associated with the message. 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. - -```javascript -let tags = ["pinnedMessage"]; + +```typescript +let tags: Array = ["pinnedMessage"]; textMessage.setTags(tags); ``` + - + ```javascript let tags = ["pinnedMessage"]; -customMessage.setTags(tags); +textMessage.setTags(tags); ``` + - + ```typescript let tags: Array = ["pinnedMessage"]; -textMessage.setTags(tags); +customMessage.setTags(tags); ``` + - -```typescript -let tags: Array = ["pinnedMessage"]; + +```javascript +let tags = ["pinnedMessage"]; 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()`. - -```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"; @@ -116,183 +98,64 @@ CometChat.editMessage(textMessage).then( ); ``` - - - -**On Success** — `editMessage()` returns the edited message object with `editedAt` and `editedBy` fields: - - - -**Message Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25652"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-7"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Edited message text content | `"Nice, Any Update?"` | -| `sentAt` | number | Unix timestamp when originally sent | `1772446840` | -| `editedAt` | number | Unix timestamp when edited | `1772446861` | -| `editedBy` | string | UID of user who edited the message | `"cometchat-uid-6"` | -| `deliveredAt` | number | Unix timestamp when delivered | `1772446841` | -| `readAt` | number | Unix timestamp when read | `1772446841` | -| `updatedAt` | number | Unix timestamp when updated | `1772446841` | -| `sender` | object | Sender user details | [See below ↓](#edit-message-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#edit-message-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#edit-message-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#edit-message-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1772446655` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1772446782` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Nice, Any Update?"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `entities` | object | Sender and receiver entities | [See below ↓](#edit-message-data-entities-object) | -| `metadata` | object | Injected metadata | [See below ↓](#edit-message-data-metadata-object) | -| `moderation` | object | Moderation status | `{"status": "approved"}` | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#edit-message-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#edit-message-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#edit-message-data-entities-sender-entity-object) | - ---- - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1772446655` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#edit-message-data-entities-receiver-entity-object) | - ---- - - + +```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); -**`data.entities.receiver.entity` Object:** +textMessage.setId(messageId); -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1772446782` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `tags` | array | User tags | `[]` | +CometChat.editMessage(textMessage).then( +message => { + console.log("Message Edited", message); +}, error => { + console.log("Message editing failed with error:", error); +} +); +``` ---- +Alternatively, you can use the `async/await` syntax: - +```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); -**`data.metadata` Object:** + textMessage.setId(messageId); -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `edited` | boolean | Indicates message was edited | `true` | + const message = await CometChat.editMessage(textMessage); + console.log("Message Edited", message); +} catch (error) { + console.log("Message editing failed with error:", error); +} +``` + ---- + - +The edited message object is returned with `editedAt` (timestamp) and `editedBy` (UID of editor) fields set. -**`metadata` Object:** +The `editMessage()` method returns a [`BaseMessage`](/sdk/reference/messages#basemessage) object (or a subclass like [`TextMessage`](/sdk/reference/messages#textmessage)). -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `edited` | boolean | Indicates message was edited | `true` | +Relevant fields to access on the returned message: - +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| editedAt | `getEditedAt()` | `number` | Timestamp when the message was edited | +| editedBy | `getEditedBy()` | `string` | UID of the user who edited the message | -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. +By default, CometChat allows certain users to edit a message. -By default, CometChat allows certain roles to edit a message. +Message editing in CometChat is controlled by - -| User Role | Conversation Type | Edit Capabilities | +| User | Conversation Type | Edit Capabilities | | --------------- | ----------------------- | -------------------------- | | Message Sender | One-on-One Conversation | Messages they have sent. | | Message Sender | Group Conversation | Messages they have sent. | @@ -301,432 +164,89 @@ 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?* - -To receive real-time events for a message being edited, you need to override the `onMessageEdited()` method of the `MessageListener` class. +Use `onMessageEdited` in `MessageListener` to receive real-time edit events. - -```javascript -var 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); } }) -); +); ``` + - -```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); } }) ); ``` - - - - -**On Event** — `onMessageEdited` callback receives the edited message object: - - - -**Message Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25652"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-7"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Edited message text content | `"Nice, Any Update?"` | -| `sentAt` | number | Unix timestamp when originally sent | `1772446840` | -| `editedAt` | number | Unix timestamp when edited | `1772446861` | -| `editedBy` | string | UID of user who edited the message | `"cometchat-uid-6"` | -| `deliveredAt` | number | Unix timestamp when delivered | `1772446841` | -| `readAt` | number | Unix timestamp when read | `1772446841` | -| `updatedAt` | number | Unix timestamp when updated | `1772446841` | -| `sender` | object | Sender user details | [See below ↓](#on-message-edited-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#on-message-edited-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#on-message-edited-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#on-message-edited-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1772446655` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1772446782` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Nice, Any Update?"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `entities` | object | Sender and receiver entities | [See below ↓](#on-message-edited-data-entities-object) | -| `metadata` | object | Injected metadata | [See below ↓](#on-message-edited-data-metadata-object) | -| `moderation` | object | Moderation status | `{"status": "approved"}` | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#on-message-edited-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#on-message-edited-data-entities-receiver-object) | ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#on-message-edited-data-entities-sender-entity-object) | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1772446655` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#on-message-edited-data-entities-receiver-entity-object) | - ---- - - - -**`data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1772446782` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `edited` | boolean | Indicates message was edited | `true` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `edited` | boolean | Indicates message was edited | `true` | + - + -Always remove your message listeners when the component unmounts to prevent memory leaks and unexpected behavior. Call `CometChat.removeMessageListener("UNIQUE_LISTENER_ID")` in your cleanup function (e.g., in a `useEffect` return or `componentWillUnmount`). - - -## 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, 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: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25652"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-7"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Edited message text content | `"Nice, Any Update?"` | -| `sentAt` | number | Unix timestamp when originally sent | `1772446840` | -| `editedAt` | number | Unix timestamp when edited | `1772446861` | -| `editedBy` | string | UID of user who edited the message | `"cometchat-uid-6"` | -| `deliveredAt` | number | Unix timestamp when delivered | `1772446841` | -| `readAt` | number | Unix timestamp when read | `1772446841` | -| `updatedAt` | number | Unix timestamp when updated | `1772446841` | -| `sender` | object | Sender user details | [See below ↓](#missed-edit-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#missed-edit-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#missed-edit-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#missed-edit-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1772446655` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1772446782` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Nice, Any Update?"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `entities` | object | Sender and receiver entities | [See below ↓](#missed-edit-data-entities-object) | -| `metadata` | object | Injected metadata | [See below ↓](#missed-edit-data-metadata-object) | -| `moderation` | object | Moderation status | `{"status": "approved"}` | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#missed-edit-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#missed-edit-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#missed-edit-data-entities-sender-entity-object) | +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. ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1772446655` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#missed-edit-data-entities-receiver-entity-object) | - ---- - - - -**`data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1772446782` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `edited` | boolean | Indicates message was edited | `true` | - ---- +```javascript +CometChat.removeMessageListener("UNIQUE_LISTENER_ID"); +``` + - +The `onMessageEdited` callback receives a [`BaseMessage`](/sdk/reference/messages#basemessage) object with the `editedAt` and `editedBy` fields set. -**`metadata` Object:** +Relevant fields to access on the returned message: -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `edited` | boolean | Indicates message was edited | `true` | +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| editedAt | `getEditedAt()` | `number` | Timestamp when the message was edited | +| editedBy | `getEditedBy()` | `string` | UID of the user who edited the message | - +## Missed Message Edit Events -For the message edited event, in the `Action` object received, the following fields can help you get the relevant information: +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. -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`](/sdk/reference/messages#action) object contains: +- `action` — `edited` +- `actionOn` — Updated message object +- `actionBy` — User who edited the message +- `actionFor` — Receiver (User/Group) -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. - - -- Always verify the message type (`TextMessage` or `CustomMessage`) before attempting an edit, as other message types are not supported. -- Use the `editedAt` and `editedBy` fields to display edit indicators in your UI so users know a message has been modified. -- Register your message edit listener early in the component lifecycle to avoid missing real-time edit events. -- When updating tags via `setTags()`, remember that the new tags fully replace any previously set tags — merge existing tags manually if you need to preserve them. - - - -- **Edit fails with permission error**: Ensure the current user is the message sender, or a group owner/moderator for group messages. -- **`onMessageEdited` not firing**: Confirm that `CometChat.addMessageListener()` has been called with a unique listener ID and that the listener has not been removed prematurely. -- **Edited message not reflected in history**: After editing, re-fetch or update the local message list. The `editedAt` field on the message object confirms the edit was applied. -- **Tags not updating**: Make sure you call `setTags()` on the message object before passing it to `editMessage()`. Tags set during editing replace all previous tags. - - +--- ## Next Steps - - Remove messages from conversations for users or groups. - - - Send text, media, and custom messages to users and groups. - - - Listen for incoming messages in real time and fetch missed messages. - - - Send and receive replies within message threads. - + + 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/react-native/expo-integration-guide.mdx b/sdk/react-native/expo-integration-guide.mdx index ed0a8b85f..3ce9c67c4 100644 --- a/sdk/react-native/expo-integration-guide.mdx +++ b/sdk/react-native/expo-integration-guide.mdx @@ -1,43 +1,35 @@ --- title: "Expo Integration" +sidebarTitle: "Expo Integration" description: "Configure CometChat Calls SDK in an Expo React Native app — add dependencies, set Android and iOS permissions, and use development builds instead of Expo GO." --- - -**Quick Reference** - Key Expo setup steps: + -```json -// Android: app.json → android block -"permissions": ["CAMERA", "RECORD_AUDIO", "INTERNET", "MODIFY_AUDIO_SETTINGS"], -"plugins": [["expo-build-properties", { "android": { "minSdkVersion": 24 } }]] +| Key Step | Details | +|----------|---------| +| **Expo GO** | Not supported — use [development builds](https://docs.expo.dev/develop/development-builds/introduction/) | +| **Android** | Add `CAMERA`, `RECORD_AUDIO`, `INTERNET`, `MODIFY_AUDIO_SETTINGS` permissions; set `minSdkVersion: 24` | +| **iOS** | Add `NSCameraUsageDescription` and `NSMicrophoneUsageDescription` to `infoPlist` | +| **Package** | Install `expo-build-properties` for Android config | -// iOS: app.json → ios block -"infoPlist": { - "NSCameraUsageDescription": "This app uses the camera for video calls.", - "NSMicrophoneUsageDescription": "This app uses the microphone for audio/video calls." -} -``` - + -## Add the CometChatCalls Dependency + +Expo GO is not supported. You must use [development builds](https://docs.expo.dev/develop/development-builds/introduction/) to use the CometChat Calls SDK in an Expo app. + - +The CometChat React Native Calls SDK requires custom native modules, which means Expo GO cannot be used. Follow the official Expo [guide](https://docs.expo.dev/guides/local-app-development/) to set up development builds. -To add CometChat Calls SDK, please refer to the steps mentioned [here](/sdk/react-native/calling-setup#add-the-cometchatcalls-dependency). +## Add the CometChatCalls Dependency - +To add the CometChat Calls SDK, refer to the steps in the [Calling Setup guide](/sdk/react-native/calling-setup#add-the-cometchatcalls-dependency). ## Permissions -Our React Native Calls SDK does not work with Expo GO since it requires some custom native modules. Also, expo does not recommend using Expo GO for building production grade apps. So in order to use our Calls SDK in an expo app you need to use [development builds](https://docs.expo.dev/develop/development-builds/introduction/). You can follow the official Expo [guide](https://docs.expo.dev/guides/local-app-development/) for more details. - - -Expo GO is not supported. You must use [development builds](https://docs.expo.dev/develop/development-builds/introduction/) to use the CometChat Calls SDK in an Expo app. - - ### Android -You need to add the below `permissions` & `plugin` block inside `android` block of the `app.json` file. You need to install `expo-build-properties` package in your app. +Add the following `permissions` and `plugins` block inside the `android` block of your `app.json`. You need to install the `expo-build-properties` package in your app. @@ -64,56 +56,34 @@ You need to add the below `permissions` & `plugin` block inside `android` block ] ] ``` - - ### iOS -You need to add the below `permissions` block inside `ios` block of the `app.json` file. +Add the following `infoPlist` block inside the `ios` block of your `app.json`: ```json "infoPlist": { "NSCameraUsageDescription": "This app uses the camera for video calls.", - "NSMicrophoneUsageDescription": "This app uses the microphonr for audio/video calls." + "NSMicrophoneUsageDescription": "This app uses the microphone for audio/video calls." } ``` - - ## Initialize CometChat Calls - - -To initialize CometChat Calls SDK, please refer to the guide [here](/sdk/react-native/calling-setup#initialize-cometchatcalls) - - - -## Troubleshooting - - - - Ensure you're using a development build, not Expo GO. Run `npx expo prebuild` followed by `npx expo run:android` or `npx expo run:ios` to create a development build with native modules. - - - Verify that `minSdkVersion` is set to at least `24` in the `expo-build-properties` plugin config. The CometChat Calls SDK requires Android API level 24 or higher. - - - Check that `NSCameraUsageDescription` and `NSMicrophoneUsageDescription` are set in the `infoPlist` block of your `app.json`. Without these, iOS will silently deny access to camera and microphone. - - +To initialize the CometChat Calls SDK, refer to the [initialization guide](/sdk/react-native/calling-setup#initialize-cometchatcalls). --- ## Next Steps - + Complete Calls SDK installation and initialization guide @@ -125,4 +95,4 @@ To initialize CometChat Calls SDK, please refer to the guide [here](/sdk/react-n Set up the core CometChat Chat SDK for React Native - \ No newline at end of file + diff --git a/sdk/react-native/flag-message.mdx b/sdk/react-native/flag-message.mdx index 7193d3ae6..e59e8fe10 100644 --- a/sdk/react-native/flag-message.mdx +++ b/sdk/react-native/flag-message.mdx @@ -1,32 +1,28 @@ --- title: "Flag Message" -description: "Flag and report inappropriate messages for moderation review using the CometChat React Native SDK." +sidebarTitle: "Flag Message" +description: "Flag inappropriate messages for moderation review using the CometChat React Native 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 with a reason -const payload = { reasonId: "spam", remark: "Promotional content" }; -await CometChat.flagMessage("MESSAGE_ID", payload); +// Flag a message +await CometChat.flagMessage("MESSAGE_ID", { + reasonId: "spam", + remark: "Promotional content" +}); ``` - -**Required:** Moderation enabled in [Dashboard](https://app.cometchat.com) → Moderation → Advanced Settings - + ## 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](/sdk/react-native/flag-message) | [REST API](/rest-api/moderation/flag-a-message) | [UI Kits](/ui-kit/react-native/core-features#report-message) - - For a complete understanding of how flagged messages are reviewed and managed, see the [Flagged Messages](/moderation/flagged-messages) documentation. @@ -65,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); } ); @@ -95,60 +91,57 @@ Before flagging a message, retrieve the list of available flag reasons configure - -**On Success** — `getFlagReasons()` returns an array of flag reason objects: - - +### Response -**Flag Reason Array (per item):** +The response is an array of `FlagReason` objects, each with an `id` and `reason` string: -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique identifier for the flag reason | `"spam"` | -| `name` | string | Display name of the flag reason | `"Spam"` | -| `description` | string | Detailed description of the reason | `"Repeated, promotional, or irrelevant content"` | -| `createdAt` | number | Unix timestamp when reason was created | `1761627675` | -| `updatedAt` | number | Unix timestamp when reason was last updated | `1761627675` | -| `default` | boolean | Whether this is a default reason | `false` | - - +```javascript +[ + { "id": "spam", "reason": "Spam or misleading" }, + { "id": "harassment", "reason": "Harassment or bullying" }, + { "id": "hate_speech", "reason": "Hate speech" }, + { "id": "violence", "reason": "Violence or dangerous content" }, + { "id": "inappropriate", "reason": "Inappropriate content" }, + { "id": "other", "reason": "Other" } +] +``` ## Flag a Message 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); } ); @@ -156,20 +149,6 @@ To flag a message, use the `flagMessage()` method with the message ID and a payl - -**On Success** — `flagMessage()` returns a success response: - - - -**Response Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `success` | boolean | Indicates if the flag operation succeeded | `true` | -| `message` | string | Confirmation message with flagged message ID | `"Message 25300 has been flagged successfully."` | - - - ### Parameters | Parameter | Type | Required | Description | @@ -178,6 +157,19 @@ To flag a message, use the `flagMessage()` method with the message ID and a payl | payload.reasonId | string | Yes | ID of the flag reason (from `getFlagReasons()`) | | payload.remark | string | No | Additional context or explanation from the user | +### Response + +The `Promise` resolves with a success confirmation object: + +```javascript +{ + "success": true, + "message": "Message with id {{messageId}} has been flagged successfully" +} +``` + +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 Here's a complete implementation showing how to build a report message flow: @@ -248,38 +240,21 @@ if (result.success) { } ``` - - - - - **Cache flag reasons:** Call `getFlagReasons()` once at app initialization or when the report dialog is first opened, then reuse the cached list. Avoid fetching reasons on every report action. - - **Require a reason:** Always require users to select a reason before submitting a flag. This improves the quality of moderation data and helps moderators prioritize reviews. - - **Provide a remark field:** Allow users to add optional context via the `remark` parameter. Additional details help moderators make faster, more informed decisions. - - **Confirm before submitting:** Show a confirmation dialog before calling `flagMessage()` to prevent accidental reports. - - **Show feedback after flagging:** Display a success message or toast after a message is flagged so the user knows their report was submitted. - - - - **`getFlagReasons()` returns an empty array:** Ensure that flag reasons are configured in the [CometChat Dashboard](https://app.cometchat.com) under **Moderation > Advanced Settings**. Moderation must also be enabled for your app. - - **`flagMessage()` fails with an error:** Verify that the `reasonId` matches one of the IDs returned by `getFlagReasons()`. Also confirm that the `messageId` is valid and belongs to a conversation the logged-in user has access to. - - **Flagged messages not appearing in Dashboard:** Check that moderation is enabled in your Dashboard settings. Flagged messages appear under **Moderation > Flagged Messages**. - - **Permission errors:** The logged-in user must be a participant in the conversation containing the message they want to flag. Users cannot flag messages from conversations they are not part of. - - - --- ## Next Steps - - Edit sent messages in one-on-one and group conversations + + Automate content moderation with AI - - Delete messages for yourself or for all participants + + Remove messages from conversations - + Listen for incoming messages in real time - - Track message delivery and read status + + Send text, media, and custom messages diff --git a/sdk/react-native/group-add-members.mdx b/sdk/react-native/group-add-members.mdx index d91e61738..80270208f 100644 --- a/sdk/react-native/group-add-members.mdx +++ b/sdk/react-native/group-add-members.mdx @@ -1,45 +1,51 @@ --- title: "Add Members To A Group" -description: "Add members to a group, listen for real-time member added events, and handle missed events using the CometChat React Native SDK." +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 React Native SDK." --- - -**Quick Reference** - Add members to a group: + ```javascript +// Add members to a group const members = [ - new CometChat.GroupMember("UID", CometChat.GROUP_MEMBER_SCOPE.PARTICIPANT), + 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) => { } +})); ``` - + - -**Available via:** [SDK](/sdk/react-native/group-add-members) | [REST API](/rest-api/group-members/add-members) - +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 -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) | - -```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); } ); @@ -47,19 +53,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); } ); @@ -69,46 +75,30 @@ 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. - - -**On Success** — `addMembersToGroup()` returns an object with each UID as key and result as value: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `[UID]` | string | Result for each UID ("success" or error message) | `"success"` | - -**Example:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `cometchat-uid-7` | string | Result for the added member | `"success"` | - - +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 -*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. - -```javascript -var 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, @@ -122,19 +112,14 @@ CometChat.addGroupListener( - -```typescript -var 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, @@ -151,151 +136,39 @@ CometChat.addGroupListener( -Always remove group listeners when the component unmounts using `CometChat.removeGroupListener(listenerId)`. Failing to remove listeners can cause memory leaks and duplicate event handling. - - - -**On Event** — `onMemberAddedToGroup` listener receives the following parameters: - - - -**Listener Parameters:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `message` | object | Action message object | [See `message` Object ↓](#added-message-object) | -| `userAdded` | object | User who was added | [See `userAdded` Object ↓](#user-added-object) | -| `userAddedBy` | object | User who performed the add | [See `userAddedBy` Object ↓](#user-added-by-object) | -| `userAddedIn` | object | Group to which user was added | [See `userAddedIn` Object ↓](#user-added-in-object) | - ---- - - - -**`message` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message ID | `"25544"` | -| `conversationId` | string | Conversation ID | `"group_group_1772430752261"` | -| `type` | string | Message type | `"groupMember"` | -| `receiverType` | string | Receiver type | `"group"` | -| `category` | string | Message category | `"action"` | -| `action` | string | Action performed | `"added"` | -| `message` | string | Human-readable action message | `"Henry Marino added Ronald Jerry"` | -| `sentAt` | number | Unix timestamp when sent | `1772430763` | -| `updatedAt` | number | Unix timestamp when updated | `1772430763` | - ---- +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. - - -**`userAdded` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the added user | `"cometchat-uid-6"` | -| `name` | string | Display name | `"Ronald Jerry"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `status` | string | Online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1772430654` | -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | -| `deactivatedAt` | number | Timestamp when deactivated (0 if active) | `0` | - ---- - - - -**`userAddedBy` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user who added | `"cometchat-uid-7"` | -| `name` | string | Display name | `"Henry Marino"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | Online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1772430649` | -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | -| `deactivatedAt` | number | Timestamp when deactivated (0 if active) | `0` | - ---- - - - -**`userAddedIn` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `guid` | string | Unique identifier of the group | `"group_1772430752261"` | -| `name` | string | Name of the group | `"Hike"` | -| `type` | string | Type of the group | `"public"` | -| `membersCount` | number | Total members in the group | `2` | -| `hasJoined` | boolean | Whether logged-in user has joined | `false` | -| `isBanned` | boolean | Whether logged-in user is banned | `false` | -| `conversationId` | string | Conversation ID for the group | `"group_group_1772430752261"` | -| `createdAt` | number | Unix timestamp when created | `1772430752` | -| `owner` | string | UID of the group owner | `"cometchat-uid-7"` | -| `onlineMembersCount` | number | Number of online members | `1` | - - - -## 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- - -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 - -## Best Practices +```javascript +CometChat.removeGroupListener("UNIQUE_LISTENER_ID"); +``` + - - - The `addMembersToGroup()` response includes per-UID results ("success" or error). Check each result rather than assuming all members were added successfully. - - - The logged-in user must have Admin or Moderator scope to add members. Verify scope before attempting the operation. - - +## Missed Member Added Events -## Troubleshooting +When fetching previous messages, member additions appear as [Action](/sdk/reference/messages#action) messages (a subclass of `BaseMessage`). - - - Verify the logged-in user has Admin or Moderator scope in the group. Participants cannot add members. - - - Check the per-UID results in the response object. Common causes include invalid UIDs or users that don't exist in your CometChat app. - - - Ensure the group listener is registered before the add event occurs. Also verify the `listenerId` is unique. - - +| 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 | --- ## Next Steps - - Fetch group member lists with filtering and pagination + + Remove or ban members from a group - - Kick, ban, and unban group members + + Promote or demote group members - - Update member roles within a group + + Fetch the list of members in a group - Join public or password-protected groups + Allow users to join public or password-protected groups - \ No newline at end of file + diff --git a/sdk/react-native/group-change-member-scope.mdx b/sdk/react-native/group-change-member-scope.mdx index b1593d084..63c26c231 100644 --- a/sdk/react-native/group-change-member-scope.mdx +++ b/sdk/react-native/group-change-member-scope.mdx @@ -1,64 +1,57 @@ --- title: "Change Member Scope" -description: "Learn how to change the scope (role) of a group member using the CometChat React Native SDK, including real-time and missed scope change events." +sidebarTitle: "Change Scope" +description: "Learn how to change group member scope (admin, moderator, participant) and receive real-time scope change events using the CometChat React Native SDK." --- - -**Quick Reference** + + ```javascript -// Change member scope -CometChat.updateGroupMemberScope("GUID", "UID", CometChat.GROUP_MEMBER_SCOPE.ADMIN); +// Change member scope to admin +await CometChat.updateGroupMemberScope("GUID", "UID", CometChat.GROUP_MEMBER_SCOPE.ADMIN); -// Listen for scope changes -CometChat.addGroupListener("listenerId", new CometChat.GroupListener({ - onGroupMemberScopeChanged: (message, changedUser, newScope, oldScope, changedGroup) => {} +// Listen for scope change events +CometChat.addGroupListener("listener", new CometChat.GroupListener({ + onGroupMemberScopeChanged: (message, changedUser, newScope, oldScope, changedGroup) => { } })); ``` - + - -Available via: [SDK](/sdk/react-native/group-change-member-scope) | [REST API](/rest-api/group-members/change-scope) - +Promote or demote group members between admin, moderator, and participant scopes. Only admins can change member scopes, and only the group owner can change admin scopes. ## 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 scope within a [Group](/sdk/reference/entities#group). - -```javascript -var GUID = "GUID"; -var UID = "UID"; -var scope = CometChat.GROUP_MEMBER_SCOPE.ADMIN; + +```typescript +let GUID: string = "GUID"; +let UID: string = "UID"; -CometChat.updateGroupMemberScope(GUID, UID, scope).then( - (response) => { - console.log("Group member scopped changed", response); - }, - (error) => { - console.log("Group member scopped changed failed", error); +CometChat.updateGroupMemberScope(GUID, UID, CometChat.GROUP_MEMBER_SCOPE.ADMIN).then( + (response: boolean) => { + console.log("Group member scope changed", response); + }, (error: CometChat.CometChatException) => { + console.log("Group member scope change failed", error); } ); ``` - -```typescript -let GUID: string = "GUID"; -let UID: string = "UID"; + +```javascript +let GUID = "GUID"; +let UID = "UID"; +let scope = CometChat.GROUP_MEMBER_SCOPE.ADMIN; -CometChat.updateGroupMemberScope( - GUID, - UID, - CometChat.GroupMemberScope.Admin -).then( - (response: boolean) => { - console.log("Group member scopped changed", response); - }, - (error: CometChat.CometChatException) => { - console.log("Group member scopped changed failed", error); - } +CometChat.updateGroupMemberScope(GUID, UID, scope).then( +response => { + console.log("Group member scope changed", response); +}, error => { + console.log("Group member scope change failed", error); +} ); ``` @@ -70,79 +63,46 @@ 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` | - -The default scope of any member is `participant`. Only the **Admin** of the group can change the scope of any participant in the group. +| `UID` | The UID of the member whose scope you want to change | +| `GUID` | The GUID of the group | +| `scope` | The new scope: `CometChat.GROUP_MEMBER_SCOPE.ADMIN`, `CometChat.GROUP_MEMBER_SCOPE.MODERATOR`, or `CometChat.GROUP_MEMBER_SCOPE.PARTICIPANT` | - -**On Success** — `updateGroupMemberScope()` returns a boolean: +The default scope is `participant`. Only Admins can change member scopes. -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `response` | boolean | Indicates whether the scope was successfully changed | `true` | - - +On success, the method resolves with `true` (boolean). ## 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. - -```javascript -var listenerID = "UNIQUE_LISTENER_ID"; + +```typescript +let listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addGroupListener( listenerID, new CometChat.GroupListener({ - onGroupMemberScopeChanged: ( - message, - changedUser, - newScope, - oldScope, - changedGroup - ) => { - console.log("User joined", { - message, - changedUser, - newScope, - oldScope, - changedGroup, - }); - }, + onGroupMemberScopeChanged: (message: CometChat.Action, changedUser: CometChat.User, newScope: string, oldScope: string, changedGroup: CometChat.Group) => { + console.log("Scope changed", { message, changedUser, newScope, oldScope, changedGroup }); + } }) ); ``` - -```typescript -let listenerID: string = "UNIQUE_LISTENER_ID"; + +```javascript +let listenerID = "UNIQUE_LISTENER_ID"; 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, - }); - }, - }) +listenerID, +new CometChat.GroupListener({ + onGroupMemberScopeChanged: (message, changedUser, newScope, oldScope, changedGroup) => { + console.log("Scope changed", {message, changedUser, newScope, oldScope, changedGroup}); + } +}) ); ``` @@ -151,7 +111,8 @@ CometChat.addGroupListener( -Always remove group listeners when the component unmounts to prevent memory leaks. +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"); ``` @@ -159,48 +120,32 @@ 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. +When fetching previous messages, scope changes appear as [Action](/sdk/reference/messages#action) messages (a subclass of `BaseMessage`). -For the group member scope changed event, in the `Action` object received, the following fields can help you get the relevant information- +| 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 | -1. `action` - `scopeChanged` -2. `actionOn` - User object containing the details of the user whos 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 - - - -- Only admins can change member scope — validate roles before calling `updateGroupMemberScope()` -- Update your local group member list after a successful scope change to keep the UI in sync -- Handle the `onGroupMemberScopeChanged` listener to reflect scope changes made by other admins in real time -- Consider showing a confirmation dialog before promoting a member to admin, as this grants full group control - - - -- **ERR_NOT_A_MEMBER**: The logged-in user is not a member of the group. Ensure the user has joined the group first. -- **ERR_INSUFFICIENT_PERMISSIONS**: Only group admins can change member scope. Verify the logged-in user's role. -- **Scope change not reflecting**: Make sure you've registered a `GroupListener` and are handling `onGroupMemberScopeChanged`. -- **Missed events not appearing**: Fetch previous messages using `MessagesRequest` — scope change actions appear as `Action` messages in the message history. - - +--- ## Next Steps - -Remove or restrict members from a group - - -Transfer group ownership to another member - - -Fetch the list of members in a group - - -Add new members to a group - + + 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/react-native/group-kick-ban-members.mdx b/sdk/react-native/group-kick-ban-members.mdx index 9809a217a..ca32fb722 100644 --- a/sdk/react-native/group-kick-ban-members.mdx +++ b/sdk/react-native/group-kick-ban-members.mdx @@ -1,71 +1,59 @@ --- -title: "Kick Member From A Group" -description: "Learn how to kick, ban, and unban group members using the CometChat React Native SDK, including fetching banned member lists and handling real-time events." +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 React Native SDK." --- - -**Quick Reference** + + ```javascript // Kick a member -CometChat.kickGroupMember("GUID", "UID"); +await CometChat.kickGroupMember("GUID", "UID"); // Ban a member -CometChat.banGroupMember("GUID", "UID"); +await CometChat.banGroupMember("GUID", "UID"); // Unban a member -CometChat.unbanGroupMember("GUID", "UID"); +await CometChat.unbanGroupMember("GUID", "UID"); // Fetch banned members -let request = new CometChat.BannedMembersRequestBuilder("GUID").setLimit(30).build(); -request.fetchNext(); +const request = new CometChat.BannedMembersRequestBuilder("GUID").setLimit(30).build(); +const bannedMembers = await request.fetchNext(); ``` - - - -Available via: [SDK](/sdk/react-native/group-kick-ban-members) | REST API: [Kick](/rest-api/group-members/kick), [Ban](/rest-api/banned-users/ban) - - -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 the above actions can only be performed by the **Admin** or the **Moderator** of the group. +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 -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. - -```javascript -var GUID = "GUID"; -var UID = "UID"; + +```typescript +let GUID: string = "GUID"; +let UID: string = "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: boolean) => { + console.log("Group member kicked successfully", response); + }, (error: CometChat.CometChatException) => { + console.log("Group member kicking failed with error", error); } ); ``` - -```typescript -let GUID: string = "GUID"; -let UID: string = "UID"; + +```javascript +let GUID = "GUID"; +let UID = "UID"; CometChat.kickGroupMember(GUID, UID).then( - (response: Object) => { + (response) => { console.log("Group member kicked successfully", response); - }, - (error: CometChat.CometChatException) => { + }, (error) => { console.log("Group member kicking failed with error", error); } ); @@ -75,7 +63,7 @@ CometChat.kickGroupMember(GUID, UID).then( -The `kickGroupMember()` takes following parameters +The `kickGroupMember()` takes the following parameters: | Parameter | Description | | --------- | ----------------------------------------------------- | @@ -84,49 +72,40 @@ 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** — `kickGroupMember()` returns a boolean: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `response` | boolean | Indicates whether the member was successfully kicked | `true` | - - +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. +Admins or Moderators can ban a member using `banGroupMember()`. Unlike kicked users, banned users cannot rejoin until unbanned. - -```javascript -var GUID = "GUID"; -var UID = "UID"; + +```typescript +let GUID: string = "GUID"; +let UID: string = "UID"; CometChat.banGroupMember(GUID, UID).then( - (response) => { - console.log("Group member banned successfully", response); - }, - (error) => { - console.log("Group member banning failed with error", error); + (response: boolean) => { + console.log("Group member banned successfully", response); + }, (error: CometChat.CometChatException) => { + console.log("Group member banning failed with error", error); } ); ``` - -```typescript -let GUID: string = "GUID"; -let UID: string = "UID"; + +```javascript +const GUID = "GUID"; +const UID = "UID"; CometChat.banGroupMember(GUID, UID).then( - (response: Object) => { - console.log("Group member banned successfully", response); - }, - (error: CometChat.CometChatException) => { - console.log("Group member banning failed with error", error); - } +response => { + console.log("Group member banned successfully", response); +}, error => { + console.log("Group member banning failed with error", error); +} ); ``` @@ -138,54 +117,45 @@ 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. | +| `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. - -**On Success** — `banGroupMember()` returns a boolean: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `response` | boolean | Indicates whether the member was successfully banned | `true` | - - +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 -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()`. - -```javascript -var GUID = "GUID"; -var UID = "UID"; + +```typescript +let GUID: string = "GUID"; +let UID: string = "UID"; CometChat.unbanGroupMember(GUID, UID).then( - (response) => { - console.log("Group member unbanned successfully", response); - }, - (error) => { - console.log("Group member unbanning failed with error", error); + (response: boolean) => { + console.log("Group member unbanned successfully", response); + }, (error: CometChat.CometChatException) => { + console.log("Group member unbanning failed with error", error); } ); ``` - -```typescript -let GUID: string = "GUID"; -let UID: string = "UID"; + +```javascript +const GUID = "GUID"; +const UID = "UID"; CometChat.unbanGroupMember(GUID, UID).then( - (response: Object) => { - console.log("Group member unbanned successfully", response); - }, - (error: CometChat.CometChatException) => { - console.log("Group member unbanning failed with error", error); - } +response => { + console.log("Group member unbanned successfully", response); +}, error => { + console.log("Group member unbanning failed with error", error); +} ); ``` @@ -197,255 +167,172 @@ 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 | - -The unbanned user can now rejoin the group. +| `UID` | The UID of the user to be unbanned | +| `GUID` | The GUID of the group from which user is to be unbanned | - -**On Success** — `unbanGroupMember()` returns a boolean: +Once unbanned, the user can rejoin the group. -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `response` | boolean | Indicates whether the member was successfully unbanned | `true` | - - +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. - -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. - -```javascript -let GUID = "GUID"; -let limit = 30; -let bannedGroupMembersRequest = new CometChat.BannedMembersRequestBuilder(GUID) - .setLimit(limit) - .build(); -``` - - - ```typescript let GUID: string = "GUID"; let limit: number = 30; -let bannedGroupMembersRequest: CometChat.BannedMembersRequest = - new CometChat.BannedMembersRequestBuilder(GUID).setLimit(limit).build(); +let bannedGroupMembersRequest: CometChat.BannedMembersRequest = new CometChat.BannedMembersRequestBuilder(GUID) + .setLimit(limit) + .build(); ``` - - -### Set Search Keyword - -This method allows you to set the search string based on which the banned group members are to be fetched. - - ```javascript let GUID = "GUID"; let limit = 30; -let searchKeyword = "super"; let bannedGroupMembersRequest = new CometChat.BannedMembersRequestBuilder(GUID) - .setLimit(limit) - .setSearchKeyword(searchKeyword) - .build(); + .setLimit(limit) + .build(); ``` + + +### 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(); +let bannedGroupMembersRequest: CometChat.BannedMembersRequest = new CometChat.BannedMembersRequestBuilder(GUID) + .setLimit(limit) + .setSearchKeyword(searchKeyword) + .build(); ``` - - -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. - - ```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 - ); - } -); +let searchKeyword = "super"; +let bannedGroupMembersRequest = new CometChat.BannedMembersRequestBuilder(GUID) + .setLimit(limit) + .setSearchKeyword(searchKeyword) + .build(); ``` + + +Once configured, call `build()` to create the request, then `fetchNext()` to retrieve banned members. + + ```typescript let GUID: string = "GUID"; let limit: number = 30; -let bannedGroupMembersRequest: CometChat.BannedMembersRequest = - new CometChat.BannedMembersRequestBuilder(GUID).setLimit(limit).build(); +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 - ); + console.log("Banned Group Member list fetched successfully:", bannedMembers); + }, (error: CometChat.CometChatException) => { + console.log("Banned Group Member list fetching failed with exception:", error); } ); ``` - - + +```javascript +let GUID = "GUID"; +let limit = 30; +let bannedGroupMembersRequest = new CometChat.BannedMembersRequestBuilder(GUID) + .setLimit(limit) + .build(); - -**On Success** — `fetchNext()` returns an array of banned `GroupMember` objects: - - - -**Banned GroupMember Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | -| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | -| `uid` | string | Unique identifier of the user | `"cometchat-uid-6"` | -| `joinedAt` | number | Unix timestamp when the user originally joined the group | `1772430763` | -| `name` | string | Display name of the user | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `statusMessage` | string | User's status message | `"Testing CometChat SDK"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1772430654` | -| `scope` | string | Member's scope in the group before being banned | `"participant"` | -| `isBanned` | boolean | Whether the user is banned from the group | `true` | -| `conversationId` | string | Conversation ID between this user and logged-in user | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `guid` | string | GUID of the group | `"group_1772430752261"` | +bannedGroupMembersRequest.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 +The `fetchNext()` method returns an array of [`GroupMember`](/sdk/reference/entities#groupmember) objects representing the banned members of the group. -*In other words, as a member of a group, how do I know when someone is banned/kicked when my app is running?* +## Real-Time Kick/Ban/Unban Events -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 | - -```javascript -let listenerID = "UNIQUE_LISTENER_ID"; + +```typescript +let listenerID: string = "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, - }); - }, + onGroupMemberKicked: (message: CometChat.Action, kickedUser: CometChat.User, kickedBy: CometChat.User, kickedFrom: CometChat.Group) => { + console.log("User kicked", { message, kickedUser, kickedBy, kickedFrom }); + }, + onGroupMemberBanned: (message: CometChat.Action, bannedUser: CometChat.User, bannedBy: CometChat.User, bannedFrom: CometChat.Group) => { + console.log("User banned", { message, bannedUser, bannedBy, bannedFrom }); + }, + onGroupMemberUnbanned: (message: CometChat.Action, unbannedUser: CometChat.User, unbannedBy: CometChat.User, unbannedFrom: CometChat.Group) => { + console.log("User unbanned", { message, unbannedUser, unbannedBy, unbannedFrom }); + } }) ); ``` - -```typescript -let listenerID: string = "UNIQUE_LISTENER_ID"; + +```javascript +let listenerID = "UNIQUE_LISTENER_ID"; CometChat.addGroupListener( - listenerID, - new CometChat.GroupListener({ - onGroupMemberKicked: ( - message: CometChat.Action, - kickedUser: CometChat.User, - kickedBy: CometChat.User, - kickedFrom: CometChat.Group - ) => { - console.log("User kicked", { message, kickedUser, kickedBy, kickedFrom }); - }, - onGroupMemberBanned: ( - message: CometChat.Action, - bannedUser: CometChat.User, - bannedBy: CometChat.User, - bannedFrom: CometChat.Group - ) => { - console.log("User banned", { message, bannedUser, bannedBy, bannedFrom }); - }, - onGroupMemberUnbanned: ( - message: CometChat.Action, - unbannedUser: CometChat.User, - unbannedBy: CometChat.User, - unbannedFrom: CometChat.Group - ) => { - console.log("User unbanned", { - message, - unbannedUser, - unbannedBy, - unbannedFrom, - }); - }, - }) +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}); + } +}) ); ``` @@ -454,161 +341,59 @@ CometChat.addGroupListener( -Always remove group listeners when the component unmounts to prevent memory leaks. +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"); ``` - -**On Event** — `onGroupMemberBanned` listener receives the following parameters: - - - -**Listener Parameters:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `message` | object | Action message object | [See `message` Object ↓](#banned-message-object) | -| `bannedUser` | object | User who was banned | [See `bannedUser` Object ↓](#banned-user-object) | -| `bannedBy` | object | User who performed the ban | [See `bannedBy` Object ↓](#banned-by-object) | -| `bannedFrom` | object | Group from which user was banned | [See `bannedFrom` Object ↓](#banned-from-object) | - ---- - - - -**`message` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message ID | `"25545"` | -| `conversationId` | string | Conversation ID | `"group_group_1772430752261"` | -| `type` | string | Message type | `"groupMember"` | -| `receiverType` | string | Receiver type | `"group"` | -| `category` | string | Message category | `"action"` | -| `action` | string | Action performed | `"banned"` | -| `message` | string | Human-readable action message | `"Henry Marino banned Ronald Jerry"` | -| `sentAt` | number | Unix timestamp when sent | `1772430770` | -| `updatedAt` | number | Unix timestamp when updated | `1772430770` | - ---- - - - -**`bannedUser` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the banned user | `"cometchat-uid-6"` | -| `name` | string | Display name | `"Ronald Jerry"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `status` | string | Online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1772430654` | -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | -| `deactivatedAt` | number | Timestamp when deactivated (0 if active) | `0` | - ---- - - - -**`bannedBy` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user who banned | `"cometchat-uid-7"` | -| `name` | string | Display name | `"Henry Marino"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | Online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1772430649` | -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | -| `deactivatedAt` | number | Timestamp when deactivated (0 if active) | `0` | - ---- - - - -**`bannedFrom` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `guid` | string | Unique identifier of the group | `"group_1772430752261"` | -| `name` | string | Name of the group | `"Hike"` | -| `type` | string | Type of the group | `"public"` | -| `membersCount` | number | Total members in the group | `1` | -| `hasJoined` | boolean | Whether logged-in user has joined | `false` | -| `isBanned` | boolean | Whether logged-in user is banned | `false` | -| `conversationId` | string | Conversation ID for the group | `"group_group_1772430752261"` | -| `createdAt` | number | Unix timestamp when created | `1772430752` | -| `owner` | string | UID of the group owner | `"cometchat-uid-7"` | -| `updatedAt` | number | Unix timestamp when updated | `1772430763` | -| `onlineMembersCount` | number | Number of online members | `2` | - - - ## 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 | - - - -- Always confirm with the user before kicking or banning — these are disruptive actions -- Use ban for persistent rule violations and kick for temporary removals (kicked users can rejoin) -- Keep your local member list in sync by handling `onGroupMemberKicked`, `onGroupMemberBanned`, and `onGroupMemberUnbanned` listeners -- When fetching banned members, use pagination (`fetchNext()`) to handle large lists efficiently -- Only admins and moderators can perform these actions — check the logged-in user's scope before showing kick/ban UI controls - - - -- **ERR_NOT_A_MEMBER**: The logged-in user is not a member of the group. Ensure the user has joined the group first. -- **ERR_INSUFFICIENT_PERMISSIONS**: Only admins or moderators can kick/ban members. Verify the logged-in user's role. -- **Banned user can still rejoin**: Make sure you used `banGroupMember()` and not `kickGroupMember()` — kicked users can rejoin, banned users cannot. -- **Unban not working**: Only admins or moderators can unban. Also ensure the user was actually banned (not just kicked). -- **Listener events not firing**: Confirm you registered a `GroupListener` with the correct listener ID and are handling the right callback methods. - - +--- ## Next Steps - -Promote or demote group members - - -Transfer group ownership to another member - - -Fetch the list of members in a group - - -Add new members to a group - + + 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/react-native/groups-overview.mdx b/sdk/react-native/groups-overview.mdx index 119e4be1e..7054f36b9 100644 --- a/sdk/react-native/groups-overview.mdx +++ b/sdk/react-native/groups-overview.mdx @@ -1,14 +1,55 @@ --- title: "Groups" sidebarTitle: "Overview" -description: "Overview of group functionality in CometChat React Native SDK — create, manage, and interact with public, private, and password-protected groups." +description: "Overview of group management in the CometChat React Native SDK including group types, member roles, and available operations." --- -## Overview + -Groups help your users to converse together in a single space. You can have three types of groups- private, public and password protected. +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| 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/react-native/create-group), [Join Group](/sdk/react-native/join-group), [Retrieve Groups](/sdk/react-native/retrieve-groups) | -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 + +| 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 | + +## Available Operations + +- [Create a Group](/sdk/react-native/create-group) — Create public, private, or password-protected groups +- [Join a Group](/sdk/react-native/join-group) — Join existing groups as a participant +- [Leave a Group](/sdk/react-native/leave-group) — Leave a group you're a member of +- [Update a Group](/sdk/react-native/update-group) — Update group name, description, icon, and settings +- [Delete a Group](/sdk/react-native/delete-group) — Permanently delete a group (owner only) +- [Transfer Ownership](/sdk/react-native/transfer-group-ownership) — Transfer group ownership to another member +- [Retrieve Groups](/sdk/react-native/retrieve-groups) — Fetch and filter the list of groups +- [Retrieve Group Members](/sdk/react-native/retrieve-group-members) — Get the member list for a group +- [Add Members](/sdk/react-native/group-add-members) — Add users to a group +- [Kick & Ban Members](/sdk/react-native/group-kick-ban-members) — Remove or ban members from a group +- [Change Member Scope](/sdk/react-native/group-change-member-scope) — Promote or demote members --- @@ -18,13 +59,13 @@ Each group includes three kinds of users- owner, moderator, member. Create public, private, or password-protected groups - - Fetch group lists, search groups, and get group details - - Join public or password-protected groups + Join existing groups as a participant + + + Fetch and filter the list of groups - - Manage members, roles, and permissions within groups + + Get the member list for a group - \ No newline at end of file + diff --git a/sdk/react-native/interactive-messages.mdx b/sdk/react-native/interactive-messages.mdx index 26f7a68eb..b5782e8dc 100644 --- a/sdk/react-native/interactive-messages.mdx +++ b/sdk/react-native/interactive-messages.mdx @@ -3,8 +3,7 @@ title: "Interactive Messages" description: "Send and receive interactive messages with embedded forms, cards, and custom interactive elements using the CometChat React Native SDK." --- - -**Quick Reference** - Send an interactive message and listen for it: + ```javascript // Send an interactive message @@ -14,18 +13,24 @@ const interactiveMessage = new CometChat.InteractiveMessage( await CometChat.sendInteractiveMessage(interactiveMessage); // Listen for incoming interactive messages -CometChat.addMessageListener("interactive-listener", new CometChat.MessageListener({ +CometChat.addMessageListener("listener-id", new CometChat.MessageListener({ onInteractiveMessageReceived: (msg) => console.log("Interactive:", msg), onInteractionGoalCompleted: (msg) => console.log("Goal completed:", msg), })); + +// Mark an element as interacted +await CometChat.markAsInteracted(messageId, elementId); ``` - - -**Available via:** [SDK](/sdk/react-native/interactive-messages) | [REST API](/rest-api/chat-apis) - +| Method | Description | +|---|---| +| `sendInteractiveMessage()` | Send a message with embedded interactive content | +| `markAsInteracted()` | Mark a specific element as interacted | +| `onInteractiveMessageReceived` | Listener for incoming interactive messages | +| `onInteractionGoalCompleted` | Listener for when an interaction goal is met | + -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. +An [`InteractiveMessage`](/sdk/reference/entities#interactivemessage) is a specialized message that encapsulates interactive content within a chat message, such as an embedded form that users can fill out directly in the chat interface. ## InteractiveMessage @@ -34,326 +39,116 @@ An `InteractiveMessage` is a specialized object that encapsulates an interactive | Parameter | Description | | | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- | -------- | | `receiverId` | The UID or GUID of the recipient | Required | -| `receiverType` | The type of the receiver to whom the message is to be sent i.e `CometChat.RECEIVER_TYPE.USER (user)` or `CometChat.RECEIVER_TYPE.GROUP (group)` | Required | +| `receiverType` | The type of the receiver: `CometChat.RECEIVER_TYPE.USER` or `CometChat.RECEIVER_TYPE.GROUP` | Required | | `messageType` | The type of the message that needs to be sent | Required | | `interactiveData` | A JSONObject holding structured data for the interactive element | Required | -| `allowSenderInteraction` | A boolean determining whether the message sender can interact with the message by default it is set to false | | -| `interactionGoal` | An InteractionGoal object encapsulating the intended outcome of interacting with the `InteractiveMessage` by default it is set to none | | +| `allowSenderInteraction` | Whether the message sender can interact with the message (default: `false`) | | +| `interactionGoal` | An `InteractionGoal` object encapsulating the intended outcome (default: `none`) | | ## Interaction -An `Interaction` represents a user action involved with an `InteractiveMessage`. It includes: +An `Interaction` represents a user action on an `InteractiveMessage`. It includes: * `elementId`: An identifier for a specific interactive element. * `interactedAt`: A timestamp indicating when the interaction occurred. ## 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. +Marks a message as interacted by identifying it with the provided ID. It also logs the interactive element associated with the interaction. - - ```javascript - CometChat.markAsInteracted(message?.getId(), elementId) - .then((response) => { - console.log("Mark As Interacted", response); - }) - .catch((error) => { - console.log("error while markAsInteracted", error); - }); - ``` - - - ```typescript - CometChat.markAsInteracted(message?.getId(), elementId) - .then((response) => { - console.log("Mark As Interacted", response); - }) - .catch((error) => { - console.log("error while markAsInteracted", error); - }); - ``` - - - - -**On Success** — `markAsInteracted()` returns a success message: + +```typescript +CometChat.markAsInteracted(message?.getId(), elementId) + .then((response: string) => { + console.log("Mark As Interacted", response); + }) + .catch((error: CometChat.CometChatException) => { + console.log("error while markAsInteracted", error); + }); +``` + + +```javascript +CometChat.markAsInteracted(message?.getId(), elementId) + .then((response) => { + console.log("Mark As Interacted", response); + }) + .catch((error) => { + console.log("error while markAsInteracted", error); + }); +``` -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `message` | string | Confirmation message | `"The message id 25308 has been marked as interacted for the user cometchat-uid-7."` | +Alternatively, using `async/await`: - +```javascript +try { + const response = await CometChat.markAsInteracted(message?.getId(), elementId); + console.log("Mark As Interacted", response); +} catch (error) { + console.log("error while markAsInteracted", error); +} +``` + + ## Goal Completion -A key feature of `InteractiveMessage` is checking whether a user's interactions with the message meet the defined `InteractionGoal`. - -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: +A key feature of `InteractiveMessage` is checking whether a user's interactions meet the defined `InteractionGoal`. The completion of a goal varies depending on the goal type: -| Goals | Description | Keys | +| Goal | Description | Key | | -------------------------------- | ---------------------------------------------------------------------- | ------------------------------ | -| **Any Interaction** | The goal is considered completed if there is at least one interaction. | CometChat.GoalType.ANY\_ACTION | -| **Any of Specific Interactions** | The goal is achieved if any of the specified interactions occurred. | CometChat.GoalType.ANY\_OF | -| **All of Specific Interactions** | The goal is completed when all specified interactions occur. | CometChat.GoalType.ALL\_OF | -| **None** | The goal is never completed | CometChat.GoalType.NONE | +| **Any Interaction** | The goal is completed if there is at least one interaction. | `CometChat.GoalType.ANY_ACTION` | +| **Any of Specific Interactions** | The goal is achieved if any of the specified interactions occurred. | `CometChat.GoalType.ANY_OF` | +| **All of Specific Interactions** | The goal is completed when all specified interactions occur. | `CometChat.GoalType.ALL_OF` | +| **None** | The goal is never completed. | `CometChat.GoalType.NONE` | -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. - -InteractionGoal The `InteractionGoal` represents the desired outcome of an interaction with an `InteractiveMessage`. It includes: +The `InteractionGoal` includes: * `elementIds`: A list of identifiers for the interactive elements. -* `type`: The type of interaction goal from the `CometChat`. +* `type`: The type of interaction goal from `CometChat.GoalType`. ## Sending InteractiveMessages -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. - -Here is an example of how to use it: +Use `sendInteractiveMessage()` to send an `InteractiveMessage`. The method requires an `InteractiveMessage` object. - - ```javascript - CometChat.sendInteractiveMessage(message) - .then((message) => { - console.log("message sent successfully", message.getSentAt()); - }) - .catch((error) => { - console.log("error while sending message", { error }); - }); - ``` - - - ```typescript - CometChat.sendInteractiveMessage(message) - .then((message: CometChat.InteractiveMessage) => { - console.log("message sent successfully", message.getSentAt()); - }) - .catch((error: CometChat.CometChatException) => { - console.log("error while sending message", { error }); - }); - ``` - - - - -**On Success** — `sendInteractiveMessage()` returns the sent interactive message object: - - - -**InteractiveMessage Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25308"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-7"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"form"` | -| `category` | string | Message category | `"interactive"` | -| `sentAt` | number | Unix timestamp when sent | `1771998776` | -| `updatedAt` | number | Unix timestamp when updated | `1771998776` | -| `interactiveData` | object | Interactive element data | [See below ↓](#send-interactive-interactivedata-object) | -| `interactionGoal` | object | Goal for tracking interactions | [See below ↓](#send-interactive-interactiongoal-object) | -| `sender` | object | Sender user details | [See below ↓](#send-interactive-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#send-interactive-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#send-interactive-data-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`interactiveData` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `title` | string | Form title | `"Quick Survey"` | -| `formFields` | array | Form field definitions | [See below ↓](#send-interactive-formfields-array) | -| `submitElement` | object | Submit button configuration | [See below ↓](#send-interactive-submitelement-object) | -| `interactableElementIds` | array | IDs of interactable elements | `["submit_btn"]` | - ---- - - - -**`interactiveData.formFields` Array (per item):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `elementType` | string | Type of form element | `"textInput"` | -| `elementId` | string | Unique element identifier | `"field1"` | -| `label` | string | Field label text | `"How was your experience?"` | -| `optional` | boolean | Whether field is optional | `false` | - ---- - - - -**`interactiveData.submitElement` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `elementType` | string | Type of element | `"button"` | -| `elementId` | string | Unique element identifier | `"submit_btn"` | -| `buttonText` | string | Button display text | `"Submit"` | - ---- - - - -**`interactionGoal` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `elementIds` | array | Target element IDs for goal | `[]` | -| `type` | string | Goal type | `"anyAction"` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771998694` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771998700` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `interactiveData` | object | Interactive element data | [See below ↓](#send-interactive-data-interactivedata-object) | -| `interactionGoal` | object | Goal configuration | [See below ↓](#send-interactive-data-interactiongoal-object) | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `allowSenderInteraction` | boolean | Whether sender can interact | `false` | -| `entities` | object | Sender and receiver entities | [See below ↓](#send-interactive-data-entities-object) | - ---- - - - -**`data.interactiveData` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `title` | string | Form title | `"Quick Survey"` | -| `formFields` | array | Form field definitions | `[{"elementType": "textInput", "elementId": "field1", "label": "How was your experience?", "optional": false}]` | -| `submitElement` | object | Submit button configuration | `{"elementType": "button", "elementId": "submit_btn", "buttonText": "Submit"}` | -| `interactableElementIds` | array | IDs of interactable elements | `["submit_btn"]` | - ---- - - - -**`data.interactionGoal` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `elementIds` | array | Target element IDs for goal | `[]` | -| `type` | string | Goal type | `"anyAction"` | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#send-interactive-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#send-interactive-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#send-interactive-data-entities-sender-entity-object) | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771998694` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#send-interactive-data-entities-receiver-entity-object) | - ---- - - + +```typescript +CometChat.sendInteractiveMessage(message) + .then((message: CometChat.InteractiveMessage) => { + console.log("message sent successfully", message.getSentAt()); + }) + .catch((error: CometChat.CometChatException) => { + console.log("error while sending message", { error }); + }); +``` + + +```javascript +CometChat.sendInteractiveMessage(message) + .then((message) => { + console.log("message sent successfully", message.getSentAt()); + }) + .catch((error) => { + console.log("error while sending message", { error }); + }); +``` -**`data.entities.receiver.entity` Object:** +Alternatively, using `async/await`: -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771998700` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `tags` | array | User tags | `[]` | +```javascript +try { + const sentMessage = await CometChat.sendInteractiveMessage(message); + console.log("message sent successfully", sentMessage.getSentAt()); +} catch (error) { + console.log("error while sending message", { error }); +} +``` + + - +On success, the `Promise` resolves with an [`InteractiveMessage`](/sdk/reference/entities#interactivemessage) object. ## Event Listeners @@ -363,317 +158,73 @@ CometChat SDK provides event listeners to handle real-time events related to `In The `onInteractiveMessageReceived` event listener is triggered when an `InteractiveMessage` is received. -Here is an example: - - - ```javascript - CometChat.addMessageListener( - "UNIQUE_LISTENER_ID", - new CometChat.MessageListener({ - onInteractiveMessageReceived: (message) => { - console.log("on Interactive Message Received", message); - } - }) - ); - ``` - - - ```typescript - CometChat.addMessageListener( - "UNIQUE_LISTENER_ID", - new CometChat.MessageListener({ - onInteractiveMessageReceived: (message: CometChat.InteractiveMessage) => { - console.log("on Interactive Message Received", message); - } - }) - ); - ``` - + +```typescript +CometChat.addMessageListener( + "UNIQUE_LISTENER_ID", + new CometChat.MessageListener({ + onInteractiveMessageReceived: (message: CometChat.InteractiveMessage) => { + console.log("on Interactive Message Received", message); + } + }) +); +``` + + +```javascript +CometChat.addMessageListener( + "UNIQUE_LISTENER_ID", + new CometChat.MessageListener({ + onInteractiveMessageReceived: (message) => { + console.log("on Interactive Message Received", message); + } + }) +); +``` + - -**On Event** — `onInteractiveMessageReceived` returns the received interactive message object: - - - -**InteractiveMessage Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25308"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-7"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"form"` | -| `category` | string | Message category | `"interactive"` | -| `sentAt` | number | Unix timestamp when sent | `1771998776` | -| `updatedAt` | number | Unix timestamp when updated | `1771998776` | -| `interactiveData` | object | Interactive element data | [See below ↓](#receive-interactive-interactivedata-object) | -| `interactionGoal` | object | Goal for tracking interactions | [See below ↓](#receive-interactive-interactiongoal-object) | -| `sender` | object | Sender user details | [See below ↓](#receive-interactive-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#receive-interactive-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#receive-interactive-data-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`interactiveData` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `title` | string | Form title | `"Quick Survey"` | -| `formFields` | array | Form field definitions | [See below ↓](#receive-interactive-formfields-array) | -| `submitElement` | object | Submit button configuration | [See below ↓](#receive-interactive-submitelement-object) | -| `interactableElementIds` | array | IDs of interactable elements | `["submit_btn"]` | - ---- - - - -**`interactiveData.formFields` Array (per item):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `elementType` | string | Type of form element | `"textInput"` | -| `elementId` | string | Unique element identifier | `"field1"` | -| `label` | string | Field label text | `"How was your experience?"` | -| `optional` | boolean | Whether field is optional | `false` | - ---- - - - -**`interactiveData.submitElement` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `elementType` | string | Type of element | `"button"` | -| `elementId` | string | Unique element identifier | `"submit_btn"` | -| `buttonText` | string | Button display text | `"Submit"` | - ---- - - - -**`interactionGoal` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `elementIds` | array | Target element IDs for goal | `[]` | -| `type` | string | Goal type | `"anyAction"` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771998694` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771998700` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `interactiveData` | object | Interactive element data | [See below ↓](#receive-interactive-data-interactivedata-object) | -| `interactionGoal` | object | Goal configuration | [See below ↓](#receive-interactive-data-interactiongoal-object) | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `allowSenderInteraction` | boolean | Whether sender can interact | `false` | -| `entities` | object | Sender and receiver entities | [See below ↓](#receive-interactive-data-entities-object) | - ---- - - - -**`data.interactiveData` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `title` | string | Form title | `"Quick Survey"` | -| `formFields` | array | Form field definitions | `[{"elementType": "textInput", "elementId": "field1", "label": "How was your experience?", "optional": false}]` | -| `submitElement` | object | Submit button configuration | `{"elementType": "button", "elementId": "submit_btn", "buttonText": "Submit"}` | -| `interactableElementIds` | array | IDs of interactable elements | `["submit_btn"]` | - ---- - - - -**`data.interactionGoal` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `elementIds` | array | Target element IDs for goal | `[]` | -| `type` | string | Goal type | `"anyAction"` | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#receive-interactive-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#receive-interactive-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#receive-interactive-data-entities-sender-entity-object) | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771998694` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#receive-interactive-data-entities-receiver-entity-object) | - ---- - - - -**`data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771998700` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `tags` | array | User tags | `[]` | - - - ### On Interaction Goal Completed The `onInteractionGoalCompleted` event listener is invoked when an interaction goal is achieved. -Here is an example: - - - ```javascript - CometChat.addMessageListener( - "UNIQUE_LISTENER_ID", - new CometChat.MessageListener({ - onInteractionGoalCompleted: (message) => { - console.log("on Interaction Goal Completed", message); - } - }) - ); - ``` - - - ```typescript - CometChat.addMessageListener( - "UNIQUE_LISTENER_ID", - new CometChat.MessageListener({ - onInteractionGoalCompleted: (message: CometChat.InteractiveMessage) => { - console.log("on Interaction Goal Completed", message); - } - }) - ); - ``` - + +```typescript +CometChat.addMessageListener( + "UNIQUE_LISTENER_ID", + new CometChat.MessageListener({ + onInteractionGoalCompleted: (message: CometChat.InteractiveMessage) => { + console.log("on Interaction Goal Completed", message); + } + }) +); +``` + + +```javascript +CometChat.addMessageListener( + "UNIQUE_LISTENER_ID", + new CometChat.MessageListener({ + onInteractionGoalCompleted: (message) => { + console.log("on Interaction Goal Completed", message); + } + }) +); +``` + -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. - -**Listener Cleanup:** Always remove message listeners when they are no longer needed. Remove the listener in `componentWillUnmount()` or the cleanup function of a `useEffect` hook to prevent memory leaks. +Always remove message listeners when they are no longer needed. Remove the listener in `componentWillUnmount()` or the cleanup function of a `useEffect` hook to prevent memory leaks. ```javascript CometChat.removeMessageListener("UNIQUE_LISTENER_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. - - - - - Use descriptive, unique listener IDs (e.g., `"interactive-form-listener"`) to avoid conflicts with other listeners - - Always remove message listeners on component unmount to prevent memory leaks - - Set `allowSenderInteraction` to `true` only when the sender needs to interact with their own message (e.g., previewing a form) - - Define clear `InteractionGoal` types to accurately track user engagement with interactive elements - - Handle both `onInteractiveMessageReceived` and `onInteractionGoalCompleted` events to provide a complete interactive experience - - - - **Interactive message not sending:** Verify that `interactiveData` is a valid JSON object and all required fields (`receiverId`, `receiverType`, `messageType`) are set - - **Not receiving interactive messages:** Ensure the message listener is registered with `onInteractiveMessageReceived` and the user is logged in - - **Goal not completing:** Check that the `InteractionGoal` type matches the expected interactions — use `ANY_ACTION` for simple cases and `ALL_OF` only when every specified element must be interacted with - - **`markAsInteracted` failing:** Confirm that the message ID and element ID are valid and that the user has permission to interact with the message - - **Duplicate events:** Verify you are not registering the same listener ID multiple times without removing the previous one - - +--- ## Next Steps diff --git a/sdk/react-native/join-group.mdx b/sdk/react-native/join-group.mdx index 5e63ed60f..47faf1f66 100644 --- a/sdk/react-native/join-group.mdx +++ b/sdk/react-native/join-group.mdx @@ -1,10 +1,10 @@ --- title: "Join A Group" -description: "Join public or password-protected groups, listen for real-time join events, and handle missed join events using the CometChat React Native SDK." +sidebarTitle: "Join Group" +description: "Learn how to join public, password-protected, and private groups, and receive real-time join events using the CometChat React Native SDK." --- - -**Quick Reference** - Join a group: + ```javascript // Join a public group @@ -12,23 +12,44 @@ 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) => { } +})); ``` - + - -**Available via:** [SDK](/sdk/react-native/join-group) | [REST API](/rest-api/group-members/add-members) - +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 -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. + +```typescript +const GUID: string = "GUID"; + +const password: string = ""; +const groupType: string = CometChat.GROUP_TYPE.PUBLIC; + +CometChat.joinGroup(GUID, groupType, password).then( + (group: CometChat.Group) => { + console.log("Group joined successfully:", group); + }, (error: CometChat.CometChatException) => { + console.log("Group joining failed with exception:", error); + } +); +``` + + + ```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 => { @@ -41,70 +62,29 @@ group => { - -```typescript -var 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); - } -); -``` - - - -The `joinGroup()` method takes the below 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. 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. - - -**On Success** — `joinGroup()` returns a `Group` object: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `hasJoined` | boolean | Whether the logged-in user has joined the group | `true` | -| `membersCount` | number | Total number of members in the group | `2` | -| `isBanned` | boolean | Whether the logged-in user is banned from the group | `false` | -| `guid` | string | Unique identifier of the group | `"group_1772427551785"` | -| `name` | string | Name of the group | `"Comet Group"` | -| `type` | string | Type of the group (public, private, password) | `"public"` | -| `scope` | string | Scope of the logged-in user in the group | `"participant"` | -| `joinedAt` | number | Unix timestamp when the user joined | `1772427667` | -| `conversationId` | string | Conversation ID for the group | `"group_group_1772427551785"` | -| `createdAt` | number | Unix timestamp when the group was created | `1772427556` | -| `owner` | string | UID of the group owner | `"cometchat-uid-6"` | -| `onlineMembersCount` | number | Number of online members in the group | `1` | - - +| Parameter | Description | +| --------- | ----------- | +| `GUID` | The GUID of the group to join | +| `groupType` | `CometChat.GROUP_TYPE.PUBLIC`, `PASSWORD`, or `PRIVATE` | +| `password` | Required for password-protected groups | -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. +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. -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`. ## 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. - -```javascript + +```typescript CometChat.addGroupListener( - "UNIQUE_LISTNER_ID", + "UNIQUE_LISTENER_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 }); } }) @@ -113,12 +93,12 @@ CometChat.addGroupListener( - -```typescript + +```javascript CometChat.addGroupListener( - "UNIQUE_LISTNER_ID", + "UNIQUE_LISTENER_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 }); } }) @@ -130,45 +110,19 @@ CometChat.addGroupListener( -Always remove group listeners when the component unmounts using `CometChat.removeGroupListener(listenerId)`. Failing to remove listeners can cause memory leaks and duplicate event handling. +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 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 - -## Best Practices - - - - Before calling `joinGroup()`, check the `hasJoined` property on the `Group` object. If the user has already joined, calling `joinGroup()` again will return an error. - - - For password-protected groups, prompt the user for the password before calling `joinGroup()`. Pass the password as the third parameter. - - - -## Troubleshooting - - - - Private groups cannot be joined directly. Members must be added by an admin or owner using the group members API. Only public and password-protected groups support `joinGroup()`. - - - Ensure the password string matches exactly. Passwords are case-sensitive. If the user enters an incorrect password, the SDK returns an error. - - - Verify the group listener is registered with `addGroupListener()` before the join event occurs. Also ensure the `listenerId` is unique and hasn't been overwritten. - - +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 --- @@ -176,15 +130,15 @@ For the group member joined event, in the `Action` object received, the followin - Leave groups and stop receiving updates + Allow members to leave a group - - Manage members, roles, and permissions within groups + + Fetch the list of members in a group - Send text, media, and custom messages to groups + Send messages to group conversations - - Fetch group lists and group details + + Programmatically add members to a group - \ No newline at end of file + diff --git a/sdk/react-native/key-concepts.mdx b/sdk/react-native/key-concepts.mdx index 458c45e21..295fb3fd8 100644 --- a/sdk/react-native/key-concepts.mdx +++ b/sdk/react-native/key-concepts.mdx @@ -3,160 +3,144 @@ title: "Key Concepts" description: "Understand the fundamental building blocks of CometChat — users, groups, messaging categories, authentication, and roles." --- - -**Quick Reference** - Core identifiers you'll use throughout the SDK: + -```javascript -// User identified by UID -const user = new CometChat.User("user1"); -user.setName("Kevin"); +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 identified by GUID -const group = new CometChat.Group("group1", "My Group", CometChat.GROUP_TYPE.PUBLIC); +Group types: `Public` | `Password` | `Private` +Member scopes: `Admin` | `Moderator` | `Participant` +Message categories: `message` | `custom` | `action` | `call` | `interactive` + -// Message categories: message | custom | action | call | interactive -``` - +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 - -The CometChat Dashboard enables you to create new apps (projects) and manage your existing apps. - - -**How many apps to create?** - -Ideally, you should create two apps — one for development and one for production. 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. - +## Users -- 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. +A user is anyone who uses CometChat. Each user is uniquely identified by a UID (Unique User Identifier). -## Auth & REST API Keys +- 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 -You can generate two types of keys from the dashboard. +### User Roles -| 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 | +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. - -**Security Warning:** Auth Keys should only be used during development. For production environments, use [Auth Tokens](/sdk/react-native/authentication-overview#login-using-auth-token) generated from your server to authenticate users securely. - +## Authentication -## Users +CometChat does not handle user registration or friends management — you handle that in your app, then log users into CometChat programmatically. -A user is anyone who uses CometChat. +### API Keys -### UID +You can generate two types of keys from the [CometChat Dashboard](https://app.cometchat.com): -- Each user is uniquely identified using a 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 an API call ideally, via a server-to-server call. The auth token should then be given to CometChat for login. -- An Auth Token can only be deleted via the dashboard or using the REST API. +### Auth Tokens -## Authentication +Auth Tokens are secure, per-user credentials for production use: -To allow a user to use CometChat, the user must log in to CometChat. +- 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 - -**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 does not ever directly login to CometChat. - +### Authentication Flow -**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. +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. -### Typical Workflow - -| 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 | - -## 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 - -- 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. +| 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 | ## Groups -A group can be used for multiple users to communicate with each other on a particular topic/interest. - -### GUID +A group enables multiple users to communicate on a particular topic or interest. Each group is uniquely identified using a GUID (Group Unique Identifier). -- Each group is uniquely identified using a 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. +- The GUID is typically the primary ID of the group from your database +- GUID can be alphanumeric with underscore and hyphen only - -GUID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. - +## Group Types -### Types +| 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) | -CometChat supports three different types of groups: +## Member Scopes -| 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 | +Once a user joins a group, they become a member with one of three scopes: -### Members +| 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 | -Once a participant joins a group, they become a member of the group. Members are part of the group indefinitely — they will keep receiving messages, calls & notifications. To stop, the participant must either be kicked, banned or intentionally leave the group. +## Message Categories -CometChat supports three different types of member scopes in a group: +Every message belongs to one of these categories: -| 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 | +| 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 | +| `interactive` | `form`, `card`, `customInteractive` | Interactive messages (forms, cards) | -## Messaging +For more details, see the [Message Structure and Hierarchy](/sdk/react-native/message-structure-and-hierarchy) guide. -Any message in CometChat belongs to one of the following categories: +## Glossary -| 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 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 | -| interactive | Interactive messages encapsulate interactive units within a chat message, such as forms or cards. See [Interactive Messages](/sdk/react-native/interactive-messages) | +| Term | Definition | Learn More | +| --- | --- | --- | +| UID | Unique User Identifier — alphanumeric string you assign to each user | [Users Overview](/sdk/react-native/users-overview) | +| GUID | Group Unique Identifier — alphanumeric string you assign to each group | [Groups Overview](/sdk/react-native/groups-overview) | +| Auth Key | Development-only credential for quick testing. Never use in production | [Authentication](/sdk/react-native/authentication-overview) | +| Auth Token | Secure, per-user token generated via REST API. Use in production | [Authentication](/sdk/react-native/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/react-native/send-message) | +| Scope | Group member scope: `admin`, `moderator`, or `participant` | [Change Member Scope](/sdk/react-native/group-change-member-scope) | +| Listener | Callback handler for real-time events (messages, presence, calls, groups) | [All Real-Time Listeners](/sdk/react-native/real-time-listeners) | +| Conversation | A chat thread between two users or within a group | [Retrieve Conversations](/sdk/react-native/retrieve-conversations) | +| Metadata | Custom JSON data attached to users, groups, or messages | [Send Message](/sdk/react-native/send-message) | +| Tags | String labels for categorizing users, groups, conversations, or messages | [Message Filtering](/sdk/react-native/additional-message-filtering) | +| RequestBuilder | Builder pattern class for constructing filtered/paginated queries | [Message Filtering](/sdk/react-native/additional-message-filtering) | +| AppSettings | Configuration object for initializing the SDK (App ID, Region, presence) | [Setup SDK](/sdk/react-native/setup) | +| Transient Message | Ephemeral message not stored on server (typing indicators, live reactions) | [Transient Messages](/sdk/react-native/transient-messages) | -For more information, you can refer to the [Message Structure and Hierarchy guide](/sdk/react-native/message-structure-and-hierarchy). +--- ## Next Steps - - Initialize CometChat and authenticate users in your app + + Install and initialize the CometChat SDK - - Start sending text, media, and custom messages + + Log users in and manage auth tokens - - Track real-time online/offline status of users + + Send your first text or media message - - Understand message categories, types, and hierarchy + + Create and manage group conversations diff --git a/sdk/react-native/leave-group.mdx b/sdk/react-native/leave-group.mdx index 10f359307..2d8902d4a 100644 --- a/sdk/react-native/leave-group.mdx +++ b/sdk/react-native/leave-group.mdx @@ -1,43 +1,36 @@ --- title: "Leave A Group" -description: "Leave groups, listen for real-time leave events, and handle missed leave events using the CometChat React Native SDK." +sidebarTitle: "Leave Group" +description: "Learn how to leave a group and receive real-time events when members leave using the CometChat React Native SDK." --- - -**Quick Reference** - Leave a group: + ```javascript +// Leave a group await CometChat.leaveGroup("GUID"); + +// Listen for member left events +CometChat.addGroupListener("listener", new CometChat.GroupListener({ + onGroupMemberLeft: (message, leavingUser, group) => { } +})); ``` - + + +Leave a group to stop receiving messages and updates from it. Once you leave, you'll need to rejoin to participate again. -**Available via:** [SDK](/sdk/react-native/leave-group) | [REST API](/rest-api/group-members/kick) +Group owners cannot leave without first transferring ownership to another member. See [Transfer Group Ownership](/sdk/react-native/transfer-group-ownership). ## 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. - -```javascript -var GUID = "GUID"; // guid of the group to join - -CometChat.leaveGroup(GUID).then( -hasLeft => { - console.log("Group left successfully:", hasLeft); -}, error => { - console.log("Group leaving failed with exception:", error); -} -); -``` - - - ```typescript -var GUID: string = "GUID"; +const GUID: string = "GUID"; CometChat.leaveGroup(GUID).then( (hasLeft: boolean) => { @@ -50,36 +43,42 @@ 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 | | --------- | -------------------------------------------- | -| `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** — `leaveGroup()` returns a boolean: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `hasLeft` | boolean | Indicates whether the user successfully left the group | `true` | - - +On success, the method resolves with `true` (boolean). ## 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. - -```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 }); } }) @@ -88,12 +87,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 }); } }) @@ -105,42 +104,19 @@ CometChat.addGroupListener( -Always remove group listeners when the component unmounts using `CometChat.removeGroupListener(listenerId)`. Failing to remove listeners can cause memory leaks and duplicate event handling. +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?* - -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 - -## Best Practices - - - - After successfully leaving a group, remove any local references to the group's messages, members, or conversation data. This prevents stale data from appearing in your UI. - - - If the logged-in user is the group owner, consider transferring ownership to another admin or member before leaving. Leaving as the owner may have different behavior depending on your app's configuration. - - - -## Troubleshooting - - - - Verify the GUID is correct and the logged-in user is actually a member of the group. You can check membership using `getGroup()` and the `hasJoined` property. - - - Ensure the `leaveGroup()` call completed successfully (resolved the promise). Also remove any active group listeners for that group to stop receiving real-time events. - - +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 --- @@ -151,12 +127,12 @@ For the group member left event, in the `Action` object received, the following Join public or password-protected groups - Delete groups and handle related cleanup + Permanently delete a group - - Manage members, roles, and permissions within groups + + Remove or ban members from a group - - Fetch group lists and group details + + Fetch and filter the list of groups - \ No newline at end of file + diff --git a/sdk/react-native/login-listener.mdx b/sdk/react-native/login-listener.mdx index 626896499..bbd648cde 100644 --- a/sdk/react-native/login-listener.mdx +++ b/sdk/react-native/login-listener.mdx @@ -3,10 +3,10 @@ title: "Login Listener" description: "Receive real-time updates for login and logout events using the LoginListener class in CometChat React Native SDK." --- - -**Quick Reference** - Register a login listener: + ```javascript +// Register a login listener CometChat.addLoginListener( "UNIQUE_LISTENER_ID", new CometChat.LoginListener({ @@ -16,107 +16,105 @@ CometChat.addLoginListener( logoutFailure: (e) => console.log("Logout failed", e), }) ); + +// Remove when no longer needed +CometChat.removeLoginListener("UNIQUE_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. LoginListener provides the following 4 methods: +| Callback | Fires when | +|---|---| +| `loginSuccess` | User logged in — provides [`User`](/sdk/reference/entities#user) | +| `loginFailure` | Login failed — provides [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | +| `logoutSuccess` | User logged out | +| `logoutFailure` | Logout failed — provides [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + +The CometChat SDK provides real-time updates for `login` and `logout` events via the `LoginListener` class. -| 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. | -| 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. | +| Callback | Description | +| --- | --- | +| `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). | ## Add Login Listener -To add the `LoginListener`, use the `addLoginListener()` method provided by the SDK. It takes a unique identifier for the listener and an instance of the `LoginListener` class. +Use `addLoginListener()` with a unique identifier and a `LoginListener` instance. - - ```javascript - var 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); - }, - }) - ); - ``` - - - ```typescript - var 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); - }, - }) - ); - ``` - + +```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); + }, + }) +); +``` + + +```javascript +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 -To stop receiving events related to login and logout, use the `removeLoginListener()` method and pass the ID of the listener that needs to be removed. +Remove listeners when they are no longer needed to prevent memory leaks. - - ```javascript - var listenerID = "UNIQUE_LISTENER_ID"; - CometChat.removeLoginListener(listenerID); - ``` - - - ```typescript - var listenerID: string = "UNIQUE_LISTENER_ID"; - CometChat.removeLoginListener(listenerID); - ``` - + +```typescript +const listenerID: string = "UNIQUE_LISTENER_ID"; +CometChat.removeLoginListener(listenerID); +``` + + +```javascript +let listenerID = "UNIQUE_LISTENER_ID"; +CometChat.removeLoginListener(listenerID); +``` + -**Listener Cleanup:** Always remove your login listeners when they are no longer needed (e.g., when a component unmounts) to prevent memory leaks and unexpected behavior. Use `removeLoginListener()` with the same listener ID you used when adding it. +Always remove login listeners when they're no longer needed (e.g., on component unmount). Failing to remove listeners can cause memory leaks and duplicate event handling. - - - - Use unique, descriptive listener IDs to avoid conflicts (e.g., `"login-screen-listener"`) - - Add listeners in component mount lifecycle and remove them on unmount - - Handle all four events to provide a complete user experience - - Use `loginFailure` to display user-friendly error messages - - - - **Listener not firing:** Ensure the listener was added before the login/logout event occurs - - **Duplicate events:** Check that you're not adding the same listener multiple times without removing it first - - **Memory leaks:** Verify that `removeLoginListener()` is called when the component unmounts - - +--- ## Next Steps diff --git a/sdk/react-native/managing-web-sockets-connections-manually.mdx b/sdk/react-native/managing-web-sockets-connections-manually.mdx index 1db29d054..f3679a954 100644 --- a/sdk/react-native/managing-web-sockets-connections-manually.mdx +++ b/sdk/react-native/managing-web-sockets-connections-manually.mdx @@ -3,96 +3,67 @@ title: "Managing Web Sockets Connections Manually" description: "Learn how to manually manage WebSocket connections in the CometChat React Native SDK, including connecting, disconnecting, and maintaining background connections." --- - -**Quick Reference** + + ```javascript -// Disable auto connection during init -new CometChat.AppSettingsBuilder() +// 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 / ping +// Manually connect/disconnect/ping CometChat.connect(); CometChat.disconnect(); -CometChat.ping(); +CometChat.ping(); // Keep alive in background (call within 30s) ``` - - -## Default SDK Behaviour on Login - -When the login method of the SDK is called, the SDK performs the below 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. - -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 the app is reopened, and the init() method is called, the web-socket connection to the server is established automatically. +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. -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. +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. -## Auto Mode +## Default Behavior (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. +When `autoEstablishSocketConnection` is `true` (the default): -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. +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 -| App State | Behaviour | -| ----------------- | --------------------------------------- | -| App in foreground | Connected with WebSocket | +| App State | Behavior | +| --- | --- | +| App in foreground | Connected with WebSocket | | App in background | Immediately disconnected with WebSocket | -Reconnection If the app is in the foreground and there is no internet connection, the SDK will handle the reconnection of the WebSocket in auto mode. +If the app is in the foreground and there is no internet connection, the SDK will handle the reconnection of the WebSocket automatically in auto mode. -## 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. - -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. - -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. - -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. - - - - - -| App State | Behaviour | -| ----------------- | ------------------------------------------------------------------------------------------------------------------ | -| 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 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: - -## Enable Manual Mode +## Manual Connection Management -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: - -```javascript -let appID = "APP_ID"; -let region = "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); } ); @@ -100,20 +71,20 @@ CometChat.init(appID, appSetting).then( - -```typescript -let appID: string = "APP_ID", - region: string = "APP_REGION", - appSetting: CometChat.AppSettings = new CometChat.AppSettingsBuilder() - .subscribePresenceForAllUsers() - .setRegion(region) - .autoEstablishSocketConnection(false) - .build(); + +```javascript +let appID = "APP_ID"; +let region = "APP_REGION"; +let appSetting = new CometChat.AppSettingsBuilder() + .subscribePresenceForAllUsers() + .setRegion(region) + .autoEstablishSocketConnection(false) + .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); } ); @@ -123,103 +94,89 @@ CometChat.init(appID, appSetting).then( -You can manage the connection to the web-socket server using the connect() , disconnect() and ping() methods provided by the SDK. +In manual mode, the SDK will disconnect the WebSocket connection after 30 seconds if the app goes into the background. The connection remains alive for 30 seconds after backgrounding, but disconnects after that if no pings are received. -## Connect to the Web-Socket Server +| App State | Behavior | +| --- | --- | +| App in foreground | Call `CometChat.connect()` to create the WebSocket connection | +| App in background | Disconnects if no ping is received within 30 seconds | -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 +Once initialized with manual mode, use `connect()`, `disconnect()`, and `ping()` to control the WebSocket connection. - - -```javascript -CometChat.connect({onSuccess?: Function, onError?: Function}); -``` +### Connect - +Establishes the WebSocket connection. The user must be logged in first (check with `CometChat.getLoggedinUser()`). Once connected, real-time events start flowing. + ```typescript CometChat.connect({ onSuccess: Function, onError: Function }); ``` - - - - -## Disconnect from the Web-Socket 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. - - ```javascript -CometChat.disconnect({onSuccess?: Function, onError?: Function}); +CometChat.connect({onSuccess?: Function, onError?: Function}); ``` - + +### Disconnect + +Breaks the WebSocket connection. Real-time events stop until you call `connect()` again. + + ```typescript CometChat.disconnect({ onSuccess: Function, onError: Function }); ``` - - - - -### 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. - - -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. - - ```javascript -CometChat.ping({onSuccess?: Function, onError?: Function}); +CometChat.disconnect({onSuccess?: Function, onError?: Function}); ``` - + +### Ping (Background Keep-Alive) + +To keep the WebSocket connection alive when your app is in the background, call `CometChat.ping()` within 30 seconds of your app entering the background or after the previous `ping()` call. + + ```typescript CometChat.ping({ onSuccess: Function, onError: Function }); ``` - - + +```javascript +CometChat.ping({onSuccess?: Function, onError?: Function}); +``` + -## Reconnection + +To ensure the WebSocket connection stays alive, you can create a background service that calls `CometChat.ping()` in a loop every 25 seconds (under the 30-second timeout). + -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 - - -- Use auto mode (default) unless you have a specific need to control the WebSocket lifecycle — it handles reconnection and background disconnection automatically -- In manual mode, always call `CometChat.connect()` after a successful login and before attempting to send or receive messages -- Set up a background task or service to call `CometChat.ping()` every 25 seconds (under the 30-second timeout) if you need background connectivity -- Use the [Connection Status](/sdk/react-native/connection-status) listener alongside manual mode to track when the connection drops and reconnects -- Always call `CometChat.disconnect()` when the user logs out to clean up resources - +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()`, you will need to call `CometChat.connect()` to create a new WebSocket connection. - -- **Not receiving real-time events in manual mode**: Ensure you called `CometChat.connect()` after login. In manual mode, the SDK does not connect automatically. -- **Connection drops after 30 seconds in background**: This is expected behavior. Call `CometChat.ping()` within 30 seconds to keep the connection alive. -- **`connect()` fails**: Verify the user is logged in using `CometChat.getLoggedInUser()`. The SDK requires an authenticated user before establishing a WebSocket connection. -- **Messages missed while disconnected**: Fetch missed messages using `MessagesRequest` after reconnecting. The SDK does not queue messages during disconnection. - - +--- ## Next Steps - -Monitor real-time WebSocket connection status - - -Register listeners for users, groups, messages, and calls - + + Monitor the SDK connection state in real time + + + Complete reference for all SDK event listeners + + + SDK installation and initialization guide + + + Review the fundamental building blocks of CometChat + diff --git a/sdk/react-native/mentions.mdx b/sdk/react-native/mentions.mdx index d05d9cc13..d79b7c4a0 100644 --- a/sdk/react-native/mentions.mdx +++ b/sdk/react-native/mentions.mdx @@ -1,22 +1,27 @@ --- title: "Mentions" -description: "Learn how to mention users in messages using the CometChat React Native SDK. Use the <@uid:UID> format to tag specific users in text and media message captions." +sidebarTitle: "Mentions" +description: "Send messages with user mentions, retrieve mentioned users, and filter messages by mention metadata using the CometChat React Native SDK." --- - -**Quick Reference** - Mention a user in a message: + ```javascript -// Use the format <@uid:UID> to mention users -let messageText = "Hello, <@uid:cometchat-uid-1>"; -let textMessage = new CometChat.TextMessage("RECEIVER_ID", messageText, CometChat.RECEIVER_TYPE.USER); -CometChat.sendMessage(textMessage); -``` - +let message = {}; // obtained from MessageListener or fetchPrevious/fetchNext - -Available via: [SDK](/sdk/react-native/mentions) | [REST API](/rest-api/messages/list-messages) | [UI Kits](/ui-kit/react-native/core-features#mentions) - +// 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. @@ -24,10 +29,27 @@ Mentions are a powerful tool for enhancing communication in messaging platforms. ## 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>`" +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>"` - + +```typescript +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) => { + console.log("Message sent successfully:", message); + }, (error: CometChat.CometChatException) => { + console.log("Message sending failed with error:", error); + } +); +``` + + + ```javascript let receiverID = "UID"; let messageText = "Hello, <@uid:cometchat-uid-1>"; @@ -47,304 +69,93 @@ CometChat.sendMessage(textMessage).then( } ); ``` - - -```javascript -let receiverID = "GUID"; -let messageText = "Hello <@uid:cometchat-uid-1>"; -let receiverType = CometChat.RECEIVER_TYPE.GROUP; -let textMessage = new CometChat.TextMessage( + +```typescript +let receiverID: string = "GUID"; +let messageText: string = "Hello <@uid:cometchat-uid-1>"; +let receiverType: string = CometChat.RECEIVER_TYPE.GROUP; +let textMessage: CometChat.TextMessage = new CometChat.TextMessage( receiverID, messageText, receiverType ); CometChat.sendMessage(textMessage).then( - (message) => { + (message: CometChat.TextMessage) => { console.log("Message sent successfully:", message); }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Message sending failed with error:", error); } ); ``` - - -```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); - -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 +let receiverID = "GUID"; +let messageText = "Hello <@uid:cometchat-uid-1>"; +let receiverType = CometChat.RECEIVER_TYPE.GROUP; +let textMessage = new CometChat.TextMessage( + receiverID, + messageText, + receiverType ); -``` - - - - -```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) => { + (message) => { console.log("Message sent successfully:", message); }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Message sending failed with error:", error); } ); ``` - - -**On Success** — `sendMessage()` with mentions returns the sent message object with `mentionedUsers` populated: - - - -**Message Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25326"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-7"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text with mention format | `"Hello <@uid:cometchat-uid-7>, this is a test mention!"` | -| `sentAt` | number | Unix timestamp when sent | `1772006074` | -| `updatedAt` | number | Unix timestamp when updated | `1772006074` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | -| `mentionedUsers` | array | Users mentioned in message | [See below ↓](#send-mention-mentionedusers-array) | -| `sender` | object | Sender user details | [See below ↓](#send-mention-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#send-mention-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#send-mention-data-object) | -| `reactions` | array | Message reactions | `[]` | - ---- - - - -**`mentionedUsers` Array (per item):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1772005334` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1772004288` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1772005334` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Hello <@uid:cometchat-uid-7>, this is a test mention!"` | -| `entities` | object | Sender and receiver entities | [See below ↓](#send-mention-data-entities-object) | -| `mentions` | object | Mentioned users map | [See below ↓](#send-mention-data-mentions-object) | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#send-mention-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#send-mention-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#send-mention-data-entities-sender-entity-object) | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1772004288` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#send-mention-data-entities-receiver-entity-object) | - ---- - - - -**`data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1772005334` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.mentions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `cometchat-uid-7` | object | Mentioned user details keyed by UID | [See below ↓](#send-mention-data-mentions-user-object) | - ---- - - - -**`data.mentions["cometchat-uid-7"]` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1772005334` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | - - - You can mention user in text message and media messages captions - -**Push Notifications & UI Rendering:** While the message format uses `<@uid:UID>`, push notifications are sent with the parsed body containing the actual username — not the raw `<@uid:>` format. For UI rendering with the SDK, use `message.getMentionedUsers()` to get the mentioned user objects (which include both `uid` and `name`) and replace the `<@uid:>` tags in your message bubble accordingly. If you're using a UI Kit, this is handled automatically. - - - ## 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 tags and blocked relationships. -| Setting | Description | -| ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `mentionsWithTagInfo(boolean value)` | If set to `true`, SDK will fetch a list of messages where users are mentioned & will also fetch the tags of the mentioned users. **Default value = false** | -| `mentionsWithBlockedInfo(boolean value)` | If set to `true`, SDK will fetch a list of messages where users are mentioned & will also fetch their blocked relationship with the logged-in user. **Default value = false** | +| Setting | Description | +| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| mentionsWithTagInfo(boolean value) | If set to `true`, SDK will fetch a list of messages where users are mentioned & will also fetch the tags of the mentioned users. **Default value = false.** | +| mentionsWithBlockedInfo(boolean value) | If set to `true`, SDK will fetch a list of messages where users are mentioned & will also fetch their blocked relationship with the logged-in user. **Default value = false.** | ## Mentions With Tag Info To get a list of messages in a conversation where users are mentioned along with the user tags of the mentioned users. - -```javascript -let UID = "UID"; -let limit = 30; - -var messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setLimit(limit) - .mentionsWithTagInfo(true) - .build(); + +```typescript +let UID: string = "UID", + limit: number = 30, + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setLimit(limit) + .mentionsWithTagInfo(true) + .build(); messagesRequest.fetchPrevious().then( - (messages) => { - messages.forEach((eachMessage) => { - eachMessage.getMentionedUsers().forEach((eachMentionedUser) => { - console.log(eachMentionedUser.getTags()); - }); + (messages: CometChat.BaseMessage[]) => { + messages.forEach((eachMessage: CometChat.BaseMessage) => { + eachMessage + .getMentionedUsers() + .forEach((eachMentionedUser: CometChat.User) => { + console.log(eachMentionedUser.getTags()); + }); }); }, (error) => { @@ -352,16 +163,15 @@ messagesRequest.fetchPrevious().then( } ); ``` - - + ```javascript -let GUID = "GUID"; +let UID = "UID"; let limit = 30; -var messagesRequest = new CometChat.MessagesRequestBuilder() - .setGUID(GUID) +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setUID(UID) .setLimit(limit) .mentionsWithTagInfo(true) .build(); @@ -379,16 +189,15 @@ messagesRequest.fetchPrevious().then( } ); ``` - - + ```typescript -let UID: string = "UID", +let GUID: string = "GUID", limit: number = 30, messagesRequest: CometChat.MessagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) + .setGUID(GUID) .setLimit(limit) .mentionsWithTagInfo(true) .build(); @@ -408,28 +217,25 @@ messagesRequest.fetchPrevious().then( } ); ``` - - -```typescript -let GUID: string = "GUID", - limit: number = 30, - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setLimit(limit) - .mentionsWithTagInfo(true) - .build(); + +```javascript +let GUID = "GUID"; +let limit = 30; + +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setLimit(limit) + .mentionsWithTagInfo(true) + .build(); messagesRequest.fetchPrevious().then( - (messages: CometChat.BaseMessage[]) => { - messages.forEach((eachMessage: CometChat.BaseMessage) => { - eachMessage - .getMentionedUsers() - .forEach((eachMentionedUser: CometChat.User) => { - console.log(eachMentionedUser.getTags()); - }); + (messages) => { + messages.forEach((eachMessage) => { + eachMessage.getMentionedUsers().forEach((eachMentionedUser) => { + console.log(eachMentionedUser.getTags()); + }); }); }, (error) => { @@ -437,45 +243,50 @@ messagesRequest.fetchPrevious().then( } ); ``` - - -**On Success** — `mentionsWithTagInfo(true)` returns mentioned users with their tags: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `tags` | array | User's tags | `["vip"]` | - - +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. +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 -let UID = "UID"; -let limit = 30; -var messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setLimit(limit) - .mentionsWithBlockedInfo(true) - .build(); + +```typescript +let UID: string = "UID", + limit: number = 30, + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setLimit(limit) + .mentionsWithBlockedInfo(true) + .build(); messagesRequest.fetchPrevious().then( - (messages) => { - messages.forEach((eachMessage) => { - eachMessage.getMentionedUsers().forEach((eachMentionedUser) => { - console.log("blockedByMe: " + eachMentionedUser.getBlockedByMe()); - console.log("hasBlockedMe: " + eachMentionedUser.getHasBlockedMe()); - }); + (messages: CometChat.BaseMessage[]) => { + messages.forEach((eachMessage: CometChat.BaseMessage) => { + eachMessage + .getMentionedUsers() + .forEach((eachMentionedUser: CometChat.User) => { + console.log("blockedByMe: " + eachMentionedUser.getBlockedByMe()); + console.log("hasBlockedMe: " + eachMentionedUser.getHasBlockedMe()); + }); }); }, (error) => { @@ -483,16 +294,15 @@ messagesRequest.fetchPrevious().then( } ); ``` - - + ```javascript -let GUID = "GUID"; +let UID = "UID"; let limit = 30; -var messagesRequest = new CometChat.MessagesRequestBuilder() - .setGUID(GUID) +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setUID(UID) .setLimit(limit) .mentionsWithBlockedInfo(true) .build(); @@ -511,16 +321,15 @@ messagesRequest.fetchPrevious().then( } ); ``` - - + ```typescript -let UID: string = "UID", +let GUID: string = "GUID", limit: number = 30, messagesRequest: CometChat.MessagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) + .setGUID(GUID) .setLimit(limit) .mentionsWithBlockedInfo(true) .build(); @@ -541,29 +350,26 @@ messagesRequest.fetchPrevious().then( } ); ``` - - -```typescript -let GUID: string = "GUID", - limit: number = 30, - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setLimit(limit) - .mentionsWithBlockedInfo(true) - .build(); + +```javascript +let GUID = "GUID"; +let limit = 30; + +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setLimit(limit) + .mentionsWithBlockedInfo(true) + .build(); messagesRequest.fetchPrevious().then( - (messages: CometChat.BaseMessage[]) => { - messages.forEach((eachMessage: CometChat.BaseMessage) => { - eachMessage - .getMentionedUsers() - .forEach((eachMentionedUser: CometChat.User) => { - console.log("blockedByMe: " + eachMentionedUser.getBlockedByMe()); - console.log("hasBlockedMe: " + eachMentionedUser.getHasBlockedMe()); - }); + (messages) => { + messages.forEach((eachMessage) => { + eachMessage.getMentionedUsers().forEach((eachMentionedUser) => { + console.log("blockedByMe: " + eachMentionedUser.getBlockedByMe()); + console.log("hasBlockedMe: " + eachMentionedUser.getHasBlockedMe()); + }); }); }, (error) => { @@ -571,93 +377,35 @@ messagesRequest.fetchPrevious().then( } ); ``` - - -**On Success** — `mentionsWithBlockedInfo(true)` returns mentioned users with blocked relationship info: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | - - - - ## Get Users Mentioned In a Particular 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. ```javascript -message.getMentionedUsers(); +message.getMentionedUsers() ``` - -**On Success** — `getMentionedUsers()` returns an array of mentioned user objects: +The `getMentionedUsers()` method returns an array of [`User`](/sdk/reference/entities#user) objects. -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | - - - -## Best Practices - - - - Always use the `<@uid:UID>` format when mentioning users. The UID must exactly match the user's unique identifier in CometChat. Incorrect UIDs will not resolve to a valid mention. - - - Before sending a message with mentions, verify that the UIDs you are referencing exist in your CometChat app. Mentioning non-existent UIDs will not throw an error, but the mention will not resolve to a user on the recipient's end. - - - Use `mentionsWithTagInfo(true)` and `mentionsWithBlockedInfo(true)` on your `MessagesRequestBuilder` when you need to display additional context about mentioned users, such as their roles (via tags) or blocked status. Avoid enabling these filters unnecessarily to reduce payload size. - - - Mentions are supported in text messages and media message captions. Ensure your UI handles rendering mentions consistently across both message types. - - - -## Troubleshooting - - - - Ensure you are using the correct `<@uid:UID>` format. The UID must be wrapped exactly as `<@uid:your-uid-here>`. Also verify that the mentioned user exists in your CometChat app. Use `message.getMentionedUsers()` to confirm the SDK parsed the mentions correctly. - - - This typically means the mention format in the message text is incorrect or the UID does not match any registered user. Double-check the message text for proper `<@uid:UID>` syntax and ensure there are no extra spaces or typos in the UID. - - - Make sure you have set `mentionsWithTagInfo(true)` or `mentionsWithBlockedInfo(true)` on your `MessagesRequestBuilder` before calling `fetchPrevious()`. These filters are disabled by default. - - - Verify that you are setting the caption text with the `<@uid:UID>` format on the media message object. Mentions in captions follow the same format as text messages. - - +--- ## Next Steps - - Learn how to send text, media, and custom messages to users and groups. + + Send text, media, and custom messages - - Set up real-time message listeners and fetch message history. + + Listen for incoming messages in real time - Add emoji reactions to messages for richer user interactions. + Add emoji reactions to messages - Organize conversations with threaded replies on messages. + Organize conversations with message threads - \ No newline at end of file + diff --git a/sdk/react-native/message-structure-and-hierarchy.mdx b/sdk/react-native/message-structure-and-hierarchy.mdx index e046e938b..7b41e3db4 100644 --- a/sdk/react-native/message-structure-and-hierarchy.mdx +++ b/sdk/react-native/message-structure-and-hierarchy.mdx @@ -1,130 +1,187 @@ --- -title: "Message Structure And Hierarchy" -description: "Understand the various message categories, types, and statuses in CometChat — including message, custom, action, call, and interactive messages." +title: "Message Structure and Hierarchy" +sidebarTitle: "Message Structure" +description: "Understand the message categories, types, and hierarchy in the CometChat React Native SDK including text, media, custom, action, call, and interactive messages." --- - -**Quick Reference** - Message categories and their common types: + -```javascript -// Check message category and type -const category = message.getCategory(); // "message" | "custom" | "action" | "call" | "interactive" -const type = message.getType(); // "text" | "image" | "video" | "audio" | "file" | custom type -``` - +Message categories and types: +- **message** → `text`, `image`, `video`, `audio`, `file` +- **custom** → Developer-defined types (e.g., `location`, `poll`) +- **action** → `groupMember` (joined/left/kicked/banned), `message` (edited/deleted) +- **call** → `audio`, `video` +- **interactive** → `form`, `card`, `customInteractive` + -The diagram below helps you understand the various message categories and types that a CometChat message can belong to. +Every message in CometChat belongs to a category (`message`, `custom`, `action`, `call`, `interactive`) and has a specific type within that category. + +## Message Hierarchy -As you can see in the above diagram, every message belongs to a particular category. A message can belong to one of the 5 categories: - -1. Message -2. Custom -3. Action -4. Call -5. Interactive - -Each category can be further classified into types. - -## Message +## Categories Overview + +| Category | Types | Description | +| --- | --- | --- | +| `message` | `text`, `image`, `video`, `audio`, `file` | Standard user messages | +| `custom` | Developer-defined | Custom data (location, polls, etc.) | +| `action` | `groupMember`, `message` | System-generated events | +| `call` | `audio`, `video` | Call-related messages | +| `interactive` | `form`, `card`, `customInteractive` | Interactive messages (forms, cards) | + +## Checking Message Category and Type + +Use `getCategory()` and `getType()` to determine how to handle a received message: + + + +```typescript +const category: string = message.getCategory(); +const type: string = 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()); + } 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 type:", type, "data:", customMsg.getData()); + break; + case CometChat.CATEGORY_ACTION: + console.log("Action:", message.getAction()); + break; + case CometChat.CATEGORY_CALL: + console.log("Call status:", message.getStatus()); + break; +} +``` + -A message belonging to the category `message` can be classified into one of the following types: + +```javascript +const category = message.getCategory(); +const type = message.getType(); + +switch (category) { + case CometChat.CATEGORY_MESSAGE: + if (type === CometChat.MESSAGE_TYPE.TEXT) { + 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 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; +} +``` + -| Type | Description | -|-------|----------------------| -| text | A plain text message | -| image | An image message | -| video | A video message | -| audio | An audio message | -| file | A file message | + -## Custom +## Standard Messages (`message` Category) -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. +Messages with category `message` are standard user-sent messages: -A good example of a custom message would be sharing location coordinates. In this case, the developer can decide to use the custom message with type set to `location`. +| Type | Description | +| --- | --- | +| `text` | Plain text message | +| `image` | Image attachment | +| `video` | Video attachment | +| `audio` | Audio attachment | +| `file` | File attachment | -## Interactive +## Custom Messages (`custom` Category) -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. +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`). -| Type | Description | -|-------------------|----------------------------------------| -| form | For interactive form messages | -| card | For interactive card messages | -| customInteractive | For custom interaction 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 } +); +``` - -To learn more about Interactive messages, please refer to the [Interactive Messages](/sdk/react-native/interactive-messages) guide. - +See [Send Message → Custom Messages](/sdk/react-native/send-message#custom-message) for details. -## Action +## Interactive Messages (`interactive` Category) -Action messages are system-generated messages. Messages belonging to the `action` category can further be classified into one of the below types: +An InteractiveMessage encapsulates an interactive unit within a chat message, such as an embedded form that users can fill out directly within the chat interface. -| Type | Description | -|-------------|----------------------------------------| -| groupMember | Action performed on a group member | -| message | Action performed on a message | +| Type | Description | +| --- | --- | +| `form` | Interactive form messages | +| `card` | Interactive card messages | +| `customInteractive` | Custom interaction messages | -Action messages hold another property called `action` which determines the action that has been performed. +See [Interactive Messages](/sdk/react-native/interactive-messages) for details. -### groupMember Actions +## Action Messages (`action` Category) -| Action | Description | -|--------------|------------------------------------------------| -| joined | When a group member joins a group | -| left | When a group member leaves a group | -| kicked | When a group member is kicked from the group | -| banned | When a group member is banned from the group | -| unbanned | When a group member is unbanned from the group | -| added | When a user is added to the group | -| scopeChanged | When the scope of a group member is changed | +Action messages are system-generated events. They have a `type` and an `action` property: -### message Actions +**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 -| Action | Description | -|---------|----------------------------| -| edited | When a message is edited | -| deleted | When a message is deleted | +**Type: `message`** — Actions on messages: +- `edited` — Message was edited +- `deleted` — Message was deleted -## Call +## Call Messages (`call` Category) -Messages with the category `call` are calling-related messages. These can belong to either one of the 2 types: +Call messages track call events with types `audio` or `video`. The `status` property indicates the call state: -| Type | Description | -|-------|------------------| -| audio | Audio call | -| video | Video call | +| 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 | -The call messages have a property called `status` that helps you determine the status of the call: +See [Default Calling](/sdk/react-native/default-call) or [Direct Calling](/sdk/react-native/direct-call) for implementation. -| Status | Description | -|-------------|--------------------------------------------------------------------| -| initiated | When a call is initiated to a user/group | -| ongoing | When the receiver of the call has accepted the call | -| canceled | When the call has been canceled by the initiator of the call | -| rejected | When the call has been rejected by the receiver of the call | -| unanswered | When the call was not answered by the receiver | -| busy | When the receiver of the call was busy on another call | -| ended | When the call was successfully completed and ended by either party | +--- ## Next Steps - - Start sending text, media, and custom messages + + Send text, media, and custom messages + + + Listen for incoming messages in real time Build forms, cards, and custom interactive messages - - Listen for and handle incoming messages in real-time - - - Review the fundamental building blocks of CometChat + + Advanced message filtering with RequestBuilder diff --git a/sdk/react-native/messaging-overview.mdx b/sdk/react-native/messaging-overview.mdx index 103f66e97..3f4c4ea60 100644 --- a/sdk/react-native/messaging-overview.mdx +++ b/sdk/react-native/messaging-overview.mdx @@ -4,26 +4,15 @@ sidebarTitle: "Overview" description: "Overview of CometChat messaging capabilities — send, receive, and fetch message history for text, media, custom, and interactive messages." --- - -**Quick Reference** - Core messaging methods: - -```javascript -// Send a text message -const textMessage = new CometChat.TextMessage("UID", "Hello!", CometChat.RECEIVER_TYPE.USER); -await CometChat.sendMessage(textMessage); - -// Listen for incoming messages -CometChat.addMessageListener("listener-id", new CometChat.MessageListener({ - onTextMessageReceived: (msg) => console.log("Text:", msg), - onMediaMessageReceived: (msg) => console.log("Media:", msg), - onCustomMessageReceived: (msg) => console.log("Custom:", msg), -})); -``` - - - -Available via: [SDK](/sdk/react-native/messaging-overview) | [REST API](/rest-api/messages) | [UI Kits](/ui-kit/react-native/core-features#instant-messaging) - +{/* TL;DR for Agents and Quick Reference */} + + +Choose your path: +- **Send Messages** → [Send Message](/sdk/react-native/send-message) - Text, media, custom +- **Receive Messages** → [Receive Messages](/sdk/react-native/receive-messages) - Real-time listeners +- **Edit/Delete** → [Edit](/sdk/react-native/edit-message) | [Delete](/sdk/react-native/delete-message) +- **Advanced** → [Threads](/sdk/react-native/threaded-messages) | [Reactions](/sdk/react-native/reactions) | [Mentions](/sdk/react-native/mentions) + Messaging is one of the core features of CometChat. We've thoughtfully created methods to help you send, receive and fetch message history. @@ -31,633 +20,8 @@ At the minimum, you must add code for [sending messages](/sdk/react-native/send- Once you've implemented that, you can proceed to more advanced features like [typing indicators](/sdk/react-native/typing-indicators) and [delivery & read receipts](/sdk/react-native/delivery-read-receipts). -### Send a Message - -Use `CometChat.sendMessage()` to send a text message to a user or group. The method returns a `TextMessage` object on success. - - -**On Success** — Returns a TextMessage object: - - - -**TextMessage Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25182"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `text` | string | Message text content | `"Hello"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `receiverId` | string | UID of the receiver | `"cometchat-uid-3"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `sentAt` | number | Unix timestamp when sent | `1771320772` | -| `updatedAt` | number | Unix timestamp of last update | `1771320772` | -| `sender` | object | Sender user details | [See below ↓](#send-message-overview-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#send-message-overview-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#send-message-overview-data-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether logged-in user is mentioned | `false` | -| `metadata` | object | Custom metadata | `{"@injected": {"extensions": {"link-preview": {"links": []}}}}` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the sender | `"cometchat-uid-2"` | -| `name` | string | Display name | `"George Alan"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | Online status | `"online"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771320632` | -| `hasBlockedMe` | boolean | Whether sender has blocked logged-in user | `false` | -| `blockedByMe` | boolean | Whether logged-in user has blocked sender | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-3"` | -| `name` | string | Display name | `"Nancy Grace"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | Online status | `"online"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771320647` | -| `hasBlockedMe` | boolean | Whether receiver has blocked logged-in user | `false` | -| `blockedByMe` | boolean | Whether logged-in user has blocked receiver | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Hello"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_13-..."` | -| `entities` | object | Sender and receiver entities | [See below ↓](#send-message-overview-data-entities-object) | -| `metadata` | object | Injected metadata from extensions | `{"@injected": {"extensions": {"link-preview": {"links": []}}}}` | -| `moderation` | object | Moderation status | [See below ↓](#send-message-overview-data-moderation-object) | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#send-message-overview-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#send-message-overview-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | Sender user details | [See below ↓](#send-message-overview-data-entities-sender-entity-object) | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier | `"cometchat-uid-2"` | -| `name` | string | Display name | `"George Alan"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | Online status | `"online"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771320632` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | Receiver user details | [See below ↓](#send-message-overview-data-entities-receiver-entity-object) | - ---- - - - -**`data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier | `"cometchat-uid-3"` | -| `name` | string | Display name | `"Nancy Grace"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | Online status | `"online"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771320647` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.moderation` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `status` | string | Moderation status | `"pending"` | - - - -### Receive Messages in Real Time - -Use `CometChat.addMessageListener()` to listen for incoming text, media, and custom messages while your app is running. - - - -**onTextMessageReceived** — Returns a TextMessage object: - - - -**TextMessage Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25180"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `text` | string | Message text content | `"Hello"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `receiverId` | string | UID of the receiver | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `sentAt` | number | Unix timestamp when sent | `1771320657` | -| `updatedAt` | number | Unix timestamp of last update | `1771320657` | -| `sender` | object | Sender user details | [See below ↓](#listener-text-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#listener-text-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#listener-text-data-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether logged-in user is mentioned | `false` | -| `metadata` | object | Custom metadata | `{"@injected": {"extensions": {"link-preview": {"links": []}}}}` | - ---- - - - -**`sender` Object (TextMessage):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the sender | `"cometchat-uid-3"` | -| `name` | string | Display name | `"Nancy Grace"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | Online status | `"online"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771320647` | -| `hasBlockedMe` | boolean | Whether sender has blocked logged-in user | `false` | -| `blockedByMe` | boolean | Whether logged-in user has blocked sender | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object (TextMessage):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-2"` | -| `name` | string | Display name | `"George Alan"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | Online status | `"online"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771320632` | -| `hasBlockedMe` | boolean | Whether receiver has blocked logged-in user | `false` | -| `blockedByMe` | boolean | Whether logged-in user has blocked receiver | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object (TextMessage):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Hello"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_13-..."` | -| `entities` | object | Sender and receiver entities | [See below ↓](#listener-text-data-entities-object) | -| `metadata` | object | Injected metadata from extensions | `{"@injected": {"extensions": {"link-preview": {"links": []}}}}` | -| `moderation` | object | Moderation status | `{"status": "approved"}` | - ---- - - - -**`data.entities` Object (TextMessage):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#listener-text-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#listener-text-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object (TextMessage):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | Sender user details | [See below ↓](#listener-text-data-entities-sender-entity-object) | - ---- - - - -**`data.entities.sender.entity` Object (TextMessage):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier | `"cometchat-uid-3"` | -| `name` | string | Display name | `"Nancy Grace"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | Online status | `"online"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771320647` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.entities.receiver` Object (TextMessage):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | Receiver user details | [See below ↓](#listener-text-data-entities-receiver-entity-object) | - ---- - - - -**`data.entities.receiver.entity` Object (TextMessage):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier | `"cometchat-uid-2"` | -| `name` | string | Display name | `"George Alan"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | Online status | `"online"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771320632` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `tags` | array | User tags | `[]` | - --- -**onMediaMessageReceived** — Returns a MediaMessage object: - - - -**MediaMessage Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25183"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `type` | string | Media type | `"image"` | -| `category` | string | Message category | `"message"` | -| `receiverId` | string | UID of the receiver | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `sentAt` | number | Unix timestamp when sent | `1771320862` | -| `updatedAt` | number | Unix timestamp of last update | `1771320862` | -| `sender` | object | Sender user details | [See below ↓](#listener-media-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#listener-media-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#listener-media-data-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether logged-in user is mentioned | `false` | - ---- - - - -**`sender` Object (MediaMessage):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the sender | `"cometchat-uid-3"` | -| `name` | string | Display name | `"Nancy Grace"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | Online status | `"offline"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771320859` | -| `hasBlockedMe` | boolean | Whether sender has blocked logged-in user | `false` | -| `blockedByMe` | boolean | Whether logged-in user has blocked sender | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object (MediaMessage):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-2"` | -| `name` | string | Display name | `"George Alan"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | Online status | `"online"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771320632` | -| `hasBlockedMe` | boolean | Whether receiver has blocked logged-in user | `false` | -| `blockedByMe` | boolean | Whether logged-in user has blocked receiver | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object (MediaMessage):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `type` | string | Media type | `"image"` | -| `category` | string | Message category | `"message"` | -| `url` | string | URL to the media file | `"https://data-in.cometchat.io/.../1771320861_514214897_9876c9a3f300f29c8ee619765c1ad768.jpg"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_13-..."` | -| `attachments` | array | Media attachments | [See below ↓](#listener-media-data-attachments-array) | -| `entities` | object | Sender and receiver entities | [See below ↓](#listener-media-data-entities-object) | -| `moderation` | object | Moderation status | `{"status": "approved"}` | - ---- - - - -**`data.attachments` Array (per item):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `url` | string | URL to the attachment | `"https://data-in.cometchat.io/.../1771320861_514214897_9876c9a3f300f29c8ee619765c1ad768.jpg"` | -| `name` | string | File name | `"44.jpg"` | -| `mimeType` | string | MIME type | `"image/jpeg"` | -| `extension` | string | File extension | `"jpg"` | -| `size` | number | File size in bytes | `142099` | - ---- - - - -**`data.entities` Object (MediaMessage):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#listener-media-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#listener-media-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object (MediaMessage):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | Sender user details | [See below ↓](#listener-media-data-entities-sender-entity-object) | - ---- - - - -**`data.entities.sender.entity` Object (MediaMessage):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier | `"cometchat-uid-3"` | -| `name` | string | Display name | `"Nancy Grace"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | Online status | `"offline"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771320859` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.entities.receiver` Object (MediaMessage):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | Receiver user details | [See below ↓](#listener-media-data-entities-receiver-entity-object) | - ---- - - - -**`data.entities.receiver.entity` Object (MediaMessage):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier | `"cometchat-uid-2"` | -| `name` | string | Display name | `"George Alan"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | Online status | `"online"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771320632` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `tags` | array | User tags | `[]` | - ---- - -**onCustomMessageReceived** — Returns a CustomMessage object: - - - -**CustomMessage Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25191"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `type` | string | Custom message type | `"test-custom"` | -| `category` | string | Message category | `"custom"` | -| `receiverId` | string | UID of the receiver | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `sentAt` | number | Unix timestamp when sent | `1771324025` | -| `updatedAt` | number | Unix timestamp of last update | `1771324025` | -| `customData` | object | Custom payload data | [See below ↓](#listener-custom-customdata-object) | -| `sender` | object | Sender user details | [See below ↓](#listener-custom-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#listener-custom-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#listener-custom-data-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether logged-in user is mentioned | `false` | -| `metadata` | object | Custom metadata | `{"@injected": {"extensions": {"link-preview": {"links": []}}}}` | - ---- - - - -**`customData` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `greeting` | string | Custom greeting message | `"Hello from custom message!"` | -| `timestamp` | number | Custom timestamp | `1771324022864` | - ---- - - - -**`sender` Object (CustomMessage):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the sender | `"cometchat-uid-3"` | -| `name` | string | Display name | `"Nancy Grace"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | Online status | `"offline"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771323567` | -| `hasBlockedMe` | boolean | Whether sender has blocked logged-in user | `false` | -| `blockedByMe` | boolean | Whether logged-in user has blocked sender | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object (CustomMessage):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-2"` | -| `name` | string | Display name | `"George Alan"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | Online status | `"online"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771323089` | -| `hasBlockedMe` | boolean | Whether receiver has blocked logged-in user | `false` | -| `blockedByMe` | boolean | Whether logged-in user has blocked receiver | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object (CustomMessage):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Fallback text | `"Sent a custom message"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `customData` | object | Custom payload data | `{"greeting": "Hello from custom message!", "timestamp": 1771324022864}` | -| `entities` | object | Sender and receiver entities | [See below ↓](#listener-custom-data-entities-object) | -| `metadata` | object | Injected metadata from extensions | `{"@injected": {"extensions": {"link-preview": {"links": []}}}}` | -| `moderation` | object | Moderation status | `{"status": "approved"}` | - ---- - - - -**`data.entities` Object (CustomMessage):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#listener-custom-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#listener-custom-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object (CustomMessage):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | Sender user details | [See below ↓](#listener-custom-data-entities-sender-entity-object) | - ---- - - - -**`data.entities.sender.entity` Object (CustomMessage):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier | `"cometchat-uid-3"` | -| `name` | string | Display name | `"Nancy Grace"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | Online status | `"offline"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771323567` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.entities.receiver` Object (CustomMessage):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | Receiver user details | [See below ↓](#listener-custom-data-entities-receiver-entity-object) | - ---- - - - -**`data.entities.receiver.entity` Object (CustomMessage):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier | `"cometchat-uid-2"` | -| `name` | string | Display name | `"George Alan"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | Online status | `"online"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771323089` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `tags` | array | User tags | `[]` | - - - ## Next Steps @@ -667,10 +31,10 @@ Use `CometChat.addMessageListener()` to listen for incoming text, media, and cus Listen for real-time messages and fetch missed messages + + Understand message categories and types + Show real-time typing status in conversations - - Track when messages are delivered and read - diff --git a/sdk/react-native/overview.mdx b/sdk/react-native/overview.mdx index 66a78f663..1ed3dcd15 100644 --- a/sdk/react-native/overview.mdx +++ b/sdk/react-native/overview.mdx @@ -1,430 +1,118 @@ --- -title: "Overview" -description: "Get started with CometChat React Native SDK - initialize, authenticate users, and integrate chat functionality into your React Native application." +title: "React Native SDK" +sidebarTitle: "Overview" +description: "Add real-time chat, voice, and video to your React Native application with the CometChat SDK." --- - -**Quick Reference** - Copy-paste ready initialization and login: - -```javascript -useEffect(() => { - const initCometChat = async () => { - const appSetting = new CometChat.AppSettingsBuilder() - .subscribePresenceForAllUsers() - .setRegion("REGION") - .autoEstablishSocketConnection(true) - .build(); - await CometChat.init("APP_ID", appSetting); - - // Login user (check if already logged in first) - const loggedInUser = await CometChat.getLoggedinUser(); - if (!loggedInUser) { - await CometChat.login("USER_UID", "AUTH_KEY"); - } - }; - initCometChat(); -}, []); -``` - - -This guide demonstrates how to add chat to a React Native application using CometChat. Before you begin, we strongly recommend you read the [Key Concepts](/sdk/react-native/key-concepts) guide. - -#### I want to integrate with my app - -1. [Get your Application Keys](#get-your-application-keys) -2. [Add the CometChat Dependency](#add-the-cometchat-dependency) -3. [Initialize CometChat](#initialize-cometchat) -4. [Register and Login your user](#register-and-login-your-user) -5. [Integrate our UI Kits](#integrate-our-ui-kits) - -#### I want to explore a sample app (includes UI) - -Open the app folder in your favorite code editor and follow the steps mentioned in the `README.md` file. - - - Explore a complete React Native chat application with UI components - - -## Get your Application Keys - -[Signup for CometChat](https://app.cometchat.com) and then: - - - - Create a new application in your CometChat dashboard - - - Head over to the **API & Auth Keys** section and note the **Auth Key**, **App ID** & **Region** - - - -## Add the CometChat Dependency - -Install the package as an NPM module: - - - - ```bash - npm install @cometchat/chat-sdk-react-native - ``` - - - ```bash - yarn add @cometchat/chat-sdk-react-native - ``` - - - -**To integrate the CometChat React Native SDK, you need to install one more dependency.** - -### Async-Storage - - - - ```bash - npm install @react-native-async-storage/async-storage - ``` - - - ```bash - yarn add @react-native-async-storage/async-storage - ``` - - - - -v2.4+ onwards, Voice & Video Calling functionality has been moved to a separate library. In case you plan to use the calling feature, please install the Calling dependency (`@cometchat/calls-sdk-react-native`). +{/* TL;DR for Agents and Quick Reference */} + ```bash -npm install @cometchat/calls-sdk-react-native +npm install @cometchat/chat-sdk-react-native ``` -The calling component requires some configuration. Please follow the steps mentioned in the [Calling Component Configuration](#calling-component-configuration) section below. - - -## Calling Component Configuration +```javascript +import { CometChat } from "@cometchat/chat-sdk-react-native"; -For `@cometchat/calls-sdk-react-native`, please make sure you add the following additional dependencies & permissions. +// 1. Initialize (once at app startup) +const appSettings = new CometChat.AppSettingsBuilder() + .setRegion("APP_REGION") // e.g. "us", "eu", "in" + .subscribePresenceForAllUsers() + .autoEstablishSocketConnection(true) + .build(); -### Required Dependencies +await CometChat.init("APP_ID", appSettings); -```json -{ - "@cometchat/chat-sdk-react-native": "^4.0.18", - "@react-native-async-storage/async-storage": "^2.2.0", - "@react-native-community/netinfo": "^11.4.1", - "react-native-background-timer": "^2.4.1", - "react-native-callstats": "^3.73.22", - "react-native-webrtc": "^124.0.6" +// 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 } ``` -### Permissions - - - - Add the following permissions to your `AndroidManifest.xml`: - - ```xml - - - - - - ``` - - - Add the following keys to your `Info.plist`: - - ```xml - NSCameraUsageDescription - This is for Camera permission - NSMicrophoneUsageDescription - This is for Mic permission - ``` - - - -### Platform-Specific Configuration - - - - Go to the `./android` folder and open the project level `build.gradle` file. Add all repository URLs in the repositories block under the `allprojects` section. Also in the same file in the `buildscript` section in the `ext` block, make sure you have set **minSdkVersion** to **24**. - - **Add Repository URL:** - - ```gradle - allprojects { - repositories { - maven { - url "https://dl.cloudsmith.io/public/cometchat/cometchat-pro-android/maven/" - } - } - } - ``` - - **Set Minimum SDK Version:** - - ```gradle - buildscript { - ext { - buildToolsVersion = "29.0.2" - minSdkVersion = 24 - compileSdkVersion = 29 - targetSdkVersion = 29 - } - } - ``` - - - Please update the minimum target version in the Podfile. Go to the `./ios` folder and open the Podfile. In the Podfile, update the platform version to `11.0`: - - ```ruby - platform :ios, '11.0' - ``` - - Open the `ios/App` folder and run `pod install`. This will create an `App.xcworkspace` file. Open this and run the app. - - - -## Initialize CometChat +**Credentials:** App ID, Region, Auth Key from [CometChat Dashboard](https://app.cometchat.com) +**Test UIDs:** `cometchat-uid-1` through `cometchat-uid-5` + -The `init()` method initializes the settings required for CometChat. The `init()` method takes the below parameters: +The CometChat React Native SDK lets you add real-time messaging, voice, and video calling to any React Native application. -| Parameter | Description | -|-----------|-------------| -| `appID` | Your CometChat App ID | -| `appSettings` | An object of the `AppSettings` class created using the `AppSettingsBuilder` class | +## Requirements -The `AppSettings` class allows you to configure the following settings: +| Requirement | Minimum Version | +|-------------|-----------------| +| npm | 8.x | +| Node.js | 16 | +| React Native | 0.63 | +| Android minSdkVersion | 24 | +| iOS | 11.0 | -| Setting | Description | -|---------|-------------| -| **Region** | The region where your app was created (mandatory) | -| **Presence Subscription** | Represents the subscription type for user presence (real-time online/offline status). See [Presence Subscription](/sdk/react-native/user-presence) | -| **autoEstablishSocketConnection(boolean)** | When set to `true`, the SDK manages the web-socket connection internally. When set to `false`, you manage the connection manually. Default: `true`. See [Managing connections manually](/sdk/react-native/managing-web-sockets-connections-manually) | -| **overrideAdminHost(adminHost: string)** | Uses a custom admin URL instead of the default. Used for dedicated CometChat deployments | -| **overrideClientHost(clientHost: string)** | Uses a custom client URL instead of the default. Used for dedicated CometChat deployments | +## Getting Started -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 `App.tsx` file. - - - - ```javascript - let appID = "APP_ID"; - let region = "REGION"; - - // Build app settings with presence subscription and auto socket connection - let appSetting = new CometChat.AppSettingsBuilder() - .subscribePresenceForAllUsers() - .setRegion(region) - .autoEstablishSocketConnection(true) - .build(); - - // Initialize CometChat - 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", - - // Build app settings with presence subscription and auto socket connection - let appSetting: CometChat.AppSettings = new CometChat.AppSettingsBuilder() - .subscribePresenceForAllUsers() - .setRegion(region) - .autoEstablishSocketConnection(true) - .build(); - - // Initialize CometChat - CometChat.init(appID, appSetting).then( - (initialized: boolean) => { - console.log("Initialization completed successfully", initialized); - }, - (error: CometChat.CometChatException) => { - console.log("Initialization failed with error:", error); - } - ); - ``` - - - - -Make sure you replace the `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. 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. - - - - ```javascript - let authKey = "AUTH_KEY"; - let uid = "user1"; - let name = "Kevin"; - - // Create a new user object - let user = new CometChat.User(uid); - user.setName(name); - - // Register the user with CometChat - 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"; - - // Create a new user object - var user = new CometChat.User(UID); - user.setName(name); - - // Register the user with CometChat - CometChat.createUser(user, authKey).then( - (user: CometChat.User) => { - console.log("user created", user); - }, - (error: CometChat.CometChatException) => { - 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. - - -**Security Warning:** This straightforward authentication method using Auth Key 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/react-native/authentication-overview#login-using-auth-token) instead of an Auth Key to ensure enhanced security. - - - - - ```javascript - let UID = "cometchat-uid-1"; - let authKey = "AUTH_KEY"; - - // Check if user is already logged in - CometChat.getLoggedinUser().then( - (user) => { - if (!user) { - // Login the user if not already logged in - 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 - var UID: string = "cometchat-uid-1", - authKey: string = "AUTH_KEY"; + + + [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/react-native/setup-sdk). + + + Log in users with Auth Key (development) or Auth Token (production). See [Authentication](/sdk/react-native/authentication-overview). + + + Send your first message, make a call, or manage users and groups. + + - // Check if user is already logged in - CometChat.getLoggedinUser().then( - (user: CometChat.User) => { - if (!user) { - // Login the user if not already logged in - 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 }); - } - ); - ``` - - +## Features - -Make sure you replace the `AUTH_KEY` with your CometChat **Auth Key** in the above code. - + + + 1:1 and group chat, threads, reactions, typing indicators, read receipts, and file sharing. + + + 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. + + - -**Test Users Available:** 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`. - +## Sample Apps -The `login()` method returns the `User` object containing all the information of the logged-in user. +Explore working examples with full source code: - -**UID Format:** UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. - + + + React Native sample app with UI components + + -## Integrate our UI Kits +## UI Kits -Please refer to the [React Native UI Kit](/ui-kit/react-native/overview) section to integrate React Native UI Kit inside your app. +Skip the UI work — use pre-built, customizable components: - - - - Always call `init()` before any other CometChat method - - Call `init()` on app startup (preferably in `App.tsx`) - - Use `getLoggedinUser()` to check login state before calling `login()` - - Store user credentials securely and never expose Auth Keys in client-side code for production - - Use Auth Token instead of Auth Key for production environments - - - - **Initialization fails:** Verify your App ID and Region are correct - - **Login fails:** Ensure the user exists or create them first using `createUser()` - - **Network errors:** Check internet connectivity and firewall settings - - **Calling not working:** Verify all calling dependencies are installed and permissions are granted - - **iOS build fails:** Run `pod install` in the `ios` directory after adding dependencies - - + + + React Native UI Kit + + -## Next Steps +## Resources - - Understand the fundamental concepts of CometChat + + UIDs, GUIDs, auth tokens, and core SDK concepts - - Learn about secure authentication methods including Auth Tokens + + Message categories, types, and hierarchy - - Start sending text, media, and custom messages + + Latest SDK version and release notes - - Add pre-built UI components to your app + + Migration guide for V3 users diff --git a/sdk/react-native/presenter-mode.mdx b/sdk/react-native/presenter-mode.mdx index 4030ddca1..f908392eb 100644 --- a/sdk/react-native/presenter-mode.mdx +++ b/sdk/react-native/presenter-mode.mdx @@ -1,10 +1,10 @@ --- title: "Presenter Mode" +sidebarTitle: "Presenter Mode" description: "Implement presenter mode in your React Native app — allow up to 5 presenters to share video, audio, and screen with up to 100 viewers using CometChat Calls SDK." --- - -**Quick Reference** - Start a presentation session: + ```javascript // Configure presenter settings @@ -17,315 +17,258 @@ let presenterSettings = new CometChatCalls.PresenterSettingsBuilder() // Render presenter component // ``` - - -**Available via:** SDK | UI Kits - - -## 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. - -Using this feature developers can create experiences such as: - -1. All hands calls -2. Keynote speeches -3. Webinars -4. Talk shows -5. Online classes -6. and many more... +**Key points:** +- Up to 5 presenters, up to 100 total participants (presenters + viewers) +- Viewers cannot send audio, video, or screen streams +- Use `setIsPresenter(true)` for presenters, `setIsPresenter(false)` for viewers + -### About this guide +Presenter Mode lets you create a calling experience where a small number of presenters share video, audio, and/or screen with a larger audience of passive viewers. This is ideal for webinars, all-hands calls, keynote speeches, online classes, and similar broadcast-style use cases. -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](/sdk/react-native/calling-setup). +- Up to 5 concurrent presenters +- Up to 100 total participants (presenters + viewers) +- Media controls (mute, camera, recording) are only available to presenters -Before starting a call session you have to [generate a call token](/sdk/react-native/direct-call#generate-call-token). + +Before you begin, ensure you have completed the [Calls SDK setup](/sdk/react-native/calling-setup) and [generated a call token](/sdk/react-native/direct-call#generate-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. +Use the `PresentationSettingsBuilder` to configure the presentation and `CometChatCalls.PresenterComponent` to render the UI. Set the user type with `setIsPresenter(true/false)` — presenters can send media, viewers cannot. -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)` + + +```typescript +const callListener = new CometChatCalls.OngoingCallListener({ + onUserJoined: (user: CometChat.User) => { + console.log("User joined:", user); + }, + onUserLeft: (user: CometChat.User) => { + console.log("User left:", user); + }, + onUserListUpdated: (userList: CometChat.User[]) => { + console.log("User list updated:", userList); + }, + onCallEnded: () => { + console.log("Call ended"); + }, + onCallEndButtonPressed: () => { + console.log("End call button pressed"); + }, + onError: (error: CometChat.CometChatException) => { + console.log("Call error:", error); + }, + onAudioModesUpdated: (audioModes: string[]) => { + console.log("Audio modes updated:", audioModes); + }, + onUserMuted: (event: any) => { + console.log("User muted:", event); + }, + onRecordingStarted: (event: any) => { + console.log("Recording started:", event); + }, + onRecordingStopped: (event: any) => { + console.log("Recording stopped:", event); + }, +}); + +const presenterSettings = new CometChatCalls.PresenterSettingsBuilder() + .setIsPresenter(isPresenter) + .enableDefaultLayout(true) + .setCallEventListener(callListener) + .build(); -A basic example of how to start a Presentation: +// In your render method +return ( + + + +); +``` + - ```javascript -let presenterSettings = new CometChatCalls.PresenterSettingsBuilder() - .setIsPresenter(isPresenter) - .enableDefaultLayout(defaultLayout) - .setCallEventListener(callListener) - .build(); +const callListener = new CometChatCalls.OngoingCallListener({ + onUserJoined: (user) => { + console.log("User joined:", user); + }, + onUserLeft: (user) => { + console.log("User left:", user); + }, + onUserListUpdated: (userList) => { + console.log("User list updated:", userList); + }, + onCallEnded: () => { + console.log("Call ended"); + }, + onCallEndButtonPressed: () => { + console.log("End call button pressed"); + }, + onError: (error) => { + console.log("Call error:", error); + }, + onAudioModesUpdated: (audioModes) => { + console.log("Audio modes updated:", audioModes); + }, + onUserMuted: (event) => { + console.log("User muted:", event); + }, + onRecordingStarted: (event) => { + console.log("Recording started:", event); + }, + onRecordingStopped: (event) => { + console.log("Recording stopped:", event); + }, +}); + +const presenterSettings = new CometChatCalls.PresenterSettingsBuilder() + .setIsPresenter(isPresenter) + .enableDefaultLayout(true) + .setCallEventListener(callListener) + .build(); -render(){ - return( - - - - ); -} +// In your render method +return ( + + + +); ``` - - ## 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)` +Register listeners via `.setCallEventListener(listener)` in `PresenterSettingsBuilder`, or use `CometChatCalls.addCallEventListener(listenerId, listener)` to add multiple listeners. + +```typescript +useEffect(() => { + const listenerId: string = "UNIQUE_LISTENER_ID"; + + CometChatCalls.addCallEventListener(listenerId, { + onUserJoined: (user: CometChat.User) => { + console.log("User joined:", user); + }, + onUserLeft: (user: CometChat.User) => { + console.log("User left:", user); + }, + onUserListUpdated: (userList: CometChat.User[]) => { + console.log("User list updated:", userList); + }, + onCallEnded: () => { + console.log("Call ended"); + }, + onCallEndButtonPressed: () => { + console.log("End call button pressed"); + }, + onError: (error: CometChat.CometChatException) => { + console.log("Call error:", error); + }, + onAudioModesUpdated: (audioModes: string[]) => { + console.log("Audio modes updated:", audioModes); + }, + onUserMuted: (event: any) => { + console.log("User muted:", event); + }, + onRecordingStarted: (event: any) => { + console.log("Recording started:", event); + }, + onRecordingStopped: (event: any) => { + console.log("Recording stopped:", event); + }, + }); + + return () => CometChatCalls.removeCallEventListener(listenerId); +}, []); +``` + ```javascript useEffect(() => { - CometChatCalls.addCallEventListener("UNIQUE_ID", { + const listenerId = "UNIQUE_LISTENER_ID"; + + CometChatCalls.addCallEventListener(listenerId, { onUserJoined: (user) => { - console.log("user joined:", user); + console.log("User joined:", user); }, onUserLeft: (user) => { - console.log("user left:", user); + console.log("User left:", user); }, onUserListUpdated: (userList) => { - console.log("user list:", userList); + console.log("User list updated:", userList); }, onCallEnded: () => { console.log("Call ended"); }, onCallEndButtonPressed: () => { - console.log("End Call button pressed"); + console.log("End call button pressed"); }, onError: (error) => { - console.log("Call Error: ", error); + console.log("Call error:", error); }, onAudioModesUpdated: (audioModes) => { - console.log("audio modes:", audioModes); + console.log("Audio modes updated:", audioModes); }, onUserMuted: (event) => { - console.log("user muted:", event); + console.log("User muted:", event); + }, + onRecordingStarted: (event) => { + console.log("Recording started:", event); + }, + onRecordingStopped: (event) => { + console.log("Recording stopped:", event); }, }); - return () => CometChatCalls.removeCallEventListener("UNIQUE_ID"); + + return () => CometChatCalls.removeCallEventListener(listenerId); }, []); ``` - - Always remove call event listeners when the component unmounts using `CometChatCalls.removeCallEventListener(listenerId)`. Failing to remove listeners can cause memory leaks and duplicate event handling. - -**On Event** — `onUserJoined` returns a user object when a participant joins the presentation: - - - -**User Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"cometchat-uid-6"` | -| `name` | string | Display name of the user | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `id` | string | Internal session participant ID | `"cd530243"` | -| `joinedAt` | string | Unix timestamp when user joined (as string) | `"1772095303043"` | -| `isVideoMuted` | boolean | Whether user's video is muted | `true` | -| `isAudioMuted` | boolean | Whether user's audio is muted | `false` | -| `isLocalUser` | boolean | Whether this is the local user | `false` | - - - - -**On Event** — `onUserLeft` returns a user object when a participant leaves the presentation: - - - -**User Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"cometchat-uid-6"` | -| `name` | string | Display name of the user | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `id` | string | Internal session participant ID | `"cd530243"` | -| `joinedAt` | string | Unix timestamp when user joined (as string) | `"1772095303043"` | -| `isVideoMuted` | boolean | Whether user's video was muted | `true` | -| `isAudioMuted` | boolean | Whether user's audio was muted | `false` | - - - - -**On Event** — `onUserListUpdated` returns an array of all current participants in the presentation: - - - -**User Array:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| (array) | array | Array of user objects | [See below ↓](#on-user-list-updated-user-object) | - - - -**User Object (each item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"cometchat-uid-7"` | -| `name` | string | Display name of the user | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | - - - - -**On Event** — `onAudioModesUpdated` returns an array of available audio output modes: - - - -**Audio Modes Array:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| (array) | array | Array of audio mode objects | [See below ↓](#on-audio-modes-updated-mode-object) | - - - -**Audio Mode Object (each item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `type` | string | Type of audio output device | `"SPEAKER"` | -| `selected` | boolean | Whether this mode is currently selected | `true` | - - - - -**On Event** — `onRecordingStarted` returns information about the user who started the recording: - - - -**RecordingStartedBy Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user who started recording | `"cometchat-uid-7"` | -| `name` | string | Display name of the user | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `recordId` | string | Unique identifier for this recording session | `"noujausedimwfhwl"` | -| `id` | string | Internal session participant ID | `"042d0440"` | -| `isLocalUser` | string | Whether this is the local user (as string) | `"true"` | -| `isVideoMuted` | string | Whether user's video is muted (as string) | `"true"` | -| `isAudioMuted` | string | Whether user's audio is muted (as string) | `"false"` | - - - - -**On Event** — `onRecordingStopped` returns information about the user who stopped the recording: - - - -**RecordingStoppedBy Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user who stopped recording | `"cometchat-uid-7"` | -| `name` | string | Display name of the user | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `id` | string | Internal session participant ID | `"042d0440"` | -| `isLocalUser` | string | Whether this is the local user (as string) | `"true"` | -| `isVideoMuted` | string | Whether user's video is muted (as string) | `"true"` | -| `isAudioMuted` | string | Whether user's audio is muted (as string) | `"false"` | - - - -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. | +### Events + +| Callback | Description | +| -------- | ----------- | +| `onCallEnded()` | Invoked when the call is successfully ended. | +| `onCallEndButtonPressed()` | Invoked when the user presses the end call button. | +| `onUserJoined(user)` | Invoked when a participant joins the presentation. | +| `onUserLeft(user)` | Invoked when a participant leaves the presentation. | +| `onUserListUpdated(userList)` | Invoked whenever the participant list changes. | +| `onAudioModesUpdated(audioModes)` | Invoked when available audio output sources change. | +| `onUserMuted(event)` | Invoked when a user is muted in the ongoing call. | +| `onRecordingStarted(event)` | Invoked when a recording starts. | +| `onRecordingStopped(event)` | Invoked when a recording stops. | +| `onError(error)` | Invoked when an error occurs during the call session. | ## 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: - -| 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** | -| `showEndCallButton(showEndCallButton: 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 | - -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: - -## Best Practices - - - - Always explicitly set `setIsPresenter(true)` for presenters and `setIsPresenter(false)` for viewers. Viewers cannot send audio, video, or screen streams — this is enforced by the SDK, not just the UI. - - - Presenter Mode supports a maximum of 5 concurrent presenters. If your app allows dynamic role switching, enforce this limit in your logic before calling `setIsPresenter(true)` for additional users. - - - Always remove call event listeners in your component's cleanup function (e.g., the return function of `useEffect`). Orphaned listeners can cause memory leaks and duplicate event handling. - - - Call tokens are session-specific and time-limited. Generate them right before starting the presentation session rather than caching them for extended periods. - - - -## Troubleshooting - - - - Verify that `setIsPresenter(false)` is set for viewer participants. If a viewer is incorrectly set as a presenter, they will have access to media controls. - - - Ensure the `CometChatCalls.PresenterComponent` is wrapped in a `View` with `flex: 1` or explicit dimensions. Also confirm that both `presenterSettings` and `callToken` props are provided and not `null`. - - - Check that the listener is registered before the presentation session starts. If using `addCallEventListener`, ensure the `listenerId` is unique and hasn't been overwritten. Also verify the Calls SDK has been initialized via `CometChatCalls.init()`. - - - Presenter Mode supports up to 100 total participants (presenters + viewers). If users can't join, check the current participant count in your session. - - +Configure the presentation experience using `PresentationSettingsBuilder`: + +| Method | Description | +| ------ | ----------- | +| `setIsPresenter(boolean)` | `true` to join as presenter, `false` to join as viewer. Viewers cannot send audio, video, or screen streams. | +| `enableDefaultLayout(boolean)` | Enables or disables the default layout with built-in controls. Default: `true` | +| `showEndCallButton(boolean)` | Shows or hides the end call button. Default: `true` | +| `showMuteAudioButton(boolean)` | Shows or hides the mute audio button. Default: `true` | +| `showPauseVideoButton(boolean)` | Shows or hides the pause video button. Default: `true` | +| `showSwitchCameraButton(boolean)` | Shows or hides the switch camera button. Default: `true` | +| `showAudioModeButton(boolean)` | Shows or hides the audio mode button. Default: `true` | +| `setIsAudioOnlyCall(boolean)` | Sets whether the call is audio-only. Default: `false` | +| `startWithAudioMuted(boolean)` | Starts with microphone muted. Default: `false` | +| `startWithVideoMuted(boolean)` | Starts with camera off. Default: `false` | +| `showRecordingButton(boolean)` | Shows or hides the recording button. Default: `false` | +| `setDefaultAudioMode(string)` | Sets initial audio output. Available: `SPEAKER`, `EARPIECE`, `BLUETOOTH`, `HEADPHONES` | +| `setCallEventListener(OngoingCallListener)` | Sets the listener for call events. | --- @@ -338,10 +281,4 @@ For the use case where you wish to align your own custom buttons and not use the Record presentation sessions for playback and compliance - - Customize the main video container and participant tiles - - - Install dependencies, configure permissions, and initialize the Calls SDK - - \ No newline at end of file + diff --git a/sdk/react-native/push-notification-html-stripping.mdx b/sdk/react-native/push-notification-html-stripping.mdx index 84d39b45f..cad21d0eb 100644 --- a/sdk/react-native/push-notification-html-stripping.mdx +++ b/sdk/react-native/push-notification-html-stripping.mdx @@ -3,6 +3,17 @@ title: "Push Notification Content Customization" description: "Learn how to intercept and modify push notification content before display in React Native." --- + + +| Field | Value | +| --- | --- | +| Platform | Android (FCM) + iOS (APNs) | +| Key Concepts | HTML tag stripping, Notification Service Extension, `stripHtmlTags()` | +| Android Approach | Intercept in `displayLocalNotification()` via `messaging().onMessage()` / `setBackgroundMessageHandler()` | +| iOS Approach | Native `UNNotificationServiceExtension` intercepts APNs payloads before display | +| Prerequisites | Push notifications configured, `@notifee/react-native` (Android), Xcode Notification Service Extension (iOS) | + + ## Overview @@ -227,28 +238,17 @@ If your project uses React Native Firebase (e.g., for FCM on Android), you may a 3. Verify the push notification displays clean text in both background and killed states 4. Confirm that the chat UI still renders the rich text with formatting intact in both platforms - - -- **Bridging Header Error**: If you get a build error related to the Objective-C Bridging Header in the NotificationService target, go to the extension's **Build Settings → Objective-C Bridging Header** and clear the value. -- **Build Cycle Error**: If you see a build cycle error after adding the extension (common in projects using CocoaPods), go to your main app target's **Build Phases**, find **Embed Foundation Extensions**, and ensure `NotificationService.appex` is listed correctly. -- **Extension Not Working on Simulator**: Notification Service Extensions do not run on the iOS Simulator. Test on a physical device. -- **Extension Not Intercepting Notifications**: Ensure your APNs payload includes `"mutable-content": 1`. Without this flag, iOS will not route the notification through your extension. -- **Build Fails After Adding Extension**: Verify the extension's deployment target matches your main app. Also ensure the extension's bundle ID is a child of the main app's bundle ID (e.g., `com.yourapp.NotificationService`). - - - -- **Android**: Route all FCM notification flows through a single handler function to ensure consistent content transformation -- **iOS**: The Notification Service Extension handles all APNs notifications automatically — no additional routing needed -- Keep the `stripHtmlTags` function in a shared utility file so it can be reused across your app -- Handle `serviceExtensionTimeWillExpire()` gracefully on iOS — deliver the best available content if processing takes too long -- Test on physical iOS devices since Notification Service Extensions do not run on the simulator -- Consider logging stripped content during development to verify the regex handles all edge cases in your notification payloads - - +--- ## Next Steps + +Set up FCM push notifications for Android + + +Set up APNs push notifications for iOS + Learn how to send different types of messages diff --git a/sdk/react-native/rate-limits.mdx b/sdk/react-native/rate-limits.mdx index 7c7f6ecad..6dbf3b8ac 100644 --- a/sdk/react-native/rate-limits.mdx +++ b/sdk/react-native/rate-limits.mdx @@ -1,62 +1,111 @@ --- title: "Rate Limits" -description: "Understand CometChat REST API rate limits, how to monitor usage via response headers, and how to handle rate limit errors." +description: "Understand CometChat REST API rate limits, response headers, and how to handle rate-limited requests in your React Native application." --- - -**Quick Reference** - Key rate limits at a glance: + -| Operation Type | Limit | -|----------------|--------------------------| -| Core | 10,000 requests/minute | -| Standard | 20,000 requests/minute | - +- 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 +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 + +| 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 10,000 requests per minute, then you can login a user, add a user to a group, remove a user from a group, etc. for a combined total of 10,000 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. -| Operation Type | Rate Limit | Examples | -|-------------------------|-----------------------------|-----------------------------------------------------------------| -| **Core Operations** | `10,000` requests per minute | User login, create/delete user, create/join group (cumulative) | -| **Standard Operations** | `20,000` requests per minute | All other operations (cumulative) | +## Response Headers -## What Happens When the Rate Limit is Reached? +CometChat includes rate limit information in response headers: -The request isn't processed and a response is sent containing a `429` response code. Along with the response code, there will be a couple of headers sent which specify the time in seconds that you must wait before you can try the request again. +| 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) | -``` -Retry-After: 15 -X-Rate-Limit-Reset: 1625143246 -``` +## Handling Rate Limits -## Is There an Endpoint That Returns Rate Limits? +When you exceed the rate limit, CometChat returns HTTP `429 Too Many Requests`. Implement exponential backoff to handle this gracefully: -No, CometChat does not provide a dedicated rate-limit endpoint. - -However, the following response headers are included with every API response, which you can use to confirm the app's current rate limit and monitor the number of requests remaining in the current minute: + + +```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 === "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)); + } else { + throw error; + } + } + } + throw new Error("Max retries exceeded"); +} +// Usage +const users: CometChat.User[] = await callWithRetry(() => + new CometChat.UsersRequestBuilder().setLimit(30).build().fetchNext() +); ``` -X-Rate-Limit: 700 -X-Rate-Limit-Remaining: 699 + + +```javascript +async function callWithRetry(apiCall, maxRetries = 3) { + for (let attempt = 0; attempt < maxRetries; attempt++) { + try { + return await apiCall(); + } catch (error) { + 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)); + } else { + throw error; + } + } + } +} + +// Usage +const users = await callWithRetry(() => + new CometChat.UsersRequestBuilder().setLimit(30).build().fetchNext() +); ``` + + + +## Tips for Staying Within Limits - - - - Monitor `X-Rate-Limit-Remaining` headers to proactively manage your request volume - - Implement exponential backoff when you receive a `429` response - - Use the `Retry-After` header value to determine when to retry - - Batch operations where possible to reduce the total number of API calls - - Cache responses locally to avoid redundant requests - - - - **Receiving 429 errors frequently:** Review your request patterns and consider batching or caching - - **Rate limit seems too low:** Contact CometChat support to discuss adjustments based on your plan and use case - - **Inconsistent rate limit headers:** Ensure you're reading headers from the correct response object in your HTTP client - - +- **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 @@ -67,4 +116,10 @@ X-Rate-Limit-Remaining: 699 Initialize CometChat and authenticate users in your app + + Complete reference for all SDK event listeners + + + Monitor SDK connection state changes + diff --git a/sdk/react-native/reactions.mdx b/sdk/react-native/reactions.mdx index 794ac7fc9..9e321898e 100644 --- a/sdk/react-native/reactions.mdx +++ b/sdk/react-native/reactions.mdx @@ -1,46 +1,42 @@ --- title: "Reactions" -description: "Add, remove, and manage message reactions in real-time using the CometChat React Native SDK." +sidebarTitle: "Reactions" +description: "Add, remove, and fetch message reactions in real-time using the CometChat React Native SDK. Includes listener events and helper methods for updating UI." --- - -**Quick Reference** - Add and remove reactions: + ```javascript +let messageId = "MESSAGE_ID"; + // Add a reaction -await CometChat.addReaction("MESSAGE_ID", "😊"); +await CometChat.addReaction(messageId, "😊"); // Remove a reaction -await CometChat.removeReaction("MESSAGE_ID", "😊"); +await CometChat.removeReaction(messageId, "😊"); + +// Fetch reactions for a message +const request = new CometChat.ReactionsRequestBuilder() + .setMessageId(messageId).setLimit(10).build(); +const reactions = await request.fetchNext(); + +// Listen for reaction events +CometChat.addMessageListener("LISTENER_ID", new CometChat.MessageListener({ + onMessageReactionAdded: (reaction) => {}, + onMessageReactionRemoved: (reaction) => {} +})); ``` - + - -Available via: [SDK](/sdk/react-native/reactions) | [REST API](/rest-api/messages/add-reaction) | [UI Kits](/ui-kit/react-native/core-features#reactions) - +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. -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 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. - -```javascript -let messageId = "1"; -let emoji = "😊"; - -CometChat.addReaction(messageId, emoji) -.then((res) => { - console.log('response', res); -}).catch(err => { - console.log('err', err); -}) -``` - - - ```typescript let messageId:string = "1"; @@ -53,127 +49,28 @@ CometChat.addReaction(messageId, emoji) console.log('err', err); }) ``` - - - - -**On Success** — `addReaction()` returns the updated message object with the reaction added: - - - -**Message Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25327"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-7"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Message for Reactions"` | -| `sentAt` | number | Unix timestamp when sent | `1772006757` | -| `deliveredAt` | number | Unix timestamp when delivered | `1772006757` | -| `readAt` | number | Unix timestamp when read | `1772006757` | -| `updatedAt` | number | Unix timestamp when updated | `1772006757` | -| `sender` | object | Sender user details | [See below ↓](#add-reaction-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#add-reaction-receiver-object) | -| `data` | object | Additional message data with reactions | [See below ↓](#add-reaction-data-object) | -| `reactions` | array | Message reactions (root level) | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1772004288` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1772005334` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Message for Reactions"` | -| `reactions` | array | Reaction counts | [See below ↓](#add-reaction-data-reactions-array) | - ---- - - - -**`data.reactions` Array (per item):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `reaction` | string | Emoji reaction | `"😊"` | -| `count` | number | Number of users who reacted | `1` | -| `reactedByMe` | boolean | Whether current user reacted | `true` | - - - - - -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. - - ```javascript let messageId = "1"; let emoji = "😊"; -CometChat.removeReaction(messageId, emoji) +CometChat.addReaction(messageId, emoji) .then((res) => { console.log('response', res); }).catch(err => { console.log('err', err); }) ``` - + + +## Remove a Reaction + +Call `removeReaction()` with the same message ID and emoji. + ```typescript let messageId:string = "1"; @@ -186,124 +83,84 @@ CometChat.removeReaction(messageId, emoji) console.log('err', err); }) ``` - - - - -**On Success** — `removeReaction()` returns the updated message object with the reaction removed: - - - -**Message Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25327"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-7"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Message for Reactions"` | -| `sentAt` | number | Unix timestamp when sent | `1772006757` | -| `deliveredAt` | number | Unix timestamp when delivered | `1772006757` | -| `readAt` | number | Unix timestamp when read | `1772006757` | -| `updatedAt` | number | Unix timestamp when updated | `1772006757` | -| `sender` | object | Sender user details | [See below ↓](#remove-reaction-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#remove-reaction-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#remove-reaction-data-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- + +```javascript +let messageId = "1"; +let emoji = "😊"; - +CometChat.removeReaction(messageId, emoji) +.then((res) => { + console.log('response', res); +}).catch(err => { + console.log('err', err); +}) +``` + + -**`sender` Object:** +Both `addReaction()` and `removeReaction()` return a [`BaseMessage`](/sdk/reference/messages#basemessage) object with the updated reactions. -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1772004288` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | +## Read Reaction Data from a Message ---- +Any [`BaseMessage`](/sdk/reference/messages#basemessage) exposes reaction data through two methods: - +### Get All Reactions -**`receiver` Object:** +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. -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1772005334` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | + + +```typescript +message.getReactions() +``` + ---- + +```javascript +message.getReactions() +``` + + - +### Check if the Logged-in User Has Reacted -**`data` Object:** +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. -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Message for Reactions"` | + + +```typescript +let reactions:CometChat.ReactionCount[] = message.getReactions(); +reactions.forEach((reaction:CometChat.ReactionCount) => { + reaction.getReactedByMe(); //Returns true if logged-in user reacted on that message, otherwise false +}) +``` + - + +```javascript +let reactions = message.getReactions(); +reactions.forEach((reaction) => { + reaction.getReactedByMe(); //Returns true if logged-in user reacted on that message, otherwise false +}) +``` + + ## Fetch Reactions for a Message -To get all reactions for a specific message, first create a `ReactionsRequest` using `ReactionsRequestBuilder`. 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. +To get the full list of who reacted with what on a specific message, use `ReactionsRequestBuilder`. You can paginate through results with `fetchNext()` and `fetchPrevious()` (max 100 per request). -| 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 `ReactionsRequest` to only retrieve details of the provided reaction for the given message. | +| 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. | -## Fetch Next - -The `fetchNext()` method fetches the next set of reactions for the message. +### Fetch Next - -```javascript -let limit = 10; -let messageId = 1; - -let reactionsRequest = new CometChat.ReactionsRequestBuilder() -.setMessageId(messageId) -.setLimit(limit) -.build(); - -reactionsRequest.fetchNext().then( - reactions => { - console.log("list fetched:", reactions); - }, - error => { - console.log('list fetching failed with error:', error); - }, - ); -``` - - - ```typescript let limit:number = 10; @@ -323,16 +180,8 @@ reactionsRequest.fetchNext().then( }, ); ``` - - - -## Fetch Previous - -The `fetchPrevious()` method fetches the previous set of reactions for the message. - - ```javascript let limit = 10; @@ -343,7 +192,7 @@ let reactionsRequest = new CometChat.ReactionsRequestBuilder() .setLimit(limit) .build(); -reactionsRequest.fetchPrevious().then( +reactionsRequest.fetchNext().then( reactions => { console.log("list fetched:", reactions); }, @@ -352,9 +201,12 @@ reactionsRequest.fetchPrevious().then( }, ); ``` - + + +### Fetch Previous + ```typescript let limit:number = 10; @@ -374,268 +226,90 @@ reactionsRequest.fetchPrevious().then( }, ); ``` - - - - -**On Success** — `fetchNext()` or `fetchPrevious()` returns an array of `MessageReaction` objects: - - - -**MessageReaction Array (per item):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique reaction identifier | `"20014"` | -| `messageId` | string | ID of the message reacted to | `"25327"` | -| `reaction` | string | Emoji reaction | `"❤️"` | -| `uid` | string | UID of user who reacted | `"cometchat-uid-7"` | -| `reactedAt` | number | Unix timestamp when reacted | `1772007024` | -| `reactedBy` | object | User who reacted | [See below ↓](#fetch-reactions-reactedby-object) | - ---- - - - -**`reactedBy` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1772007237` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - - - - -## 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. - - ```javascript -let listenerID = "UNIQUE_LISTENER_ID"; +let limit = 10; +let messageId = 1; -CometChat.addMessageListener(listenerID, { - onMessageReactionAdded:(message) => { - console.log("Reaction added", message); +let reactionsRequest = new CometChat.ReactionsRequestBuilder() +.setMessageId(messageId) +.setLimit(limit) +.build(); + +reactionsRequest.fetchPrevious().then( + reactions => { + console.log("list fetched:", reactions); }, - onMessageReactionRemoved:(message) => { - console.log("Reaction removed", message); - } - }) + error => { + console.log('list fetching failed with error:', error); + }, + ); ``` - + +## Real-Time Reaction Events + +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. + + ```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); } - }) + })) ``` - - - - -**On Event** — `onMessageReactionAdded` returns the reaction event data: - - - -**Reaction Event Object (onMessageReactionAdded):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `parentMessageId` | null | Parent message ID (null for non-threaded) | `null` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-6"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `reaction` | object | Reaction details | [See below ↓](#reaction-added-reaction-object) | - ---- - - - -**`reaction` Object (onMessageReactionAdded):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique reaction identifier | `"20013"` | -| `messageId` | string | ID of the message reacted to | `"25327"` | -| `reaction` | string | Emoji reaction | `"❤️"` | -| `uid` | string | UID of user who reacted | `"cometchat-uid-7"` | -| `reactedAt` | number | Unix timestamp when reacted | `1772006766` | -| `reactedBy` | object | User who reacted | [See below ↓](#reaction-added-reactedby-object) | - ---- - - - -**`reaction.reactedBy` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1772005334` | - ---- - -**On Event** — `onMessageReactionRemoved` returns the reaction event data: - - - -**Reaction Event Object (onMessageReactionRemoved):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `parentMessageId` | null | Parent message ID (null for non-threaded) | `null` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-6"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `reaction` | object | Reaction details | [See below ↓](#reaction-removed-reaction-object) | - ---- - - - -**`reaction` Object (onMessageReactionRemoved):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique reaction identifier | `"20013"` | -| `messageId` | string | ID of the message | `"25327"` | -| `reaction` | string | Emoji reaction | `"❤️"` | -| `uid` | string | UID of user who removed reaction | `"cometchat-uid-7"` | -| `reactedAt` | number | Unix timestamp when originally reacted | `1772006766` | -| `reactedBy` | object | User who removed reaction | [See below ↓](#reaction-removed-reactedby-object) | - ---- - - - -**`reaction.reactedBy` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1772005334` | - - - -## Removing a Reaction Listener - -To stop listening for reaction events, remove the listener as follows: - - ```javascript let listenerID = "UNIQUE_LISTENER_ID"; -CometChat.removeMessageListener(listenerID); -``` - - - - -```typescript -let listenerID:string = "UNIQUE_LISTENER_ID"; - -CometChat.removeMessageReactionListener(listenerID); +CometChat.addMessageListener(listenerID, new CometChat.MessageListener({ + onMessageReactionAdded:(message) => { + console.log("Reaction added", message); + }, + onMessageReactionRemoved:(message) => { + console.log("Reaction removed", message); + } + })) ``` - - - -Always remove your reaction listeners when they are no longer needed — for example, when a component unmounts or a screen is navigated away from. Failing to do so can cause memory leaks and unexpected behavior from stale listeners. Use `CometChat.removeMessageListener("LISTENER_ID")` in your cleanup logic (e.g., `useEffect` return function or `componentWillUnmount`). - - -## 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. +### Remove the Listener - -```javascript -message.getReactions() -``` - - - ```typescript -message.getReactions() -``` +let listenerID:string = "UNIQUE_LISTENER_ID"; +CometChat.removeMessageListener(listenerID); +``` - - - -**On Success** — `getReactions()` returns an array of reaction counts: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `reaction` | string | Emoji reaction | `"❤️"` | -| `count` | number | Number of users who reacted | `1` | -| `reactedByMe` | boolean | Whether current user reacted | `true` | - - - -## 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`. - - ```javascript -let reactions = message.getReactions(); -reactions.forEach((reaction) => { -reaction.getReactedByMe(); //Returns true if logged-in user reacted on that message, otherwise false -}) -``` - - +let listenerID = "UNIQUE_LISTENER_ID"; - -```typescript -let reactions:CometChat.ReactionCount[] = message.getReactions(); -reactions.forEach((reaction:CometChat.ReactionCount) => { -reaction.getReactedByMe(); //Returns true if logged-in user reacted on that message, otherwise false -}) +CometChat.removeMessageListener(listenerID); ``` - - + +Always remove listeners when they're no longer needed (e.g., on component unmount or screen navigation). In React Native, place this in a cleanup function inside `useEffect` or in `componentWillUnmount`. Failing to remove listeners can cause memory leaks and duplicate event handling. + + ## 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. @@ -645,117 +319,68 @@ The `updateMessageWithReactionInfo()` method provides a seamless way to update t 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. - -```javascript + +```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; +// The received reaction event real-time action type +let action: CometChat.REACTION_ACTION = CometChat.REACTION_ACTION.REACTION_ADDED; let modifiedBaseMessage = CometChat.CometChatHelper.updateMessageWithReactionInfo( -baseMessage, -messageReaction, +message, +messageReaction, action -); +); ``` - - -```typescript + +```javascript // 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; +// The received reaction event real-time action type +let action = CometChat.REACTION_ACTION.REACTION_ADDED; let modifiedBaseMessage = CometChat.CometChatHelper.updateMessageWithReactionInfo( -baseMessage, -messageReaction, +message, +messageReaction, action ); ``` - - - -**On Success (REACTION_ADDED)** — `updateMessageWithReactionInfo()` returns the updated message. Calling `getReactions()` on it shows: +On success, this method returns a [`BaseMessage`](/sdk/reference/messages#basemessage) object. After calling this method, use `modifiedBaseMessage.getReactions()` to get the latest reactions and refresh your UI. -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `reaction` | string | Emoji reaction | `"👍"` | -| `count` | number | Number of users who reacted | `1` | -| `reactedByMe` | boolean | Whether current user reacted | `false` | +| Parameter | Type | Description | +|-----------|------|-------------| +| `message` | `BaseMessage` | The message object to update | +| `messageReaction` | `MessageReaction` | The reaction event received from the listener | +| `action` | `REACTION_ACTION` | `CometChat.REACTION_ACTION.REACTION_ADDED` or `CometChat.REACTION_ACTION.REACTION_REMOVED` | -**On Success (REACTION_REMOVED)** — When the last reaction is removed, `getReactions()` returns an empty array: `[]` - - - - -## Best Practices - - - - Always use unique, descriptive listener IDs (e.g., `"ChatScreen_ReactionListener"`) to avoid conflicts with other listeners in your app. This makes it easier to manage and remove specific listeners when needed. - - - Remove reaction listeners in your component's cleanup phase (`useEffect` return function or `componentWillUnmount`). Orphaned listeners can lead to memory leaks and unexpected UI updates on unmounted components. - - - When you receive a real-time reaction event, always call `updateMessageWithReactionInfo()` to keep your local message state in sync. This avoids stale reaction counts and ensures the UI reflects the latest state. - - - Wrap `addReaction` and `removeReaction` calls in proper error handling. Network issues or invalid message IDs can cause failures — show appropriate feedback to the user rather than silently failing. - - - When fetching reactions for messages with many reactions, use `fetchNext()` with a reasonable `setLimit()` value. Avoid fetching all reactions at once to keep performance smooth, especially on lower-end devices. - - - -## Troubleshooting - - - - Verify that the `messageId` is valid and the user is logged in. Check the error callback for details — common causes include invalid message IDs, network connectivity issues, or the user not being a participant in the conversation. - - - Ensure you have registered the message listener with `CometChat.addMessageListener()` before the reaction event occurs. Also confirm that the listener ID is unique and hasn't been accidentally removed or overwritten by another listener registration. - - - After receiving a real-time reaction event, you must call `CometChat.CometChatHelper.updateMessageWithReactionInfo()` to update the message object. Simply receiving the event does not automatically update the `BaseMessage` instance — you need to explicitly apply the update and re-render. - - - Make sure you are calling `getReactedByMe()` on the `ReactionCount` objects returned by `message.getReactions()`, not on the raw reaction event data. Also verify that the logged-in user is the same user who added the reaction. - - - Confirm that the `messageId` passed to `ReactionsRequestBuilder.setMessageId()` is correct and that the message actually has reactions. If using `setReaction()` to filter by a specific emoji, ensure the emoji string matches exactly (including any variation selectors). - - +--- ## Next Steps -Explore related features to build a richer messaging experience: - - - Learn how to send text, media, and custom messages to users and groups. + + Send text, media, and custom messages to users and groups - Set up real-time message listeners and fetch message history. + Listen for incoming messages in real-time and fetch missed messages - Tag users in messages to notify and engage them directly. + Mention specific users in messages - - Send rich, interactive messages with forms, cards, and custom elements. + + Organize conversations with message threads - \ No newline at end of file + diff --git a/sdk/react-native/real-time-listeners.mdx b/sdk/react-native/real-time-listeners.mdx index e02846e22..dc8980fed 100644 --- a/sdk/react-native/real-time-listeners.mdx +++ b/sdk/react-native/real-time-listeners.mdx @@ -1,58 +1,86 @@ --- title: "All Real Time Listeners" -description: "Learn how to register and manage all real-time listeners in the CometChat React Native SDK, including User, Group, Message, and Call listeners." +description: "Complete reference for all CometChat real-time listeners in the React Native SDK including User, Group, Message, and Call listeners." --- - -**Quick Reference** + + ```javascript -// Register listeners -CometChat.addUserListener("id", new CometChat.UserListener({ ... })); -CometChat.addGroupListener("id", new CometChat.GroupListener({ ... })); -CometChat.addMessageListener("id", new CometChat.MessageListener({ ... })); -CometChat.addCallListener("id", new CometChat.CallListener({ ... })); - -// Remove listeners -CometChat.removeUserListener("id"); -CometChat.removeGroupListener("id"); -CometChat.removeMessageListener("id"); -CometChat.removeCallListener("id"); +// 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({ + onGroupMemberJoined: (action, joinedUser, joinedGroup) => { }, + onGroupMemberLeft: (action, leftUser, leftGroup) => { } +})); + +// Call Listener — incoming/outgoing call events +CometChat.addCallListener("ID", new CometChat.CallListener({ + onIncomingCallReceived: (call) => { }, + onOutgoingCallAccepted: (call) => { } +})); + +// Always clean up +CometChat.removeUserListener("ID"); +CometChat.removeMessageListener("ID"); +CometChat.removeGroupListener("ID"); +CometChat.removeCallListener("ID"); ``` - + -CometChat provides 4 listeners viz. +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. [User Listener](#user-listener) -2. [Group Listener](#group-listener) -3. [Message Listener](#message-listener) -4. [Call Listener](#call-listener) +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 to prevent memory leaks. -Always remove all listeners when the component unmounts to prevent memory leaks. Ensure each listener has a unique ID — using duplicate IDs can lead to unexpected behavior and loss of events. +Always remove listeners when they're no longer needed (e.g., on component unmount). Failing to remove listeners can cause memory leaks and duplicate event handling. For React Native, use `useEffect` cleanup functions to handle listener removal automatically. +CometChat provides 4 listeners viz. + +1. [User Listener](/sdk/react-native/real-time-listeners#user-listener) +2. [Group Listener](/sdk/react-native/real-time-listeners#group-listener) +3. [Message Listener](/sdk/react-native/real-time-listeners#message-listener) +4. [Call Listener](/sdk/react-native/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. | +| **onUserOnline(user: [CometChat.User](/sdk/reference/entities#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](/sdk/reference/entities#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`: - -```javascript -var listenerID = "UNIQUE_LISTENER_ID"; + +```typescript +const 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 }); }, }) @@ -61,18 +89,16 @@ CometChat.addUserListener( - -```typescript -var listenerID: string = "UNIQUE_LISTENER_ID"; + +```javascript +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 }); }, }) @@ -83,21 +109,20 @@ 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: - -```javascript -CometChat.removeUserListener(UNIQUE_LISTENER_ID); + +```typescript +let listenerID: string = "UNIQUE_LISTENER_ID"; +CometChat.removeUserListener(listenerID); ``` - -```typescript -let listenerID: string = "UNIQUE_LISTENER_ID"; + +```javascript +let listenerID = "UNIQUE_LISTENER_ID"; CometChat.removeUserListener(listenerID); ``` @@ -107,33 +132,46 @@ CometChat.removeUserListener(listenerID); ## 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 | | ------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | -| **onGroupMemberJoined(action: CometChat.Action, joinedUser: CometChat.User, joinedGroup: CometChat.Group)** | This method is triggered when a user joins any group. All the members present in the group will receive this event. | -| **onGroupMemberLeft(action: CometChat.Action, leftUser: CometChat.User, leftGroup: CometChat.Group)** | This method is triggered when a user who was a member of any group leaves the group. All the members of the group receive this event. | -| **onGroupMemberKicked(action: CometChat.Action, kickedUser: CometChat.User, kickedBy: CometChat.User, kickedFrom: CometChat.Group)** | This method is triggered when a user is kicked from a group. All the members including the user receive this event | -| **onGroupMemberBanned(action: CometChat.Action, bannedUser: CometChat.User, bannedBy: CometChat.User, bannedFrom: CometChat.Group)** | This method is triggered when a user is banned from a group. All the members including the user receive this event | -| **onGroupMemberUnbanned(action: CometChat.Action, unbannedUser: CometChat.User, unbannedBy: CometChat.User, unbannedFrom: CometChat.Group)** | This method is triggered when a user is unbanned from a group. All the members of the group receive this event. | -| **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. | +| **onGroupMemberJoined(action: [CometChat.Action](/sdk/reference/messages#action), joinedUser: [CometChat.User](/sdk/reference/entities#user), joinedGroup: [CometChat.Group](/sdk/reference/entities#group))** | This method is triggered when a user joins any group. All the members present in the group will receive this event. | +| **onGroupMemberLeft(action: [CometChat.Action](/sdk/reference/messages#action), leftUser: [CometChat.User](/sdk/reference/entities#user), leftGroup: [CometChat.Group](/sdk/reference/entities#group))** | This method is triggered when a user who was a member of any group leaves the group. All the members of the group receive this event. | +| **onGroupMemberKicked(action: [CometChat.Action](/sdk/reference/messages#action), kickedUser: [CometChat.User](/sdk/reference/entities#user), kickedBy: [CometChat.User](/sdk/reference/entities#user), kickedFrom: [CometChat.Group](/sdk/reference/entities#group))** | This method is triggered when a user is kicked from a group. All the members including the user receive this event | +| **onGroupMemberBanned(action: [CometChat.Action](/sdk/reference/messages#action), bannedUser: [CometChat.User](/sdk/reference/entities#user), bannedBy: [CometChat.User](/sdk/reference/entities#user), bannedFrom: [CometChat.Group](/sdk/reference/entities#group))** | This method is triggered when a user is banned from a group. All the members including the user receive this event | +| **onGroupMemberUnbanned(action: [CometChat.Action](/sdk/reference/messages#action), unbannedUser: [CometChat.User](/sdk/reference/entities#user), unbannedBy: [CometChat.User](/sdk/reference/entities#user), unbannedFrom: [CometChat.Group](/sdk/reference/entities#group))** | This method is triggered when a user is unbanned from a group. All the members of the group receive this event. | +| **onGroupMemberScopeChanged(action: [CometChat.Action](/sdk/reference/messages#action), changedUser: [CometChat.User](/sdk/reference/entities#user), newScope: string, oldScope: string, changedGroup: [CometChat.Group](/sdk/reference/entities#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](/sdk/reference/messages#action), userAdded: [CometChat.User](/sdk/reference/entities#user), addedBy: [CometChat.User](/sdk/reference/entities#user), addedTo: [CometChat.Group](/sdk/reference/entities#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`: - -```javascript + +```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, @@ -141,7 +179,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, @@ -150,10 +193,10 @@ CometChat.addGroupListener( }); }, onGroupMemberUnbanned: ( - message, - unbannedUser, - unbannedBy, - unbannedFrom + message: CometChat.Action, + unbannedUser: CometChat.User, + unbannedBy: CometChat.User, + unbannedFrom: CometChat.Group ) => { console.log("onGroupMemberUnbanned", { message, @@ -163,11 +206,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, @@ -177,7 +220,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, @@ -191,31 +239,18 @@ CometChat.addGroupListener( - -```typescript + +```javascript 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, @@ -223,12 +258,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, @@ -237,10 +267,10 @@ CometChat.addGroupListener( }); }, onGroupMemberUnbanned: ( - message: CometChat.Action, - unbannedUser: CometChat.User, - unbannedBy: CometChat.User, - unbannedFrom: CometChat.Group + message, + unbannedUser, + unbannedBy, + unbannedFrom ) => { console.log("onGroupMemberUnbanned", { message, @@ -250,11 +280,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, @@ -264,12 +294,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, @@ -285,21 +310,20 @@ 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: - -```javascript -CometChat.removeGroupListener(UNIQUE_LISTENER_ID); + +```typescript +let listenerID: string = "UNIQUE_LISTENER_ID"; +CometChat.removeGroupListener(listenerID); ``` - -```typescript -let listenerID: string = "UNIQUE_LISTENER_ID"; + +```javascript +let listenerID = "UNIQUE_LISTENER_ID"; CometChat.removeGroupListener(listenerID); ``` @@ -309,73 +333,73 @@ CometChat.removeGroupListener(listenerID); ## 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 interactive messages. | Method | Information | | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | -| **onTextMessageReceived(message: CometChat.TextMessage)** | This event is triggered when a Text Message is received. | -| **onMediaMessageReceived(message: CometChat.MediaMessage)** | This event is triggered when a Media Message is received. | -| **onCustomMessageReceived(message: CometChat.CustomMessage)** | This event is triggered when a Custom Message is received. | -| **onTypingStarted(typingIndicator: CometChat.TypingIndicator)** | This event is triggered when a user starts typing in a user/group conversation | -| **onTypingEnded(typingIndicator: CometChat.TypingIndicator)** | This event is triggered when a user stops typing in a user/group conversation. | -| **onMessagesDelivered(messageReceipt: CometChat.MessageReceipt)** | This event is triggered when a set of messages are marked as delivered for any particular conversation. | -| **onMessagesRead(messageReceipt: CometChat.MessageReceipt)** | This event is triggered when a set of messages are marked as read for any particular conversation. | -| **onMessageEdited(message: CometChat.BaseMessage)** | This method is triggered when a particular message has been edited in a user/group conversation. | -| **onMessageDeleted(message: CometChat.BaseMessage)** | This event is triggered when a particular message is deleted in a user/group conversation. | +| **onTextMessageReceived(message: [CometChat.TextMessage](/sdk/reference/messages#textmessage))** | This event is triggered when a Text Message is received. | +| **onMediaMessageReceived(message: [CometChat.MediaMessage](/sdk/reference/messages#mediamessage))** | This event is triggered when a Media Message is received. | +| **onCustomMessageReceived(message: [CometChat.CustomMessage](/sdk/reference/messages#custommessage))** | This event is triggered when a Custom Message is received. | +| **onTypingStarted(typingIndicator: [CometChat.TypingIndicator](/sdk/reference/auxiliary#typingindicator))** | This event is triggered when a user starts typing in a user/group conversation | +| **onTypingEnded(typingIndicator: [CometChat.TypingIndicator](/sdk/reference/auxiliary#typingindicator))** | This event is triggered when a user stops typing in a user/group conversation. | +| **onMessagesDelivered(messageReceipt: [CometChat.MessageReceipt](/sdk/reference/auxiliary#messagereceipt))** | This event is triggered when a set of messages are marked as delivered for any particular conversation. | +| **onMessagesRead(messageReceipt: [CometChat.MessageReceipt](/sdk/reference/auxiliary#messagereceipt))** | This event is triggered when a set of messages are marked as read for any particular conversation. | +| **onMessageEdited(message: [CometChat.BaseMessage](/sdk/reference/messages#basemessage))** | This method is triggered when a particular message has been edited in a user/group conversation. | +| **onMessageDeleted(message: [CometChat.BaseMessage](/sdk/reference/messages#basemessage))** | This event is triggered when a particular message is deleted in a user/group conversation. | | **onInteractiveMessageReceived(message: CometChat.InteractiveMessage)** | This event is triggered when an Interactive Message is received. | | **onInteractionGoalCompleted(receipt: CometChat.InteractionReceipt)** | This event is triggered when an interaction Goal is achieved. | -| **onTransientMessageReceived(receipt: CometChat.TransientMessage)** | This event is triggered when a Transient Message is received. | -| **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 removed from a message in a user/group conversation. | +| **onTransientMessageReceived(receipt: [CometChat.TransientMessage](/sdk/reference/auxiliary#transientmessage))** | This event is triggered when a Transient Message is received. | +| **onMessageReactionAdded(receipt: [CometChat.ReactionEvent](/sdk/reference/auxiliary#reactionevent))** | This event is triggered when a reaction is added to a message in a user/group conversation. | +| **onMessageReactionRemoved(receipt: [CometChat.ReactionEvent](/sdk/reference/auxiliary#reactionevent))** | This event is triggered when a reaction is removed from a message in a user/group conversation. | -To add the `MessageListener`, you need to use the `addMessageListener()` method provided by the `CometChat` class. +To add the `MessageListener`: - -```javascript + +```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); }, - onMessageDeleted: (message) => { - console.log("Message Delted", message); + onMessageDeleted: (message: CometChat.BaseMessage) => { + console.log("Message Deleted", message); }, - onMessageEdited: (message) => { + onMessageEdited: (message: CometChat.BaseMessage) => { console.log("Message Edited", message); }, - onInteractiveMessageReceived: (message) => { - console.log("interactive Message received", message); + onInteractiveMessageReceived: (message: CometChat.InteractiveMessage) => { + console.log("Interactive Message received", message); }, - onInteractionGoalCompleted: (message) => { - console.log("Message interaction goal completed", message); + onInteractionGoalCompleted: (receipt: CometChat.InteractionReceipt) => { + console.log("Interaction goal completed", receipt); }, - 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); }, }) @@ -384,51 +408,51 @@ CometChat.addMessageListener( - -```typescript + +```javascript 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); + onMessageDeleted: (message) => { + console.log("Message Deleted", message); }, - onMessageEdited: (message: CometChat.BaseMessage) => { + onMessageEdited: (message) => { console.log("Message Edited", message); }, - onInteractiveMessageReceived: (message: CometChat.InteractiveMessage) => { - console.log("interactive Message received", message); + onInteractiveMessageReceived: (message) => { + console.log("Interactive Message received", message); }, - onInteractionGoalCompleted: (receipt: CometChat.InteractionReceipt) => { - console.log("Message interaction goal completed", message); + onInteractionGoalCompleted: (receipt) => { + console.log("Interaction goal completed", receipt); }, - 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); }, }) @@ -439,21 +463,20 @@ 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: - -```javascript -CometChat.removeMessageListener(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); ``` @@ -463,33 +486,33 @@ CometChat.removeMessageListener(listenerID); ## 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 | | ------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **onIncomingCallReceived(call: CometChat.Call)** | This event is triggered when the logged-in user receives an incoming call. The details of the call can be obtained from the Call object received as the method parameter. | -| **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 | +| **onIncomingCallReceived(call: [CometChat.Call](/sdk/reference/messages#call))** | This event is triggered when the logged-in user receives an incoming call. The details of the call can be obtained from the Call object received as the method parameter. | +| **onOutgoingCallAccepted(call: [CometChat.Call](/sdk/reference/messages#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](/sdk/reference/messages#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](/sdk/reference/messages#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`: - -```javascript + +```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); }, }) @@ -498,21 +521,21 @@ CometChat.addCallListener( - -```typescript + +```javascript 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); }, }) @@ -523,21 +546,20 @@ 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: - -```javascript -CometChat.removeCallListener(UNIQUE_LISTENER_ID); + +```typescript +let listenerID: string = "UNIQUE_LISTENER_ID"; +CometChat.removeCallListener(listenerID); ``` - -```typescript -let listenerID: string = "UNIQUE_LISTENER_ID"; + +```javascript +let listenerID = "UNIQUE_LISTENER_ID"; CometChat.removeCallListener(listenerID); ``` @@ -545,37 +567,21 @@ CometChat.removeCallListener(listenerID); - - -- Register listeners as early as possible in your app lifecycle (e.g., after successful login) to avoid missing events -- Use unique, descriptive listener IDs (e.g., `"CHAT_SCREEN_MESSAGE_LISTENER"`) to make debugging easier -- Always remove listeners when the component unmounts or the user logs out -- Avoid registering the same listener ID multiple times — this overwrites the previous listener silently -- For React Native, use `useEffect` cleanup functions to handle listener removal automatically - - - -- **Events not firing**: Ensure the listener is registered with a unique ID and that you're handling the correct callback method for the event type. -- **Duplicate events**: Check that you're not registering the same listener multiple times without removing the previous one first. -- **Events stop after navigation**: If you remove listeners on screen unmount, re-register them when the screen mounts again. -- **Missing group events**: Group listeners only fire for groups the logged-in user is a member of. Verify group membership. -- **Call events not received**: Ensure the CometChat Calling SDK is properly initialized alongside the Chat SDK. - - +--- ## Next Steps - -Track when users come online or go offline - - -Handle incoming messages in real time - - -Show when users are typing - - -Implement voice and video calling - + + Track when users come online or go offline + + + Handle incoming messages in real time + + + Show when users are typing + + + Monitor SDK connection state changes + diff --git a/sdk/react-native/receive-messages.mdx b/sdk/react-native/receive-messages.mdx index d9f67a8e5..8e6499597 100644 --- a/sdk/react-native/receive-messages.mdx +++ b/sdk/react-native/receive-messages.mdx @@ -1,3272 +1,503 @@ --- -title: "Receive A Message" -description: "Receive real-time messages, fetch missed and unread messages, retrieve message history, and get unread message counts using the CometChat React Native SDK." +title: "Receive Messages" +sidebarTitle: "Receive Messages" +description: "Receive real-time messages, fetch unread messages, retrieve message history, search messages, and get unread counts using the CometChat React Native SDK." --- - -**Quick Reference** - Listen for incoming messages: + -```javascript -CometChat.addMessageListener("listener-id", new CometChat.MessageListener({ - onTextMessageReceived: (msg) => console.log("Text:", msg), - onMediaMessageReceived: (msg) => console.log("Media:", msg), - onCustomMessageReceived: (msg) => console.log("Custom:", msg), -})); - -// Don't forget to remove the listener when done -CometChat.removeMessageListener("listener-id"); -``` - - - -Available via: [SDK](/sdk/react-native/receive-messages) | [REST API](/rest-api/messages/list-messages) | [UI Kits](/ui-kit/react-native/core-features#instant-messaging) - - -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 - -## 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. - - - - ```javascript - let listenerID = "UNIQUE_LISTENER_ID"; - - CometChat.addMessageListener( - listenerID, - new CometChat.MessageListener({ - onTextMessageReceived: (textMessage) => { - console.log("Text message received successfully", textMessage); - }, - onMediaMessageReceived: (mediaMessage) => { - console.log("Media message received successfully", mediaMessage); - }, - onCustomMessageReceived: (customMessage) => { - console.log("Custom message received successfully", customMessage); - }, - }) - ); - ``` - - - ```typescript - let listenerID: string = "UNIQUE_LISTENER_ID"; - - CometChat.addMessageListener( - listenerID, - new CometChat.MessageListener({ - onTextMessageReceived: (textMessage: CometChat.TextMessage) => { - console.log("Text message received successfully", textMessage); - }, - onMediaMessageReceived: (mediaMessage: CometChat.MediaMessage) => { - console.log("Media message received successfully", mediaMessage); - }, - onCustomMessageReceived: (customMessage: CometChat.CustomMessage) => { - console.log("Custom message received successfully", customMessage); - }, - }) - ); - ``` - - - -| Parameter | Description | -| -------------- | --------------------------------------------- | -| **listenerId** | An ID that uniquely identifies that listener. | - - - -**onTextMessageReceived** — Text message object received via the listener: - - - -**TextMessage Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25195"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Hello"` | -| `sentAt` | number | Timestamp when sent | `1771386431` | -| `updatedAt` | number | Timestamp when updated | `1771386431` | -| `sender` | object | Sender user details | [See below ↓](#realtime-text-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#realtime-text-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#realtime-text-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#realtime-text-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771386392` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771386383` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Hello"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `entities` | object | Sender and receiver entities | [See below ↓](#realtime-text-data-entities-object) | -| `metadata` | object | Injected metadata | [See below ↓](#realtime-text-data-metadata-object) | -| `moderation` | object | Moderation status | [See below ↓](#realtime-text-data-moderation-object) | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#realtime-text-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#realtime-text-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#realtime-text-data-entities-sender-entity-object) | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771386392` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#realtime-text-data-entities-receiver-entity-object) | - ---- - - - -**`data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771386383` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#realtime-text-data-metadata-injected-object) | - ---- - - - -**`data.metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#realtime-text-data-metadata-extensions-object) | - ---- - - - -**`data.metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#realtime-text-data-metadata-linkpreview-object) | - ---- - - - -**`data.metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - - - -**`data.moderation` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `status` | string | Moderation status | `"approved"` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#realtime-text-metadata-injected-object) | - ---- - - - -**`metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#realtime-text-metadata-extensions-object) | - ---- - - - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#realtime-text-metadata-linkpreview-object) | - ---- - - - -**`metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - -**onMediaMessageReceived** — Media message object received via the listener: - - - -**MediaMessage Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25196"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Media type | `"image"` | -| `category` | string | Message category | `"message"` | -| `sentAt` | number | Timestamp when sent | `1771386517` | -| `updatedAt` | number | Timestamp when updated | `1771386517` | -| `sender` | object | Sender user details | [See below ↓](#realtime-media-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#realtime-media-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#realtime-media-data-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"offline"` | -| `lastActiveAt` | number | Last active timestamp | `1771386507` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"offline"` | -| `lastActiveAt` | number | Last active timestamp | `1771386436` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `type` | string | Media type | `"image"` | -| `category` | string | Message category | `"message"` | -| `url` | string | Media file URL | `"https://data-in.cometchat.io/..."` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `attachments` | array | Media attachments | [See below ↓](#realtime-media-data-attachments-array) | -| `entities` | object | Sender and receiver entities | [See below ↓](#realtime-media-data-entities-object) | -| `moderation` | object | Moderation status | [See below ↓](#realtime-media-data-moderation-object) | - ---- - - - -**`data.attachments` Array (per item):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `url` | string | File URL | `"https://data-in.cometchat.io/..."` | -| `name` | string | File name | `"photo.jpg"` | -| `mimeType` | string | MIME type | `"image/jpeg"` | -| `extension` | string | File extension | `"jpg"` | -| `size` | number | File size in bytes | `142099` | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#realtime-media-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#realtime-media-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#realtime-media-data-entities-sender-entity-object) | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"offline"` | -| `lastActiveAt` | number | Last active timestamp | `1771386507` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#realtime-media-data-entities-receiver-entity-object) | - ---- - - - -**`data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"offline"` | -| `lastActiveAt` | number | Last active timestamp | `1771386436` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.moderation` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `status` | string | Moderation status | `"approved"` | - ---- - -**onCustomMessageReceived** — Custom message object received via the listener: - - - -**CustomMessage Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25197"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Custom message type | `"test-custom"` | -| `category` | string | Message category | `"custom"` | -| `customData` | object | Custom data payload | [See below ↓](#realtime-custom-customdata-object) | -| `sentAt` | number | Timestamp when sent | `1771386648` | -| `updatedAt` | number | Timestamp when updated | `1771386648` | -| `sender` | object | Sender user details | [See below ↓](#realtime-custom-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#realtime-custom-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#realtime-custom-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#realtime-custom-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771386640` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771386630` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`customData` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `greeting` | string | Custom greeting text | `"Hello from custom message!"` | -| `timestamp` | number | Custom timestamp | `1771386646780` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Display text | `"Sent a custom message"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `customData` | object | Custom data payload | [See below ↓](#realtime-custom-data-customdata-object) | -| `entities` | object | Sender and receiver entities | [See below ↓](#realtime-custom-data-entities-object) | -| `metadata` | object | Injected metadata | [See below ↓](#realtime-custom-data-metadata-object) | -| `moderation` | object | Moderation status | [See below ↓](#realtime-custom-data-moderation-object) | - ---- - - - -**`data.customData` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `greeting` | string | Custom greeting text | `"Hello from custom message!"` | -| `timestamp` | number | Custom timestamp | `1771386646780` | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#realtime-custom-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#realtime-custom-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#realtime-custom-data-entities-sender-entity-object) | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771386640` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#realtime-custom-data-entities-receiver-entity-object) | - ---- - - - -**`data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771386630` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#realtime-custom-data-metadata-injected-object) | - ---- - - - -**`data.metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#realtime-custom-data-metadata-extensions-object) | - ---- - - - -**`data.metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#realtime-custom-data-metadata-linkpreview-object) | - ---- - - - -**`data.metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - - - -**`data.moderation` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `status` | string | Moderation status | `"approved"` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#realtime-custom-metadata-injected-object) | - ---- - - - -**`metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#realtime-custom-metadata-extensions-object) | - ---- - - - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#realtime-custom-metadata-linkpreview-object) | - ---- - - - -**`metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - - - - -**Listener Cleanup:** Always remove the listener once you don't need to receive messages for a particular listener. Remove the listener in `componentWillUnmount()` or the cleanup function of a `useEffect` to prevent memory leaks. - - - - - ```javascript - var listenerID = "UNIQUE_LISTENER_ID"; - CometChat.removeMessageListener(listenerID); - ``` - - - ```typescript - let listenerID: string = "UNIQUE_LISTENER_ID"; - 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. - - -## Missed Messages - -*In other words, as a recipient, 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 message history instead. - -Using the same `MessagesRequest` class and the filters provided by the `MessagesRequestBuilder` class, you can fetch the messages that were 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. - -### For a Particular One-on-one Conversation - - - - ```javascript - let UID = "UID"; - let limit = 30; - let latestId = await CometChat.getLastDeliveredMessageId(); - - var 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", - limit: number = 30, - latestId: number = await CometChat.getLastDeliveredMessageId(), - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setMessageId(latestId) - .setLimit(limit) - .build(); - - messagesRequest.fetchNext().then( - (messages: CometChat.BaseMessage[]) => { - console.log("Message list fetched:", messages); - }, - (error: CometChat.CometChatException) => { - console.log("Message fetching failed with error:", error); - } - ); - ``` - - - - - -**On Success** — Returns an array of missed message objects: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25211"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Missed Message"` | -| `sentAt` | number | Timestamp when sent | `1771388912` | -| `updatedAt` | number | Timestamp when updated | `1771388912` | -| `sender` | object | Sender user details | [See below ↓](#missed-user-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#missed-user-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#missed-user-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#missed-user-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771388895` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"offline"` | -| `lastActiveAt` | number | Last active timestamp | `1771388888` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Missed Message"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `entities` | object | Sender and receiver entities | [See below ↓](#missed-user-data-entities-object) | -| `metadata` | object | Injected metadata | [See below ↓](#missed-user-data-metadata-object) | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#missed-user-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#missed-user-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#missed-user-data-entities-sender-entity-object) | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771388895` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#missed-user-data-entities-receiver-entity-object) | - ---- - - - -**`data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"offline"` | -| `lastActiveAt` | number | Last active timestamp | `1771388888` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#missed-user-data-metadata-injected-object) | - ---- - - - -**`data.metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#missed-user-data-metadata-extensions-object) | - ---- - - - -**`data.metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | `{"links": []}` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#missed-user-metadata-injected-object) | - ---- - - - -**`metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#missed-user-metadata-extensions-object) | - ---- - - - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#missed-user-metadata-linkpreview-object) | - ---- - - - -**`metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - - - -**On Failure — Error Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `code` | string | Error code | `"ERR_NOT_LOGGED_IN"` | -| `name` | string | Error name | `"Not logged in"` | -| `message` | string | Error message | `"No user is currently logged in."` | -| `details` | object | Additional error details | `{}` | - - - -### For a Particular Group - - - - ```javascript - let GUID = "GUID"; - let limit = 30; - let latestId = await CometChat.getLastDeliveredMessageId(); - - var 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); - } - ); - ``` - - - ```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(); - - messagesRequest.fetchNext().then( - (messages: CometChat.BaseMessage[]) => { - console.log("Message list fetched:", messages); - }, - (error: CometChat.CometChatException) => { - console.log("Message fetching failed with error:", error); - } - ); - ``` - - - - - -**On Success** — Returns an array of missed group message objects: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25215"` | -| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | -| `receiverId` | string | Group GUID | `"group_1748415903905"` | -| `receiverType` | string | Type of receiver | `"group"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Group Missed"` | -| `sentAt` | number | Timestamp when sent | `1771389682` | -| `updatedAt` | number | Timestamp when updated | `1771389682` | -| `sender` | object | Sender user details | [See below ↓](#missed-group-sender-object) | -| `receiver` | object | Receiver group details | [See below ↓](#missed-group-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#missed-group-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#missed-group-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771388895` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object (Group):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `guid` | string | Group's unique identifier | `"group_1748415903905"` | -| `name` | string | Group's display name | `"3 People Group"` | -| `type` | string | Group type | `"public"` | -| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | -| `owner` | string | Group owner UID | `"123456"` | -| `scope` | string | Current user's scope in group | `"admin"` | -| `membersCount` | number | Total members in group | `12` | -| `onlineMembersCount` | number | Online members count | `1` | -| `hasJoined` | boolean | Whether current user has joined | `true` | -| `isBanned` | boolean | Whether current user is banned | `false` | -| `joinedAt` | number | Timestamp when user joined | `1749203133` | -| `createdAt` | number | Group creation timestamp | `1748415957` | -| `updatedAt` | number | Group update timestamp | `1771245340` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Group Missed"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `entities` | object | Sender and receiver entities | [See below ↓](#missed-group-data-entities-object) | -| `metadata` | object | Injected metadata | [See below ↓](#missed-group-data-metadata-object) | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#missed-group-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#missed-group-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#missed-group-data-entities-sender-entity-object) | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771388895` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"group"` | -| `entity` | object | Group entity details | [See below ↓](#missed-group-data-entities-receiver-entity-object) | - ---- - - - -**`data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `guid` | string | Group's unique identifier | `"group_1748415903905"` | -| `name` | string | Group's display name | `"3 People Group"` | -| `type` | string | Group type | `"public"` | -| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | -| `owner` | string | Group owner UID | `"123456"` | -| `scope` | string | Current user's scope in group | `"admin"` | -| `membersCount` | number | Total members in group | `12` | -| `onlineMembersCount` | number | Online members count | `1` | -| `hasJoined` | boolean | Whether current user has joined | `true` | -| `joinedAt` | number | Timestamp when user joined | `1749203133` | -| `createdAt` | number | Group creation timestamp | `1748415957` | -| `updatedAt` | number | Group update timestamp | `1771245340` | - ---- - - - -**`data.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#missed-group-data-metadata-injected-object) | - ---- - - - -**`data.metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | `{"link-preview": {"links": []}}` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#missed-group-metadata-injected-object) | - ---- - - - -**`metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#missed-group-metadata-extensions-object) | - ---- - - - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#missed-group-metadata-linkpreview-object) | - ---- - - - -**`metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - - - -**On Failure — Error Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `code` | string | Error code | `"ERR_NOT_LOGGED_IN"` | -| `name` | string | Error name | `"Not logged in"` | -| `message` | string | Error message | `"No user is currently logged in."` | -| `details` | object | Additional error details | `{}` | - - - -## 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. - -### For 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", - limit: number = 30, - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setUnread(true) - .setLimit(limit) - .build(); - - messagesRequest.fetchPrevious().then( - (messages: CometChat.BaseMessage[]) => { - console.log("Message list fetched:", messages); - }, - (error: CometChat.CometChatException) => { - console.log("Message fetching failed with error:", error); - } - ); - ``` - - - - - -**On Success** — Returns an array of unread message objects: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25216"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Unread Message"` | -| `sentAt` | number | Timestamp when sent | `1771390060` | -| `deliveredAt` | number | Timestamp when delivered | `1771390061` | -| `updatedAt` | number | Timestamp when updated | `1771390061` | -| `sender` | object | Sender user details | [See below ↓](#unread-user-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#unread-user-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#unread-user-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#unread-user-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771388895` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"offline"` | -| `lastActiveAt` | number | Last active timestamp | `1771389781` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Unread Message"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `entities` | object | Sender and receiver entities | [See below ↓](#unread-user-data-entities-object) | -| `metadata` | object | Injected metadata | [See below ↓](#unread-user-data-metadata-object) | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#unread-user-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#unread-user-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#unread-user-data-entities-sender-entity-object) | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771388895` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#unread-user-data-entities-receiver-entity-object) | - ---- - - - -**`data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"offline"` | -| `lastActiveAt` | number | Last active timestamp | `1771389781` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#unread-user-data-metadata-injected-object) | - ---- - - - -**`data.metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | `{"link-preview": {"links": []}}` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#unread-user-metadata-injected-object) | - ---- - - - -**`metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#unread-user-metadata-extensions-object) | - ---- - - - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#unread-user-metadata-linkpreview-object) | - ---- - - - -**`metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - - - -**On Failure — Error Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `code` | string | Error code | `"ERR_NOT_LOGGED_IN"` | -| `name` | string | Error name | `"Not logged in"` | -| `message` | string | Error message | `"No user is currently logged in."` | -| `details` | object | Additional error details | `{}` | - - - -### For a Particular Group - - - - ```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); - } - ); - ``` - - - ```typescript - let GUID: string = "GUID", - limit: number = 30, - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setUnread(true) - .setLimit(limit) - .build(); - - messagesRequest.fetchPrevious().then( - (messages: CometChat.BaseMessage[]) => { - console.log("Message list fetched:", messages); - }, - (error: CometChat.CometChatException) => { - console.log("Message fetching failed with error:", error); - } - ); - ``` - - - - - -**On Success** — Returns an array of unread group message objects: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25217"` | -| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | -| `receiverId` | string | Group GUID | `"group_1748415903905"` | -| `receiverType` | string | Type of receiver | `"group"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Unread Group Message"` | -| `sentAt` | number | Timestamp when sent | `1771390129` | -| `updatedAt` | number | Timestamp when updated | `1771390129` | -| `sender` | object | Sender user details | [See below ↓](#unread-group-sender-object) | -| `receiver` | object | Receiver group details | [See below ↓](#unread-group-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#unread-group-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#unread-group-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771388895` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object (Group):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `guid` | string | Group's unique identifier | `"group_1748415903905"` | -| `name` | string | Group's display name | `"3 People Group"` | -| `type` | string | Group type | `"public"` | -| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | -| `owner` | string | Group owner UID | `"123456"` | -| `scope` | string | Current user's scope in group | `"admin"` | -| `membersCount` | number | Total members in group | `12` | -| `onlineMembersCount` | number | Online members count | `1` | -| `hasJoined` | boolean | Whether current user has joined | `true` | -| `isBanned` | boolean | Whether current user is banned | `false` | -| `joinedAt` | number | Timestamp when user joined | `1749203133` | -| `createdAt` | number | Group creation timestamp | `1748415957` | -| `updatedAt` | number | Group update timestamp | `1771245340` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Unread Group Message"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `entities` | object | Sender and receiver entities | [See below ↓](#unread-group-data-entities-object) | -| `metadata` | object | Injected metadata | [See below ↓](#unread-group-data-metadata-object) | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#unread-group-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#unread-group-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#unread-group-data-entities-sender-entity-object) | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771388895` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"group"` | -| `entity` | object | Group entity details | [See below ↓](#unread-group-data-entities-receiver-entity-object) | - ---- - - - -**`data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `guid` | string | Group's unique identifier | `"group_1748415903905"` | -| `name` | string | Group's display name | `"3 People Group"` | -| `type` | string | Group type | `"public"` | -| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | -| `owner` | string | Group owner UID | `"123456"` | -| `scope` | string | Current user's scope in group | `"admin"` | -| `membersCount` | number | Total members in group | `12` | -| `onlineMembersCount` | number | Online members count | `1` | -| `hasJoined` | boolean | Whether current user has joined | `true` | -| `joinedAt` | number | Timestamp when user joined | `1749203133` | -| `createdAt` | number | Group creation timestamp | `1748415957` | -| `updatedAt` | number | Group update timestamp | `1771245340` | - ---- - - - -**`data.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | `{"extensions": {"link-preview": {"links": []}}}` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#unread-group-metadata-injected-object) | - ---- - - - -**`metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#unread-group-metadata-extensions-object) | - ---- - - - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#unread-group-metadata-linkpreview-object) | - ---- - - - -**`metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - - - -**On Failure — Error Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `code` | string | Error code | `"ERR_NOT_LOGGED_IN"` | -| `name` | string | Error name | `"Not logged in"` | -| `message` | string | Error message | `"No user is currently logged in."` | -| `details` | object | Additional error details | `{}` | - - - - -**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 - -*In other words, as a logged-in user, how do I fetch the complete message history?* - -### For 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. - - - - ```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); - } - ); - ``` - - - ```typescript - let UID: string = "UID", - limit: number = 30, - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder().setUID(UID).setLimit(limit).build(); - - messagesRequest.fetchPrevious().then( - (messages: CometChat.BaseMessage[]) => { - console.log("Message list fetched:", messages); - }, - (error: CometChat.CometChatException) => { - console.log("Message fetching failed with error:", error); - } - ); - ``` - - - -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. - - - -**On Success** — Returns an array of message history objects: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25220"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Historic 1-1"` | -| `sentAt` | number | Timestamp when sent | `1771390691` | -| `updatedAt` | number | Timestamp when updated | `1771390691` | -| `sender` | object | Sender user details | [See below ↓](#history-user-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#history-user-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#history-user-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#history-user-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771388895` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"offline"` | -| `lastActiveAt` | number | Last active timestamp | `1771389781` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Historic 1-1"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `entities` | object | Sender and receiver entities | [See below ↓](#history-user-data-entities-object) | -| `metadata` | object | Injected metadata | [See below ↓](#history-user-data-metadata-object) | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#history-user-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#history-user-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#history-user-data-entities-sender-entity-object) | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771388895` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#history-user-data-entities-receiver-entity-object) | - ---- - - - -**`data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"offline"` | -| `lastActiveAt` | number | Last active timestamp | `1771389781` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | `{"extensions": {"link-preview": {"links": []}}}` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#history-user-metadata-injected-object) | - ---- - - - -**`metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#history-user-metadata-extensions-object) | - ---- - - - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#history-user-metadata-linkpreview-object) | - ---- - - - -**`metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - - - -**On Failure — Error Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `code` | string | Error code | `"ERR_NOT_LOGGED_IN"` | -| `name` | string | Error name | `"Not logged in"` | -| `message` | string | Error message | `"No user is currently logged in."` | -| `details` | object | Additional error details | `{}` | - - - -### For a Particular Group - -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. - - - - ```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); - } - ); - ``` - - - ```typescript - let GUID: string = "GUID", - limit: number = 30, - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setLimit(limit) - .build(); - - messagesRequest.fetchPrevious().then( - (messages: CometChat.BaseMessage[]) => { - console.log("Message list fetched:", messages); - }, - (error: CometChat.CometChatException) => { - console.log("Message fetching failed with error:", error); - } - ); - ``` - - - -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. - - - -**On Success** — Returns an array of group message history objects: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25218"` | -| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | -| `receiverId` | string | Group GUID | `"group_1748415903905"` | -| `receiverType` | string | Type of receiver | `"group"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Historic Message 1"` | -| `sentAt` | number | Timestamp when sent | `1771390631` | -| `updatedAt` | number | Timestamp when updated | `1771390631` | -| `sender` | object | Sender user details | [See below ↓](#history-group-sender-object) | -| `receiver` | object | Receiver group details | [See below ↓](#history-group-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#history-group-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#history-group-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771388895` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object (Group):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `guid` | string | Group's unique identifier | `"group_1748415903905"` | -| `name` | string | Group's display name | `"3 People Group"` | -| `type` | string | Group type | `"public"` | -| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | -| `owner` | string | Group owner UID | `"123456"` | -| `scope` | string | Current user's scope in group | `"admin"` | -| `membersCount` | number | Total members in group | `12` | -| `onlineMembersCount` | number | Online members count | `1` | -| `hasJoined` | boolean | Whether current user has joined | `true` | -| `isBanned` | boolean | Whether current user is banned | `false` | -| `joinedAt` | number | Timestamp when user joined | `1749203133` | -| `createdAt` | number | Group creation timestamp | `1748415957` | -| `updatedAt` | number | Group update timestamp | `1771245340` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Historic Message 1"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `entities` | object | Sender and receiver entities | [See below ↓](#history-group-data-entities-object) | -| `metadata` | object | Injected metadata | [See below ↓](#history-group-data-metadata-object) | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#history-group-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#history-group-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#history-group-data-entities-sender-entity-object) | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771388895` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"group"` | -| `entity` | object | Group entity details | [See below ↓](#history-group-data-entities-receiver-entity-object) | - ---- - - - -**`data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `guid` | string | Group's unique identifier | `"group_1748415903905"` | -| `name` | string | Group's display name | `"3 People Group"` | -| `type` | string | Group type | `"public"` | -| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | -| `owner` | string | Group owner UID | `"123456"` | -| `scope` | string | Current user's scope in group | `"admin"` | -| `membersCount` | number | Total members in group | `12` | -| `onlineMembersCount` | number | Online members count | `1` | -| `hasJoined` | boolean | Whether current user has joined | `true` | -| `joinedAt` | number | Timestamp when user joined | `1749203133` | -| `createdAt` | number | Group creation timestamp | `1748415957` | -| `updatedAt` | number | Group update timestamp | `1771245340` | - ---- - - - -**`data.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | `{"extensions": {"link-preview": {"links": []}}}` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#history-group-metadata-injected-object) | - ---- - - - -**`metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#history-group-metadata-extensions-object) | - ---- - - - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#history-group-metadata-linkpreview-object) | - ---- - - - -**`metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - - - -**On Failure — Error Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `code` | string | Error code | `"ERR_NOT_LOGGED_IN"` | -| `name` | string | Error name | `"Not logged in"` | -| `message` | string | Error message | `"No user is currently logged in."` | -| `details` | object | Additional error details | `{}` | +| Field | Value | +| --- | --- | +| Key Classes | `CometChat.MessageListener`, `CometChat.MessagesRequestBuilder` | +| Key Methods | `addMessageListener()`, `fetchPrevious()`, `fetchNext()`, `getUnreadMessageCount()` | +| Listener Events | `onTextMessageReceived`, `onMediaMessageReceived`, `onCustomMessageReceived` | +| Prerequisites | SDK initialized, user logged in | -## Search Messages - -*In other words, as a logged-in user, how do I search a message?* +Receiving messages with CometChat has two parts: -In order to do this, you can use the `setSearchKeyword()` method. This method accepts a string as input. When set, the SDK will fetch messages which match the `searchKeyword`. +1. Adding a [real-time listener](#real-time-messages) to receive messages while your app is running +2. Fetching [unread](#unread-messages), or [historical](#message-history) messages when your app starts up or the user scrolls back -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). +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. -| Feature | Basic Search | Advanced Search | -| ---------------- | ------------ | --------------- | -| Text search | ✅ | ✅ | -| File name search | ❌ | ✅ | -| Mentions search | ❌ | ✅ | -| Mime type search | ❌ | ✅ | +## Real-Time Messages -### For a Particular One-on-one Conversation +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). - - ```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", - limit: number = 30, - searchKeyword: string = "Hello", - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setLimit(limit) - .setSearchKeyword(searchKeyword) - .build(); - - messagesRequest.fetchPrevious().then( - (messages: CometChat.BaseMessage[]) => { - console.log("Message list fetched:", messages); - }, - (error: CometChat.CometChatException) => { - console.log("Message fetching failed with error:", error); - } - ); - ``` - - - - - -**On Success** — Returns an array of messages matching the search keyword: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25224"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"xq7SearchTest"` | -| `sentAt` | number | Timestamp when sent | `1771392432` | -| `deliveredAt` | number | Timestamp when delivered | `1771392432` | -| `readAt` | number | Timestamp when read | `1771392432` | -| `updatedAt` | number | Timestamp when updated | `1771392432` | -| `sender` | object | Sender user details | [See below ↓](#search-user-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#search-user-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#search-user-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#search-user-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771391162` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771391157` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"xq7SearchTest"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `entities` | object | Sender and receiver entities | [See below ↓](#search-user-data-entities-object) | -| `metadata` | object | Injected metadata | `{"@injected": {"extensions": {"link-preview": {"links": []}}}}` | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | Contains `entityType` and `entity` | -| `receiver` | object | Receiver entity wrapper | Contains `entityType` and `entity` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | `{"extensions": {"link-preview": {"links": []}}}` | - ---- - - - -**On Failure — Error Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `code` | string | Error code | `"ERR_NOT_LOGGED_IN"` | -| `name` | string | Error name | `"Not logged in"` | -| `message` | string | Error message | `"No user is currently logged in."` | -| `details` | object | Additional error details | `{}` | - - - -### For a Particular Group + +```typescript +let listenerID: string = "UNIQUE_LISTENER_ID"; + +CometChat.addMessageListener( + listenerID, + new CometChat.MessageListener({ + onTextMessageReceived: (textMessage: CometChat.TextMessage) => { + console.log("Text message received successfully", textMessage); + }, + onMediaMessageReceived: (mediaMessage: CometChat.MediaMessage) => { + console.log("Media message received successfully", mediaMessage); + }, + onCustomMessageReceived: (customMessage: CometChat.CustomMessage) => { + console.log("Custom message received successfully", customMessage); + }, + }) +); +``` + - - - ```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); - } - ); - ``` - - - ```typescript - let GUID: string = "GUID", - limit: number = 30, - searchKeyword: string = "Hello", - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setLimit(limit) - .setSearchKeyword(searchKeyword) - .build(); - - messagesRequest.fetchPrevious().then( - (messages: CometChat.BaseMessage[]) => { - console.log("Message list fetched:", messages); - }, - (error: CometChat.CometChatException) => { - console.log("Message fetching failed with error:", error); - } - ); - ``` - + +```javascript +let listenerID = "UNIQUE_LISTENER_ID"; + +CometChat.addMessageListener( + listenerID, + new CometChat.MessageListener({ + onTextMessageReceived: (textMessage) => { + console.log("Text message received successfully", textMessage); + }, + onMediaMessageReceived: (mediaMessage) => { + console.log("Media message received successfully", mediaMessage); + }, + onCustomMessageReceived: (customMessage) => { + console.log("Custom message received successfully", customMessage); + }, + }) +); +``` + - - -**On Success** — Returns an array of group messages matching the search keyword: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25225"` | -| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | -| `receiverId` | string | Group GUID | `"group_1748415903905"` | -| `receiverType` | string | Type of receiver | `"group"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"xq8SearchTest"` | -| `sentAt` | number | Timestamp when sent | `1771392513` | -| `updatedAt` | number | Timestamp when updated | `1771392513` | -| `sender` | object | Sender user details | [See below ↓](#search-group-sender-object) | -| `receiver` | object | Receiver group details | [See below ↓](#search-group-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#search-group-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#search-group-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** +| Parameter | Description | +| --- | --- | +| `listenerID` | An ID that uniquely identifies that listener. Use the same ID to remove it later. | -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771391162` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | +Remove the listener when you no longer need it: ---- - - - -**`receiver` Object (Group):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `guid` | string | Group's unique identifier | `"group_1748415903905"` | -| `name` | string | Group's display name | `"3 People Group"` | -| `type` | string | Group type | `"public"` | -| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | -| `owner` | string | Group owner UID | `"123456"` | -| `scope` | string | Current user's scope in group | `"admin"` | -| `membersCount` | number | Total members in group | `12` | -| `onlineMembersCount` | number | Online members count | `2` | -| `hasJoined` | boolean | Whether current user has joined | `true` | -| `isBanned` | boolean | Whether current user is banned | `false` | -| `joinedAt` | number | Timestamp when user joined | `1749203133` | -| `createdAt` | number | Group creation timestamp | `1748415957` | -| `updatedAt` | number | Group update timestamp | `1771245340` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"xq8SearchTest"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `entities` | object | Sender and receiver entities | Contains `sender` and `receiver` wrappers | -| `metadata` | object | Injected metadata | `{"@injected": {"extensions": {"link-preview": {"links": []}}}}` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | `{"extensions": {"link-preview": {"links": []}}}` | - ---- - - - -**On Failure — Error Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `code` | string | Error code | `"ERR_NOT_LOGGED_IN"` | -| `name` | string | Error name | `"Not logged in"` | -| `message` | string | Error message | `"No user is currently logged in."` | -| `details` | object | Additional error details | `{}` | - - - -## Unread Message Count - -*In other words, as a logged-in user, how do I find out the number of unread messages that I have?* - -### For a Particular One-on-one Conversation - -*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()` method. +```javascript +CometChat.removeMessageListener("UNIQUE_LISTENER_ID"); +``` -This method has the below two variants: + +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. + - - - ```javascript - CometChat.getUnreadMessageCountForUser(UID); - ``` - - - ```typescript - let UID: string = "UID"; - CometChat.getUnreadMessageCountForUser(UID); - ``` - - + +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. + -If you wish to ignore the messages from blocked users you can use the below syntax setting the boolean parameter to true: +## Missed Messages - - - ```javascript - CometChat.getUnreadMessageCountForUser(UID, hideMessagesFromBlockedUsers); - ``` - - - ```typescript - let UID: string = "UID", - hideMessagesFromBlockedUsers: boolean = true; - CometChat.getUnreadMessageCountForUser(UID, hideMessagesFromBlockedUsers); - ``` - - +Fetch messages that were sent while the user was offline using `getLastDeliveredMessageId()` and `fetchNext()`. - - ```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); - } - ); - ``` - - - ```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); - } - ); - ``` - + +```typescript +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[]) => { + console.log("Message list fetched:", messages); + }, + (error: CometChat.CometChatException) => { + console.log("Message fetching failed with error:", error); + } +); +``` + + + +```typescript +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[]) => { + console.log("Message list fetched:", messages); + }, + (error: CometChat.CometChatException) => { + console.log("Message fetching failed with error:", error); + } +); +``` + -It will return an object which will contain the UID as the key and the unread message count as the value. - - - -**On Success** — Returns an object with UID as key and unread count as value: - - - -**Unread Count Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `{UID}` | number | Unread message count for the specified user | `2` | - -Example: `{"cometchat-uid-3": 2}` - ---- - - - -**On Failure — Error Object:** +Call `fetchNext()` repeatedly on the same object to paginate through all missed messages. -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `code` | string | Error code | `"ERR_NOT_LOGGED_IN"` | -| `name` | string | Error name | `"Not logged in"` | -| `message` | string | Error message | `"No user is currently logged in."` | -| `details` | object | Additional error details | `{}` | - - - -### For a Particular Group Conversation - -*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()` method. - -This method has the below two variants: - - - - ```javascript - CometChat.getUnreadMessageCountForGroup(GUID); - ``` - - - ```typescript - let GUID: string = "GUID"; - 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: +## Unread Messages - - - ```javascript - CometChat.getUnreadMessageCountForGroup(GUID, hideMessagesFromBlockedUsers); - ``` - - - ```typescript - let GUID: string = "GUID", - hideMessagesFromBlockedUsers: boolean = true; - CometChat.getUnreadMessageCountForGroup(GUID, hideMessagesFromBlockedUsers); - ``` - - +Fetch unread messages by adding `setUnread(true)` to the builder. Use `fetchPrevious()` to retrieve them. - - ```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); - } - ); - ``` - - - ```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); - } - ); - ``` - + +```typescript +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[]) => { + console.log("Message list fetched:", messages); + }, + (error: CometChat.CometChatException) => { + console.log("Message fetching failed with error:", error); + } +); +``` + + + +```typescript +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[]) => { + console.log("Message list fetched:", messages); + }, + (error: CometChat.CometChatException) => { + console.log("Message fetching failed with error:", error); + } +); +``` + -It will return an object which will contain the GUID as the key and the unread message count as the value. - - - -**On Success** — Returns an object with GUID as key and unread count as value: - - - -**Unread Count Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `{GUID}` | number | Unread message count for the specified group | `3` | - -Example: `{"group_1748415903905": 3}` - ---- - - - -**On Failure — Error Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `code` | string | Error code | `"ERR_NOT_LOGGED_IN"` | -| `name` | string | Error name | `"Not logged in"` | -| `message` | string | Error message | `"No user is currently logged in."` | -| `details` | object | Additional error details | `{}` | - - - -### For All One-on-one & Group Conversations - -*How do I find out the number of unread messages for every one-on-one and group conversation?* + +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. + -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. +## Message History -This method has two variants: +Fetch the full conversation history using `fetchPrevious()`. Call it repeatedly on the same request object to paginate — useful for implementing upward scrolling. - - ```javascript - CometChat.getUnreadMessageCount(); - ``` - - - ```typescript - CometChat.getUnreadMessageCount(); - ``` - + +```typescript +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[]) => { + console.log("Message list fetched:", messages); + }, + (error: CometChat.CometChatException) => { + console.log("Message fetching failed with error:", error); + } +); +``` + + + +```typescript +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[]) => { + console.log("Message list fetched:", messages); + }, + (error: CometChat.CometChatException) => { + console.log("Message fetching failed with error:", error); + } +); +``` + -If you wish to ignore the messages from blocked users you can use the below syntax setting the boolean parameter to true: +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). - - - ```javascript - CometChat.getUnreadMessageCount(hideMessagesFromBlockedUsers); - ``` - - - ```typescript - let hideMessagesFromBlockedUsers: boolean = true; - CometChat.getUnreadMessageCount(hideMessagesFromBlockedUsers); - ``` - - +## Search Messages + +Add `setSearchKeyword()` to the builder to filter messages by keyword. - - ```javascript - CometChat.getUnreadMessageCount().then( - (unreadMessageCountObject) => { - console.log("Unread message count fetched", unreadMessageCountObject); - }, - (error) => { - console.log("Error in getting unread message count", 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); - } - ); - ``` - + +```typescript +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[]) => { + console.log("Message list fetched:", messages); + }, + (error: CometChat.CometChatException) => { + console.log("Message fetching failed with error:", error); + } +); +``` + + + +```typescript +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[]) => { + console.log("Message list fetched:", messages); + }, + (error: CometChat.CometChatException) => { + console.log("Message fetching failed with error:", error); + } +); +``` + -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. - - - -**On Success** — Returns an object with users and groups unread counts: - - - -**Unread Count Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `users` | object | Object with UIDs as keys and unread counts as values | [See below ↓](#unread-count-all-users-object) | -| `groups` | object | Object with GUIDs as keys and unread counts as values | [See below ↓](#unread-count-all-groups-object) | - ---- - - - -**`users` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `{UID}` | number | Unread count for each user | `2` | - -Example: `{"cometchat-uid-3": 2}` - ---- - - +### Search Capabilities -**`groups` Object:** +By default, search only matches message text. With `Conversation & Advanced Search` enabled, it also matches file names, mentions, and MIME types. -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `{GUID}` | number | Unread count for each group | `2` | - -Example: `{"group_1748415903905": 2}` - ---- +| Feature | Basic Search | Advanced Search | +| ---------------- | ------------ | --------------- | +| Text search | ✅ | ✅ | +| File name search | ❌ | ✅ | +| Mentions search | ❌ | ✅ | +| MIME type search | ❌ | ✅ | - + +`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. + -**On Failure — Error Object:** +## Unread Message Count -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `code` | string | Error code | `"ERR_NOT_LOGGED_IN"` | -| `name` | string | Error name | `"Not logged in"` | -| `message` | string | Error message | `"No user is currently logged in."` | -| `details` | object | Additional error details | `{}` | +CometChat provides several methods to get unread counts at different scopes. All return a `Promise` that resolves with an object mapping IDs to counts. - +Each method accepts an optional boolean parameter to exclude messages from blocked users. -### For All One-on-one Conversations +| 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: { ... } }` | -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: +### Single Conversation - - ```javascript - CometChat.getUnreadMessageCountForAllUsers(); - ``` - - - ```typescript - CometChat.getUnreadMessageCountForAllUsers(); - ``` - + +```typescript +// One-on-one +let UID: string = "UID"; +CometChat.getUnreadMessageCountForUser(UID).then( + (count: Object) => console.log("Unread count:", count), + (error: CometChat.CometChatException) => console.log("Error:", error) +); + +// Group +let GUID: string = "GUID"; +CometChat.getUnreadMessageCountForGroup(GUID).then( + (count: Object) => console.log("Unread count:", count), + (error: CometChat.CometChatException) => console.log("Error:", error) +); +``` + + +```javascript +// One-on-one +let UID = "UID"; +CometChat.getUnreadMessageCountForUser(UID).then( + (count) => console.log("Unread count:", count), + (error) => console.log("Error:", error) +); + +// 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: - - - - ```javascript - CometChat.getUnreadMessageCountForAllUsers(hideMessagesFromBlockedUsers); - ``` - - - ```typescript - let hideMessagesFromBlockedUsers: boolean = true; - CometChat.getUnreadMessageCountForAllUsers(hideMessagesFromBlockedUsers); - ``` - - +### All Conversations - - ```javascript - CometChat.getUnreadMessageCountForAllUsers().then( - (unreadMessageCountObject) => { - console.log("Unread message count fetched", unreadMessageCountObject); - }, - (error) => { - console.log("Error in getting unread message count", error); - } - ); - ``` - - - ```typescript - CometChat.getUnreadMessageCountForAllUsers().then( - (unreadMessageCount: Object) => { - console.log("Unread message count fetched", unreadMessageCount); - }, - (error: CometChat.CometChatException) => { - console.log("Error in getting unread message count", error); - } - ); - ``` - + +```typescript +// All users and groups combined +CometChat.getUnreadMessageCount().then( + (count: Object) => console.log("Unread count:", count), + (error: CometChat.CometChatException) => console.log("Error:", error) +); + +// All user conversations only +CometChat.getUnreadMessageCountForAllUsers().then( + (count: Object) => console.log("Unread count:", count), + (error: CometChat.CometChatException) => 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) +); +``` + + +```javascript +// All users and groups combined +CometChat.getUnreadMessageCount().then( + (count) => console.log("Unread count:", count), + (error) => console.log("Error:", error) +); + +// All user conversations only +CometChat.getUnreadMessageCountForAllUsers().then( + (count) => console.log("Unread count:", count), + (error) => console.log("Error:", error) +); + +// All group conversations only +CometChat.getUnreadMessageCountForAllGroups().then( + (count) => console.log("Unread count:", count), + (error) => console.log("Error:", error) +); +``` + -It returns an object which will contain the UID as the key and the unread message count as the value. - - - -**On Success** — Returns an object with UIDs as keys and unread counts as values: - - +### Excluding Blocked Users -**Unread Count Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `{UID}` | number | Unread message count for each user | `2` or `3` | - -Example: `{"cometchat-uid-3": 2, "cometchat-uid-4": 3}` - ---- - - - -**On Failure — Error Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `code` | string | Error code | `"ERR_NOT_LOGGED_IN"` | -| `name` | string | Error name | `"Not logged in"` | -| `message` | string | Error message | `"No user is currently logged in."` | -| `details` | object | Additional error details | `{}` | - - - -### For 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: +Pass `true` as the last argument to any of the methods above: - - ```javascript - CometChat.getUnreadMessageCountForAllGroups(); - ``` - - - ```typescript - CometChat.getUnreadMessageCountForAllGroups(); - ``` - + +```typescript +CometChat.getUnreadMessageCountForUser(UID, true); +CometChat.getUnreadMessageCountForGroup(GUID, true); +CometChat.getUnreadMessageCount(true); +CometChat.getUnreadMessageCountForAllUsers(true); +CometChat.getUnreadMessageCountForAllGroups(true); +``` + + +```javascript +CometChat.getUnreadMessageCountForUser(UID, true); +CometChat.getUnreadMessageCountForGroup(GUID, true); +CometChat.getUnreadMessageCount(true); +CometChat.getUnreadMessageCountForAllUsers(true); +CometChat.getUnreadMessageCountForAllGroups(true); +``` + -If you wish to ignore the messages from blocked users you can use the below syntax setting the boolean parameter to true: +## Get Message Details - - - ```javascript - CometChat.getUnreadMessageCountForAllGroups(hideMessagesFromBlockedUsers); - ``` - - - ```typescript - let hideMessagesFromBlockedUsers: boolean = true; - CometChat.getUnreadMessageCountForAllGroups(hideMessagesFromBlockedUsers); - ``` - - +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), or [`CustomMessage`](/sdk/reference/messages#custommessage)). - - ```javascript - CometChat.getUnreadMessageCountForAllGroups().then( - (unreadMessageCountObject) => { - console.log("Unread message count fetched", unreadMessageCountObject); - }, - (error) => { - console.log("Error in getting unread message count", error); - } - ); - ``` - - - ```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); - } - ); - ``` - + +```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); + } +); +``` + -It returns an object which will contain the GUID as the key and the unread message count as the value. - - - -**On Success** — Returns an object with GUIDs as keys and unread counts as values: - - - -**Unread Count Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `{GUID}` | number | Unread message count for each group | `2` or `5` | +| Parameter | Type | Description | +|-----------|------|-------------| +| `messageId` | `string` | The ID of the message to fetch | -Example: `{"group_1748415903905": 2, "group_1762515421478": 2, "group_1762515423434": 5}` +Returns a [`BaseMessage`](/sdk/reference/messages#basemessage) object (which may be a [`TextMessage`](/sdk/reference/messages#textmessage), [`MediaMessage`](/sdk/reference/messages#mediamessage), or [`CustomMessage`](/sdk/reference/messages#custommessage)). --- - - -**On Failure — Error Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `code` | string | Error code | `"ERR_NOT_LOGGED_IN"` | -| `name` | string | Error name | `"Not logged in"` | -| `message` | string | Error message | `"No user is currently logged in."` | -| `details` | object | Additional error details | `{}` | - - - - - - - Always remove message listeners when a component unmounts to prevent memory leaks - - Use unique, descriptive listener IDs (e.g., `"chat-screen-listener"`) to avoid conflicts - - Use `getLastDeliveredMessageId()` to efficiently fetch only missed messages - - Implement pagination with `fetchPrevious()` for message history to avoid loading too many messages at once - - Use `setUnread(true)` to fetch only unread messages when building notification badges - - - - **Not receiving messages:** Ensure the message listener is registered and the user is logged in - - **Duplicate messages:** Check that you're not adding the same listener ID multiple times - - **Missing messages after reconnect:** Use the missed messages pattern with `getLastDeliveredMessageId()` to catch up - - **Unread count not updating:** Ensure you're calling the unread count methods after marking messages as read - - - ## Next Steps - - Send text, media, and custom messages to users and groups - - Track when messages are delivered and read + Track when messages are delivered and read by recipients Show real-time typing status in conversations - - Understand message categories, types, and hierarchy - diff --git a/sdk/react-native/recording.mdx b/sdk/react-native/recording.mdx index f5a7bcc87..f1a6f5372 100644 --- a/sdk/react-native/recording.mdx +++ b/sdk/react-native/recording.mdx @@ -1,10 +1,10 @@ --- title: "Recording (Beta)" -description: "Add call recording to your React Native app with start/stop controls, recording listeners, and automatic recording on call start." +sidebarTitle: "Recording" +description: "Implement call recording for voice and video calls using the CometChat React Native SDK, including start/stop controls, listeners, and accessing recordings from the Dashboard." --- - -**Quick Reference** - Start and stop call recording: + ```javascript // Start recording @@ -13,196 +13,138 @@ CometChatCalls.startRecording(); // Stop recording CometChatCalls.stopRecording(); -// Or enable auto-recording via CallSettings -new CometChatCalls.CallSettingsBuilder() - .startRecordingOnCallStart(true) - .showRecordingButton(true) - .build(); +// Listen for recording events (in CallSettings) +const callListener = new CometChatCalls.OngoingCallListener({ + onRecordingStarted: (event) => console.log("Recording started", event), + onRecordingStopped: (event) => console.log("Recording stopped", event), +}); ``` - - - -**Available via:** SDK | UI Kits - -## Overview - -This section guides you through implementing call recording for voice and video calls. +**Recordings are available on the [CometChat Dashboard](https://app.cometchat.com) → Calls section.** + -Once you have decided to implement [Ringing](/sdk/react-native/default-call) or [Call Session](/sdk/react-native/direct-call) and followed the steps to implement them, a few additional listeners and methods will help you quickly implement call recording in your app. +Record voice and video calls for playback, compliance, or archival purposes. Recording is built on top of the [Call Session](/sdk/react-native/direct-call) — you add recording listeners to your call settings and optionally control recording programmatically. -You need to make changes in the `CometChatCalls.OngoingCallListener` constructor and add the required listeners for recording. Please make sure your callSettings is configured accordingly for [Ringing](/sdk/react-native/default-call) or [Call Session](/sdk/react-native/direct-call). +## Setup -A basic example of how to make changes to implement recording: +Add `onRecordingStarted` and `onRecordingStopped` callbacks to your `OngoingCallListener` when building call settings. These fire for all participants when any user starts or stops recording. - -```javascript -// Add listeners onRecordingStarted and onRecordingStopped to the startSession method + +```typescript +// Add listeners onRecordingStarted and onRecordingStopped to the startCall method const audioOnly = false; -const deafaultLayout = true; +const defaultLayout = true; const callListener = new CometChatCalls.OngoingCallListener({ - onRecordingStarted: recordingStartedBy => { - // This event will work in JS SDK v3.0.8 & later. - console.log("Listener => onRecordingStarted:", recordingStartedBy); - }, - onRecordingStopped: recordingStoppedBy => { - // This event will work in JS SDK v3.0.8 & later. - console.log("Listener => onRecordingStopped:", recordingStoppedBy); - }, + onRecordingStarted: (recordingStartedBy) => + console.log("Listener => onRecordingStarted:", recordingStartedBy), + onRecordingStopped: (recordingStoppedBy) => + console.log("Listener => onRecordingStopped:", recordingStoppedBy), }); const callSettings = new CometChatCalls.CallSettingsBuilder() - .enableDefaultLayout(deafaultLayout) + .enableDefaultLayout(defaultLayout) .setIsAudioOnlyCall(audioOnly) .setCallEventListener(callListener) .build(); -render(){ - return( - - - - ); -} +// In your render method +return ( + + + +); ``` - - -```typescript + +```javascript // Add listeners onRecordingStarted and onRecordingStopped to the startCall method const audioOnly = false; -const deafaultLayout = true; +const defaultLayout = true; const callListener = new CometChatCalls.OngoingCallListener({ - onRecordingStarted: recordingStartedBy => { - // This event will work in JS SDK v3.0.8 & later. - console.log("Listener => onRecordingStarted:", recordingStartedBy); - }, - onRecordingStopped: recordingStoppedBy => { - // This event will work in JS SDK v3.0.8 & later. - console.log("Listener => onRecordingStopped:", recordingStoppedBy); - }, + onRecordingStarted: (recordingStartedBy) => + console.log("Listener => onRecordingStarted:", recordingStartedBy), + onRecordingStopped: (recordingStoppedBy) => + console.log("Listener => onRecordingStopped:", recordingStoppedBy), }); const callSettings = new CometChatCalls.CallSettingsBuilder() - .enableDefaultLayout(deafaultLayout) + .enableDefaultLayout(defaultLayout) .setIsAudioOnlyCall(audioOnly) .setCallEventListener(callListener) .build(); -render(){ - return( - - - - ); -} +// In your render method +return ( + + + +); ``` - - - -**On Event** — `onRecordingStarted` returns information about the user who started the recording: - - - -**RecordingStartedBy Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user who started recording | `"cometchat-uid-7"` | -| `name` | string | Display name of the user | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `recordId` | string | Unique identifier for this recording session | `"noujausedimwfhwl"` | -| `id` | string | Internal session participant ID | `"042d0440"` | -| `isLocalUser` | string | Whether this is the local user (as string) | `"true"` | -| `isVideoMuted` | string | Whether user's video is muted (as string) | `"true"` | -| `isAudioMuted` | string | Whether user's audio is muted (as string) | `"false"` | +The `onRecordingStarted` callback receives an event object with the user who started recording — see the [`OngoingCallListener`](/sdk/react-native/all-real-time-listeners#ongoing-call-listener-calls-sdk) reference for the full shape. - - - -**On Event** — `onRecordingStopped` returns information about the user who stopped the recording: - - - -**RecordingStoppedBy Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user who stopped recording | `"cometchat-uid-7"` | -| `name` | string | Display name of the user | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `id` | string | Internal session participant ID | `"042d0440"` | -| `isLocalUser` | string | Whether this is the local user (as string) | `"true"` | -| `isVideoMuted` | string | Whether user's video is muted (as string) | `"true"` | -| `isAudioMuted` | string | Whether user's audio is muted (as string) | `"false"` | - - +The `onRecordingStopped` callback receives an event object with the user who stopped recording. -## Settings for Call Recording + +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 `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 an object of the `CallSettings` class which you can pass to the `CometChatCalls.Component` to start the call. +## CallSettings Options -The options available for recording of calls are: - -| 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 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: +## 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 -You can use the `startRecording()` method to start call recording. +You can use the startRecording() method to start call recording. - -```javascript + +```typescript CometChatCalls.startRecording(); ``` - - -```typescript + +```javascript CometChatCalls.startRecording(); ``` - - ### Stop Recording -You can use the `stopRecording()` method to stop call recording. +You can use the stopRecording() method to stop call recording. - -```javascript + +```typescript CometChatCalls.stopRecording(); ``` - - -```typescript + +```javascript CometChatCalls.stopRecording(); ``` - - -## Downloading Recording +## Downloading Recordings -Currently, the call recordings are available on the [CometChat Dashboard](https://app.cometchat.com) under the Calls Section. 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". @@ -216,49 +158,15 @@ Currently, the call recordings are available on the [CometChat Dashboard](https: -## Best Practices - - - - The ongoing call component automatically displays a recording badge when recording starts — you don't need to build or control this UI. Use the `onRecordingStarted` and `onRecordingStopped` listeners if you need to track recording state in your app logic (e.g., logging or analytics). - - - If your app requires all calls to be recorded (e.g., for compliance or audit purposes), enable `startRecordingOnCallStart(true)` in your `CallSettingsBuilder` to ensure no calls are missed. - - - If you're using a custom layout (`enableDefaultLayout(false)`), track the recording state using `onRecordingStarted` and `onRecordingStopped` listeners to toggle your custom recording button's appearance. - - - -## Troubleshooting - - - - Ensure `showRecordingButton(true)` is set in your `CallSettingsBuilder`. The recording button is hidden by default (`false`). Also verify that `enableDefaultLayout(true)` is set, as the button is part of the default layout. - - - These listeners require JS SDK v3.0.8 or later. Verify your SDK version. Also ensure the listeners are registered in the `OngoingCallListener` before the call session starts. - - - Recordings may take a few minutes to process after the call ends. Check the Calls section in the [CometChat Dashboard](https://app.cometchat.com). If still missing, verify that recording was actually started (check `onRecordingStarted` callback). - - - --- ## Next Steps - - Start and manage call sessions with full configuration options - - - Implement a complete calling experience with incoming and outgoing call UI - - - Customize the main video container and participant tiles + + Implement ringing call flows with accept/reject functionality - Retrieve and display call history including duration and participants + Retrieve and display call history for users and groups - \ No newline at end of file + diff --git a/sdk/react-native/retrieve-conversations.mdx b/sdk/react-native/retrieve-conversations.mdx index 98676cea5..b0d2e2f30 100644 --- a/sdk/react-native/retrieve-conversations.mdx +++ b/sdk/react-native/retrieve-conversations.mdx @@ -1,80 +1,83 @@ --- title: "Retrieve Conversations" -description: "Fetch recent one-on-one and group conversations for the logged-in user using the ConversationsRequestBuilder, with support for filtering, tagging, and pagination." +sidebarTitle: "Retrieve Conversations" +description: "Fetch, filter, tag, and search conversations using the CometChat React Native SDK." --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + ```javascript -// Build a conversations request -let conversationsRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(30) - .build(); +// Fetch conversations list +const request = new CometChat.ConversationsRequestBuilder() + .setLimit(30).build(); +const conversations = await request.fetchNext(); -// Fetch conversations (paginated) -conversationsRequest.fetchNext().then( - conversationList => console.log("Conversations:", conversationList), - error => console.log("Error:", error) -); +// Get a specific conversation +const conversation = await CometChat.getConversation("UID", "user"); -// Retrieve a single conversation -CometChat.getConversation("UID_OR_GUID", "user_or_group").then( - conversation => console.log("Conversation:", conversation), - error => console.log("Error:", error) -); -``` - +// Tag a conversation +await CometChat.tagConversation("UID", "user", ["archived"]); -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. +// Convert message to conversation +let message = {}; // obtained from MessageListener or fetchPrevious/fetchNext +const conv = await CometChat.CometChatHelper.getConversationFromMessage(message); +``` + - -**Available via:** [SDK](/sdk/react-native/retrieve-conversations) | [REST API](/rest-api/conversations/list-conversations) | [UI Kits](/ui-kit/react-native/core-features#conversation-and-advanced-search) - +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 -*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: +Fetching using this builder will return [`Conversation`](/sdk/reference/entities#conversation) objects. + +The `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. + +```typescript +let limit: number = 30, + conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .build(); +``` + + + ```javascript let limit = 30; let conversationRequest = new CometChat.ConversationsRequestBuilder() .setLimit(limit) - .build(); + .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, + conversationType: string = "group", conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() .setLimit(limit) + .setConversationType(conversationType) .build(); ``` - - -### 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. - - ```javascript let limit = 30; @@ -86,3856 +89,602 @@ let conversationRequest = new CometChat.ConversationsRequestBuilder() ``` + + + +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`](/sdk/reference/entities#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 + +Use `withUserAndGroupTags(true)` to include user/group tags in the response. Default is `false`. + + ```typescript let limit: number = 30, - conversationType: string = "group", conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() .setLimit(limit) - .setConversationType(conversationType) + .withUserAndGroupTags(true) .build(); ``` - - - -**On Success** — `fetchNext()` returns an array of `Conversation` objects (group conversations only): - + +```javascript +let limit = 30; +let conversationRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .withUserAndGroupTags(true) + .build(); +``` + -**Conversation Object (per item in array):** + -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `conversationId` | string | Unique conversation identifier | `"group_group_1748415903905"` | -| `conversationType` | string | Type of conversation | `"group"` | -| `unreadMentionsCount` | number | Count of unread mentions | `0` | -| `lastReadMessageId` | string | ID of last read message | `"25243"` | -| `unreadMessageCount` | number | Count of unread messages | `0` | -| `latestMessageId` | string | ID of latest message | `"25243"` | -| `lastMessage` | object | Last message in conversation | [See below ↓](#conv-type-lastmessage-object) | -| `conversationWith` | object | Group details | [See below ↓](#conv-type-conversationwith-group-object) | +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: - - -**`lastMessage` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25243"` | -| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | -| `receiverId` | string | Group's GUID | `"group_1748415903905"` | -| `receiverType` | string | Type of receiver | `"group"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Susan here "` | -| `sentAt` | number | Unix timestamp when sent | `1771413931` | -| `updatedAt` | number | Unix timestamp when updated | `1771413931` | -| `sender` | object | Sender user details | [See below ↓](#conv-type-sender-object) | -| `receiver` | object | Receiver group details | [See below ↓](#conv-type-receiver-group-object) | -| `data` | object | Additional message data | [See below ↓](#conv-type-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#conv-type-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| conversationWith tags | `getConversationWith().getTags()` | `string[]` | Tags associated with the user or group in the conversation | ---- +### Set User Tags - +Fetch user conversations where the user has specific tags. -**`lastMessage.sender` Object:** + + +```typescript +let limit: number = 30, + userTags: Array = ["tag1"], + conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setUserTags(userTags) + .build(); +``` + -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-4"` | -| `name` | string | User's display name | `"Susan Marie"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-4.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"admin"` | -| `lastActiveAt` | number | Last active timestamp | `1771413925` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | + +```javascript +let limit = 30; +let userTags = ["tag1"]; +let conversationRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setUserTags(userTags) + .build(); +``` + ---- + - - -**`lastMessage.receiver` Object (Group):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `guid` | string | Group's unique identifier | `"group_1748415903905"` | -| `name` | string | Group's display name | `"3 People Group"` | -| `type` | string | Group type | `"public"` | -| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | -| `owner` | string | Group owner's UID | `"123456"` | -| `scope` | string | Current user's scope in group | `"admin"` | -| `membersCount` | number | Total members in group | `12` | -| `onlineMembersCount` | number | Online members count | `3` | -| `hasJoined` | boolean | Whether current user has joined | `true` | -| `isBanned` | boolean | Whether current user is banned | `false` | -| `joinedAt` | number | Timestamp when user joined | `1748415973` | -| `createdAt` | number | Group creation timestamp | `1748415957` | -| `updatedAt` | number | Group update timestamp | `1771245340` | +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 | -**`lastMessage.data` Object:** +### Set Group Tags -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Susan here "` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_12-..."` | -| `entities` | object | Sender and receiver entities | [See below ↓](#conv-type-data-entities-object) | -| `metadata` | object | Injected metadata | [See below ↓](#conv-type-data-metadata-object) | +Fetch group conversations where the group has specific tags. ---- + + +```typescript +let limit: number = 30, + groupTags: Array = ["tag1"], + conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setGroupTags(groupTags) + .build(); +``` + - + +```javascript +let limit = 30; +let groupTags = ["tag1"]; +let conversationRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setGroupTags(groupTags) + .build(); +``` + -**`lastMessage.data.entities` Object:** + -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#conv-type-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#conv-type-data-entities-receiver-object) | +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 | -**`lastMessage.data.entities.sender` Object:** +### With Tags -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#conv-type-data-entities-sender-entity-object) | +Use `withTags(true)` to include conversation tags in the response. Default is `false`. ---- + + +```typescript +let limit: number = 30, +conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .withTags(true) + .build(); +``` + - + +```javascript +let limit = 30; +let conversationRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .withTags(true) + .build(); +``` + -**`lastMessage.data.entities.sender.entity` Object:** + -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-4"` | -| `name` | string | User's display name | `"Susan Marie"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-4.webp"` | -| `role` | string | User's role | `"admin"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771413925` | -| `tags` | array | User tags | `[]` | +Relevant fields to access on returned conversations: ---- +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| tags | `getTags()` | `string[]` | Tags associated with the conversation | - +### Set Tags -**`lastMessage.data.entities.receiver` Object:** +Fetch conversations that have specific tags. -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"group"` | -| `entity` | object | Group entity details | [See below ↓](#conv-type-data-entities-receiver-entity-object) | + + +```typescript +let limit: number = 30, + tags: Array = ["archivedChat"], + conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setTags(tags) + .build(); +``` + ---- + +```javascript +let limit = 30; +let tags = ["archivedChat"]; +let conversationRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setTags(tags) + .build(); +``` + - - -**`lastMessage.data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `guid` | string | Group's unique identifier | `"group_1748415903905"` | -| `name` | string | Group's display name | `"3 People Group"` | -| `type` | string | Group type | `"public"` | -| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | -| `owner` | string | Group owner's UID | `"123456"` | -| `scope` | string | Current user's scope in group | `"admin"` | -| `membersCount` | number | Total members in group | `12` | -| `onlineMembersCount` | number | Online members count | `3` | -| `hasJoined` | boolean | Whether current user has joined | `true` | -| `joinedAt` | number | Timestamp when user joined | `1748415973` | -| `createdAt` | number | Group creation timestamp | `1748415957` | -| `updatedAt` | number | Group update timestamp | `1771245340` | + ---- +Relevant fields to access on returned conversations: - +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| tags | `getTags()` | `string[]` | Tags associated with the conversation | -**`lastMessage.data.metadata` Object:** +### Include Blocked Users -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#conv-type-data-metadata-injected-object) | +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(); +``` - + -**`lastMessage.data.metadata.@injected` Object:** + +```javascript +let limit = 30; +let conversationRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setIncludeBlockedUsers(true) + .build(); +``` -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#conv-type-data-metadata-extensions-object) | + ---- + - +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`. -**`lastMessage.data.metadata.@injected.extensions` Object:** +### With Blocked Info -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#conv-type-data-metadata-linkpreview-object) | +Use `setWithBlockedInfo(true)` to include blocked user information in the response. ---- + + +```typescript +let limit: number = 30, + conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setWithBlockedInfo(true) + .build(); +``` - + -**`lastMessage.data.metadata.@injected.extensions.link-preview` Object:** + +```javascript +let limit = 30; +let conversationRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setWithBlockedInfo(true) + .build(); +``` -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | + ---- + - +Relevant fields to access on returned conversations: -**`lastMessage.metadata` Object:** +| 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 | -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#conv-type-metadata-injected-object) | +### Search Conversations ---- +Use `setSearchKeyword()` to search conversations by user or group name. - + -**`lastMessage.metadata.@injected` Object:** +This feature is only available with `Conversation & Advanced Search`. 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) -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#conv-type-metadata-extensions-object) | + ---- + + +```typescript +let limit: number = 30, + conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setSearchKeyword("Hiking") + .build(); +``` - + -**`lastMessage.metadata.@injected.extensions` Object:** + +```javascript +let limit = 30; +let conversationRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setSearchKeyword("Hiking") + .build(); +``` -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#conv-type-metadata-linkpreview-object) | + ---- + - +When conversations are fetched successfully, the response includes conversations where the user or group name matches the search keyword. -**`lastMessage.metadata.@injected.extensions.link-preview` Object:** +### Unread Conversations -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | +Use `setUnread(true)` to fetch only conversations with unread messages. ---- + - - -**`conversationWith` Object (Group):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `guid` | string | Group's unique identifier | `"group_1748415903905"` | -| `name` | string | Group's display name | `"3 People Group"` | -| `type` | string | Group type | `"public"` | -| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | -| `owner` | string | Group owner's UID | `"123456"` | -| `scope` | string | Current user's scope in group | `"admin"` | -| `membersCount` | number | Total members in group | `12` | -| `onlineMembersCount` | number | Online members count | `1` | -| `hasJoined` | boolean | Whether current user has joined | `true` | -| `isBanned` | boolean | Whether current user is banned | `false` | -| `joinedAt` | number | Timestamp when user joined | `1748437105` | -| `createdAt` | number | Group creation timestamp | `1748415957` | -| `updatedAt` | number | Group update timestamp | `1771245340` | +This feature is only available with `Conversation & Advanced Search`. 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) - + -### With User and Group Tags + + +```typescript +let limit: number = 30, + conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setUnread(true) + .build(); +``` -This method can be used to fetch the user/group tags in the `Conversation` Object. By default the value is false. + - ```javascript let limit = 30; let conversationRequest = new CometChat.ConversationsRequestBuilder() .setLimit(limit) - .withUserAndGroupTags(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, conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() .setLimit(limit) - .withUserAndGroupTags(true) + .setHideAgentic(true) .build(); ``` - - - - -`withUserAndGroupTags(true)` adds the `tags` array to the `conversationWith` object (user/group tags). The tags you see inside `lastMessage.data.entities` and `sender`/`receiver` are part of the message payload, not the conversation's `conversationWith` object. - - - -**On Success** — `fetchNext()` returns an array of `Conversation` objects with user/group tags: - - - -**Conversation Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `conversationType` | string | Type of conversation | `"user"` | -| `unreadMentionsCount` | number | Count of unread mentions | `0` | -| `lastReadMessageId` | string | ID of last read message | `"25276"` | -| `unreadMessageCount` | number | Count of unread messages | `0` | -| `latestMessageId` | string | ID of latest message | `"25276"` | -| `lastMessage` | object | Last message in conversation | [See below ↓](#conv-usrgrptags-lastmessage-object) | -| `conversationWith` | object | User details with tags | [See below ↓](#conv-usrgrptags-conversationwith-object) | - ---- - - - -**`lastMessage` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25276"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Message for mentioned users, Hello <@uid:cometchat-uid-2>"` | -| `sentAt` | number | Unix timestamp when sent | `1771495242` | -| `deliveredAt` | number | Unix timestamp when delivered | `1771495244` | -| `readAt` | number | Unix timestamp when read | `1771495244` | -| `updatedAt` | number | Unix timestamp when updated | `1771495244` | -| `sender` | object | Sender user details | [See below ↓](#conv-usrgrptags-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#conv-usrgrptags-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#conv-usrgrptags-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#conv-usrgrptags-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | [See below ↓](#conv-usrgrptags-mentionedusers-array) | -| `mentionedMe` | boolean | Whether current user is mentioned | `true` | - ---- - - - -**`lastMessage.mentionedUsers` Array (per item):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771738926` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`lastMessage.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771495034` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `["userTag2"]` | - ---- - - - -**`lastMessage.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771494233` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `["userTag1"]` | - ---- - - - -**`lastMessage.data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Message for mentioned users, Hello <@uid:cometchat-uid-2>"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `mentions` | object | Map of mentioned users by UID | [See below ↓](#conv-usrgrptags-data-mentions-object) | -| `entities` | object | Sender and receiver entities | [See below ↓](#conv-usrgrptags-data-entities-object) | -| `metadata` | object | Injected metadata | [See below ↓](#conv-usrgrptags-data-metadata-object) | - ---- - - - -**`lastMessage.data.mentions` Object (keyed by UID):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771494233` | - ---- - - - -**`lastMessage.data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#conv-usrgrptags-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#conv-usrgrptags-data-entities-receiver-object) | - ---- - - - -**`lastMessage.data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#conv-usrgrptags-data-entities-sender-entity-object) | - ---- - - - -**`lastMessage.data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771495034` | -| `tags` | array | User tags | `["userTag2"]` | - ---- - - -**`lastMessage.data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#conv-usrgrptags-data-entities-receiver-entity-object) | - ---- - - - -**`lastMessage.data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771494233` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `tags` | array | User tags | `["userTag1"]` | - ---- - - - -**`lastMessage.data.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#conv-usrgrptags-data-metadata-injected-object) | - ---- - - - -**`lastMessage.data.metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#conv-usrgrptags-data-metadata-extensions-object) | - ---- - - - -**`lastMessage.data.metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#conv-usrgrptags-data-metadata-linkpreview-object) | - ---- - - - -**`lastMessage.data.metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - - - -**`lastMessage.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#conv-usrgrptags-metadata-injected-object) | - ---- - - - -**`lastMessage.metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#conv-usrgrptags-metadata-extensions-object) | - ---- - - - -**`lastMessage.metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#conv-usrgrptags-metadata-linkpreview-object) | - ---- - - - -**`lastMessage.metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - - - -**`conversationWith` Object (User with tags):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771818451` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags (added by withUserAndGroupTags) | `["userTag2"]` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | - - - -### Set User Tags - -This method fetches user conversations that have the specified tags. + - ```javascript let limit = 30; -let userTags = ["tag1"]; let conversationRequest = new CometChat.ConversationsRequestBuilder() .setLimit(limit) - .setUserTags(userTags) + .setHideAgentic(true) .build(); ``` + + + +### Only Agentic Conversations + +Use `setOnlyAgentic(true)` to fetch only AI agent conversations. + + ```typescript let limit: number = 30, - userTags: Array = ["tag1"], conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() .setLimit(limit) - .setUserTags(userTags) + .setOnlyAgentic(true) .build(); ``` - - - -**On Success** — `fetchNext()` returns an array of `Conversation` objects filtered by user tags: - - - -**Conversation Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-2_user_cometchat-uid-5"` | -| `conversationType` | string | Type of conversation | `"user"` | -| `unreadMentionsCount` | number | Count of unread mentions | `0` | -| `lastReadMessageId` | string | ID of last read message | `"24957"` | -| `unreadMessageCount` | number | Count of unread messages | `0` | -| `latestMessageId` | string | ID of latest message | `"24957"` | -| `lastMessage` | object | Last message in conversation | [See below ↓](#conv-usertags-lastmessage-object) | -| `conversationWith` | object | User details | [See below ↓](#conv-usertags-conversationwith-object) | - ---- - - - -**`lastMessage` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"24955"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-5"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Not yet, I will update you if any."` | -| `sentAt` | number | Unix timestamp when sent | `1770973162` | -| `editedAt` | number | Unix timestamp when edited | `1770973219` | -| `editedBy` | string | UID of user who edited | `"cometchat-uid-5"` | -| `updatedAt` | number | Unix timestamp when updated | `1770973219` | -| `sender` | object | Sender user details | [See below ↓](#conv-usertags-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#conv-usertags-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#conv-usertags-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#conv-usertags-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - -**`lastMessage.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-5"` | -| `name` | string | User's display name | `"John Paul"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-5.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"admin"` | -| `lastActiveAt` | number | Last active timestamp | `1770973064` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `["tag1"]` | - ---- - - - -**`lastMessage.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1770973150` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `["tag1"]` | - ---- - - + +```javascript +let limit = 30; +let conversationRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setOnlyAgentic(true) + .build(); +``` + -**`lastMessage.data` Object:** + -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Not yet, I will update you if any."` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `entities` | object | Sender and receiver entities | [See below ↓](#conv-usertags-data-entities-object) | -| `metadata` | object | Injected metadata | [See below ↓](#conv-usertags-data-metadata-object) | + ---- +The `setHideAgentic()` and `setOnlyAgentic()` methods are mutually exclusive. You should only use one of them in a single request builder instance. - + -**`lastMessage.data.entities` Object:** +When conversations are fetched successfully, the response will include only conversations with AI agents. Agent users have `role: "@agentic"` and include agent-specific metadata. -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#conv-usertags-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#conv-usertags-data-entities-receiver-object) | +### Fetch Conversations ---- +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. - + + +```typescript +let limit: number = 30, + conversationsRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .build(); -**`lastMessage.data.entities.sender` Object:** +conversationsRequest.fetchNext().then( + (conversationList: CometChat.Conversation[]) => { + console.log("Conversations list received:", conversationList); + }, + (error: CometChat.CometChatException) => { + console.log("Conversations list fetching failed with error:", error); + } +); +``` -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#conv-usertags-data-entities-sender-entity-object) | + ---- + +```javascript +let limit = 30; +let conversationsRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .build(); - +conversationsRequest.fetchNext().then( + (conversationList) => { + console.log("Conversations list received:", conversationList); + }, + (error) => { + console.log("Conversations list fetching failed with error:", error); + } +); +``` -**`lastMessage.data.entities.sender.entity` Object:** + -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-5"` | -| `name` | string | User's display name | `"John Paul"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-5.webp"` | -| `role` | string | User's role | `"admin"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1770973064` | -| `tags` | array | User tags | `["tag1"]` | + ---- +The `fetchNext()` method returns an array of [`Conversation`](/sdk/reference/entities#conversation) objects. - +## Tag Conversation -**`lastMessage.data.entities.receiver` Object:** +Use `tagConversation()` to add tags to a conversation. -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#conv-usertags-data-entities-receiver-entity-object) | +| Parameter | Description | +| --- | --- | +| `conversationWith` | UID or GUID of the user/group | +| `conversationType` | `user` or `group` | +| `tags` | Array of tags to add | ---- + + +```typescript +let conversationWith: string = "UID", + tags: Array = ["archivedChat"], + conversationType: string = "user"; + +CometChat.tagConversation(conversationWith, conversationType, tags).then( + (conversation: CometChat.Conversation) => { + console.log("conversation", conversation); + }, + (error: CometChat.CometChatException) => { + console.log("error while fetching a conversation", error); + } +); +``` + - + +```javascript +let conversationWith = "UID"; +let tags = ["archivedChat"]; +let conversationType = "user"; + +CometChat.tagConversation(conversationWith, conversationType, tags).then( + (conversation) => { + console.log("conversation", conversation); + }, + (error) => { + console.log("error while fetching a conversation", error); + } +); +``` + -**`lastMessage.data.entities.receiver.entity` Object:** + -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"offline"` | -| `lastActiveAt` | number | Last active timestamp | `1770973150` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-5"` | -| `tags` | array | User tags | `["tag1"]` | + ---- +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. - + -**`lastMessage.data.metadata` Object:** +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. -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#conv-usertags-data-metadata-injected-object) | +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 | -**`lastMessage.data.metadata.@injected` Object:** +## Retrieve Single Conversation -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#conv-usertags-data-metadata-extensions-object) | +Use `getConversation()` to fetch a specific conversation. ---- +| Parameter | Description | +| --- | --- | +| `conversationWith` | UID or GUID of the user/group | +| `conversationType` | `user` or `group` | - + + +```typescript +let conversationWith: string = "UID", + conversationType: string = "user"; + +CometChat.getConversation(conversationWith, conversationType).then( + (conversation: CometChat.Conversation) => { + console.log("conversation", conversation); + }, + (error: CometChat.CometChatException) => { + console.log("error while fetching a conversation", error); + } +); +``` + -**`lastMessage.data.metadata.@injected.extensions` Object:** + +```javascript +let conversationWith = "UID"; +let conversationType = "user"; + +CometChat.getConversation(conversationWith, conversationType).then( + (conversation) => { + console.log("conversation", conversation); + }, + (error) => { + console.log("error while fetching a conversation", error); + } +); +``` + -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#conv-usertags-data-metadata-linkpreview-object) | + ---- +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. -**`lastMessage.data.metadata.@injected.extensions.link-preview` Object:** +## Convert Messages to Conversations -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | +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. ---- + + +```typescript +let message: CometChat.TextMessage | CometChat.MediaMessage | CometChat.CustomMessage; - +CometChat.CometChatHelper.getConversationFromMessage(message).then( + (conversation: CometChat.Conversation) => { + console.log("Conversation Object", conversation); + },(error: CometChat.CometChatException) => { + console.log("Error while converting message object", error); + } +); +``` -**`lastMessage.metadata` Object:** + -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#conv-usertags-metadata-injected-object) | + +```javascript +CometChat.CometChatHelper.getConversationFromMessage(message).then( + (conversation) => { + console.log("Conversation Object", conversation); + }, (error) => { + console.log("Error while converting message object", error); + } +); +``` ---- + - - -**`lastMessage.metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#conv-usertags-metadata-extensions-object) | - ---- - - - -**`lastMessage.metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#conv-usertags-metadata-linkpreview-object) | - ---- - - - -**`lastMessage.metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - - - -**`conversationWith` Object (User):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-5"` | -| `name` | string | User's display name | `"John Paul"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-5.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"admin"` | -| `lastActiveAt` | number | Last active timestamp | `1771668031` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-5"` | - - - -### Set Group Tags - -This method fetches group conversations that have the specified tags. - - - -```javascript -let limit = 30; -let groupTags = ["tag1"]; -let conversationRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setGroupTags(groupTags) - .build(); -``` - - - -```typescript -let limit: number = 30, - groupTags: Array = ["tag1"], - conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setGroupTags(groupTags) - .build(); -``` - - - - -**On Success** — `fetchNext()` returns an array of `Conversation` objects filtered by group tags: - - - -**Conversation Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `conversationId` | string | Unique conversation identifier | `"group_group_1748415903905"` | -| `conversationType` | string | Type of conversation | `"group"` | -| `unreadMentionsCount` | number | Count of unread mentions | `0` | -| `lastReadMessageId` | string | ID of last read message | `"25243"` | -| `unreadMessageCount` | number | Count of unread messages | `0` | -| `latestMessageId` | string | ID of latest message | `"25243"` | -| `lastMessage` | object | Last message in conversation | [See below ↓](#conv-grouptags-lastmessage-object) | -| `conversationWith` | object | Group details | [See below ↓](#conv-grouptags-conversationwith-object) | - ---- - - - -**`lastMessage` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25243"` | -| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | -| `receiverId` | string | Group's GUID | `"group_1748415903905"` | -| `receiverType` | string | Type of receiver | `"group"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Susan here "` | -| `sentAt` | number | Unix timestamp when sent | `1771413931` | -| `updatedAt` | number | Unix timestamp when updated | `1771413931` | -| `sender` | object | Sender user details | [See below ↓](#conv-grouptags-sender-object) | -| `receiver` | object | Receiver group details | [See below ↓](#conv-grouptags-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#conv-grouptags-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#conv-grouptags-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`lastMessage.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-4"` | -| `name` | string | User's display name | `"Susan Marie"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-4.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"admin"` | -| `lastActiveAt` | number | Last active timestamp | `1771413925` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`lastMessage.receiver` Object (Group with tags):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `guid` | string | Group's unique identifier | `"group_1748415903905"` | -| `name` | string | Group's display name | `"3 People Group"` | -| `type` | string | Group type | `"public"` | -| `tags` | array | Group tags | `["tag1"]` | -| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | -| `owner` | string | Group owner's UID | `"123456"` | -| `scope` | string | Current user's scope in group | `"admin"` | -| `membersCount` | number | Total members in group | `12` | -| `onlineMembersCount` | number | Online members count | `3` | -| `hasJoined` | boolean | Whether current user has joined | `true` | -| `isBanned` | boolean | Whether current user is banned | `false` | -| `joinedAt` | number | Timestamp when user joined | `1748415973` | -| `createdAt` | number | Group creation timestamp | `1748415957` | -| `updatedAt` | number | Group update timestamp | `1771245340` | - ---- - - - -**`conversationWith` Object (Group):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `guid` | string | Group's unique identifier | `"group_1748415903905"` | -| `name` | string | Group's display name | `"3 People Group"` | -| `type` | string | Group type | `"public"` | -| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | -| `owner` | string | Group owner's UID | `"123456"` | -| `scope` | string | Current user's scope in group | `"admin"` | -| `membersCount` | number | Total members in group | `12` | -| `onlineMembersCount` | number | Online members count | `1` | -| `hasJoined` | boolean | Whether current user has joined | `true` | -| `isBanned` | boolean | Whether current user is banned | `false` | -| `joinedAt` | number | Timestamp when user joined | `1748437105` | -| `createdAt` | number | Group creation timestamp | `1748415957` | -| `updatedAt` | number | Group update timestamp | `1771820149` | -| `updatedBy` | string | UID of user who last updated | `"cometchat-uid-2"` | - - - -### 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`. - - - -```javascript -let limit = 30; -let conversationRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .withTags(true) - .build(); -``` - - - -```typescript -let limit: number = 30, - conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .withTags(true) - .build(); -``` - - - - -**On Success** — `fetchNext()` returns an array of `Conversation` objects with conversation tags: - - - -**Conversation Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `conversationType` | string | Type of conversation | `"user"` | -| `unreadMentionsCount` | number | Count of unread mentions | `0` | -| `lastReadMessageId` | string | ID of last read message | `"25276"` | -| `unreadMessageCount` | number | Count of unread messages | `0` | -| `latestMessageId` | string | ID of latest message | `"25276"` | -| `tags` | array | Conversation tags (added by withTags) | `["archivedChat"]` | -| `lastMessage` | object | Last message in conversation | [See below ↓](#conv-withtags-lastmessage-object) | -| `conversationWith` | object | User details | [See below ↓](#conv-withtags-conversationwith-object) | - ---- - - - -**`lastMessage` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25276"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Message for mentioned users, Hello <@uid:cometchat-uid-2>"` | -| `sentAt` | number | Unix timestamp when sent | `1771495242` | -| `deliveredAt` | number | Unix timestamp when delivered | `1771495244` | -| `readAt` | number | Unix timestamp when read | `1771495244` | -| `updatedAt` | number | Unix timestamp when updated | `1771495244` | -| `sender` | object | Sender user details | [See below ↓](#conv-withtags-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#conv-withtags-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#conv-withtags-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#conv-withtags-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | [See below ↓](#conv-withtags-mentionedusers-array) | -| `mentionedMe` | boolean | Whether current user is mentioned | `true` | - ---- - - - -**`lastMessage.mentionedUsers` Array (per item):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771738926` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`lastMessage.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771495034` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`lastMessage.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771494233` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`lastMessage.data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Message for mentioned users, Hello <@uid:cometchat-uid-2>"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `mentions` | object | Map of mentioned users by UID | [See below ↓](#conv-withtags-data-mentions-object) | -| `entities` | object | Sender and receiver entities | [See below ↓](#conv-withtags-data-entities-object) | -| `metadata` | object | Injected metadata | [See below ↓](#conv-withtags-data-metadata-object) | - ---- - - - -**`lastMessage.data.mentions` Object (keyed by UID):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771494233` | - ---- - - - -**`lastMessage.data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#conv-withtags-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#conv-withtags-data-entities-receiver-object) | - ---- - - - -**`lastMessage.data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#conv-withtags-data-entities-sender-entity-object) | - ---- - - - -**`lastMessage.data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771495034` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`lastMessage.data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#conv-withtags-data-entities-receiver-entity-object) | - ---- - - - -**`lastMessage.data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771494233` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`lastMessage.data.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#conv-withtags-data-metadata-injected-object) | - ---- - - - -**`lastMessage.data.metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#conv-withtags-data-metadata-extensions-object) | - ---- - - - -**`lastMessage.data.metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#conv-withtags-data-metadata-linkpreview-object) | - ---- - - - -**`lastMessage.data.metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - - - -**`lastMessage.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#conv-withtags-metadata-injected-object) | - ---- - - - -**`lastMessage.metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#conv-withtags-metadata-extensions-object) | - ---- - - - -**`lastMessage.metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#conv-withtags-metadata-linkpreview-object) | - ---- - - - -**`lastMessage.metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - - - -**`conversationWith` Object (User):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771818451` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | - - - -### Set Tags - -This method helps you fetch the conversations based on the specified tags. - - - -```javascript -let limit = 30; -let tags = ["archivedChat"]; -let conversationRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setTags(tags) - .build(); -``` - - - -```typescript -let limit: number = 30, - tags: Array = ["archivedChat"], - conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setTags(tags) - .build(); -``` - - - - -**On Success** — `fetchNext()` returns an array of `Conversation` objects filtered by conversation tags: - - - -**Conversation Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `conversationType` | string | Type of conversation | `"user"` | -| `unreadMentionsCount` | number | Count of unread mentions | `0` | -| `lastReadMessageId` | string | ID of last read message | `"25276"` | -| `unreadMessageCount` | number | Count of unread messages | `0` | -| `latestMessageId` | string | ID of latest message | `"25276"` | -| `lastMessage` | object | Last message in conversation | [See below ↓](#conv-settags-lastmessage-object) | -| `conversationWith` | object | User details | [See below ↓](#conv-settags-conversationwith-object) | - ---- - - - -**`lastMessage` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25276"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Message for mentioned users, Hello <@uid:cometchat-uid-2>"` | -| `sentAt` | number | Unix timestamp when sent | `1771495242` | -| `deliveredAt` | number | Unix timestamp when delivered | `1771495244` | -| `readAt` | number | Unix timestamp when read | `1771495244` | -| `updatedAt` | number | Unix timestamp when updated | `1771495244` | -| `sender` | object | Sender user details | [See below ↓](#conv-settags-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#conv-settags-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#conv-settags-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#conv-settags-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | [See below ↓](#conv-settags-mentionedusers-array) | -| `mentionedMe` | boolean | Whether current user is mentioned | `true` | - ---- - - - -**`lastMessage.mentionedUsers` Array (per item):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771738926` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`lastMessage.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771495034` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`lastMessage.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771494233` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`lastMessage.data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Message for mentioned users, Hello <@uid:cometchat-uid-2>"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `mentions` | object | Map of mentioned users by UID | [See below ↓](#conv-settags-data-mentions-object) | -| `entities` | object | Sender and receiver entities | [See below ↓](#conv-settags-data-entities-object) | -| `metadata` | object | Injected metadata | [See below ↓](#conv-settags-data-metadata-object) | - ---- - - - -**`lastMessage.data.mentions` Object (keyed by UID):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771494233` | - ---- - - - -**`lastMessage.data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#conv-settags-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#conv-settags-data-entities-receiver-object) | - ---- - - - -**`lastMessage.data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#conv-settags-data-entities-sender-entity-object) | - ---- - - - -**`lastMessage.data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771495034` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`lastMessage.data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#conv-settags-data-entities-receiver-entity-object) | - ---- - - - -**`lastMessage.data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771494233` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`lastMessage.data.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#conv-settags-data-metadata-injected-object) | - ---- - - - -**`lastMessage.data.metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#conv-settags-data-metadata-extensions-object) | - ---- - - - -**`lastMessage.data.metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#conv-settags-data-metadata-linkpreview-object) | - ---- - - - -**`lastMessage.data.metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - - - -**`lastMessage.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#conv-settags-metadata-injected-object) | - ---- - - - -**`lastMessage.metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#conv-settags-metadata-extensions-object) | - ---- - - - -**`lastMessage.metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#conv-settags-metadata-linkpreview-object) | - ---- - - - -**`lastMessage.metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - - - -**`conversationWith` Object (User):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771818451` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | - - - - -**Blocked Users in Conversations - Quick Reference** - -| Flag | Effect | -| ---- | ------ | -| `setIncludeBlockedUsers(true)` | Includes blocked user conversations in results (hidden by default) | -| `setWithBlockedInfo(true)` | Adds `blockedByMe`, `hasBlockedMe`, `blockedByMeAt`, `blockedAt` to `conversationWith` | - -**Usage:** -- Use both together to see blocked conversations with accurate block status -- `conversationWith` contains current block status -- `lastMessage.sender`/`receiver` contains historical data from message time (may show `false` even if currently blocked) - - -### Include Blocked Users - -This method helps you fetch the conversations of users whom the logged-in user has blocked. - - - -```javascript -let limit = 30; -let conversationRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setIncludeBlockedUsers(true) - .build(); -``` - - - -```typescript -let limit: number = 30, - conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setIncludeBlockedUsers(true) - .build(); -``` - - - - -**On Success** — `fetchNext()` returns an array of `Conversation` objects (includes conversations with blocked users): - - - -**Conversation Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `conversationType` | string | Type of conversation | `"user"` | -| `unreadMentionsCount` | number | Count of unread mentions | `0` | -| `lastReadMessageId` | string | ID of last read message | `"25280"` | -| `unreadMessageCount` | number | Count of unread messages | `0` | -| `latestMessageId` | string | ID of latest message | `"25276"` | -| `lastMessage` | object | Last message in conversation | [See below ↓](#conv-blocked-lastmessage-object) | -| `conversationWith` | object | User details | [See below ↓](#conv-blocked-conversationwith-object) | - ---- - - - -**`lastMessage` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25280"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Hello Blocker"` | -| `sentAt` | number | Unix timestamp when sent | `1771820699` | -| `updatedAt` | number | Unix timestamp when updated | `1771820699` | -| `sender` | object | Sender user details | [See below ↓](#conv-blocked-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#conv-blocked-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#conv-blocked-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#conv-blocked-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`lastMessage.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#conv-blocked-metadata-injected-object) | - ---- - - - -**`lastMessage.metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#conv-blocked-metadata-extensions-object) | - ---- - - - -**`lastMessage.metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#conv-blocked-metadata-linkpreview-object) | - ---- - - - -**`lastMessage.metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - - - -**`lastMessage.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771818451` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`lastMessage.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771738926` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`lastMessage.data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Hello Blocker"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `entities` | object | Sender and receiver entities | [See below ↓](#conv-blocked-data-entities-object) | -| `metadata` | object | Injected metadata | [See below ↓](#conv-blocked-data-metadata-object) | -| `moderation` | object | Moderation status | `{"status": "approved"}` | - ---- - - - -**`lastMessage.data.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#conv-blocked-data-metadata-injected-object) | - ---- - - - -**`lastMessage.data.metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#conv-blocked-data-metadata-extensions-object) | - ---- - - - -**`lastMessage.data.metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#conv-blocked-data-metadata-linkpreview-object) | - ---- - - - -**`lastMessage.data.metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - - - -**`lastMessage.data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#conv-blocked-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#conv-blocked-data-entities-receiver-object) | - ---- - - - -**`lastMessage.data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | Sender user details | [See below ↓](#conv-blocked-data-entities-sender-entity-object) | - ---- - - - -**`lastMessage.data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771818451` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`lastMessage.data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | Receiver user details with block info | [See below ↓](#conv-blocked-data-entities-receiver-entity-object) | - ---- - - - -**`lastMessage.data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"offline"` | -| `lastActiveAt` | number | Last active timestamp | `1771738926` | -| `tags` | array | User tags | `[]` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `hasBlockedMeAt` | number | Timestamp when blocked by user | `0` | -| `blockedAt` | number | Timestamp when blocked | `0` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | - ---- - - - -**`conversationWith` Object (User):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771738926` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | - - - -### With Blocked Info - -This method can be used to fetch the blocked information of the blocked user in the `ConversationWith` object. - - - -```javascript -let limit = 30; -let conversationRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setWithBlockedInfo(true) - .build(); -``` - - - -```typescript -let limit: number = 30, - conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setWithBlockedInfo(true) - .build(); -``` - - - - -**On Success** — `fetchNext()` returns an array of `Conversation` objects with blocked info in `conversationWith`: - - - -**Conversation Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `conversationType` | string | Type of conversation | `"user"` | -| `unreadMentionsCount` | number | Count of unread mentions | `0` | -| `lastReadMessageId` | string | ID of last read message | `"25276"` | -| `unreadMessageCount` | number | Count of unread messages | `0` | -| `latestMessageId` | string | ID of latest message | `"25276"` | -| `lastMessage` | object | Last message in conversation | [See below ↓](#conv-blockedinfo-lastmessage-object) | -| `conversationWith` | object | User details with blocked info | [See below ↓](#conv-blockedinfo-conversationwith-object) | - ---- - - - -**`lastMessage` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25276"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Message for mentioned users, Hello <@uid:cometchat-uid-2>"` | -| `sentAt` | number | Unix timestamp when sent | `1771495242` | -| `deliveredAt` | number | Unix timestamp when delivered | `1771495244` | -| `readAt` | number | Unix timestamp when read | `1771495244` | -| `updatedAt` | number | Unix timestamp when updated | `1771495244` | -| `sender` | object | Sender user details | [See below ↓](#conv-blockedinfo-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#conv-blockedinfo-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#conv-blockedinfo-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#conv-blockedinfo-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | [See below ↓](#conv-blockedinfo-mentionedusers-array) | -| `mentionedMe` | boolean | Whether current user is mentioned | `true` | - ---- - - - -**`lastMessage.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#conv-blockedinfo-metadata-injected-object) | - ---- - - - -**`lastMessage.metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#conv-blockedinfo-metadata-extensions-object) | - ---- - - - -**`lastMessage.metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#conv-blockedinfo-metadata-linkpreview-object) | - ---- - - - -**`lastMessage.metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - - - -**`lastMessage.mentionedUsers` Array (per item):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771738926` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`lastMessage.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771495034` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`lastMessage.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771494233` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`lastMessage.data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Message for mentioned users, Hello <@uid:cometchat-uid-2>"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `mentions` | object | Map of mentioned users by UID | [See below ↓](#conv-blockedinfo-data-mentions-object) | -| `entities` | object | Sender and receiver entities | [See below ↓](#conv-blockedinfo-data-entities-object) | -| `metadata` | object | Injected metadata | [See below ↓](#conv-blockedinfo-data-metadata-object) | - ---- - - - -**`lastMessage.data.mentions` Object (keyed by UID):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771494233` | - ---- - - - -**`lastMessage.data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#conv-blockedinfo-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#conv-blockedinfo-data-entities-receiver-object) | - ---- - - - -**`lastMessage.data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#conv-blockedinfo-data-entities-sender-entity-object) | - ---- - - - -**`lastMessage.data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771495034` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`lastMessage.data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#conv-blockedinfo-data-entities-receiver-entity-object) | - ---- - - - -**`lastMessage.data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | -| `name` | string | User's display name | `"George Alan"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771494233` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`lastMessage.data.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#conv-blockedinfo-data-metadata-injected-object) | - ---- - - - -**`lastMessage.data.metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#conv-blockedinfo-data-metadata-extensions-object) | - ---- - - - -**`lastMessage.data.metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#conv-blockedinfo-data-metadata-linkpreview-object) | - ---- - - - -**`lastMessage.data.metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - - - -**`conversationWith` Object (User with blocked info):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771818451` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `true` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `blockedByMeAt` | number | Timestamp when blocked by current user | `1771820668` | -| `blockedAt` | number | Block timestamp | `1771820668` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | - - - -### Search Conversations - -This method helps you search for a conversation based on a User or Group name. - - - -This feature is only available with `Conversation & Advanced Search`. 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) - - - - - -```javascript -let limit = 30; -let conversationRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setSearchKeyword("Hiking") - .build(); -``` - - - -```typescript -let limit: number = 30, - conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setSearchKeyword("Hiking") - .build(); -``` - - - - -**On Success** — `fetchNext()` returns an array of `Conversation` objects matching the search keyword: - - - -**Conversation Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `conversationId` | string | Unique conversation identifier | `"group_cometchat-guid-1"` | -| `conversationType` | string | Type of conversation | `"group"` | -| `unreadMentionsCount` | number | Count of unread mentions | `0` | -| `lastReadMessageId` | string | ID of last read message | `"4791"` | -| `unreadMessageCount` | number | Count of unread messages | `0` | -| `latestMessageId` | string | ID of latest message | `"4791"` | -| `lastMessage` | object | Last message in conversation | [See below ↓](#conv-search-lastmessage-object) | -| `conversationWith` | object | Group details | [See below ↓](#conv-search-conversationwith-object) | - ---- - - - -**`lastMessage` Object (Action Message):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"4791"` | -| `conversationId` | string | Conversation identifier | `"group_cometchat-guid-1"` | -| `receiverId` | string | Group's GUID | `"cometchat-guid-1"` | -| `receiverType` | string | Type of receiver | `"group"` | -| `type` | string | Message type | `"groupMember"` | -| `category` | string | Message category | `"action"` | -| `action` | string | Action performed | `"kicked"` | -| `message` | string | Action message text | `"John Paul kicked Andrew Joseph"` | -| `sentAt` | number | Unix timestamp when sent | `1753946954` | -| `deliveredAt` | number | Unix timestamp when delivered | `1764150385` | -| `updatedAt` | number | Unix timestamp when updated | `1764150385` | -| `actionBy` | object | User who performed action | [See below ↓](#conv-search-actionby-object) | -| `actionFor` | object | Group the action was for | [See below ↓](#conv-search-actionfor-object) | -| `actionOn` | object | User the action was on | [See below ↓](#conv-search-actionon-object) | -| `sender` | object | Sender user details | Same as `actionBy` | -| `receiver` | object | Receiver group details | Same as `actionFor` | -| `data` | object | Additional message data | [See below ↓](#conv-search-data-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`lastMessage.actionBy` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-5"` | -| `name` | string | User's display name | `"John Paul"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-5.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1753945410` | -| `createdAt` | number | User creation timestamp | `1746375164` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`lastMessage.actionFor` Object (Group):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `guid` | string | Group's unique identifier | `"cometchat-guid-1"` | -| `name` | string | Group's display name | `"Hiking Group"` | -| `type` | string | Group type | `"private"` | -| `description` | string | Group description | `"Explore, connect, and chat with fellow outdoor enthusiasts..."` | -| `icon` | string | URL to group icon | `"https://assets.cometchat.io/sampleapp/v2/groups/cometchat-guid-1.webp"` | -| `conversationId` | string | Conversation identifier | `"group_cometchat-guid-1"` | -| `owner` | string | Group owner's UID | `"cometchat-uid-5"` | -| `membersCount` | number | Total members in group | `3` | -| `hasJoined` | boolean | Whether current user has joined | `false` | -| `isBanned` | boolean | Whether current user is banned | `false` | -| `createdAt` | number | Group creation timestamp | `1746375164` | -| `updatedAt` | number | Group update timestamp | `1753945144` | - ---- - - - -**`lastMessage.actionOn` Object (User):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-1"` | -| `name` | string | User's display name | `"Andrew Joseph"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | -| `status` | string | User's online status | `"offline"` | -| `statusMessage` | string | User's status message | `"Hey there I'm using CometChat"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1753944766` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-1_user_cometchat-uid-5"` | -| `createdAt` | number | User creation timestamp | `1746375164` | -| `updatedAt` | number | User update timestamp | `1749731589` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | - ---- - - - -**`lastMessage.data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `action` | string | Action type | `"kicked"` | -| `entities` | object | Action entities | [See below ↓](#conv-search-data-entities-object) | - ---- - - - -**`lastMessage.data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `by` | object | User who performed action | [See below ↓](#conv-search-data-entities-by-object) | -| `for` | object | Group the action was for | [See below ↓](#conv-search-data-entities-for-object) | -| `on` | object | User the action was on | [See below ↓](#conv-search-data-entities-on-object) | - ---- - - - -**`lastMessage.data.entities.by` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#conv-search-data-entities-by-entity-object) | - ---- - - - -**`lastMessage.data.entities.by.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-5"` | -| `name` | string | User's display name | `"John Paul"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-5.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"offline"` | -| `lastActiveAt` | number | Last active timestamp | `1753945410` | -| `createdAt` | number | User creation timestamp | `1746375164` | - ---- - - - -**`lastMessage.data.entities.for` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"group"` | -| `entity` | object | Group entity details | [See below ↓](#conv-search-data-entities-for-entity-object) | - ---- - - - -**`lastMessage.data.entities.for.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `guid` | string | Group's unique identifier | `"cometchat-guid-1"` | -| `name` | string | Group's display name | `"Hiking Group"` | -| `type` | string | Group type | `"private"` | -| `description` | string | Group description | `"Explore, connect, and chat with fellow outdoor enthusiasts..."` | -| `icon` | string | URL to group icon | `"https://assets.cometchat.io/sampleapp/v2/groups/cometchat-guid-1.webp"` | -| `conversationId` | string | Conversation identifier | `"group_cometchat-guid-1"` | -| `owner` | string | Group owner's UID | `"cometchat-uid-5"` | -| `membersCount` | number | Total members in group | `3` | -| `hasJoined` | boolean | Whether current user has joined | `false` | -| `isBanned` | boolean | Whether current user is banned | `false` | -| `createdAt` | number | Group creation timestamp | `1746375164` | -| `updatedAt` | number | Group update timestamp | `1753945144` | - ---- - - - -**`lastMessage.data.entities.on` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#conv-search-data-entities-on-entity-object) | - ---- - - - -**`lastMessage.data.entities.on.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-1"` | -| `name` | string | User's display name | `"Andrew Joseph"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"offline"` | -| `statusMessage` | string | User's status message | `"Hey there I'm using CometChat"` | -| `lastActiveAt` | number | Last active timestamp | `1753944766` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-1_user_cometchat-uid-5"` | -| `createdAt` | number | User creation timestamp | `1746375164` | -| `updatedAt` | number | User update timestamp | `1749731589` | - ---- - - - -**`conversationWith` Object (Group):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `guid` | string | Group's unique identifier | `"cometchat-guid-1"` | -| `name` | string | Group's display name | `"Hiking Group"` | -| `type` | string | Group type | `"private"` | -| `description` | string | Group description | `"Explore, connect, and chat with fellow outdoor enthusiasts..."` | -| `icon` | string | URL to group icon | `"https://assets.cometchat.io/sampleapp/v2/groups/cometchat-guid-1.webp"` | -| `conversationId` | string | Conversation identifier | `"group_cometchat-guid-1"` | -| `owner` | string | Group owner's UID | `"cometchat-uid-5"` | -| `scope` | string | Current user's scope in group | `"participant"` | -| `membersCount` | number | Total members in group | `3` | -| `onlineMembersCount` | number | Online members count | `1` | -| `hasJoined` | boolean | Whether current user has joined | `true` | -| `isBanned` | boolean | Whether current user is banned | `false` | -| `joinedAt` | number | Timestamp when user joined | `1746375164` | -| `createdAt` | number | Group creation timestamp | `1746375164` | -| `updatedAt` | number | Group update timestamp | `1753946955` | - - - -### Unread Conversations - -This method helps you fetch unread conversations. - - - -This feature is only available with `Conversation & Advanced Search`. 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) - - - - - -```javascript -let limit = 30; -let conversationRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setUnread(true) - .build(); -``` - - - -```typescript -let limit: number = 30, - conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setUnread(true) - .build(); -``` - - - - -**On Success** — `fetchNext()` returns an array of `Conversation` objects with unread messages: - - - -**Conversation Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `conversationId` | string | Unique conversation identifier | `"group_group_1762515421478"` | -| `conversationType` | string | Type of conversation | `"group"` | -| `unreadMentionsCount` | number | Count of unread mentions | `0` | -| `lastReadMessageId` | string | ID of last read message | `"24359"` | -| `unreadMessageCount` | number | Count of unread messages | `2` | -| `latestMessageId` | string | ID of latest message | `"25236"` | -| `lastMessage` | object | Last message in conversation | [See below ↓](#conv-unread-lastmessage-object) | -| `conversationWith` | object | Group details | [See below ↓](#conv-unread-conversationwith-object) | - ---- - - - -**`lastMessage` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25236"` | -| `conversationId` | string | Conversation identifier | `"group_group_1762515421478"` | -| `receiverId` | string | Group's GUID | `"group_1762515421478"` | -| `receiverType` | string | Type of receiver | `"group"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Hru"` | -| `sentAt` | number | Unix timestamp when sent | `1771400675` | -| `updatedAt` | number | Unix timestamp when updated | `1771400675` | -| `sender` | object | Sender user details | [See below ↓](#conv-unread-sender-object) | -| `receiver` | object | Receiver group details | [See below ↓](#conv-unread-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#conv-unread-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#conv-unread-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`lastMessage.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#conv-unread-metadata-injected-object) | - ---- - - - -**`lastMessage.metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#conv-unread-metadata-extensions-object) | - ---- - - - -**`lastMessage.metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#conv-unread-metadata-linkpreview-object) | - ---- - - - -**`lastMessage.metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - - - -**`lastMessage.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771397739` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`lastMessage.receiver` Object (Group):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `guid` | string | Group's unique identifier | `"group_1762515421478"` | -| `name` | string | Group's display name | `"TwoMemberGroup"` | -| `type` | string | Group type | `"public"` | -| `conversationId` | string | Conversation identifier | `"group_group_1762515421478"` | -| `owner` | string | Group owner's UID | `"cometchat-uid-2"` | -| `scope` | string | Current user's scope in group | `"participant"` | -| `membersCount` | number | Total members in group | `3` | -| `onlineMembersCount` | number | Online members count | `2` | -| `hasJoined` | boolean | Whether current user has joined | `true` | -| `isBanned` | boolean | Whether current user is banned | `false` | -| `joinedAt` | number | Timestamp when user joined | `1762515534` | -| `createdAt` | number | Group creation timestamp | `1762515421` | -| `updatedAt` | number | Group update timestamp | `1768888876` | - ---- - - - -**`lastMessage.data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Hru"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `entities` | object | Sender and receiver entities | [See below ↓](#conv-unread-data-entities-object) | -| `metadata` | object | Injected metadata | [See below ↓](#conv-unread-data-metadata-object) | - ---- - - - -**`lastMessage.data.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#conv-unread-data-metadata-injected-object) | - ---- - - - -**`lastMessage.data.metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#conv-unread-data-metadata-extensions-object) | - ---- - - - -**`lastMessage.data.metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#conv-unread-data-metadata-linkpreview-object) | - ---- - - - -**`lastMessage.data.metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - - - -**`lastMessage.data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#conv-unread-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#conv-unread-data-entities-receiver-object) | - ---- - - - -**`lastMessage.data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#conv-unread-data-entities-sender-entity-object) | - ---- - - - -**`lastMessage.data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | -| `name` | string | User's display name | `"Nancy Grace"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771397739` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`lastMessage.data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"group"` | -| `entity` | object | Group entity details | [See below ↓](#conv-unread-data-entities-receiver-entity-object) | - ---- - - - -**`lastMessage.data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `guid` | string | Group's unique identifier | `"group_1762515421478"` | -| `name` | string | Group's display name | `"TwoMemberGroup"` | -| `type` | string | Group type | `"public"` | -| `conversationId` | string | Conversation identifier | `"group_group_1762515421478"` | -| `owner` | string | Group owner's UID | `"cometchat-uid-2"` | -| `scope` | string | Current user's scope in group | `"participant"` | -| `membersCount` | number | Total members in group | `3` | -| `onlineMembersCount` | number | Online members count | `2` | -| `hasJoined` | boolean | Whether current user has joined | `true` | -| `joinedAt` | number | Timestamp when user joined | `1762515534` | -| `createdAt` | number | Group creation timestamp | `1762515421` | -| `updatedAt` | number | Group update timestamp | `1768888876` | - ---- - - - -**`conversationWith` Object (Group):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `guid` | string | Group's unique identifier | `"group_1762515421478"` | -| `name` | string | Group's display name | `"TwoMemberGroup"` | -| `type` | string | Group type | `"public"` | -| `conversationId` | string | Conversation identifier | `"group_group_1762515421478"` | -| `owner` | string | Group owner's UID | `"cometchat-uid-2"` | -| `scope` | string | Current user's scope in group | `"admin"` | -| `membersCount` | number | Total members in group | `3` | -| `onlineMembersCount` | number | Online members count | `1` | -| `hasJoined` | boolean | Whether current user has joined | `true` | -| `isBanned` | boolean | Whether current user is banned | `false` | -| `joinedAt` | number | Timestamp when user joined | `1762515421` | -| `createdAt` | number | Group creation timestamp | `1762515421` | -| `updatedAt` | number | Group update timestamp | `1768888876` | - - - -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. - -A Maximum of only 50 Conversations can be fetched at once. - - - -```javascript -let limit = 30; -let conversationsRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .build(); - -conversationsRequest.fetchNext().then( - conversationList => { - console.log("Conversations list received:", conversationList); - }, error => { - console.log("Conversations list fetching failed with error:", error); - } -); -``` - - - -```typescript -let limit: number = 30, - conversationsRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .build(); - -conversationsRequest.fetchNext().then( - (conversationList: CometChat.Conversation[]) => { - console.log("Conversations list received:", conversationList); - }, (error: CometChat.CometChatException) => { - console.log("Conversations list fetching failed with error:", error); - } -); -``` - - - -The `Conversation` Object consists of the following fields: - -| Field | Information | -| ------------------ | ----------------------------------------------------------------- | -| conversationId | ID of the conversation. | -| conversationType | Type of conversation. (user/group) | -| lastMessage | Last message in the conversation. | -| conversationWith | User or Group object containing the details of the user or group. | -| unreadMessageCount | Unread message count for the conversation. | - -## 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 tag. - -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. - - - -```javascript -let tags = ["archivedChat"]; -CometChat.tagConversation('conversationWith', 'conversationType', tags).then( - conversation => { - console.log('conversation', conversation); - }, error => { - console.log('error while fetching a conversation', error); - } -); -``` - - - - -**On Success** — `tagConversation()` returns the updated `Conversation` object with the new tags: - - - -**Conversation Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `conversationType` | string | Type of conversation | `"user"` | -| `unreadMentionsCount` | number | Count of unread mentions | `0` | -| `lastReadMessageId` | string | ID of last read message | `"25291"` | -| `unreadMessageCount` | number | Count of unread messages | `0` | -| `latestMessageId` | string | ID of latest message | `"25291"` | -| `tags` | array | Conversation tags | `["archivedChat"]` | -| `lastMessage` | object | Last message in conversation | [See below ↓](#conv-tag-lastmessage-object) | -| `conversationWith` | object | User details | [See below ↓](#conv-tag-conversationwith-object) | - ---- - - - -**`lastMessage` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25291"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-6"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Hello"` | -| `sentAt` | number | Unix timestamp when sent | `1771831336` | -| `deliveredAt` | number | Unix timestamp when delivered | `1771832977` | -| `readAt` | number | Unix timestamp when read | `1771832977` | -| `updatedAt` | number | Unix timestamp when updated | `1771832977` | -| `sender` | object | Sender user details | [See below ↓](#conv-tag-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#conv-tag-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#conv-tag-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#conv-tag-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`lastMessage.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#conv-tag-metadata-injected-object) | - ---- - - - -**`lastMessage.metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#conv-tag-metadata-extensions-object) | - ---- - - - -**`lastMessage.metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#conv-tag-metadata-linkpreview-object) | - ---- - - - -**`lastMessage.metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - - - -**`lastMessage.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771829868` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`lastMessage.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771829859` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`lastMessage.data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Hello"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `entities` | object | Sender and receiver entities | [See below ↓](#conv-tag-data-entities-object) | -| `metadata` | object | Injected metadata | [See below ↓](#conv-tag-data-metadata-object) | - ---- - - - -**`lastMessage.data.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#conv-tag-data-metadata-injected-object) | - ---- - - - -**`lastMessage.data.metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#conv-tag-data-metadata-extensions-object) | - ---- - - - -**`lastMessage.data.metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#conv-tag-data-metadata-linkpreview-object) | - ---- - - - -**`lastMessage.data.metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - - - -**`lastMessage.data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#conv-tag-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#conv-tag-data-entities-receiver-object) | - ---- - - - -**`lastMessage.data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#conv-tag-data-entities-sender-entity-object) | - ---- - - - -**`lastMessage.data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771829868` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`lastMessage.data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#conv-tag-data-entities-receiver-entity-object) | - ---- - - - -**`lastMessage.data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771829859` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`conversationWith` Object (User):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771834604` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | - - - - - -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. - - - -## 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. - -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: - -* user - Only fetches user conversation. -* group - Only fetches group conversations. - - - -```javascript -CometChat.getConversation('conversationWith', 'conversationType').then( - conversation => { - console.log('conversation', conversation); - }, error => { - console.log('error while fetching a conversation', error); - } -); -``` - - - - -**On Success** — `getConversation()` returns the `Conversation` object: - - - -**Conversation Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `conversationType` | string | Type of conversation | `"user"` | -| `unreadMentionsCount` | number | Count of unread mentions | `0` | -| `lastReadMessageId` | string | ID of last read message | `"25291"` | -| `unreadMessageCount` | number | Count of unread messages | `0` | -| `latestMessageId` | string | ID of latest message | `"25291"` | -| `tags` | array | Conversation tags | `["archivedChat"]` | -| `lastMessage` | object | Last message in conversation | [See below ↓](#conv-single-lastmessage-object) | -| `conversationWith` | object | User details | [See below ↓](#conv-single-conversationwith-object) | - ---- - - - -**`lastMessage` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25291"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-6"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Hello"` | -| `sentAt` | number | Unix timestamp when sent | `1771831336` | -| `deliveredAt` | number | Unix timestamp when delivered | `1771832977` | -| `readAt` | number | Unix timestamp when read | `1771832977` | -| `updatedAt` | number | Unix timestamp when updated | `1771832977` | -| `sender` | object | Sender user details | [See below ↓](#conv-single-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#conv-single-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#conv-single-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#conv-single-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`lastMessage.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#conv-single-metadata-injected-object) | - ---- - - - -**`lastMessage.metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#conv-single-metadata-extensions-object) | - ---- - - - -**`lastMessage.metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#conv-single-metadata-linkpreview-object) | - ---- - - - -**`lastMessage.metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - - - -**`lastMessage.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771829868` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`lastMessage.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771829859` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`lastMessage.data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Hello"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `entities` | object | Sender and receiver entities | [See below ↓](#conv-single-data-entities-object) | -| `metadata` | object | Injected metadata | [See below ↓](#conv-single-data-metadata-object) | - ---- - - - -**`lastMessage.data.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#conv-single-data-metadata-injected-object) | - ---- - - - -**`lastMessage.data.metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#conv-single-data-metadata-extensions-object) | - ---- - - - -**`lastMessage.data.metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#conv-single-data-metadata-linkpreview-object) | - ---- - - - -**`lastMessage.data.metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - - - -**`lastMessage.data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#conv-single-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#conv-single-data-entities-receiver-object) | - ---- - - - -**`lastMessage.data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#conv-single-data-entities-sender-entity-object) | - ---- - - - -**`lastMessage.data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771829868` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`lastMessage.data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#conv-single-data-entities-receiver-entity-object) | - ---- - - - -**`lastMessage.data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771829859` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`conversationWith` Object (User):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771834604` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | - - - -## Convert Messages to Conversations - -As per our [receive messages](/sdk/react-native/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(BaseMessage message)` method of the `CometChatHelper` class. - - - -```javascript -CometChat.CometChatHelper.getConversationFromMessage(message).then( -conversation => { - console.log("Conversation Object", conversation); -}, error => { - console.log("Error while converting message object", error); -} -); -``` - - - - -**On Success** — `getConversationFromMessage()` returns the converted `Conversation` object: - - - -**Conversation Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `conversationType` | string | Type of conversation | `"user"` | -| `unreadMentionsCount` | number | Count of unread mentions | `0` | -| `lastReadMessageId` | string | ID of last read message (empty when converted) | `""` | -| `unreadMessageCount` | number | Count of unread messages (0 when converted) | `0` | -| `latestMessageId` | string | ID of latest message (empty when converted) | `""` | -| `lastMessage` | object | The source message converted to lastMessage | [See below ↓](#conv-convert-lastmessage-object) | -| `conversationWith` | object | User details from message receiver | [See below ↓](#conv-convert-conversationwith-object) | - ---- - - - -**`lastMessage` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25291"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-6"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Hello"` | -| `sentAt` | number | Unix timestamp when sent | `1771831336` | -| `deliveredAt` | number | Unix timestamp when delivered | `1771832977` | -| `readAt` | number | Unix timestamp when read | `1771832977` | -| `updatedAt` | number | Unix timestamp when updated | `1771832977` | -| `sender` | object | Sender user details | [See below ↓](#conv-convert-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#conv-convert-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#conv-convert-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#conv-convert-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`lastMessage.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#conv-convert-metadata-injected-object) | - ---- - - - -**`lastMessage.metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#conv-convert-metadata-extensions-object) | - ---- - - - -**`lastMessage.metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#conv-convert-metadata-linkpreview-object) | - ---- - - - -**`lastMessage.metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - - - -**`lastMessage.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771829868` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`lastMessage.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771829859` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`lastMessage.data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Hello"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `entities` | object | Sender and receiver entities | [See below ↓](#conv-convert-data-entities-object) | -| `metadata` | object | Injected metadata | [See below ↓](#conv-convert-data-metadata-object) | - ---- - - - -**`lastMessage.data.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#conv-convert-data-metadata-injected-object) | - ---- - - - -**`lastMessage.data.metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#conv-convert-data-metadata-extensions-object) | - ---- - - - -**`lastMessage.data.metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#conv-convert-data-metadata-linkpreview-object) | - ---- - - - -**`lastMessage.data.metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - - - -**`lastMessage.data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#conv-convert-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#conv-convert-data-entities-receiver-object) | - ---- - - - -**`lastMessage.data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#conv-convert-data-entities-sender-entity-object) | - ---- - - - -**`lastMessage.data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771829868` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`lastMessage.data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#conv-convert-data-entities-receiver-entity-object) | - ---- - - - -**`lastMessage.data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771829859` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`conversationWith` Object (User):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771829868` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - - + - -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. -## Best Practices & Troubleshooting - - - - Always use `fetchNext()` in a loop or on-scroll handler to paginate through conversations. Fetching all conversations at once is not supported — the maximum per request is 50. Store the `ConversationsRequest` object and call `fetchNext()` repeatedly until it returns an empty list. - - - Use [real-time message listeners](/sdk/react-native/receive-messages) to receive new messages, then call `CometChatHelper.getConversationFromMessage()` to convert incoming messages into `Conversation` objects and update your list. Note that `unreadMessageCount` and `tags` are not available when converting from a message — manage those on the client side. - - - Use `setTags()` to categorize conversations (e.g., `archivedChat`, `pinned`). Remember that conversation tags are one-way — tagging a conversation only applies for the logged-in user, not the other participant. - - - Ensure the logged-in user has actually exchanged messages with the expected users or groups. Conversations only appear once at least one message has been sent. Also verify that any filters (conversation type, tags, unread) are not excluding the results you expect. - - - The `setSearchKeyword()` and `setUnread()` methods require the `Conversation & Advanced Search` feature, which is only 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. - - +The `getConversationFromMessage()` method returns a [`Conversation`](/sdk/reference/entities#conversation) object. --- @@ -3943,15 +692,15 @@ While converting the `Message` object to the `Conversation` object, the `unreadM - Remove a conversation from the logged-in user's conversation list. + Remove conversations from the logged-in user's list - - Listen for real-time messages and update your conversation list. + + Listen for incoming messages to update conversation lists in real time - Show real-time typing status within conversations. + Show real-time typing status in conversations - Track when messages are delivered and read. + Track message delivery and read status per conversation diff --git a/sdk/react-native/retrieve-group-members.mdx b/sdk/react-native/retrieve-group-members.mdx index 969c4e923..8a017ebc2 100644 --- a/sdk/react-native/retrieve-group-members.mdx +++ b/sdk/react-native/retrieve-group-members.mdx @@ -1,47 +1,40 @@ --- title: "Retrieve Group Members" -description: "Fetch group member lists with filtering by scope, search, and pagination using the CometChat React Native SDK." +sidebarTitle: "Retrieve Members" +description: "Fetch and filter group members by scope, status, and search keyword using the CometChat React Native SDK with pagination support." --- - -**Quick Reference** - Fetch group members: + ```javascript +// Fetch group members const request = new CometChat.GroupMembersRequestBuilder("GUID") - .setLimit(30) - .build(); + .setLimit(30).build(); const members = await request.fetchNext(); + +// Filter by scope +const scopeRequest = new CometChat.GroupMembersRequestBuilder("GUID") + .setLimit(30).setScopes(["admin", "moderator"]).build(); + +// Search members +const searchRequest = new CometChat.GroupMembersRequestBuilder("GUID") + .setLimit(30).setSearchKeyword("john").build(); ``` - + - -**Available via:** [SDK](/sdk/react-native/retrieve-group-members) | [REST API](/rest-api/group-members/list) | [UI Kits](/ui-kit/react-native/groups) - +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 -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. +Use `GroupMembersRequestBuilder` to fetch members of a [Group](/sdk/reference/entities#group). The GUID must be specified in the constructor. -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`](/sdk/reference/entities#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. +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"; @@ -53,26 +46,24 @@ 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. - - ```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"; @@ -86,26 +77,26 @@ let groupMembersRequest: CometChat.GroupMembersRequest = new CometChat.GroupMemb - - -### Set Scopes - -This method allows you to fetch group members based on multiple scopes. - - ```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"; @@ -116,33 +107,40 @@ let groupMembersRequest: CometChat.GroupMembersRequest = new CometChat.GroupMemb .setScopes(scopes) .build(); ``` - - - -### 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) - .setStatus(CometChat.USER_STATUS.ONLINE) + .setScopes(scopes) .build(); ``` - + + +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 + +Filters members by online status: + +| Value | Description | +|-------|-------------| +| `CometChat.USER_STATUS.ONLINE` | Only online members | +| `CometChat.USER_STATUS.OFFLINE` | Only offline members | + +If not set, returns all members regardless of status. + + ```typescript let GUID: string = "GUID"; @@ -155,32 +153,23 @@ 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. - - ```javascript let GUID = "GUID"; let limit = 30; -lett 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); -} -); +let groupMembersRequest = new CometChat.GroupMembersRequestBuilder(GUID) + .setLimit(limit) + .setStatus(CometChat.USER_STATUS.ONLINE) + .build(); ``` + + +After configuring the builder, call `build()` to create the request, then `fetchNext()` to retrieve members. Call `fetchNext()` repeatedly on the same instance to paginate. + + ```typescript let GUID: string = "GUID"; @@ -200,58 +189,28 @@ 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); +} +); +``` - -**On Success** — `fetchNext()` returns an array of `GroupMember` objects: - - - -**GroupMember Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | -| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | -| `uid` | string | Unique identifier of the user | `"cometchat-uid-7"` | -| `joinedAt` | number | Unix timestamp when the user joined the group | `1772428121` | -| `name` | string | Display name of the user | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `statusMessage` | string | User's status message | `"Testing CometChat SDK"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1772427635` | -| `scope` | string | Member's scope in the group (admin, moderator, participant) | `"participant"` | -| `conversationId` | string | Conversation ID between this user and logged-in user | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `guid` | string | GUID of the group | `"group_1772427551785"` | + - + -## Best Practices - - - - Always use `fetchNext()` with a reasonable `setLimit()` value (e.g., 20-30). For groups with many members, paginate through results rather than fetching all at once. - - - The `GroupMembersRequest` object maintains an internal cursor. Creating a new instance resets the cursor. Reuse the same instance across `fetchNext()` calls. - - - Use `setScopes()` to fetch only admins or moderators when building admin management UIs, rather than fetching all members and filtering client-side. - - - -## Troubleshooting - - - - Verify the GUID is correct and the logged-in user is a member of the group. Non-members cannot fetch the member list of private groups. - - - Ensure you're reusing the same `GroupMembersRequest` instance. Creating a new builder resets the pagination cursor. - - +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. --- @@ -259,10 +218,10 @@ groupMembersRequest.fetchNext().then( - Add new members to a group + Add users to a group programmatically - - Kick, ban, and unban group members + + Remove or ban members from a group Update member roles within a group @@ -270,4 +229,4 @@ groupMembersRequest.fetchNext().then( Fetch group lists and group details - \ No newline at end of file + diff --git a/sdk/react-native/retrieve-groups.mdx b/sdk/react-native/retrieve-groups.mdx index b0e6fe768..7e9d4be48 100644 --- a/sdk/react-native/retrieve-groups.mdx +++ b/sdk/react-native/retrieve-groups.mdx @@ -1,95 +1,75 @@ --- title: "Retrieve Groups" -description: "Fetch group lists, search groups, get group details, and retrieve online member counts using the CometChat React Native SDK." +sidebarTitle: "Retrieve Groups" +description: "Fetch, filter, and search groups using the CometChat React Native SDK. Includes pagination, tag-based filtering, joined-only groups, and online member counts." --- - -**Quick Reference** - Fetch groups: +{/* TL;DR for Agents and Quick Reference */} + ```javascript -// Fetch group list -const groupsRequest = new CometChat.GroupsRequestBuilder().setLimit(30).build(); -const groups = await groupsRequest.fetchNext(); +// Fetch groups list +const request = new CometChat.GroupsRequestBuilder() + .setLimit(30).build(); +const groups = await request.fetchNext(); -// Get specific group +// Get specific group details const group = await CometChat.getGroup("GUID"); +// Fetch only joined groups +const joinedRequest = new CometChat.GroupsRequestBuilder() + .setLimit(30).joinedOnly(true).build(); + // Get online member count -const counts = await CometChat.getOnlineGroupMemberCount(["GUID"]); +const count = await CometChat.getOnlineGroupMemberCount(["GUID"]); ``` - - - -**Available via:** [SDK](/sdk/react-native/retrieve-groups) | [REST API](/rest-api/groups/list) | [UI Kits](/ui-kit/react-native/groups) - - -## Overview + -*In other words, as a logged-in user, how do I retrieve the list of groups I've joined and groups that are available?* +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. -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. +## Retrieve List of Groups -## GroupsRequestBuilder +Use `GroupsRequestBuilder` to fetch groups with filtering, searching, and pagination. -The `GroupsRequestBuilder` class allows you to set the below parameters: +Fetching using this builder will return [`Group`](/sdk/reference/entities#group) objects. ### 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. - -```javascript -let limit = 30; -let groupsRequest = new CometChat.GroupsRequestBuilder() + +```typescript +let limit: number = 30; +let groupsRequest: CometChat.GroupsRequest = new CometChat.GroupsRequestBuilder() .setLimit(limit) .build(); ``` - -```typescript -let limit: number = 30; -let groupsRequest: CometChat.GroupsRequest = - new CometChat.GroupsRequestBuilder().setLimit(limit).build(); + +```javascript +let limit = 30; +let groupsRequest = new CometChat.GroupsRequestBuilder() + .setLimit(limit) + .build(); ``` - -**On Success** — `fetchNext()` with basic limit returns an array of `Group` objects: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `guid` | string | Unique identifier of the group | `"007007"` | -| `name` | string | Display name of the group | `"Bond"` | -| `type` | string | Group type (public, private, password) | `"public"` | -| `owner` | string | UID of the group owner | `"user-b"` | -| `membersCount` | number | Total number of members in the group | `5` | -| `hasJoined` | boolean | Whether the logged-in user has joined this group | `false` | -| `isBanned` | boolean | Whether the logged-in user is banned from this group | `false` | -| `conversationId` | string | Conversation ID for this group | `"group_007007"` | -| `createdAt` | number | Unix timestamp when group was created | `1760001806` | -| `updatedAt` | number | Unix timestamp of last update | `1768398330` | -| `updatedBy` | string | UID of user who last updated the group (if updated) | `"123456"` | -| `description` | string | Group description (if set) | `"Testing group for QA users"` | -| `icon` | string | URL to group icon image (if set) | `"https://images.unsplash.com/..."` | - - - ### 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. - -```javascript -let limit = 30; -let searchKeyword = "group"; -let groupsRequest = new CometChat.GroupsRequestBuilder() + +```typescript +let limit: number = 30; +let searchKeyword: string = "group"; +let groupsRequest: CometChat.GroupsRequest = new CometChat.GroupsRequestBuilder() .setLimit(limit) .setSearchKeyword(searchKeyword) .build(); @@ -97,50 +77,29 @@ let groupsRequest = new CometChat.GroupsRequestBuilder() - -```typescript -let limit: number = 30; -let searchKeyword: string = "group"; -let groupsRequest: CometChat.GroupsRequest = - new CometChat.GroupsRequestBuilder() - .setLimit(limit) - .setSearchKeyword(searchKeyword) - .build(); + +```javascript +let limit = 30; +let searchKeyword = "group"; +let groupsRequest = new CometChat.GroupsRequestBuilder() + .setLimit(limit) + .setSearchKeyword(searchKeyword) + .build(); ``` - -**On Success** — `fetchNext()` with search filter returns an array of `Group` objects matching the keyword: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `guid` | string | Unique identifier of the group | `"group_1748350143247"` | -| `name` | string | Display name of the group | `"testmemebrrole"` | -| `type` | string | Group type (public, private, password) | `"public"` | -| `owner` | string | UID of the group owner | `"123456"` | -| `membersCount` | number | Total number of members in the group | `7` | -| `hasJoined` | boolean | Whether the logged-in user has joined this group | `false` | -| `isBanned` | boolean | Whether the logged-in user is banned from this group | `false` | -| `conversationId` | string | Conversation ID for this group | `"group_group_1748350143247"` | -| `createdAt` | number | Unix timestamp when group was created | `1748350143` | -| `updatedAt` | number | Unix timestamp of last update | `1768888876` | -| `description` | string | Group description (if set) | `"Testing group for QA users"` | -| `icon` | string | URL to group icon image (if set) | `"https://images.unsplash.com/..."` | - - - ### 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. - -```javascript -let limit = 30; -let groupsRequest = new CometChat.GroupsRequestBuilder() + +```typescript +let limit: number = 30; +let groupsRequest: CometChat.GroupsRequest = new CometChat.GroupsRequestBuilder() .setLimit(limit) .joinedOnly(true) .build(); @@ -148,49 +107,29 @@ let groupsRequest = new CometChat.GroupsRequestBuilder() - -```typescript -let limit: number = 30; -let groupsRequest: CometChat.GroupsRequest = - new CometChat.GroupsRequestBuilder().setLimit(limit).joinedOnly(true).build(); + +```javascript +let limit = 30; +let groupsRequest = new CometChat.GroupsRequestBuilder() + .setLimit(limit) + .joinedOnly(true) + .build(); ``` - -**On Success** — `fetchNext()` with `joinedOnly(true)` returns groups the user has joined, with additional fields: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `guid` | string | Unique identifier of the group | `"tg1"` | -| `name` | string | Display name of the group | `"Touring Group"` | -| `type` | string | Group type (public, private, password) | `"public"` | -| `owner` | string | UID of the group owner | `"app_system"` | -| `membersCount` | number | Total number of members in the group | `2` | -| `hasJoined` | boolean | Whether the logged-in user has joined this group | `true` | -| `isBanned` | boolean | Whether the logged-in user is banned from this group | `false` | -| `scope` | string | User's scope/role in the group (participant, admin, moderator) | `"participant"` | -| `joinedAt` | number | Unix timestamp when user joined the group | `1771829827` | -| `onlineMembersCount` | number | Number of online members in the group | `2` | -| `conversationId` | string | Conversation ID for this group | `"group_tg1"` | -| `createdAt` | number | Unix timestamp when group was created | `1771829812` | -| `updatedAt` | number | Unix timestamp of last update | `1771829832` | -| `icon` | string | URL to group icon image (if set) | `"https://static.vecteezy.com/..."` | - - - ### 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. - -```javascript -let limit = 30; -let tags = ["tag1", "tag2"]; -let groupsRequest = new CometChat.GroupsRequestBuilder() + +```typescript +let limit: number = 30; +let tags: Array = ["tag1", "tag2"]; +let groupsRequest: CometChat.GroupsRequest = new CometChat.GroupsRequestBuilder() .setLimit(limit) .setTags(tags) .build(); @@ -198,122 +137,91 @@ let groupsRequest = new CometChat.GroupsRequestBuilder() - -```typescript -let limit: number = 30; -let tags: Array = ["tag1", "tag2"]; -let groupsRequest: CometChat.GroupsRequest = - new CometChat.GroupsRequestBuilder().setLimit(limit).setTags(tags).build(); + +```javascript +let limit = 30; +let tags = ["tag1", "tag2"]; +let groupsRequest = new CometChat.GroupsRequestBuilder() + .setLimit(limit) + .setTags(tags) + .build(); ``` - -**On Success** — `fetchNext()` with tags filter returns groups matching the specified tags: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `guid` | string | Unique identifier of the group | `"group_1748264644578"` | -| `name` | string | Display name of the group | `"Password123NameChangedAgain"` | -| `type` | string | Group type (public, private, password) | `"password"` | -| `owner` | string | UID of the group owner | `"123456"` | -| `membersCount` | number | Total number of members in the group | `2` | -| `hasJoined` | boolean | Whether the logged-in user has joined this group | `false` | -| `isBanned` | boolean | Whether the logged-in user is banned from this group | `false` | -| `conversationId` | string | Conversation ID for this group | `"group_group_1748264644578"` | -| `createdAt` | number | Unix timestamp when group was created | `1748264644` | -| `updatedAt` | number | Unix timestamp of last update | `1768888876` | -| `updatedBy` | string | UID of user who last updated the group | `"123456"` | - - - ### 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. - -```javascript -let limit = 30; -let groupsRequest = new CometChat.GroupsRequestBuilder() + +```typescript +let limit: number = 30; +let groupsRequest: CometChat.GroupsRequest = new CometChat.GroupsRequestBuilder() .setLimit(limit) .withTags(true) .build(); ``` - - -```typescript -let limit: number = 30; -let groupsRequest: CometChat.GroupsRequest = - new CometChat.GroupsRequestBuilder().setLimit(limit).withTags(true).build(); + +```javascript +let limit = 30; +let groupsRequest = new CometChat.GroupsRequestBuilder() + .setLimit(limit) + .withTags(true) + .build(); ``` - - -**On Success** — `fetchNext()` with `withTags(true)` returns groups including the `tags` field: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `guid` | string | Unique identifier of the group | `"courses"` | -| `name` | string | Display name of the group | `"Courses"` | -| `type` | string | Group type (public, private, password) | `"public"` | -| `owner` | string | UID of the group owner | `"app_system"` | -| `membersCount` | number | Total number of members in the group | `4` | -| `hasJoined` | boolean | Whether the logged-in user has joined this group | `false` | -| `isBanned` | boolean | Whether the logged-in user is banned from this group | `false` | -| `tags` | array | Tags associated with the group | `["courses"]` | -| `conversationId` | string | Conversation ID for this group | `"group_courses"` | -| `createdAt` | number | Unix timestamp when group was created | `1764919309` | -| `updatedAt` | number | Unix timestamp of last update | `1764929127` | +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. +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| tags | `getTags()` | `string[]` | Tags associated with the group | -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. +After configuring the builder, call `build()` to get the `GroupsRequest` object, then call `fetchNext()` to retrieve groups. -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. + - -```javascript -let limit = 30; -let groupsRequest = new CometChat.GroupsRequestBuilder() + +```typescript +let limit: number = 30; +let groupsRequest: CometChat.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); + (groupList: CometChat.Group[]) => { + console.log("Groups list fetched successfully", groupList); + }, (error: CometChat.CometChatException) => { + console.log("Groups list fetching failed with error", error); } ); ``` - -```typescript -let limit: number = 30; -let groupsRequest: CometChat.GroupsRequest = - new CometChat.GroupsRequestBuilder().setLimit(limit).build(); + +```javascript +let limit = 30; +let groupsRequest = new CometChat.GroupsRequestBuilder() + .setLimit(limit) + .build(); groupsRequest.fetchNext().then( - (groupList: CometChat.Group[]) => { - console.log("Groups list fetched successfully", groupList); - }, - (error: CometChat.CometChatException) => { - console.log("Groups list fetching failed with error", error); - } +groupList => { + console.log("Groups list fetched successfully", groupList); +}, error => { + console.log("Groups list fetching failed with error", error); +} ); ``` @@ -321,104 +229,77 @@ groupsRequest.fetchNext().then( - -**On Success** — `fetchNext()` returns an array of `Group` objects. See the filter-specific Response accordions above for field details based on your query configuration. - - +The `fetchNext()` method returns an array of [`Group`](/sdk/reference/entities#group) objects. ## 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. - -```javascript -var GUID = "GUID"; + +```typescript +const GUID: string = "GUID"; CometChat.getGroup(GUID).then( - (group) => { - console.log("Group details fetched successfully:", group); - }, - (error) => { - console.log("Group details fetching failed with exception:", error); + (group: CometChat.Group) => { + console.log("Group details fetched successfully:", group); + }, (error: CometChat.CometChatException) => { + console.log("Group details fetching failed with exception:", error); } ); ``` - -```typescript -var GUID: string = "GUID"; + +```javascript +const GUID = "GUID"; CometChat.getGroup(GUID).then( - (group: CometChat.Group) => { - console.log("Group details fetched successfully:", group); - }, - (error: CometChat.CometChatException) => { - console.log("Group details fetching failed with exception:", error); - } -); +group => { + console.log("Group details fetched successfully:", group); +}, error => { + console.log("Group details fetching failed with exception:", error); +} +); ``` -| Parameter | Description | -| --------- | ------------------------------------------------------------ | -| `GUID` | The GUID of the group for whom the details are to be fetched | - - -**On Success** — `getGroup()` returns a `Group` object: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `guid` | string | Unique identifier of the group | `"007007"` | -| `name` | string | Display name of the group | `"Bond"` | -| `type` | string | Group type (public, private, password) | `"public"` | -| `owner` | string | UID of the group owner | `"user-b"` | -| `membersCount` | number | Total number of members in the group | `5` | -| `hasJoined` | boolean | Whether the logged-in user has joined this group | `false` | -| `isBanned` | boolean | Whether the logged-in user is banned from this group | `false` | -| `conversationId` | string | Conversation ID for this group | `"group_007007"` | -| `createdAt` | number | Unix timestamp when group was created | `1760001806` | -| `updatedAt` | number | Unix timestamp of last update | `1768398330` | - - +| Parameter | Description | +| --------- | ------------------------------ | +| `GUID` | The GUID of the group to fetch | -It returns `Group` object containing the details of the group. +The method returns a [`Group`](/sdk/reference/entities#group) object. -## 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. - -```javascript -let guids = ["cometchat-guid-1"]; + +```typescript +let guids: String[] = ["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); + (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); } ); ``` - -```typescript -let guids: String[] = ["cometchat-guid-1"]; + +```javascript +let guids = ["cometchat-guid-1"]; CometChat.getOnlineGroupMemberCount(guids).then( - (groupMemberCount: number) => { - console.log("Total online user for specified groups:", groupMemberCount); - }, - (error: CometChat.CometChatException) => { - console.log("Online group member count fetching failed with error:", error); - } +groupMemberCount => { + console.log("Total online user for specified groups:", groupMemberCount); +}, error => { + console.log("Online group member count fetching failed with error:", error); +} ); ``` @@ -426,62 +307,19 @@ CometChat.getOnlineGroupMemberCount(guids).then( - -**On Success** — `getOnlineGroupMemberCount()` returns an object with GUID as key and online count as value: +Returns an object with GUIDs as keys and online member counts as values. -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `[GUID]` | number | Online member count for the specified group | `0` | - -Example: `{"tg1": 2}` - - - -This method returns a JSON Object with the GUID as the key and the online member count for that group as the value. - -## Best Practices - - - - Always use `fetchNext()` with a reasonable `setLimit()` value (e.g., 20-30) rather than fetching all groups at once. This improves performance and reduces memory usage. - - - The `GroupsRequest` object maintains an internal cursor. Creating a new instance resets the cursor, causing the same page to be fetched repeatedly. Reuse the same instance across `fetchNext()` calls. - - - When displaying "My Groups" in your UI, use `joinedOnly(true)` to fetch only groups the user belongs to, rather than filtering the full list client-side. - - - -## Troubleshooting - - - - Private groups are only returned if the logged-in user is a member. This is by design — use `joinedOnly(true)` to see all groups the user has access to, including private ones. - - - Verify the logged-in user session is active. Also check if filters like `setTags` or `setSearchKeyword` are too restrictive. Try removing filters to confirm groups exist. - - - Ensure the GUID exists in your CometChat app. GUIDs are case-sensitive — double-check the exact GUID string. - - +`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. --- ## Next Steps - + Create public, private, or password-protected groups - - Join public or password-protected groups - - - Manage members, roles, and permissions within groups - - - Send text, media, and custom messages to groups + + Fetch and filter members of a specific group - \ No newline at end of file + diff --git a/sdk/react-native/retrieve-users.mdx b/sdk/react-native/retrieve-users.mdx index 73a1601ff..776f0f5b8 100644 --- a/sdk/react-native/retrieve-users.mdx +++ b/sdk/react-native/retrieve-users.mdx @@ -1,45 +1,46 @@ --- title: "Retrieve Users" -description: "Fetch user lists, search users, get logged-in user details, and retrieve online user counts using the CometChat React Native SDK." +sidebarTitle: "Retrieve Users" +description: "Fetch, filter, search, and sort users using the CometChat React Native SDK. Includes pagination, role-based filtering, tag support, and online user counts." --- - -**Quick Reference** - Fetch users: + ```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(); -// Fetch user list -const usersRequest = new CometChat.UsersRequestBuilder().setLimit(30).build(); -const users = await usersRequest.fetchNext(); - -// Get specific user -const user = await CometChat.getUser("UID"); +// Get online user count +const count = await CometChat.getOnlineUserCount(); ``` - + - -**Available via:** [SDK](/sdk/react-native/retrieve-users) | [REST API](/rest-api/users/list) | [UI Kits](/ui-kit/react-native/users) - +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. -## Retrieve Logged In User Details +### User Object Fields -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. +| 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 | - - -```javascript -var user = CometChat.getLoggedinUser().then( -user => { - console.log("user details:", { user }); -}, error => { - console.log("error getting details:", { error }); -} -); -``` +## Get the Logged-In User - +Use `getLoggedinUser()` to get the current user's details. Resolves with `null` if no user is logged in. + + ```typescript @@ -49,58 +50,41 @@ CometChat.getLoggedinUser().then( }, (error: CometChat.CometChatException) => { console.log("error getting details:", { error }); } -); +); ``` - - - -**On Success** — `getLoggedinUser()` returns a `User` object containing the logged-in user's details: - - - -**User Object:** + +```javascript +CometChat.getLoggedinUser().then( +user => { + console.log("user details:", { user }); +}, error => { + console.log("error getting details:", { error }); +} +); +``` -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"cometchat-uid-7"` | -| `name` | string | Display name of the user | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar image | `"https://artriva.com/media/k2/galleries/20/d.jpg"` | -| `authToken` | string | Authentication token for the user | `"cometchat-uid-7_177199269018c2c2995f0b69b3844abc9fdb9843"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771853565` | -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | -| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | -| `tags` | array | Tags associated with the user | `["vip"]` | + - + -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 ## 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 -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. - -```javascript -let limit = 30; -let usersRequest = new CometChat.UsersRequestBuilder() - .setLimit(limit) - .build(); -``` - - ```typescript @@ -112,43 +96,24 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() - - - -**On Success** — `fetchNext()` with basic limit returns an array of `User` objects: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"cometchat-uid-6"` | -| `name` | string | Display name of the user | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar image | `"https://media.istockphoto.com/id/1682296067/photo/happy-studio-portrait-or-professional-man-real-estate-agent-or-asian-businessman-smile-for.jpg?s=612x612&w=0&k=20&c=9zbG2-9fl741fbTWw5fNgcEEe4ll-JegrGlQQ6m54rg="` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1772163872` | -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | -| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | -| `conversationId` | string | Conversation ID between this user and logged-in user | `"cometchat-uid-6_user_cometchat-uid-7"` | - - - -### Set Search Keyword - -This method allows you to set the search string based on which the users are to be fetched. - - ```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; @@ -161,27 +126,26 @@ 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. - - ```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; @@ -196,97 +160,65 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() - - - -**On Success** — `fetchNext()` with search filter returns an array of `User` objects matching the search criteria: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"123456"` | -| `name` | string | Display name of the user | `"Farhan Ahmed"` | -| `avatar` | string | URL to user's avatar image | `"https://st2.depositphotos.com/38197074/46684/v/450/depositphotos_466848082-stock-illustration-initial-letter-vector-logo.jpg"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"extrarole"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1768988601` | -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `true` | -| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | -| `metadata` | object | Custom metadata attached to the user | `{"metadata": "something"}` | -| `blockedByMeAt` | number | Timestamp when blocked by current user | `1772164515` | -| `blockedAt` | number | Timestamp of block action | `1772164515` | -| `conversationId` | string | Conversation ID between this user and logged-in user | `"123456_user_cometchat-uid-7"` | - - - -### Set Status - -The status based on which the users 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 users. -* CometChat.USER\_STATUS.OFFLINE - will return the list of only offline users. - -If this parameter is not set, will return all the available users. - - ```javascript let limit = 30; +let searchKeyword = "super"; +let searchIn = ["uid", "name"]; let usersRequest = new CometChat.UsersRequestBuilder() .setLimit(limit) - .setStatus(CometChat.USER_STATUS.ONLINE) - .build() + .setSearchKeyword(searchKeyword) + .searchIn(searchIn) + .build(); ``` + + +### Set Status + +Filters users by online status: + +- `CometChat.USER_STATUS.ONLINE` — Only online users +- `CometChat.USER_STATUS.OFFLINE` — Only offline users + +If not set, returns all users. + + ```typescript let limit: number = 30; let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() .setLimit(limit) .setStatus(CometChat.USER_STATUS.ONLINE) - .build(); + .build(); ``` + + +```javascript +let limit = 30; +let usersRequest = new CometChat.UsersRequestBuilder() + .setLimit(limit) + .setStatus(CometChat.USER_STATUS.ONLINE) + .build(); +``` - -**On Success** — `fetchNext()` with status filter returns an array of `User` objects with matching status: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"cometchat-uid-6"` | -| `name` | string | Display name of the user | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar image | `"https://media.istockphoto.com/id/1682296067/photo/happy-studio-portrait-or-professional-man-real-estate-agent-or-asian-businessman-smile-for.jpg?s=612x612&w=0&k=20&c=9zbG2-9fl741fbTWw5fNgcEEe4ll-JegrGlQQ6m54rg="` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1772163872` | -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | -| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | -| `conversationId` | string | Conversation ID between this user and logged-in user | `"cometchat-uid-6_user_cometchat-uid-7"` | +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. +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(); -``` - - - ```typescript let limit: number = 30; @@ -298,43 +230,24 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() - - - -**On Success** — `fetchNext()` with `hideBlockedUsers(true)` returns an array of `User` objects excluding blocked users: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"cometchat-uid-6"` | -| `name` | string | Display name of the user | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar image | `"https://media.istockphoto.com/id/1682296067/photo/happy-studio-portrait-or-professional-man-real-estate-agent-or-asian-businessman-smile-for.jpg?s=612x612&w=0&k=20&c=9zbG2-9fl741fbTWw5fNgcEEe4ll-JegrGlQQ6m54rg="` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1772163872` | -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | -| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | -| `conversationId` | string | Conversation ID between this user and logged-in user | `"cometchat-uid-6_user_cometchat-uid-7"` | - - - -### Set Roles - -This method allows you to fetch the users based on multiple 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; @@ -344,45 +257,32 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() .setRoles(roles) .build(); ``` + + +```javascript +let limit = 30; +let roles = ["default", "dev"]; +let usersRequest = new CometChat.UsersRequestBuilder() + .setLimit(limit) + .setRoles(roles) + .build(); +``` - -**On Success** — `fetchNext()` with roles filter returns an array of `User` objects with matching roles: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"cometchat-uid-6"` | -| `name` | string | Display name of the user | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar image | `"https://media.istockphoto.com/id/1682296067/photo/happy-studio-portrait-or-professional-man-real-estate-agent-or-asian-businessman-smile-for.jpg?s=612x612&w=0&k=20&c=9zbG2-9fl741fbTWw5fNgcEEe4ll-JegrGlQQ6m54rg="` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1772163872` | -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | -| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | -| `conversationId` | string | Conversation ID between this user and logged-in user | `"cometchat-uid-6_user_cometchat-uid-7"` | +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. +When `true`, returns only friends of the logged-in user. - -```javascript -let limit = 30; -let usersRequest = new CometChat.UsersRequestBuilder() - .setLimit(limit) - .friendsOnly(true) - .build(); -``` - - - ```typescript let limit: number = 30; @@ -394,43 +294,24 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() - - - -**On Success** — `fetchNext()` with `friendsOnly(true)` returns an array of `User` objects who are friends: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"cometchat-uid-6"` | -| `name` | string | Display name of the user | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar image | `"https://media.istockphoto.com/id/1682296067/photo/happy-studio-portrait-or-professional-man-real-estate-agent-or-asian-businessman-smile-for.jpg?s=612x612&w=0&k=20&c=9zbG2-9fl741fbTWw5fNgcEEe4ll-JegrGlQQ6m54rg="` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1772163872` | -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | -| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | -| `conversationId` | string | Conversation ID between this user and logged-in user | `"cometchat-uid-6_user_cometchat-uid-7"` | - - - -### 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. - - ```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; @@ -440,44 +321,32 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() .setTags(tags) .build(); ``` + + +```javascript +let limit = 30; +let tags = ["tag1", "tag2"]; +let usersRequest = new CometChat.UsersRequestBuilder() + .setLimit(limit) + .setTags(tags) + .build(); +``` - -**On Success** — `fetchNext()` with tags filter returns an array of `User` objects with matching tags: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"user509"` | -| `name` | string | Display name of the user | `"again stokes"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1759921301` | -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | -| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | -| `conversationId` | string | Conversation ID between this user and logged-in user | `"cometchat-uid-7_user_user509"` | +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. +When `true`, includes tag data in the returned user objects. - -```javascript -let limit = 30; -let usersRequest = new CometChat.UsersRequestBuilder() - .setLimit(limit) - .withTags(true) - .build(); -``` - - - ```typescript let limit: number = 30; @@ -486,35 +355,43 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() .withTags(true) .build(); ``` + + +```javascript +let limit = 30; +let usersRequest = new CometChat.UsersRequestBuilder() + .setLimit(limit) + .withTags(true) + .build(); +``` - -**On Success** — `fetchNext()` with `withTags(true)` returns an array of `User` objects including the `tags` field: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"cometchat-uid-6"` | -| `name` | string | Display name of the user | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar image | `"https://media.istockphoto.com/id/1682296067/photo/happy-studio-portrait-or-professional-man-real-estate-agent-or-asian-businessman-smile-for.jpg?s=612x612&w=0&k=20&c=9zbG2-9fl741fbTWw5fNgcEEe4ll-JegrGlQQ6m54rg="` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1772163872` | -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | -| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | -| `tags` | array | Tags associated with the user | `["vip"]` | -| `conversationId` | string | Conversation ID between this user and logged-in user | `"cometchat-uid-6_user_cometchat-uid-7"` | +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. +Fetches specific users by their UIDs. Maximum 25 users per request. + +```typescript +let limit: number = 30; +let UIDs: Array = ["cometchat-uid-1", "cometchat-uid-2"]; +let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() + .setLimit(limit) + .setUIDs(UIDs) + .build(); +``` + + + ```javascript let limit = 30; @@ -527,47 +404,28 @@ let 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`. + + ```typescript let limit: number = 30; -let UIDs: Array = ["cometchat-uid-1", "cometchat-uid-2"]; +let sortBy: string = "name"; let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() .setLimit(limit) - .setUIDs(UIDs) - .build(); + .sortBy(sortBy) + .build(); ``` - - - -**On Success** — `fetchNext()` with UIDs filter returns an array of `User` objects for the specified UIDs: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"cometchat-uid-5"` | -| `name` | string | Display name of the user | `"John Paul"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-5.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"admin"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1772087140` | -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | -| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | -| `conversationId` | string | Conversation ID between this user and logged-in user | `"cometchat-uid-5_user_cometchat-uid-7"` | - - - -### 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`. - - ```javascript let limit = 30; -let UIDs = ["cometchat-uid-1", "cometchat-uid-2"]; let sortBy = "name"; let usersRequest = new CometChat.UsersRequestBuilder() .setLimit(limit) @@ -577,47 +435,30 @@ 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) + .sortByOrder(sortOrder) .build(); ``` - - - -**On Success** — `fetchNext()` with `sortBy("name")` returns an array of `User` objects sorted by name: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"1"` | -| `name` | string | Display name of the user | `"1"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1770017972` | -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | -| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | -| `conversationId` | string | Conversation ID between this user and logged-in user | `"1_user_cometchat-uid-7"` | - - - -### 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. - - ```javascript let limit = 30; -let sortByOrder = "desc"; -let usersReques = new CometChat.UsersRequestBuilder() +let sortOrder = "desc"; +let usersRequest = new CometChat.UsersRequestBuilder() .setLimit(limit) .sortByOrder(sortOrder) .build(); @@ -625,48 +466,35 @@ 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); + } +); ``` - - - -**On Success** — `fetchNext()` with `sortByOrder("desc")` returns an array of `User` objects in descending order: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"voip3"` | -| `name` | string | Display name of the user | `"voip3"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1770193733` | -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | -| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | -| `conversationId` | string | Conversation ID between this user and logged-in user | `"cometchat-uid-7_user_voip3"` | - - - -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. - - ```javascript -var limit = 30; -var usersRequest = new CometChat.UsersRequestBuilder() - .setLimit(limit) - .build(); +const limit = 30; +const usersRequest = new CometChat.UsersRequestBuilder() +.setLimit(limit) +.build(); usersRequest.fetchNext().then( userList => { @@ -679,57 +507,29 @@ userList => { + + +The `fetchNext()` method returns an array of [`User`](/sdk/reference/entities#user) objects. + +## Retrieve Particular User Details + +Use `getUser()` to fetch a specific user's details by UID. + + ```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); +let UID: string = "UID"; +CometChat.getUser(UID).then( + (user: CometChat.User) => { + console.log("User details fetched for user:", user); }, (error: CometChat.CometChatException) => { - console.log("User list fetching failed with error:", error); + console.log("User details fetching failed with error:", error); } ); ``` - - - -**On Success** — `fetchNext()` returns an array of `User` objects: - - - -**User Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"cometchat-uid-6"` | -| `name` | string | Display name of the user | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar image | `"https://media.istockphoto.com/id/1682296067/photo/happy-studio-portrait-or-professional-man-real-estate-agent-or-asian-businessman-smile-for.jpg?s=612x612&w=0&k=20&c=9zbG2-9fl741fbTWw5fNgcEEe4ll-JegrGlQQ6m54rg="` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1772163872` | -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | -| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | -| `conversationId` | string | Conversation ID between this user and logged-in user | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `tags` | array | Tags associated with the user (when `withTags(true)`) | `["vip"]` | -| `metadata` | object | Custom metadata attached to the user (if set) | `{"metadata": "something"}` | -| `blockedByMeAt` | number | Timestamp when blocked by current user (if blocked) | `1772164515` | -| `blockedAt` | number | Timestamp of block action (if blocked) | `1772164515` | - - - -## Retrieve Particular User Details - -To get the information of a user, you can use the `getUser()` method. - - ```javascript let UID = "UID"; @@ -744,56 +544,32 @@ user => { + + +| Parameter | Description | +| --------- | ----------- | +| UID | The UID of the user to fetch | + +It returns the [`User`](/sdk/reference/entities#user) object containing the details of the user. + +## Get Online User Count + +Use `getOnlineUserCount()` to get the total number of online users in your app. + + ```typescript -let UID: string = "UID"; -CometChat.getUser(UID).then( - (user: CometChat.User) => { - console.log("User details fetched for user:", user); +CometChat.getOnlineUserCount().then( + (userCount: number) => { + console.log("Total online user count:", userCount); }, (error: CometChat.CometChatException) => { - console.log("User details fetching failed with error:", error); + console.log("Online user count fetching failed with error:", error); } ); ``` - - -The `getUser()` method takes the following parameters: - -| Parameter | Description | -| --------- | ---------------------------------------------------------- | -| UID | The UID of the user for whom the details are to be fetched | - - -**On Success** — `getUser()` returns a `User` object containing the requested user's details: - - - -**User Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"cometchat-uid-5"` | -| `name` | string | Display name of the user | `"John Paul"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-5.webp"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"admin"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1772087140` | -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | -| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | -| `tags` | array | Tags associated with the user | `["tag1"]` | -| `conversationId` | string | Conversation ID between this user and logged-in user | `"cometchat-uid-5_user_cometchat-uid-7"` | - - - -## Get online user count - -To get the total count of online users for your app, you can use the `getOnlineUserCount()` method. - - ```javascript CometChat.getOnlineUserCount().then( @@ -807,79 +583,25 @@ userCount => { - -```typescript -CometChat.getOnlineUserCount().then( - (userCount: number) => { - console.log("Total online user count:", userCount); - }, (error: CometChat.CometChatException) => { - console.log("Online user count fetching failed with error:", error); - } -); -``` - - - - -**On Success** — `getOnlineUserCount()` returns an object with the count: - - - -**Response Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `count` | number | Total number of online users | `2` | - - - -This method returns the total online user count for your app. - -## Best Practices - - - - Always use `fetchNext()` with a reasonable `setLimit()` value (e.g., 20-30) rather than fetching all users at once. This improves performance and reduces memory usage. - - - The `UsersRequest` object maintains an internal cursor. Creating a new instance resets the cursor, causing the same page to be fetched repeatedly. Reuse the same instance across `fetchNext()` calls. - - - Use the builder's filter methods (`setSearchKeyword`, `setStatus`, `setRoles`, `setTags`) to narrow results at the API level rather than fetching all users and filtering in your app. - - - -## Troubleshooting - - - - Verify the logged-in user session is active. Also check if filters like `setRoles`, `setTags`, or `setStatus` are too restrictive. Try removing filters to confirm users exist. - - - Ensure the UID exists in your CometChat app. UIDs are case-sensitive — double-check the exact UID string. - - - By default, blocked users are included in the user list. Use `hideBlockedUsers(true)` in the `UsersRequestBuilder` to exclude them. - - +Returns the total online user count as a number. --- ## Next Steps - - Create, update, and delete users in CometChat + + Track and subscribe to user online/offline status - Block and unblock users, retrieve blocked user lists + Block and unblock users from your application - - Track online/offline status of users in real time + + Create, update, and delete users programmatically - Fetch conversation lists with last message and unread counts + Fetch conversation lists for your chat UI - \ No newline at end of file + diff --git a/sdk/react-native/send-message.mdx b/sdk/react-native/send-message.mdx index 1dc1683e6..1f6560c68 100644 --- a/sdk/react-native/send-message.mdx +++ b/sdk/react-native/send-message.mdx @@ -1,2239 +1,889 @@ --- -title: "Send A Message" +title: "Send Messages" +sidebarTitle: "Send Messages" description: "Send text, media, and custom messages to users and groups using the CometChat React Native SDK." --- - -**Quick Reference** - Send a text message: + -```javascript -// Send text to a user -const textMessage = new CometChat.TextMessage("UID", "Hello!", CometChat.RECEIVER_TYPE.USER); -const sent = await CometChat.sendMessage(textMessage); - -// Send media to a group -const mediaMessage = new CometChat.MediaMessage("GUID", file, CometChat.MESSAGE_TYPE.IMAGE, CometChat.RECEIVER_TYPE.GROUP); -const sentMedia = await CometChat.sendMediaMessage(mediaMessage); -``` - +| Field | Value | +| --- | --- | +| 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` | +| Prerequisites | SDK initialized, user logged in | - -**Available via:** [SDK](/sdk/react-native/send-message) | [REST API](/rest-api/messages/send-message) | [UI Kits](/ui-kit/react-native/core-features#instant-messaging) - - -Using CometChat, you can send three types of messages: + -1. [Text Message](#text-message) is the most common and standard message type. -2. [Media Message](#media-message), for sending photos, videos and files. -3. [Custom Message](#custom-message), for sending completely custom data using JSON structures. -4. [Interactive Message](/sdk/react-native/interactive-messages) for sending end-user interactive messages of type form, card and custom interactive. +CometChat supports three types of messages: -You can also send metadata along with a text, media or custom message. Think, for example, if you 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 -*In other words, as a sender, 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. - -### 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. +Send a text message using `CometChat.sendMessage()` with a [`TextMessage`](/sdk/reference/messages#textmessage) object. - - ```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 | Required | -| ---------------- | ------------------------------------------------------------------------------------------- | -------- | -| **receiverID** | `UID` of the user or `GUID` of the group receiving the message | YES | -| **messageText** | The text message | YES | -| **receiverType** | The type of the receiver- `CometChat.RECEIVER_TYPE.USER` or `CometChat.RECEIVER_TYPE.GROUP` | YES | - -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: - - - -**TextMessage Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25182"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `text` | string | Message text content | `"Hello world!"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `receiverId` | string | UID of the receiver | `"cometchat-uid-3"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `sentAt` | number | Unix timestamp when sent | `1771320772` | -| `updatedAt` | number | Unix timestamp of last update | `1771320772` | -| `sender` | object | Sender user details | [See below ↓](#send-text-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#send-text-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#send-text-data-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether logged-in user is mentioned | `false` | -| `metadata` | object | Custom metadata | `{"@injected": {"extensions": {"link-preview": {"links": []}}}}` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the sender | `"cometchat-uid-2"` | -| `name` | string | Display name | `"George Alan"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | Online status | `"online"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771320632` | -| `hasBlockedMe` | boolean | Whether sender has blocked logged-in user | `false` | -| `blockedByMe` | boolean | Whether logged-in user has blocked sender | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-3"` | -| `name` | string | Display name | `"Nancy Grace"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | Online status | `"online"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771320647` | -| `hasBlockedMe` | boolean | Whether receiver has blocked logged-in user | `false` | -| `blockedByMe` | boolean | Whether logged-in user has blocked receiver | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Hello world!"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_13-..."` | -| `entities` | object | Sender and receiver entities | [See below ↓](#send-text-data-entities-object) | -| `metadata` | object | Injected metadata from extensions | `{"@injected": {"extensions": {"link-preview": {"links": []}}}}` | -| `moderation` | object | Moderation status | [See below ↓](#send-text-data-moderation-object) | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#send-text-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#send-text-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | Sender user details | [See below ↓](#send-text-data-entities-sender-entity-object) | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier | `"cometchat-uid-2"` | -| `name` | string | Display name | `"George Alan"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | Online status | `"online"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771320632` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | Receiver user details | [See below ↓](#send-text-data-entities-receiver-entity-object) | - ---- - - - -**`data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier | `"cometchat-uid-3"` | -| `name` | string | Display name | `"Nancy Grace"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | Online status | `"online"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771320647` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.moderation` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `status` | string | Moderation status | `"pending"` | - - + +```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); + } +); +``` + -### Set Quoted Message Id + +```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); + } +); +``` -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. +Alternatively, you can use the `async/await` syntax: - - - ```javascript - textMessage.setQuotedMessageId(10); - ``` - - - ```typescript - textMessage.setQuotedMessageId(10); - ``` - - +```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); +} +``` + + + +```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); + } +); +``` + -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 = "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); + } +); +``` + - - - ```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: +The [`TextMessage`](/sdk/reference/messages#textmessage) class constructor takes the following parameters: -| Parameter | Description | Required | -| ---------------- | -------------------------------------------------------------------------------------------- | -------- | -| **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 | +| Parameter | Description | Required | +| --- | --- | --- | +| `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 | -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, `sendMessage()` returns a [`TextMessage`](/sdk/reference/messages#textmessage) | [`MediaMessage`](/sdk/reference/messages#mediamessage) | [`CustomMessage`](/sdk/reference/messages#custommessage) | [`BaseMessage`](/sdk/reference/messages#basemessage) object containing 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: +Send images, videos, audio, or files using `CometChat.sendMediaMessage()`. -### 1. By Providing the 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 -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. +### Upload a File -**Getting the file Object:** You can use different React Native packages for sending media messages. We demonstrate how to send images using CometChat. +Get the file using a React Native image picker and pass it to [`MediaMessage`](/sdk/reference/messages#mediamessage): ```javascript ImagePicker.showImagePicker(options, (response) => { -if (response.didCancel) { - console.log('User cancelled photo picker'); -} else if (response.error) { - console.log('ImagePicker Error: ', response.error); -} else if (response.customButton) { - console.log('User tapped custom button: ', response.customButton); -} else { - console.log('ImagePicker Response: ', response); - if (Platform.OS === 'ios' && response.fileName != undefined) { - var ext = response.fileName.split('.')[1].toLowerCase(); - var type = this.getMimeType(ext); - var name = response.fileName; - } else { - var type = response.type; - var name = 'Camera_001.jpeg'; - } - var file = { - name: Platform.OS === "android" ? response.fileName : name, - type: Platform.OS === "android" ? response.type : type, + if (response.didCancel || response.error) return; + + const file = { + name: Platform.OS === "android" ? response.fileName : response.fileName || "Camera_001.jpeg", + type: response.type, uri: Platform.OS === "android" ? response.uri : response.uri.replace("file://", ""), - } - console.log('file: ', file); - this.setState({ mediaMsg: file }) -} + }; + // Use this file object in MediaMessage }); -} ``` - - ```javascript - let receiverID = "UID"; - let messageType = CometChat.MESSAGE_TYPE.FILE; - let receiverType = CometChat.RECEIVER_TYPE.USER; - let mediaMessage = new CometChat.MediaMessage( - receiverID, - this.state.mediaMsg, - 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, - this.state.mediaMsg, - 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, - this.state.mediaMsg, - 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, - this.state.mediaMsg, - 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 | Required | -| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | -| **receiverId** | The `UID` or `GUID` of the recipient. | YES | -| **file** | The file object to be sent | YES | -| **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` | YES | -| **receiverType** | The type of the receiver to whom the message is to be sent.
`1. CometChat.RECEIVER_TYPE.USER`
`2. CometChat.RECEIVER_TYPE.GROUP` | YES | - - -**On Success** — Returns a MediaMessage object: - - - -**MediaMessage Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25189"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `type` | string | Media type | `"image"` | -| `category` | string | Message category | `"message"` | -| `receiverId` | string | UID of the receiver | `"cometchat-uid-3"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `sentAt` | number | Unix timestamp when sent | `1771323061` | -| `updatedAt` | number | Unix timestamp of last update | `1771323061` | -| `sender` | object | Sender user details | [See below ↓](#send-media-file-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#send-media-file-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#send-media-file-data-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether logged-in user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the sender | `"cometchat-uid-2"` | -| `name` | string | Display name | `"George Alan"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | Online status | `"online"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771323060` | -| `hasBlockedMe` | boolean | Whether sender has blocked logged-in user | `false` | -| `blockedByMe` | boolean | Whether logged-in user has blocked sender | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-3"` | -| `name` | string | Display name | `"Nancy Grace"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | Online status | `"offline"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771322968` | -| `hasBlockedMe` | boolean | Whether receiver has blocked logged-in user | `false` | -| `blockedByMe` | boolean | Whether logged-in user has blocked receiver | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `type` | string | Media type | `"image"` | -| `category` | string | Message category | `"message"` | -| `url` | string | URL to the uploaded media file | `"https://data-in.cometchat.io/.../c35f9734fc20947b7456bbea68126f99.png"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `attachments` | array | Media attachments | [See below ↓](#send-media-file-data-attachments-array) | -| `entities` | object | Sender and receiver entities | [See below ↓](#send-media-file-data-entities-object) | -| `moderation` | object | Moderation status | `{"status": "pending"}` | - ---- - - - -**`data.attachments` Array (per item):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `url` | string | URL to the attachment | `"https://data-in.cometchat.io/.../c35f9734fc20947b7456bbea68126f99.png"` | -| `name` | string | File name | `"1770616246_260562078_3832605b5c8a337ac672b0c60933d208.png"` | -| `mimeType` | string | MIME type | `"image/png"` | -| `extension` | string | File extension | `"png"` | -| `size` | number | File size in bytes | `2295572` | - ---- - - - -**`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 | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | Sender user details | [See below ↓](#send-media-file-data-entities-sender-entity-object) | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier | `"cometchat-uid-2"` | -| `name` | string | Display name | `"George Alan"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | Online status | `"online"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771323060` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | Receiver user details | [See below ↓](#send-media-file-data-entities-receiver-entity-object) | - ---- - - - -**`data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier | `"cometchat-uid-3"` | -| `name` | string | Display name | `"Nancy Grace"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | Online status | `"offline"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771322968` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `tags` | array | User tags | `[]` | - - + +```typescript +let receiverID: string = "UID", + messageType: string = CometChat.MESSAGE_TYPE.IMAGE, + receiverType: string = CometChat.RECEIVER_TYPE.USER, + 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); + } +); +``` + -### 2. By Providing the URL of the File + +```javascript +let receiverID = "UID"; +let messageType = CometChat.MESSAGE_TYPE.IMAGE; +let 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); + } +); +``` + + + +```typescript +let receiverID: string = "GUID", + messageType: string = CometChat.MESSAGE_TYPE.IMAGE, + receiverType: string = CometChat.RECEIVER_TYPE.GROUP, + 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); + } +); +``` + -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 = "GUID"; +let messageType = CometChat.MESSAGE_TYPE.IMAGE; +let receiverType = CometChat.RECEIVER_TYPE.GROUP; +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 = "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. - - -**On Success** — Returns a MediaMessage object: - - - -**MediaMessage Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25189"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `type` | string | Media type | `"image"` | -| `category` | string | Message category | `"message"` | -| `receiverId` | string | UID of the receiver | `"cometchat-uid-3"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `sentAt` | number | Unix timestamp when sent | `1771323061` | -| `updatedAt` | number | Unix timestamp of last update | `1771323061` | -| `sender` | object | Sender user details | [See below ↓](#send-media-url-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#send-media-url-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#send-media-url-data-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether logged-in user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the sender | `"cometchat-uid-2"` | -| `name` | string | Display name | `"George Alan"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | Online status | `"online"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771323060` | -| `hasBlockedMe` | boolean | Whether sender has blocked logged-in user | `false` | -| `blockedByMe` | boolean | Whether logged-in user has blocked sender | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-3"` | -| `name` | string | Display name | `"Nancy Grace"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | Online status | `"offline"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771322968` | -| `hasBlockedMe` | boolean | Whether receiver has blocked logged-in user | `false` | -| `blockedByMe` | boolean | Whether logged-in user has blocked receiver | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `type` | string | Media type | `"image"` | -| `category` | string | Message category | `"message"` | -| `url` | string | URL to the media file | `"https://data-in.cometchat.io/.../c35f9734fc20947b7456bbea68126f99.png"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `attachments` | array | Media attachments | [See below ↓](#send-media-url-data-attachments-array) | -| `entities` | object | Sender and receiver entities | [See below ↓](#send-media-url-data-entities-object) | -| `moderation` | object | Moderation status | `{"status": "pending"}` | - ---- - - +### Send a URL -**`data.attachments` Array (per item):** +Send media hosted on your server or cloud storage using the [`Attachment`](/sdk/reference/auxiliary#attachment) class: -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `url` | string | URL to the attachment | `"https://pngimg.com/uploads/mario/mario_PNG125.png"` | -| `name` | string | File name | `"mario"` | -| `mimeType` | string | MIME type | `"image/png"` | -| `extension` | string | File extension | `"png"` | - ---- - - + + +```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", +}; -**`data.entities` Object:** +let attachment: CometChat.Attachment = new CometChat.Attachment(file); +mediaMessage.setAttachment(attachment); -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#send-media-url-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#send-media-url-data-entities-receiver-object) | +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 = "UID"; +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); -**`data.entities.sender` Object:** +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.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", +}; -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | Sender user details | [See below ↓](#send-media-url-data-entities-sender-entity-object) | +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); + } +); +``` + - + +```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", +}; -**`data.entities.sender.entity` Object:** +let attachment = new CometChat.Attachment(file); +mediaMessage.setAttachment(attachment); -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier | `"cometchat-uid-2"` | -| `name` | string | Display name | `"George Alan"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | Online status | `"online"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771323060` | -| `tags` | array | User tags | `[]` | +CometChat.sendMediaMessage(mediaMessage).then( + (message) => { + console.log("Media message sent successfully", message); + }, + (error) => { + console.log("Media message sending failed with error", error); + } +); +``` + ---- + - +The [`MediaMessage`](/sdk/reference/messages#mediamessage) class constructor takes the following parameters: -**`data.entities.receiver` Object:** +| Parameter | Description | Required | +| --- | --- | --- | +| `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 | -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | Receiver user details | [See below ↓](#send-media-url-data-entities-receiver-entity-object) | +On success, `sendMediaMessage()` returns a [`MediaMessage`](/sdk/reference/messages#mediamessage) object. ---- +### Add Caption - +Add text along with the media: -**`data.entities.receiver.entity` Object:** +```javascript +mediaMessage.setCaption("Check out this photo!"); +``` -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier | `"cometchat-uid-3"` | -| `name` | string | Display name | `"Nancy Grace"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | Online status | `"offline"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771322968` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `tags` | array | User tags | `[]` | +### Add Metadata and Tags - +```javascript +mediaMessage.setMetadata({ location: "Paris" }); +mediaMessage.setTags(["vacation"]); +mediaMessage.setQuotedMessageId(10); +``` ## 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: +Starting version 3.0.9 & above, the SDK supports sending multiple attachments in a single media message. There are two ways: -### 1. By Providing an Array of Files +1. **By providing an array of files** — Pass an array of file objects and CometChat uploads them automatically. +2. **By providing URLs** — Use the [`Attachment`](/sdk/reference/auxiliary#attachment) class with multiple URLs. -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. +### Upload Multiple Files -**Getting the file Object:** You can use different React Native packages for sending media messages. We demonstrate how to send images using CometChat. + + +```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 options = { - selectionLimit: 0 -}; -ImagePicker.showImagePicker(options, (response) => { -if (response.didCancel) { - console.log('User cancelled photo picker'); -} else if (response.error) { - console.log('ImagePicker Error: ', response.error); -} else if (response.customButton) { - console.log('User tapped custom button: ', response.customButton); -} else { - console.log('ImagePicker Response: ', response); - let files = response.assets; - let allFiles = []; - if (files && files.length > 0) { - console.log("files", files); - files.forEach(file => { - if (Platform.OS === 'ios' && file.fileName !== undefined) { - name = file.fileName; - type = file.type; - } else { - type = file.type; - name = 'Camera_001.jpeg'; - } - if (mediaType == 'video') { - type = 'video/quicktime'; - name = 'Camera_002.mov'; - } - let tempFile = { - name: name, - type: - Platform.OS === 'android' && mediaType != 'video' - ? file.type - : type, - uri: - Platform.OS === 'android' - ? file.uri - : file.uri.replace('file://', ''), - size: file.fileSize - }; - allFiles.push(tempFile); - }); - this.props.sendMediaMessage( - allFiles, - mediaType === 'photo' - ? CometChat.MESSAGE_TYPE.IMAGE - : CometChat.MESSAGE_TYPE.VIDEO, - ); +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 = "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); + } +); +``` + - - - ```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); - } - ); - ``` - - - ```javascript - let receiverID = "GUID"; - let messageType = CometChat.MESSAGE_TYPE.FILE; - let receiverType = CometChat.RECEIVER_TYPE.GROUP; - let mediaMessage = new CometChat.MediaMessage( - receiverID, - this.state.mediaMsg, - 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, - this.state.mediaMsg, - 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, - this.state.mediaMsg, - 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 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 = "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); + } +); +``` + - - - ```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); - } - ); - ``` - - - ```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 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); - } - ); - ``` - - - ```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 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); - } - ); - ``` - -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 attachments: - - - -**MediaMessage Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25189"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `type` | string | Media type | `"image"` | -| `category` | string | Message category | `"message"` | -| `receiverId` | string | UID of the receiver | `"cometchat-uid-3"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `sentAt` | number | Unix timestamp when sent | `1771323061` | -| `updatedAt` | number | Unix timestamp of last update | `1771323061` | -| `sender` | object | Sender user details | [See below ↓](#send-multi-attach-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#send-multi-attach-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#send-multi-attach-data-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether logged-in user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the sender | `"cometchat-uid-2"` | -| `name` | string | Display name | `"George Alan"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | Online status | `"online"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771323060` | -| `hasBlockedMe` | boolean | Whether sender has blocked logged-in user | `false` | -| `blockedByMe` | boolean | Whether logged-in user has blocked sender | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-3"` | -| `name` | string | Display name | `"Nancy Grace"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | Online status | `"offline"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771322968` | -| `hasBlockedMe` | boolean | Whether receiver has blocked logged-in user | `false` | -| `blockedByMe` | boolean | Whether logged-in user has blocked receiver | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `type` | string | Media type | `"image"` | -| `category` | string | Message category | `"message"` | -| `url` | string | URL to the primary media file | `"https://data-in.cometchat.io/.../c35f9734fc20947b7456bbea68126f99.png"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `attachments` | array | Media attachments | [See below ↓](#send-multi-attach-data-attachments-array) | -| `entities` | object | Sender and receiver entities | [See below ↓](#send-multi-attach-data-entities-object) | -| `moderation` | object | Moderation status | `{"status": "pending"}` | - ---- - - +### Send Multiple URLs -**`data.attachments` Array (per item):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `url` | string | URL to the attachment | `"https://pngimg.com/uploads/mario/mario_PNG125.png"` | -| `name` | string | File name | `"mario"` | -| `mimeType` | string | MIME type | `"image/png"` | -| `extension` | string | File extension | `"png"` | - -Example with multiple attachments: -- Attachment 1: `{"name": "mario", "extension": "png", "mimeType": "image/png", "url": "https://pngimg.com/uploads/mario/mario_PNG125.png"}` -- Attachment 2: `{"name": "jaguar", "extension": "png", "mimeType": "image/png", "url": "https://pngimg.com/uploads/jaguar/jaguar_PNG20759.png"}` - ---- - - + + +```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", +}; -**`data.entities` Object:** +let attachment2: Object = { + name: "jaguar", + extension: "png", + mimeType: "image/png", + url: "https://pngimg.com/uploads/jaguar/jaguar_PNG20759.png", +}; -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#send-multi-attach-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#send-multi-attach-data-entities-receiver-object) | +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); + } +); +``` + -**`data.entities.sender` Object:** + +```javascript +let receiverID = "UID"; +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", +}; -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | Sender user details | [See below ↓](#send-multi-attach-data-entities-sender-entity-object) | +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); -**`data.entities.sender.entity` Object:** +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.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", +}; -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier | `"cometchat-uid-2"` | -| `name` | string | Display name | `"George Alan"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | Online status | `"online"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771323060` | -| `tags` | array | User tags | `[]` | +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); -**`data.entities.receiver` Object:** +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); + } +); +``` + -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | Receiver user details | [See below ↓](#send-multi-attach-data-entities-receiver-entity-object) | + +```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)); -**`data.entities.receiver.entity` Object:** +mediaMessage.setAttachments(attachments); -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier | `"cometchat-uid-3"` | -| `name` | string | Display name | `"Nancy Grace"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | Online status | `"offline"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771322968` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `tags` | array | User tags | `[]` | +CometChat.sendMediaMessage(mediaMessage).then( + (message) => { + console.log("Media message sent successfully", message); + }, + (error) => { + console.log("Media message sending failed with error", error); + } +); +``` + - +
## 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. - -In order to send a custom message, you need to use the `sendCustomMessage()` method. The `sendCustomMessage()` method takes an object of the `CustomMessage` which can be obtained using the below constructor. +Send structured data that doesn't fit text or media categories — like location coordinates, polls, or game moves. - - ```javascript - let customMessage = new CometChat.CustomMessage( - receiverID, - receiverType, - customType, - customData - ); - ``` - - - ```typescript - let customMessage: CometChat.CustomMessage = new CometChat.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: - -| Parameter | Description | -| -------------- | ------------------------------------------------------------------------------ | -| `receiverId` | The unique ID of the user or group to which the message is to be sent | -| `receiverType` | Type of the receiver i.e user or group | -| `customType` | Custom message type that you need to set | -| `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. - -### 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. + +```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 - let tags = ["starredMessage"]; - - customMessage.setTags(tags); - ``` - - - ```typescript - let tags: Array = ["starredMessage"]; - - customMessage.setTags(tags); - ``` - - + +```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); + } +); +``` + + + +```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); + } +); +``` + -Once the object of `CustomMessage` class is ready you can send the custom message using the `sendCustomMessage()` method. + +```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); + } +); +``` + - - - ```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); - } - ); - ``` - - - ```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 - 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 successfully", message); - }, - (error: CometChat.CometChatException) => { - console.log("custom message sending failed with error", error); - } - ); - ``` - -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. - - -**On Success** — Returns a CustomMessage object: - - - -**CustomMessage Object:** +The [`CustomMessage`](/sdk/reference/messages#custommessage) class constructor takes the following parameters: -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25190"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `type` | string | Custom message type | `"location"` | -| `category` | string | Message category | `"custom"` | -| `receiverId` | string | UID of the receiver | `"cometchat-uid-3"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `sentAt` | number | Unix timestamp when sent | `1771323234` | -| `updatedAt` | number | Unix timestamp of last update | `1771323234` | -| `customData` | object | Custom payload data | [See below ↓](#send-custom-customdata-object) | -| `sender` | object | Sender user details | [See below ↓](#send-custom-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#send-custom-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#send-custom-data-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether logged-in user is mentioned | `false` | -| `metadata` | object | Custom metadata | `{"@injected": {"extensions": {"link-preview": {"links": []}}}}` | +| Parameter | Description | Required | +| --- | --- | --- | +| `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 | ---- - - - -**`customData` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `latitude` | string | Latitude coordinate | `"50.6192171633316"` | -| `longitude` | string | Longitude coordinate | `"-72.68182268750002"` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the sender | `"cometchat-uid-2"` | -| `name` | string | Display name | `"George Alan"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | Online status | `"online"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771323089` | -| `hasBlockedMe` | boolean | Whether sender has blocked logged-in user | `false` | -| `blockedByMe` | boolean | Whether logged-in user has blocked sender | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- +On success, `sendCustomMessage()` returns a [`CustomMessage`](/sdk/reference/messages#custommessage) object. - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-3"` | -| `name` | string | Display name | `"Nancy Grace"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | Online status | `"offline"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771322968` | -| `hasBlockedMe` | boolean | Whether receiver has blocked logged-in user | `false` | -| `blockedByMe` | boolean | Whether logged-in user has blocked receiver | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Fallback text | `"Sent a custom message"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `customData` | object | Custom payload data | `{"latitude": "50.6192171633316", "longitude": "-72.68182268750002"}` | -| `entities` | object | Sender and receiver entities | [See below ↓](#send-custom-data-entities-object) | -| `metadata` | object | Injected metadata from extensions | `{"@injected": {"extensions": {"link-preview": {"links": []}}}}` | -| `moderation` | object | Moderation status | `{"status": "pending"}` | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#send-custom-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#send-custom-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** +### Add Tags -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | Sender user details | [See below ↓](#send-custom-data-entities-sender-entity-object) | +```javascript +customMessage.setTags(["starredMessage"]); +``` ---- +### Quote a Message - +```javascript +customMessage.setQuotedMessageId(10); +``` -**`data.entities.sender.entity` Object:** +### Control Conversation Update -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier | `"cometchat-uid-2"` | -| `name` | string | Display name | `"George Alan"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | -| `status` | string | Online status | `"online"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771323089` | -| `tags` | array | User tags | `[]` | +By default, custom messages update the conversation's last message. To prevent this: ---- +```javascript +customMessage.shouldUpdateConversation(false); +``` - +### Custom Notification Text -**`data.entities.receiver` Object:** +Set custom text for push, email, and SMS notifications: -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | Receiver user details | [See below ↓](#send-custom-data-entities-receiver-entity-object) | +```javascript +customMessage.setConversationText("Shared a location"); +``` --- - - -**`data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier | `"cometchat-uid-3"` | -| `name` | string | Display name | `"Nancy Grace"` | -| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | -| `status` | string | Online status | `"offline"` | -| `role` | string | User role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1771322968` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | -| `tags` | array | User tags | `[]` | - - - -### 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 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. - - - - ```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 - ); - - 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( - 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); - } - ); - ``` - - - ```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); - } - ); - ``` - - - ```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); - } - ); - ``` - - - -### Custom Notification Body - -*How can I customize the notification body of a 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 the CustomMessage 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 - ); - - 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); - } - ); - ``` - - - ```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 notification body"); - CometChat.sendCustomMessage(customMessage).then( - (message) => { - console.log("custom message sent successfully", message); - }, - (error) => { - console.log("custom message sending failed with 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.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); - } - ); - ``` - - - ```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); - } - ); - ``` - - - - -It is also possible to send interactive messages from CometChat. To learn more, see [Interactive Messages](/sdk/react-native/interactive-messages). - - - - - - Use appropriate message types (`TEXT`, `IMAGE`, `VIDEO`, `AUDIO`, `FILE`) for media messages - - Add metadata to messages when you need to pass additional context (e.g., location, user preferences) - - Use tags to categorize messages for easier filtering and retrieval - - Set `shouldUpdateConversation(false)` for background or system-level custom messages that shouldn't appear in conversation lists - - Use `setConversationText()` to provide meaningful notification text for custom messages - - - - **Message not sending:** Ensure the user is logged in and CometChat is initialized - - **Media upload fails:** Check file size limits and ensure the file object has correct `name`, `type`, and `uri` properties - - **Custom message not appearing:** Verify the receiver UID/GUID is correct and the receiver type matches - - **Notifications not showing custom text:** Make sure `setConversationText()` is called before sending the message - - - ## Next Steps - Listen for real-time messages and fetch missed messages + Listen for incoming messages in real-time - + Edit previously sent messages - - Send forms, cards, and custom interactive messages - - - Show real-time typing status in conversations + + Delete sent messages diff --git a/sdk/react-native/session-timeout.mdx b/sdk/react-native/session-timeout.mdx index 5de98331f..5e5e02678 100644 --- a/sdk/react-native/session-timeout.mdx +++ b/sdk/react-native/session-timeout.mdx @@ -1,50 +1,117 @@ --- -title: "Session Timeout Flow" -description: "Understand how CometChat Calls SDK handles idle session timeouts — automatic call termination, user prompts, and the onSessionTimeout event (v4.2.0+)." +title: "Session Timeout" +sidebarTitle: "Session Timeout" +description: "Handle idle session timeouts in CometChat calls, including automatic termination, user prompts, and the onSessionTimeout event." --- -Available since v4.2.0 + -## Overview +```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(); +``` -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: +- Default idle timeout: 180 seconds (3 minutes) alone in a session +- Warning dialog appears 60 seconds before auto-termination +- Listen for `onSessionTimeout` to handle auto-termination +- Customize with `setIdleTimeoutPeriod(seconds)` in CallSettings (v4.2.0+) + -1. After 120 seconds of being alone in the session, the participant will see a dialog box +*Available since v4.2.0* -2. This dialog provides options to either: +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. - * Stay in the call - * Leave immediately +## How It Works -3. If no action is taken within the next 60 seconds, the call will automatically end +When a participant is alone in a session: -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. +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 - -You can customize the idle timeout period using `setIdleTimeoutPeriod(seconds)` in the `CallSettingsBuilder`. See the [Call Session settings](/sdk/react-native/direct-call#call-settings) for details. - - -### Session Timeout Flow +The default timeout is 180 seconds (3 minutes). - - -The `onSessionTimeout` event is triggered when the call automatically terminates due to session timeout, as illustrated in the diagram above. - - +## Configuration + +Set a custom timeout period using `setIdleTimeoutPeriod()` in `CallSettingsBuilder`. The warning dialog will always appear 60 seconds before the configured timeout. + + + +```typescript +const callSettings: any = new CometChatCalls.CallSettingsBuilder() + .setIdleTimeoutPeriod(300) // 5 minutes + .enableDefaultLayout(true) + .setCallListener(callListener) + .build(); +``` + + +```javascript +const callSettings = new CometChatCalls.CallSettingsBuilder() + .setIdleTimeoutPeriod(300) // 5 minutes + .enableDefaultLayout(true) + .setCallListener(callListener) + .build(); +``` + + + +## Handling the Timeout Event + +Listen for `onSessionTimeout` in your `OngoingCallListener` to clean up when the call auto-terminates: + + + +```typescript +const callListener = new CometChatCalls.OngoingCallListener({ + onSessionTimeout: () => { + console.log("Session timed out due to inactivity"); + CometChatCalls.endSession(); + // Close the calling screen + }, + // ... other listeners +}); +``` + + +```javascript +const callListener = new CometChatCalls.OngoingCallListener({ + onSessionTimeout: () => { + console.log("Session timed out due to inactivity"); + CometChatCalls.endSession(); + // Close the calling screen + }, + // ... other listeners +}); +``` + + + +See [Call Session — Call Listeners](/sdk/react-native/direct-call#call-listeners) for the full list of events. --- ## Next Steps + + Implement ringing call flows with accept/reject functionality + - Start and manage call sessions with full configuration options + Configure call settings including idle timeout - - Implement a complete calling experience with incoming and outgoing call UI + + Implement calling without the Chat SDK - \ No newline at end of file + diff --git a/sdk/react-native/setup-sdk.mdx b/sdk/react-native/setup-sdk.mdx index 4e42fc67b..c4a02bcb1 100644 --- a/sdk/react-native/setup-sdk.mdx +++ b/sdk/react-native/setup-sdk.mdx @@ -1,117 +1,105 @@ --- title: "Setup" -description: "Install the CometChat React Native SDK, configure dependencies and permissions, and initialize CometChat in your application." +sidebarTitle: "Setup" +description: "Install, configure, and initialize the CometChat React Native SDK in your application." --- - -**Quick Reference** - Install and initialize in three steps: +{/* TL;DR for Agents and Quick Reference */} + -```javascript -// 1. Install dependencies -// npm i @cometchat/chat-sdk-react-native @react-native-async-storage/async-storage +```bash +npm install @cometchat/chat-sdk-react-native @react-native-async-storage/async-storage +``` -// 2. Initialize CometChat (call once on app startup) -const appSetting = new CometChat.AppSettingsBuilder() +```typescript +import { CometChat } from "@cometchat/chat-sdk-react-native"; + +const appSettings: CometChat.AppSettings = new CometChat.AppSettingsBuilder() + .setRegion("APP_REGION") .subscribePresenceForAllUsers() - .setRegion("REGION") .autoEstablishSocketConnection(true) .build(); -await CometChat.init("APP_ID", appSetting); -``` - - -**Migrating from v3 to v4?** - -Skip the create new app step. Your existing v3 app can be migrated to v4. +await CometChat.init("APP_ID", appSettings); +await CometChat.login("UID", "AUTH_KEY"); // dev only +``` -Follow the steps mentioned in the [Add the CometChat Dependency](#add-the-cometchat-dependency) section below to upgrade to the latest version of v4. - +**Prerequisites:** npm 8+, Node.js 16+, React Native 0.63+, credentials from [CometChat Dashboard](https://app.cometchat.com) + -## Get your Application Keys +## Prerequisites -[Signup for CometChat](https://app.cometchat.com) and then: +| Requirement | Version | +|-------------|---------| +| npm | 8.x or above | +| Node.js | 16 or above | +| React Native | 0.63 or above | +| Android minSdkVersion | 24 | +| iOS | 11.0 | -1. Create a new app -2. Head over to the **API & Auth Keys** section and note the **Auth Key**, **App ID** & **Region** +Get your credentials from the [CometChat Dashboard](https://app.cometchat.com): +- App ID +- Region +- Auth Key (for development) -## Add the CometChat Dependency + +**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. + -Install the package as an NPM module: + +**Migrating from v3 to v4?** Your existing v3 app can be migrated directly — no need to create a new app. Follow the installation steps below to upgrade to the latest version of v4. + - - - ```bash - npm i @cometchat/chat-sdk-react-native - ``` - - - ```bash - yarn add @cometchat/chat-sdk-react-native - ``` - - +## Installation -In order to integrate the CometChat React Native SDK, you need to install one more dependency. +```bash +npm install @cometchat/chat-sdk-react-native +``` -### Async-Storage +The React Native SDK requires `async-storage` as a peer dependency: - - - ```bash - npm install @react-native-async-storage/async-storage - ``` - - - ```bash - yarn add @react-native-async-storage/async-storage - ``` - - +```bash +npm install @react-native-async-storage/async-storage +``` -**Android only:** `@react-native-async-storage/async-storage` v3 ships a local Maven artifact. Add this to your `android/build.gradle` or the Android build will fail. - +**Android only:** `@react-native-async-storage/async-storage` v3 ships a local Maven artifact. Add this to your `android/build.gradle` or the Android build will fail: - - - ```gradle - allprojects { - repositories { - google() - mavenCentral() - maven { - url = uri(project(":react-native-async-storage_async-storage").file("local_repo")) - } +```gradle +allprojects { + repositories { + google() + mavenCentral() + maven { + url = uri(project(":react-native-async-storage_async-storage").file("local_repo")) } } - ``` - - +} +``` + -## Calling Component Configuration +### Voice & Video Calling (Optional) -For `@cometchat/calls-sdk-react-native`, please make sure you add the following additional dependencies & permissions. +v2.4+ onwards, calling functionality lives in a separate package. Install it only if you need voice/video: + +```bash +npm install @cometchat/calls-sdk-react-native +``` -### Required Dependencies +Required additional dependencies for calling: ```json { - "@cometchat/chat-sdk-react-native": "^4.0.18", - "@react-native-async-storage/async-storage": "^1.23.1", - "@react-native-community/netinfo": "^11.3.1", // for react-native 0.63 & above - "@react-native-community/netinfo": "6.1.0", // for react-native below 0.63 + "@react-native-community/netinfo": "^11.3.1", "react-native-background-timer": "^2.4.1", "react-native-callstats": "^3.73.7", "react-native-webrtc": "^1.106.1" } ``` -### Permissions - - Add the following permissions to your `AndroidManifest.xml`: + Add permissions to your `AndroidManifest.xml`: ```xml @@ -120,24 +108,8 @@ For `@cometchat/calls-sdk-react-native`, please make sure you add the following ``` - - - Add the following keys to your `Info.plist`: - - ```xml - NSCameraUsageDescription - This is for Camera permission - NSMicrophoneUsageDescription - This is for Mic permission - ``` - - -### Platform-Specific Configuration - - - - Go to the `./android` folder and open the **project level** `build.gradle` file. Add all repository URLs in the `repositories` block under the `allprojects` section. + Add the CometChat Maven repository to your project-level `build.gradle`: ```gradle allprojects { @@ -149,7 +121,7 @@ For `@cometchat/calls-sdk-react-native`, please make sure you add the following } ``` - Also in the same file, in the `buildscript` section in the `ext` block, make sure you have set **minSdkVersion** to **24**. + Ensure `minSdkVersion` is set to **24** in the `buildscript` ext block: ```gradle buildscript { @@ -161,53 +133,64 @@ For `@cometchat/calls-sdk-react-native`, please make sure you add the following } } ``` - - - Please update the minimum target version in the Podfile. Go to the `./ios` folder and open the Podfile. In the Podfile, update the platform version to `11.0`: + + + Add keys to your `Info.plist`: - ```ruby - platform :ios, '11.0' + ```xml + NSCameraUsageDescription + This is for Camera permission + NSMicrophoneUsageDescription + This is for Mic permission ``` - Open the `ios/App` folder and run `pod install`. This will create an `App.xcworkspace` file. Open this and run the app. - - + Update the minimum platform version in your Podfile: -## Initialize CometChat + ```ruby + platform :ios, '11.0' + ``` -The `init()` method initializes the settings required for CometChat. The `init()` method takes the below parameters: + Then run `pod install` in the `ios` directory. + +
-| Parameter | Description | -| ------------ | ---------------------------------------------------------------------------------------------------------- | -| `appID` | Your CometChat App ID | -| `appSettings`| An object of the `AppSettings` class created using the `AppSettingsBuilder` class. The region is mandatory. | +## Initialization -The `AppSettings` class allows you to configure the following settings: +The `init()` method initializes the SDK and must be called before any other CometChat method. Call it once at app startup, typically in `App.tsx`. -| Setting | Description | -|---------|-------------| -| **Region** | The region where your app was created (mandatory). Set using `setRegion()` | -| **Presence Subscription** | Represents the subscription type for user presence (real-time online/offline status). See [User Presence](/sdk/react-native/user-presence) | -| **autoEstablishSocketConnection(boolean)** | When set to `true`, the SDK manages the web-socket connection internally. When set to `false`, you manage the connection manually. Default: `true`. See [Managing Web-Socket connections manually](/sdk/react-native/managing-web-sockets-connections-manually) | -| **overrideAdminHost(adminHost: string)** | Uses a custom admin URL instead of the default. Used for dedicated CometChat deployments | -| **overrideClientHost(clientHost: string)** | Uses a custom client URL instead of the default. Used for dedicated CometChat deployments | + + + ```typescript + let appID: string = "APP_ID"; + let region: string = "APP_REGION"; -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 `App.tsx` file. + 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 = "REGION"; + let region = "APP_REGION"; - // Build app settings with presence subscription and auto socket connection let appSetting = new CometChat.AppSettingsBuilder() .subscribePresenceForAllUsers() .setRegion(region) .autoEstablishSocketConnection(true) .build(); - // Initialize CometChat — call once on app startup CometChat.init(appID, appSetting).then( () => { console.log("Initialization completed successfully"); @@ -217,82 +200,102 @@ You need to call `init()` before calling any other method from CometChat. We sug } ); ``` - - - ```typescript - let appID: string = "APP_ID", - region: string = "APP_REGION", - // Build app settings with presence subscription and auto socket connection - let appSetting: CometChat.AppSettings = new CometChat.AppSettingsBuilder() + Alternatively, you can use the `async/await` syntax: + + ```javascript + let appID = "APP_ID"; + let region = "APP_REGION"; + + let appSetting = new CometChat.AppSettingsBuilder() .subscribePresenceForAllUsers() .setRegion(region) .autoEstablishSocketConnection(true) .build(); - // Initialize CometChat — call once on app startup - CometChat.init(appID, appSetting).then( - (initialized: boolean) => { - console.log("Initialization completed successfully", initialized); - }, - (error: CometChat.CometChatException) => { - console.log("Initialization failed with error:", error); - } - ); + try { + await CometChat.init(appID, appSetting); + console.log("Initialization completed successfully"); + } catch (error) { + console.log("Initialization failed with error:", error); + } ``` +Replace `APP_ID` and `APP_REGION` with your credentials from the [Dashboard](https://app.cometchat.com). + -Make sure you replace the `APP_ID` with your CometChat **App ID** and `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. - -**On Success** — `init()` returns `true` and logs: -``` -Initialization completed successfully +### 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`) | 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) | — | + +### 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(); ``` -**On Failure** — Returns a CometChatException object: +See [User Presence](/sdk/react-native/user-presence) for more details. -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `code` | string | Error code | `"ERR_INVALID_APP_ID"` | -| `name` | string | Error name | `"Invalid App ID"` | -| `message` | string | Error description | `"The App ID provided is incorrect. Please verify your App ID from the CometChat Dashboard."` | -| `details` | object | Additional error details | `{}` | +### WebSocket Connection - +By default, the SDK manages WebSocket connections automatically. To manage them manually: - - - - Always call `init()` before any other CometChat method - - Call `init()` on app startup, preferably in `App.tsx` - - Use `autoEstablishSocketConnection(true)` unless you have a specific need to manage connections manually - - For dedicated deployments, use `overrideAdminHost` and `overrideClientHost` to point to your custom URLs - - - - **Initialization fails:** Verify your App ID and Region are correct - - **Network errors:** Check internet connectivity and firewall settings - - **Calling not working:** Verify all calling dependencies are installed and permissions are granted - - **iOS build fails:** Run `pod install` in the `ios` directory after adding dependencies - - **Android build fails:** Ensure `minSdkVersion` is set to 24 and the CometChat Maven repository is added - - +```javascript +let appSetting = new CometChat.AppSettingsBuilder() + .setRegion(region) + .autoEstablishSocketConnection(false) + .build(); +``` + +See [Managing WebSocket Connections](/sdk/react-native/managing-web-sockets-connections-manually) for manual control. + +--- ## Next Steps - Register and log in users with Auth Key or Auth Token - - - Understand the fundamental building blocks of CometChat - - - Start sending text, media, and custom messages + Log in users with Auth Key or Auth Token - - Add pre-built UI components to your app + + Send your first message diff --git a/sdk/react-native/standalone-calling.mdx b/sdk/react-native/standalone-calling.mdx index e4bc97276..746a77a48 100644 --- a/sdk/react-native/standalone-calling.mdx +++ b/sdk/react-native/standalone-calling.mdx @@ -1,32 +1,40 @@ --- title: "Standalone Calling" -description: "Implement audio and video calling using only the CometChat Calls SDK, without the Chat SDK — ideal for apps that need calling without full chat infrastructure." +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." --- - -**Quick Reference** - Generate token and start a standalone call session: + ```javascript -// Generate call token (auth token from REST API, not Chat SDK) +let sessionId = "SESSION_ID"; +let userAuthToken = "USER_AUTH_TOKEN"; +let callListener = { + onCallEnded: () => console.log("Call ended"), + onUserJoined: (user) => console.log("User joined:", user), + onUserLeft: (user) => console.log("User left:", user), +}; + +// Generate call token (requires user auth token from REST API) const callToken = await CometChatCalls.generateToken(sessionId, userAuthToken); -// Configure and render +// Start call session const callSettings = new CometChatCalls.CallSettingsBuilder() .enableDefaultLayout(true) .setIsAudioOnlyCall(false) + .setCallEventListener(callListener) .build(); -// -``` - +// - -**Available via:** SDK | UI Kits - +// End session +CometChatCalls.endSession(); +``` + -## Overview +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. -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. +The key difference from the regular [Call Session](/sdk/react-native/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/react-native/calling-setup). @@ -45,10 +53,6 @@ You can obtain the auth token using one of these REST API endpoints: - [Create Auth Token](/rest-api/auth-tokens/create) — Creates a new auth token for a user - [Get Auth Token](/rest-api/auth-tokens/get) — Retrieves an existing auth token - -Auth tokens grant access to call sessions on behalf of a user. Never expose auth tokens in client-side code in production. Use a secure backend to generate and deliver tokens to your app. - - For testing or POC purposes, you can create an auth token directly from the [CometChat Dashboard](https://app.cometchat.com). Navigate to **Users & Groups → Users**, select a user, and click **+ Create Auth Token**. @@ -64,42 +68,51 @@ 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: GenerateToken) => { console.log("Call token generated:", callToken.token); // Use callToken to start the session }, - (error) => { + (error: CometChat.CometChatException) => { 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: GenerateToken) => { + (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 +const sessionId = "UNIQUE_SESSION_ID"; +const userAuthToken = "USER_AUTH_TOKEN"; + +try { + const callToken = await CometChatCalls.generateToken(sessionId, userAuthToken); + console.log("Call token generated:", callToken.token); +} catch (error) { + console.log("Token generation failed:", error); +} +``` + | Parameter | Description | @@ -107,35 +120,23 @@ 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. | - -**On Success** — `generateToken()` returns a `GenerateToken` object containing the session ID and JWT token: - - - -**GenerateToken Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sessionId` | string | Unique identifier for the call session | `"v1.in.2748663902141719.1772095292a49c6a5198e07f9096447749e87124204d95cfc8"` | -| `token` | string | JWT token for authenticating the call session | `"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6ImNjcHJvX2p3dF9yczI1Nl9rZXkxIn0..."` | - - +The `Promise` resolves with an object containing a `token` property (string) that you pass to the `CometChatCalls.Component`. ## Start Call Session Use the `CometChatCalls.Component` to render the call UI. This component requires a call token (generated in the previous step) and a `CallSettings` object that configures the call UI and behavior. - -```javascript + +```typescript const callListener = new CometChatCalls.OngoingCallListener({ - onUserJoined: (user) => { + onUserJoined: (user: CometChat.User) => { console.log("User joined:", user); }, - onUserLeft: (user) => { + onUserLeft: (user: CometChat.User) => { console.log("User left:", user); }, - onUserListUpdated: (userList) => { + onUserListUpdated: (userList: CometChat.User[]) => { console.log("User list updated:", userList); }, onCallEnded: () => { @@ -148,16 +149,16 @@ const callListener = new CometChatCalls.OngoingCallListener({ CometChatCalls.endSession(); // Close calling screen }, - onError: (error) => { + onError: (error: CometChat.CometChatException) => { console.log("Call error:", error); }, - onAudioModesUpdated: (audioModes) => { + onAudioModesUpdated: (audioModes: string[]) => { console.log("Audio modes updated:", audioModes); }, - onCallSwitchedToVideo: (event) => { + onCallSwitchedToVideo: (event: any) => { console.log("Call switched to video:", event); }, - onUserMuted: (event) => { + onUserMuted: (event: any) => { console.log("User muted:", event); }, onSessionTimeout: () => { @@ -178,19 +179,18 @@ return ( ); ``` - - -```typescript + +```javascript const callListener = new CometChatCalls.OngoingCallListener({ - onUserJoined: (user: CometChat.User) => { + onUserJoined: (user) => { console.log("User joined:", user); }, - onUserLeft: (user: CometChat.User) => { + onUserLeft: (user) => { console.log("User left:", user); }, - onUserListUpdated: (userList: CometChat.User[]) => { + onUserListUpdated: (userList) => { console.log("User list updated:", userList); }, onCallEnded: () => { @@ -203,16 +203,16 @@ const callListener = new CometChatCalls.OngoingCallListener({ CometChatCalls.endSession(); // Close calling screen }, - onError: (error: CometChat.CometChatException) => { + onError: (error) => { console.log("Call error:", error); }, - onAudioModesUpdated: (audioModes: string[]) => { + onAudioModesUpdated: (audioModes) => { console.log("Audio modes updated:", audioModes); }, - onCallSwitchedToVideo: (event: any) => { + onCallSwitchedToVideo: (event) => { console.log("Call switched to video:", event); }, - onUserMuted: (event: any) => { + onUserMuted: (event) => { console.log("User muted:", event); }, onSessionTimeout: () => { @@ -233,14 +233,12 @@ return ( ); ``` - - | Parameter | Description | | -------------- | -------------------------------------------------------- | -| `callToken` | The `GenerateToken` object received from `generateToken()` onSuccess | +| `callToken` | The token received from `generateToken()` onSuccess | | `callSettings` | Object of `CallSettings` class configured via `CallSettingsBuilder` | ### Call Settings @@ -249,10 +247,10 @@ Configure the call experience using the following `CallSettingsBuilder` methods: | Method | Description | | ------ | ----------- | -| `enableDefaultLayout(boolean)` | Enables or disables the default call UI layout with built-in controls. `true` shows the default layout with end call, mute, video toggle buttons. `false` hides the button layout. Default: `true` | +| `enableDefaultLayout(boolean)` | Enables or disables the default call UI layout with built-in controls. `true` shows the default layout. `false` hides the button layout. Default: `true` | | `setIsAudioOnlyCall(boolean)` | Sets whether the call is audio-only or audio-video. `true` for audio-only, `false` for audio-video. Default: `false` | -| `setCallEventListener(OngoingCallListener)` | Sets the listener to receive call events. See [Call Listeners](#call-listeners) for available callbacks. | -| `setMode(string)` | Sets the call UI layout mode. Available: `CometChat.CALL_MODE.DEFAULT` (grid), `CometChat.CALL_MODE.SPOTLIGHT` (active speaker), `CometChat.CALL_MODE.SINGLE` (one participant). Default: `DEFAULT` | +| `setCallEventListener(OngoingCallListener)` | Sets the listener to receive call events. See [Call Listeners](#call-listeners). | +| `setMode(string)` | Sets the call UI layout mode. Available: `CometChat.CALL_MODE.DEFAULT`, `CometChat.CALL_MODE.SPOTLIGHT`, `CometChat.CALL_MODE.SINGLE`. Default: `DEFAULT` | | `setAvatarMode(string)` | Sets how avatars are displayed when video is off. Available: `circle`, `square`, `fullscreen`. Default: `circle` | | `setDefaultAudioMode(string)` | Sets the initial audio output device. Available: `SPEAKER`, `EARPIECE`, `BLUETOOTH`, `HEADPHONES` | | `startWithAudioMuted(boolean)` | Starts the call with the microphone muted. Default: `false` | @@ -268,6 +266,28 @@ Configure the call experience using the following `CallSettingsBuilder` methods: | `enableVideoTileDrag(boolean)` | Enables or disables drag functionality for video tiles in Spotlight mode. Default: `true` | | `setIdleTimeoutPeriod(number)` | Sets idle timeout in seconds. Warning appears 60 seconds before auto-termination. Default: `180` seconds. *v4.2.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 @@ -282,20 +302,24 @@ 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. + + - -```javascript + +```typescript useEffect(() => { - const listenerId = "UNIQUE_LISTENER_ID"; - + const listenerId: string = "UNIQUE_LISTENER_ID"; + CometChatCalls.addCallEventListener(listenerId, { - onUserJoined: (user) => { + onUserJoined: (user: CometChat.User) => { console.log("User joined:", user); }, - onUserLeft: (user) => { + onUserLeft: (user: CometChat.User) => { console.log("User left:", user); }, - onUserListUpdated: (userList) => { + onUserListUpdated: (userList: CometChat.User[]) => { console.log("User list updated:", userList); }, onCallEnded: () => { @@ -308,16 +332,16 @@ useEffect(() => { CometChatCalls.endSession(); // Close calling screen }, - onError: (error) => { + onError: (error: CometChat.CometChatException) => { console.log("Call error:", error); }, - onAudioModesUpdated: (audioModes) => { + onAudioModesUpdated: (audioModes: string[]) => { console.log("Audio modes updated:", audioModes); }, - onCallSwitchedToVideo: (event) => { + onCallSwitchedToVideo: (event: any) => { console.log("Call switched to video:", event); }, - onUserMuted: (event) => { + onUserMuted: (event: any) => { console.log("User muted:", event); }, onSessionTimeout: () => { @@ -329,22 +353,20 @@ useEffect(() => { return () => CometChatCalls.removeCallEventListener(listenerId); }, []); ``` - - - -```typescript + +```javascript useEffect(() => { - const listenerId: string = "UNIQUE_LISTENER_ID"; - + const listenerId = "UNIQUE_LISTENER_ID"; + CometChatCalls.addCallEventListener(listenerId, { - onUserJoined: (user: CometChat.User) => { + onUserJoined: (user) => { console.log("User joined:", user); }, - onUserLeft: (user: CometChat.User) => { + onUserLeft: (user) => { console.log("User left:", user); }, - onUserListUpdated: (userList: CometChat.User[]) => { + onUserListUpdated: (userList) => { console.log("User list updated:", userList); }, onCallEnded: () => { @@ -357,16 +379,16 @@ useEffect(() => { CometChatCalls.endSession(); // Close calling screen }, - onError: (error: CometChat.CometChatException) => { + onError: (error) => { console.log("Call error:", error); }, - onAudioModesUpdated: (audioModes: string[]) => { + onAudioModesUpdated: (audioModes) => { console.log("Audio modes updated:", audioModes); }, - onCallSwitchedToVideo: (event: any) => { + onCallSwitchedToVideo: (event) => { console.log("Call switched to video:", event); }, - onUserMuted: (event: any) => { + onUserMuted: (event) => { console.log("User muted:", event); }, onSessionTimeout: () => { @@ -378,148 +400,14 @@ useEffect(() => { return () => CometChatCalls.removeCallEventListener(listenerId); }, []); ``` - - - -Always remove call event listeners when the component unmounts using `CometChatCalls.removeCallEventListener(listenerId)`. Failing to remove listeners can cause memory leaks and duplicate event handling. - - ### 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.2.0+* | -| `onCallEndButtonPressed()` | Invoked when the local user taps 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). | -| `onAudioModesUpdated(audioModes)` | Invoked when available audio devices change (e.g., Bluetooth connected). | -| `onCallSwitchedToVideo(event)` | Invoked when an audio call is upgraded to a video call. | -| `onUserMuted(event)` | Invoked when a participant's mute state changes. | -| `onScreenShareStarted()` | Invoked when the local user starts sharing a screen. | -| `onScreenShareStopped()` | Invoked when the local user stops sharing a screen. | -| `onError(error)` | Invoked when an error occurs during the call session. | - - -**On Event** — `onUserJoined` returns a user object when a participant joins the call: - - - -**User Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"cometchat-uid-6"` | -| `name` | string | Display name of the user | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `id` | string | Internal session participant ID | `"cd530243"` | -| `joinedAt` | string | Unix timestamp when user joined (as string) | `"1772095303043"` | -| `isVideoMuted` | boolean | Whether user's video is muted | `true` | -| `isAudioMuted` | boolean | Whether user's audio is muted | `false` | -| `isLocalUser` | boolean | Whether this is the local user | `false` | - - +For the full list of callbacks, their descriptions, and parameter shapes, see the [`OngoingCallListener`](/sdk/react-native/all-real-time-listeners#ongoing-call-listener-calls-sdk) reference. - -**On Event** — `onUserLeft` returns a user object when a participant leaves the call: - - - -**User Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"cometchat-uid-6"` | -| `name` | string | Display name of the user | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `id` | string | Internal session participant ID | `"cd530243"` | -| `joinedAt` | string | Unix timestamp when user joined (as string) | `"1772095303043"` | -| `isVideoMuted` | boolean | Whether user's video was muted | `true` | -| `isAudioMuted` | boolean | Whether user's audio was muted | `false` | - - - - -**On Event** — `onUserListUpdated` returns an array of all current participants in the call: - - - -**User Array:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| (array) | array | Array of user objects | [See below ↓](#on-user-list-updated-user-object) | - - - -**User Object (each item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"cometchat-uid-7"` | -| `name` | string | Display name of the user | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | - - - - -**On Event** — `onAudioModesUpdated` returns an array of available audio output modes: - - - -**Audio Modes Array:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| (array) | array | Array of audio mode objects | [See below ↓](#on-audio-modes-updated-mode-object) | - - - -**Audio Mode Object (each item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `type` | string | Type of audio output device | `"SPEAKER"` | -| `selected` | boolean | Whether this mode is currently selected | `true` | - - - - -**On Event** — `onCallSwitchedToVideo` is invoked when an audio call is upgraded to video. This event may not include additional data. - - -## End Call Session - -To end the call session and release all media resources (camera, microphone, network connections), call `CometChatCalls.endSession()` in the `onCallEndButtonPressed()` callback. - - - -```javascript -onCallEndButtonPressed: () => { - CometChatCalls.endSession(); - // Close the calling screen -} -``` - - - - -```typescript -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. @@ -529,23 +417,19 @@ These methods can only be called when a call session is active. ### Switch Camera -Toggles between the front and rear camera during a video call. Useful for allowing users to switch their camera view without leaving the call. +Toggles between the front and rear camera during a video call. - -```javascript + +```typescript CometChatCalls.switchCamera(); ``` - - - -```typescript + +```javascript CometChatCalls.switchCamera(); ``` - - ### Mute Audio @@ -556,20 +440,16 @@ 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); ``` - - ### Pause Video @@ -580,20 +460,16 @@ 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); ``` - - ### Set Audio Mode @@ -607,20 +483,16 @@ Routes the audio output to a specific device. Use this to let users choose betwe - `CometChat.AUDIO_MODE.HEADPHONES` — Wired headphones - -```javascript + +```typescript CometChatCalls.setAudioMode(CometChat.AUDIO_MODE.EARPIECE); ``` - - - -```typescript + +```javascript CometChatCalls.setAudioMode(CometChat.AUDIO_MODE.EARPIECE); ``` - - ### Switch To Video Call @@ -628,20 +500,16 @@ CometChatCalls.setAudioMode(CometChat.AUDIO_MODE.EARPIECE); 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(); ``` - - ### Get Audio Output Modes @@ -649,136 +517,68 @@ CometChatCalls.switchToVideoCall(); Returns the list of available audio output devices. Use this to display audio options to the user and then set the selected mode using `setAudioMode()`. - -```javascript + +```typescript CometChatCalls.getAudioOutputModes().then( - (modes) => { + (modes: CometChat.AudioMode[]) => { console.log("Available audio modes:", modes); - // Each mode has: mode (string) and isSelected (boolean) }, - (error) => { + (error: CometChat.CometChatException) => { console.log("Failed to get audio modes:", error); } ); ``` - - - -```typescript + +```javascript CometChatCalls.getAudioOutputModes().then( - (modes: CometChat.AudioMode[]) => { + (modes) => { console.log("Available audio modes:", modes); - // Each mode has: mode (string) and isSelected (boolean) }, - (error: CometChat.CometChatException) => { + (error) => { console.log("Failed to get audio modes:", error); } ); ``` - - + +```javascript +try { + const modes = await CometChatCalls.getAudioOutputModes(); + console.log("Available audio modes:", modes); +} catch (error) { + console.log("Failed to get audio modes:", error); +} +``` + - -**On Success** — `getAudioOutputModes()` returns an object containing an array of available audio modes: - - - -**Response Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `modes` | array | Array of available audio output modes | [See below ↓](#get-audio-modes-mode-object) | - - - -**Mode Object (each item in `modes` array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `type` | string | Type of audio output device | `"SPEAKER"` | -| `selected` | boolean | Whether this mode is currently selected | `true` | - - - ### End Call 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(); ``` - - -## Best Practices - - - - Call tokens are session-specific and time-limited. Generate them right before starting the call session rather than caching them for extended periods. This ensures the token is fresh and reduces the chance of token expiry errors. - - - All participants who need to join the same call must use the same `sessionId` when generating their call tokens. Share this ID through your backend or signaling mechanism so both parties can join the same session. - - - Since standalone calling uses REST API auth tokens instead of the Chat SDK login flow, ensure tokens are generated server-side and delivered securely to the client. Never hardcode auth tokens in your app bundle. - - - Always remove call event listeners in your component's cleanup function (e.g., the return function of `useEffect`). Orphaned listeners can cause memory leaks, duplicate event handling, and unexpected behavior when navigating between screens. - - - The `CometChatCalls.Component` should be rendered inside a `View` with `height: '100%'`, `width: '100%'`, and `position: 'relative'`. This ensures the call UI fills the screen correctly and overlays render in the right position. - - - -## Troubleshooting - - - - Verify the auth token is valid and hasn't expired. Auth tokens obtained from the REST API or Dashboard have an expiry — generate a fresh one if needed. Also confirm the `sessionId` is a non-empty string. - - - Ensure the `CometChatCalls.Component` is wrapped in a `View` with explicit dimensions (`height: '100%'`, `width: '100%'`). Also confirm that both `callSettings` and `callToken` props are provided and not `null` or `undefined`. - - - Both participants must use the exact same `sessionId` when generating their call tokens. Double-check that the session ID is being shared correctly between devices. - - - Check that the listener is registered before the call session starts. If using `addCallEventListener`, ensure the `listenerId` is unique and hasn't been overwritten by another registration. Also verify that the Calls SDK has been initialized via `CometChatCalls.init()`. - - - Check device permissions for camera and microphone. On React Native, request `CAMERA` and `RECORD_AUDIO` permissions on Android, and add `NSCameraUsageDescription` and `NSMicrophoneUsageDescription` to `Info.plist` on iOS. - - - --- ## Next Steps - - Install dependencies, configure permissions, and initialize the Calls SDK + + Implement ringing call flows using the Chat SDK - Record call sessions for playback and compliance - - - Customize the main video container and participant tiles - - - Full call session management with the Chat SDK integration + Add call recording to your voice and video calls - \ No newline at end of file + diff --git a/sdk/react-native/threaded-messages.mdx b/sdk/react-native/threaded-messages.mdx index e3f99044d..7419f744b 100644 --- a/sdk/react-native/threaded-messages.mdx +++ b/sdk/react-native/threaded-messages.mdx @@ -1,74 +1,40 @@ --- title: "Threaded Messages" -description: "Send, receive, and fetch threaded messages (replies) in user and group conversations using the CometChat React Native SDK." +sidebarTitle: "Threaded Messages" +description: "Send, receive, and fetch threaded messages using the CometChat React Native SDK." --- {/* TL;DR for Agents and Quick Reference */} - -**Quick Reference** - Send a threaded message and fetch thread replies: + ```javascript -// Send a text message in a thread -let textMessage = new CometChat.TextMessage("UID", "Hello", CometChat.RECEIVER_TYPE.USER); -textMessage.setParentMessageId(100); -CometChat.sendMessage(textMessage).then( - message => console.log("Sent:", message), - err => console.log("Error:", err) -); - -// Fetch messages for a thread -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setLimit(30) - .setParentMessageId(100) - .build(); -messagesRequest.fetchPrevious().then( - messages => console.log("Thread messages:", messages), - error => console.log("Error:", error) -); +// 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 threadRequest = new CometChat.MessagesRequestBuilder() + .setParentMessageId(100).setLimit(30).build(); +const messages = await threadRequest.fetchPrevious(); + +// Exclude thread replies from main conversation +const mainRequest = new CometChat.MessagesRequestBuilder() + .setUID("UID").setLimit(30).hideReplies(true).build(); ``` - - - -**Available via:** [SDK](/sdk/react-native/threaded-messages) | [REST API](/rest-api/messages/list-threaded-messages) | [UI Kits](/ui-kit/react-native/core-features#threaded-conversations) - + -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/react-native/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 any of the following types: - -1. Text Message -2. Media Message -3. Custom Message - -Any of the above messages can be sent in a thread. A thread is identified based on the parent message, so while sending a message the `parentMessageId` must be set to indicate that the message belongs to 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. +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. The `parentMessageId` is dynamic and corresponds to the actual `id` of the parent message you want to reply to. In the code examples below, we use placeholder values like `100` or `1`, but in practice, you'll use the actual message ID obtained from your message list or real-time listener. -**Example to send a text message in a thread in a user conversation:** - - -```javascript -let textMessage = new CometChat.TextMessage(UID, "Hello", CometChat.RECEIVER_TYPE.USER); -textMessage.setParentMessageId(100); // Replace with actual parent message ID - -CometChat.sendMessage(textMessage).then( - message => { - console.log('Message sent successfully', message); - }, err => { - console.log('err', err); - } -) -``` - - - ```typescript let receiverId = "UID", @@ -89,252 +55,65 @@ 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. - - -**On Success** — `sendMessage()` returns the sent threaded message with `parentMessageId`: - - - -**Message Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25293"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-7"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Hello thread!"` | -| `sentAt` | number | Unix timestamp when sent | `1771839799` | -| `updatedAt` | number | Unix timestamp when updated | `1771839799` | -| `parentMessageId` | string | ID of the parent message this reply belongs to | `"25291"` | -| `sender` | object | Sender user details | [See below ↓](#send-thread-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#send-thread-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#send-thread-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#send-thread-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771839550` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771839549` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Hello thread!"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `entities` | object | Sender and receiver entities | [See below ↓](#send-thread-data-entities-object) | -| `metadata` | object | Injected metadata | [See below ↓](#send-thread-data-metadata-object) | -| `moderation` | object | Moderation status | `{"status": "pending"}` | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#send-thread-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#send-thread-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#send-thread-data-entities-sender-entity-object) | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771839550` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#send-thread-data-entities-receiver-entity-object) | - ---- - - - -**`data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771839549` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#send-thread-data-metadata-injected-object) | - ---- - - - -**`data.metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#send-thread-data-metadata-extensions-object) | - ---- - - - -**`data.metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#send-thread-data-metadata-linkpreview-object) | - ---- - - - -**`data.metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#send-thread-metadata-injected-object) | - ---- - - - -**`metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#send-thread-metadata-extensions-object) | - ---- - - - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#send-thread-metadata-linkpreview-object) | - ---- + +```javascript +let UID = "UID"; +let textMessage = new CometChat.TextMessage(UID, "Hello", CometChat.RECEIVER_TYPE.USER); +textMessage.setParentMessageId(100); // Replace with actual parent message ID - +CometChat.sendMessage(textMessage).then( + message => { + console.log('Message sent successfully', message); + }, err => { + console.log('err', err); + } +) +``` -**`metadata.@injected.extensions.link-preview` Object:** + -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | + - +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 +Use `MessageListener` to receive real-time thread messages. Check if the received message belongs to the active thread using `getParentMessageId()`. -### Receiving Real-Time Messages + + +```typescript +const listenerID: string = "UNIQUE_LISTENER_ID"; +const activeThreadId: number = 100; -The procedure to receive real-time messages is exactly the same as mentioned in the [Receive Messages](/sdk/react-native/receive-messages) section. This can be achieved using the `MessageListener` class provided by the SDK. +CometChat.addMessageListener( + listenerID, + new CometChat.MessageListener({ + onTextMessageReceived: (textMessage: CometChat.TextMessage) => { + if (textMessage.getParentMessageId() == activeThreadId) { + console.log("Text message received for active thread.", textMessage); + } + }, + onMediaMessageReceived: (mediaMessage: CometChat.MediaMessage) => { + if (mediaMessage.getParentMessageId() == activeThreadId) { + console.log("Media message received for active thread.", mediaMessage); + } + }, + onCustomMessageReceived: (customMessage: CometChat.CustomMessage) => { + if (customMessage.getParentMessageId() == activeThreadId) { + console.log("Custom message received for active thread.", customMessage); + } + } + }) +); +``` -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. + - ```javascript -var listenerID = "UNIQUE_LISTENER_ID"; -var activeThreadId = 100; +const listenerID = "UNIQUE_LISTENER_ID"; +const activeThreadId = 100; CometChat.addMessageListener( listenerID, @@ -346,12 +125,12 @@ new CometChat.MessageListener({ }, onMediaMessageReceived: mediaMessage => { if(mediaMessage.getParentMessageId() == activeThreadId) { - console.log("Media message received for active thread.", textMessage); + console.log("Media message received for active thread.", mediaMessage); } }, onCustomMessageReceived: customMessage => { if(customMessage.getParentMessageId() == activeThreadId) { - console.log("Custom message received for active thread.", textMessage); + console.log("Custom message received for active thread.", customMessage); } } }) @@ -360,48 +139,33 @@ new CometChat.MessageListener({ + + +### Fetch all the messages for any particular thread. + +Use `MessagesRequestBuilder` with `setParentMessageId()` to fetch messages belonging to a specific thread. Call `fetchPrevious()` to get messages (max 100 per request). + + ```typescript -var listenerID: string = "UNIQUE_LISTENER_ID", - activeThreadId: number = 100; +let limit: number = 30, + parentMessageId: number = 1, // Replace with actual parent message ID + messagesRequest: CometChat.MessagesRequest = new CometChat.MessagesRequestBuilder() + .setLimit(limit) + .setParentMessageId(parentMessageId) + .build(); -CometChat.addMessageListener( - listenerID, - new CometChat.MessageListener({ - onTextMessageReceived: (textMessage: CometChat.TextMessage) => { - if (textMessage.getParentMessageId() == activeThreadId) { - console.log("Text message received for active thread.", textMessage); - } - }, - onMediaMessageReceived: (mediaMessage: CometChat.MediaMessage) => { - if (mediaMessage.getParentMessageId() == activeThreadId) { - console.log("Media message received for active thread.", mediaMessage); - } - }, - onCustomMessageReceived: (customMessage: CometChat.CustomMessage) => { - if (customMessage.getParentMessageId() == activeThreadId) { - console.log("Custom message received for active thread.", customMessage); - } - } - }) -); +messagesRequest.fetchPrevious().then( + (messages: CometChat.BaseMessage[]) => { + console.log("Messages for thread fetched successfully", messages); + }, (error: CometChat.CometChatException) => { + console.log("Message fetching failed with error:", error); + } +); ``` - - - -**Remember to remove your listener on unmount.** Always call `CometChat.removeMessageListener("UNIQUE_LISTENER_ID")` when the component unmounts (e.g., in a `useEffect` cleanup or `componentWillUnmount`) to avoid memory leaks and duplicate event handling. - - -### Fetch All Messages for a Thread - -You can fetch all the messages belonging to a particular thread by using the `MessagesRequest` class. To get an object of the `MessagesRequest` class, use the `MessagesRequestBuilder` class and call the `setParentMessageId()` method 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, call the `fetchPrevious()` method to get the latest messages in the thread. In one call, a maximum of 100 messages can be fetched. To fetch the next set of messages, call the `fetchPrevious()` method again on the same object. - - ```javascript let limit = 30; @@ -422,18 +186,28 @@ messagesRequest.fetchPrevious().then( - + + +The `fetchPrevious()` method returns an array of [`BaseMessage`](/sdk/reference/messages#basemessage) objects representing thread replies. + +## Avoid Threaded Messages in User/Group Conversations + +Use `hideReplies(true)` to exclude threaded messages when fetching messages for a conversation. + + + ```typescript -let limit: number = 30, - parentMessageId: number = 1, // Replace with actual parent message ID +let UID: string = "UID", + limit: number = 30, messagesRequest: CometChat.MessagesRequest = new CometChat.MessagesRequestBuilder() + .setUID(UID) .setLimit(limit) - .setParentMessageId(parentMessageId) + .hideReplies(true) .build(); messagesRequest.fetchPrevious().then( (messages: CometChat.BaseMessage[]) => { - console.log("Messages for thread fetched successfully", messages); + console.log("Messages fetched successfully", messages); }, (error: CometChat.CometChatException) => { console.log("Message fetching failed with error:", error); } @@ -442,484 +216,41 @@ messagesRequest.fetchPrevious().then( - - - -**On Success** — `fetchPrevious()` returns an array of messages belonging to the thread: - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25293"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-7"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Hello thread!"` | -| `sentAt` | number | Unix timestamp when sent | `1771839799` | -| `updatedAt` | number | Unix timestamp when updated | `1771839799` | -| `parentMessageId` | string | ID of the parent message this reply belongs to | `"25291"` | -| `sender` | object | Sender user details | [See below ↓](#fetch-thread-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#fetch-thread-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#fetch-thread-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#fetch-thread-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- + +```javascript +let UID = "UID"; +let limit = 30; +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setLimit(limit) + .hideReplies(true) + .build(); + +messagesRequest.fetchPrevious().then( + messages => { + console.log("Messages fetched successfully", messages); + }, error => { + console.log("Message fetching failed with error:", error); + } +); +``` - + -**`sender` Object:** + +```typescript +let GUID: string = "GUID", + limit: number = 30, + messagesRequest: CometChat.MessagesRequest = new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setLimit(limit) + .hideReplies(true) + .build(); -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771839550` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771839549` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Hello thread!"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `entities` | object | Sender and receiver entities | [See below ↓](#fetch-thread-data-entities-object) | -| `metadata` | object | Injected metadata | [See below ↓](#fetch-thread-data-metadata-object) | -| `moderation` | object | Moderation status | `{"status": "approved"}` | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#fetch-thread-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#fetch-thread-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#fetch-thread-data-entities-sender-entity-object) | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771839550` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#fetch-thread-data-entities-receiver-entity-object) | - ---- - - - -**`data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771839549` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#fetch-thread-data-metadata-injected-object) | - ---- - - - -**`data.metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#fetch-thread-data-metadata-extensions-object) | - ---- - - - -**`data.metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#fetch-thread-data-metadata-linkpreview-object) | - ---- - - - -**`data.metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#fetch-thread-metadata-injected-object) | - ---- - - - -**`metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#fetch-thread-metadata-extensions-object) | - ---- - - - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#fetch-thread-metadata-linkpreview-object) | - ---- - - - -**`metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - - - -## Avoid Threaded Messages in User/Group Conversations - -While fetching messages for normal user/group conversations using the `MessagesRequest`, threaded messages will be included in the list by default. To exclude threaded messages from the list of user/group messages, use the `hideReplies()` method of the `MessagesRequestBuilder` class. This method takes a boolean argument which, when set to `true`, excludes messages belonging to threads from the list of messages. - - -**Without `hideReplies(true)`** — `fetchPrevious()` returns all messages including thread replies (note the second message has `parentMessageId`): - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25291"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-6"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Hello"` | -| `sentAt` | number | Unix timestamp when sent | `1771831336` | -| `deliveredAt` | number | Unix timestamp when delivered | `1771832977` | -| `readAt` | number | Unix timestamp when read | `1771832977` | -| `updatedAt` | number | Unix timestamp when updated | `1771832977` | -| `replyCount` | number | Number of replies to this message | `1` | -| `sender` | object | Sender user details | [See below ↓](#default-behavior-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#default-behavior-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#default-behavior-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#default-behavior-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - -Thread replies in the same response will have a `parentMessageId` field linking them to their parent message. - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771829868` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771829859` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Hello"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `entities` | object | Sender and receiver entities | [See below ↓](#default-behavior-data-entities-object) | -| `metadata` | object | Injected metadata | [See below ↓](#default-behavior-data-metadata-object) | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#default-behavior-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#default-behavior-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#default-behavior-data-entities-sender-entity-object) | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771829868` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#default-behavior-data-entities-receiver-entity-object) | - ---- - - - -**`data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771829859` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#default-behavior-data-metadata-injected-object) | - ---- - - - -**`data.metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#default-behavior-data-metadata-extensions-object) | - ---- - - - -**`data.metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#default-behavior-data-metadata-linkpreview-object) | - ---- - - - -**`data.metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#default-behavior-metadata-injected-object) | - ---- - - - -**`metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#default-behavior-metadata-extensions-object) | - ---- - - - -**`metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#default-behavior-metadata-linkpreview-object) | - ---- - - - -**`metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - - - - - -```javascript -let UID = "UID"; -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setLimit(limit) - .hideReplies(true) - .build(); - messagesRequest.fetchPrevious().then( - messages => { - console.log("Messages for thread fetched successfully", messages); - }, error => { + (messages: CometChat.BaseMessage[]) => { + console.log("Messages fetched successfully", messages); + }, (error: CometChat.CometChatException) => { console.log("Message fetching failed with error:", error); } ); @@ -927,7 +258,7 @@ messagesRequest.fetchPrevious().then( - + ```javascript let GUID = "GUID"; let limit = 30; @@ -939,50 +270,8 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() messagesRequest.fetchPrevious().then( messages => { - console.log("Messages for thread fetched successfully", messages); - }, error => { - console.log("Message fetching failed with error:", error); - } -); -``` - - - - -```typescript -let UID: string = "UID", - limit: number = 30, - messagesRequest: CometChat.MessagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setLimit(limit) - .hideReplies(true) - .build(); - -messagesRequest.fetchPrevious().then( - (messages: CometChat.BaseMessage[]) => { - console.log("Messages fetched successfully", messages); - }, (error: CometChat.CometChatException) => { - console.log("Message fetching failed with error:", error); - } -); -``` - - - - -```typescript -let GUID: string = "GUID", - limit: number = 30, - messagesRequest: CometChat.MessagesRequest = new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setLimit(limit) - .hideReplies(true) - .build(); - -messagesRequest.fetchPrevious().then( - (messages: CometChat.BaseMessage[]) => { console.log("Messages fetched successfully", messages); - }, (error: CometChat.CometChatException) => { + }, error => { console.log("Message fetching failed with error:", error); } ); @@ -992,269 +281,31 @@ messagesRequest.fetchPrevious().then( - -**On Success** — `fetchPrevious()` returns messages excluding thread replies (note: parent messages with `replyCount` are included, but their replies are not): - - - -**Message Object (per item in array):** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `id` | string | Unique message identifier | `"25291"` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `receiverId` | string | Receiver's UID | `"cometchat-uid-6"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `type` | string | Message type | `"text"` | -| `category` | string | Message category | `"message"` | -| `text` | string | Message text content | `"Hello"` | -| `sentAt` | number | Unix timestamp when sent | `1771831336` | -| `deliveredAt` | number | Unix timestamp when delivered | `1771832977` | -| `readAt` | number | Unix timestamp when read | `1771832977` | -| `updatedAt` | number | Unix timestamp when updated | `1771832977` | -| `replyCount` | number | Number of replies to this message | `1` | -| `sender` | object | Sender user details | [See below ↓](#hide-replies-sender-object) | -| `receiver` | object | Receiver user details | [See below ↓](#hide-replies-receiver-object) | -| `data` | object | Additional message data | [See below ↓](#hide-replies-data-object) | -| `metadata` | object | Message metadata | [See below ↓](#hide-replies-metadata-object) | -| `reactions` | array | Message reactions | `[]` | -| `mentionedUsers` | array | Users mentioned in message | `[]` | -| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771829868` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Last active timestamp | `1771829859` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | +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. ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `text` | string | Message text | `"Hello"` | -| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | -| `entities` | object | Sender and receiver entities | [See below ↓](#hide-replies-data-entities-object) | -| `metadata` | object | Injected metadata | [See below ↓](#hide-replies-data-metadata-object) | - ---- - - - -**`data.entities` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `sender` | object | Sender entity wrapper | [See below ↓](#hide-replies-data-entities-sender-object) | -| `receiver` | object | Receiver entity wrapper | [See below ↓](#hide-replies-data-entities-receiver-object) | - ---- - - - -**`data.entities.sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#hide-replies-data-entities-sender-entity-object) | - ---- - - - -**`data.entities.sender.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | -| `name` | string | User's display name | `"Henry Marino"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771829868` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.entities.receiver` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `entityType` | string | Type of entity | `"user"` | -| `entity` | object | User entity details | [See below ↓](#hide-replies-data-entities-receiver-entity-object) | - ---- - - - -**`data.entities.receiver.entity` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `lastActiveAt` | number | Last active timestamp | `1771829859` | -| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | -| `tags` | array | User tags | `[]` | - ---- - - - -**`data.metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#hide-replies-data-metadata-injected-object) | - ---- - - - -**`data.metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#hide-replies-data-metadata-extensions-object) | - ---- - - - -**`data.metadata.@injected.extensions` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#hide-replies-data-metadata-linkpreview-object) | - ---- - - - -**`data.metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - ---- - - - -**`metadata` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `@injected` | object | Injected extensions data | [See below ↓](#hide-replies-metadata-injected-object) | - ---- - - - -**`metadata.@injected` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `extensions` | object | Extensions data | [See below ↓](#hide-replies-metadata-extensions-object) | - ---- - - - -**`metadata.@injected.extensions` Object:** + +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. -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `link-preview` | object | Link preview extension | [See below ↓](#hide-replies-metadata-linkpreview-object) | +```javascript +CometChat.removeMessageListener("UNIQUE_LISTENER_ID"); +``` + --- - - -**`metadata.@injected.extensions.link-preview` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `links` | array | Extracted links | `[]` | - - - -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 and Troubleshooting - - - - Every message object has a `parentMessageId` field. If this field is set (non-zero), the message is part of a thread. Use `message.getParentMessageId()` to retrieve the parent message ID and match it against the active thread. - - - - By default, `MessagesRequest` includes threaded messages. Use the `hideReplies(true)` method on `MessagesRequestBuilder` when fetching messages for the main conversation to exclude thread replies. - - - - You can fetch a maximum of 100 messages per `fetchPrevious()` call. Use the `setLimit()` method on `MessagesRequestBuilder` to control the number of messages returned. To load more messages, call `fetchPrevious()` again on the same `MessagesRequest` object. - - - - Yes. The `setParentMessageId()` method is available on `TextMessage`, `MediaMessage`, and `CustomMessage` objects. Set the parent message ID before calling `CometChat.sendMessage()` to send any message type within a thread. - - - ## Next Steps - - Learn how to send text, media, and custom messages to users and groups. + + Send text, media, and custom messages to users and groups - Set up real-time message listeners and fetch message history. + Listen for incoming messages in real-time and fetch missed messages - - Filter messages by type, category, tags, timestamps, and more. + + Add emoji reactions to messages - - Understand message categories, types, and the message hierarchy. + + Advanced message filtering with RequestBuilder - \ No newline at end of file + diff --git a/sdk/react-native/transfer-group-ownership.mdx b/sdk/react-native/transfer-group-ownership.mdx index 0ce97642a..5b409c2ec 100644 --- a/sdk/react-native/transfer-group-ownership.mdx +++ b/sdk/react-native/transfer-group-ownership.mdx @@ -1,97 +1,80 @@ --- title: "Transfer Group Ownership" -description: "Learn how to transfer group ownership to another member using the CometChat React Native SDK." +sidebarTitle: "Transfer Ownership" +description: "Transfer ownership of a CometChat group to another member using the React Native SDK." --- - -**Quick Reference** + + ```javascript // Transfer group ownership -CometChat.transferGroupOwnership("GUID", "UID"); +await CometChat.transferGroupOwnership("GUID", "NEW_OWNER_UID"); ``` - - -Available via: [SDK](/sdk/react-native/transfer-group-ownership) | [REST API](/rest-api/groups/update) - +**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?* +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/react-native/leave-group). -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. +## Transfer Ownership -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 group 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); } -); +) ``` - -**On Success** — `transferGroupOwnership()` returns a success message: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `message` | string | Success confirmation message | `"Ownership transferred to user cometchat-uid-2 for the group with guid group_with_members_1772429132099."` | - - +| Parameter | Description | +|-----------|-------------| +| `GUID` | The GUID of the group | +| `UID` | The UID of the member to become the new owner | - - -- Always confirm with the user before transferring ownership — this action cannot be undone without the new owner's cooperation -- Transfer ownership before leaving a group, as the owner is not allowed to leave without doing so -- After transferring ownership, the previous owner's scope is automatically changed — update your UI accordingly -- Consider showing a list of current group members to let the owner pick the new owner easily - +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. - -- **ERR_NOT_A_MEMBER**: The logged-in user is not a member of the group. Ensure the user has joined the group first. -- **ERR_INSUFFICIENT_PERMISSIONS**: Only the group owner can transfer ownership. Verify the logged-in user is the owner, not just an admin. -- **Cannot leave group**: You must transfer ownership first before leaving. Use `transferGroupOwnership()` then `leaveGroup()`. -- **Target user not found**: Ensure the UID belongs to an existing member of the group. You cannot transfer ownership to a non-member. - - +--- ## Next Steps - -Leave a group after transferring ownership - - -Promote or demote group members - - -Remove or restrict members from a group - - -Permanently delete a group - + + Leave a group after transferring ownership + + + Promote or demote group members + + + Remove or restrict members from a group + + + Permanently delete a group + diff --git a/sdk/react-native/transient-messages.mdx b/sdk/react-native/transient-messages.mdx index 82633a423..4340c4b95 100644 --- a/sdk/react-native/transient-messages.mdx +++ b/sdk/react-native/transient-messages.mdx @@ -1,47 +1,46 @@ --- title: "Transient Messages" -description: "Send and receive real-time transient messages that are not stored or tracked using the CometChat React Native SDK." +sidebarTitle: "Transient Messages" +description: "Send and receive ephemeral real-time messages that are not stored on the server using the CometChat React Native SDK. Ideal for live reactions and temporary indicators." --- - -**Quick Reference** — Send a transient message: +{/* TL;DR for Agents and Quick Reference */} + ```javascript -let data = { "LIVE_REACTION": "heart" }; -let transientMessage = new CometChat.TransientMessage("RECEIVER_ID", CometChat.RECEIVER_TYPE.USER, data); -CometChat.sendTransientMessage(transientMessage); +// 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) +})); ``` - - - - -**Available via:** [SDK](/sdk/react-native/transient-messages) - - + 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. ## 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. - -```javascript -let receiverId = "UID"; -let receiverType = CometChat.RECEIVER_TYPE.USER; -let data = { "LIVE_REACTION": "heart" }; + +```typescript +let receiverId: string = "UID"; +let receiverType: string = CometChat.RECEIVER_TYPE.USER; +let data: Object = { "LIVE_REACTION": "heart" }; -let transientMessage = new CometChat.TransientMessage(receiverId, receiverType, data); +let transientMessage: CometChat.TransientMessage = new CometChat.TransientMessage(receiverId, receiverType, data); CometChat.sendTransientMessage(transientMessage); ``` - - + ```javascript -let receiverId = "GUID"; -let receiverType = CometChat.RECEIVER_TYPE.GROUP; +let receiverId = "UID"; +let receiverType = CometChat.RECEIVER_TYPE.USER; let data = { "LIVE_REACTION": "heart" }; let transientMessage = new CometChat.TransientMessage(receiverId, receiverType, data); @@ -49,11 +48,10 @@ CometChat.sendTransientMessage(transientMessage); ``` - - + ```typescript -let receiverId: string = "UID"; -let receiverType: string = CometChat.RECEIVER_TYPE.USER; +let receiverId: string = "GUID"; +let receiverType: string = CometChat.RECEIVER_TYPE.GROUP; let data: Object = { "LIVE_REACTION": "heart" }; let transientMessage: CometChat.TransientMessage = new CometChat.TransientMessage(receiverId, receiverType, data); @@ -61,72 +59,33 @@ CometChat.sendTransientMessage(transientMessage); ``` + +```javascript +let receiverId = "GUID"; +let receiverType = CometChat.RECEIVER_TYPE.GROUP; +let data = { "LIVE_REACTION": "heart" }; - -```typescript -let receiverId: string = "GUID"; -let receiverType: string = CometChat.RECEIVER_TYPE.GROUP; -let data: Object = { "LIVE_REACTION": "heart" }; - -let transientMessage: CometChat.TransientMessage = new CometChat.TransientMessage(receiverId, receiverType, data); -CometChat.sendTransientMessage(transientMessage); +let transientMessage = new CometChat.TransientMessage(receiverId, receiverType, data); +CometChat.sendTransientMessage(transientMessage); ``` - - -**On Success** — `sendTransientMessage()` does not return a value, but the transient message object sent looks like: - - - -**TransientMessage Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `receiverId` | string | Receiver's unique identifier | `"cometchat-uid-7"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `data` | object | Custom data payload | [See below ↓](#send-transient-data-object) | - ---- - - - -**`data` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `LIVE_REACTION` | string | Live reaction type | `"heart"` | - - +`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?* + +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. - -```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"; +let listenerId: string = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener( listenerId, @@ -140,95 +99,35 @@ CometChat.addMessageListener( - - - -**On Event** — `onTransientMessageReceived` returns the transient message object with sender info: - - - -**TransientMessage Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `receiverId` | string | Receiver's unique identifier | `"cometchat-uid-7"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `data` | object | Custom data payload | [See below ↓](#receive-transient-data-object) | -| `sender` | object | User who sent the transient message | [See below ↓](#receive-transient-sender-object) | + +```javascript +let listenerId = "UNIQUE_LISTENER_ID"; ---- +CometChat.addMessageListener( +listenerId, +new CometChat.MessageListener({ + onTransientMessageReceived: transientMessage => { + console.log('transient message received', transientMessage); + }, +}) +); +``` - + -**`data` Object:** + -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `LIVE_REACTION` | string | Live reaction type | `"heart"` | +The received object is a [`TransientMessage`](/sdk/reference/auxiliary#transientmessage). --- - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - - - - -**Listener Cleanup** — Always remove your message listeners when the component unmounts to prevent memory leaks and unexpected behavior. Use `CometChat.removeMessageListener("UNIQUE_LITENER_ID")` in your cleanup logic (e.g., inside a `useEffect` return function or `componentWillUnmount`). - - -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. | - - - -- **Use transient messages for ephemeral interactions only** — Since transient messages are not stored, they are ideal for features like live reactions, presence pings, or real-time indicators that don't need to persist. -- **Keep the data payload small** — Transient messages are designed for lightweight, real-time signals. Avoid sending large JSON objects in the `data` field. -- **Use unique listener IDs** — Each screen or component that registers a `MessageListener` should use a distinct `listenerId` to avoid conflicts with other listeners. -- **Confirm the receiver is online** — Transient messages are only delivered to online users. If guaranteed delivery is required, use a regular [message](/sdk/react-native/send-message) instead. -- **Pair with typing indicators for richer UX** — Combine transient messages with [typing indicators](/sdk/react-native/typing-indicators) to build expressive, real-time chat experiences. - - -- **Recipient not receiving transient messages** — Verify that the recipient is online and has registered a `MessageListener` with the `onTransientMessageReceived` callback before the sender dispatches the message. -- **Listener not firing** — Confirm that the `listenerId` used in `addMessageListener` is unique and that the listener has not been removed prematurely. -- **Messages not arriving in groups** — Make sure you are using `CometChat.RECEIVER_TYPE.GROUP` with the correct group ID (`GUID`), not a user ID. -- **Cannot retrieve transient messages later** — This is expected behavior. Transient messages are never stored. If you need message persistence, use [send a message](/sdk/react-native/send-message) instead. -- **Data field appears empty on the receiver side** — Ensure you are passing a valid JSON object to the `data` parameter when constructing the `TransientMessage` instance. - - - ## Next Steps - - Send and receive real-time typing indicators in conversations. - - - Send text, media, and custom messages to users and groups. - - - Set up real-time and fetch-based message receiving. - - - Explore the full messaging feature set available in the SDK. - + + Show real-time typing status in conversations + + + Send text, media, and custom messages + diff --git a/sdk/react-native/typing-indicators.mdx b/sdk/react-native/typing-indicators.mdx index 577a593bf..3efe5bccd 100644 --- a/sdk/react-native/typing-indicators.mdx +++ b/sdk/react-native/typing-indicators.mdx @@ -1,65 +1,61 @@ --- title: "Typing Indicators" -description: "Learn how to send and receive real-time typing indicators in one-on-one and group conversations using the CometChat React Native SDK." +sidebarTitle: "Typing Indicators" +description: "Send and receive real-time typing indicators using the CometChat React Native SDK." --- - -**Quick Reference** — Send and listen for typing indicators: +{/* TL;DR for Agents and Quick Reference */} + + ```javascript -// Start typing -let typing = new CometChat.TypingIndicator("RECEIVER_ID", CometChat.RECEIVER_TYPE.USER); +// Start typing indicator +const typing = new CometChat.TypingIndicator("UID", CometChat.RECEIVER_TYPE.USER); CometChat.startTyping(typing); -// Stop typing +// Stop typing indicator CometChat.endTyping(typing); // Listen for typing events -CometChat.addMessageListener("listenerId", new CometChat.MessageListener({ - onTypingStarted: (indicator) => { /* sender is typing */ }, - onTypingEnded: (indicator) => { /* sender stopped typing */ }, +CometChat.addMessageListener("LISTENER_ID", new CometChat.MessageListener({ + onTypingStarted: (indicator) => console.log("Typing started:", indicator), + onTypingEnded: (indicator) => console.log("Typing ended:", indicator) })); ``` - - - -**Available via:** [SDK](/sdk/react-native/typing-indicators) | [UI Kits](/ui-kit/react-native/core-features#typing-indicator) - + ## 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. To send the typing indicator, you need to use the `TypingIndicator` class. +Use `startTyping()` with a [`TypingIndicator`](/sdk/reference/auxiliary#typingindicator) object to notify the receiver that you're typing. - -```javascript -let receiverId = "UID"; -let receiverType = CometChat.RECEIVER_TYPE.USER; + +```typescript +let receiverId: string = "UID"; +let receiverType: string = CometChat.RECEIVER_TYPE.USER; -let typingNotification = new CometChat.TypingIndicator(receiverId, receiverType); +let typingNotification: CometChat.TypingIndicator = new CometChat.TypingIndicator(receiverId, receiverType); CometChat.startTyping(typingNotification); ``` - + ```javascript -let receiverId = "GUID"; -let receiverType = CometChat.RECEIVER_TYPE.GROUP; +let receiverId = "UID"; +let receiverType = CometChat.RECEIVER_TYPE.USER; -let typingNotification = new CometChat.TypingIndicator(receiverId,receiverType); -CometChat.startTyping(typingNotification); +let typingNotification = new CometChat.TypingIndicator(receiverId, receiverType); +CometChat.startTyping(typingNotification); ``` - + ```typescript -let receiverId: string = "UID"; -let receiverType: string = CometChat.RECEIVER_TYPE.USER; +let receiverId: string = "GUID"; +let receiverType: string = CometChat.RECEIVER_TYPE.GROUP; let typingNotification: CometChat.TypingIndicator = new CometChat.TypingIndicator(receiverId, receiverType); CometChat.startTyping(typingNotification); @@ -67,12 +63,12 @@ CometChat.startTyping(typingNotification); - -```typescript -let receiverId: string = "GUID"; -let receiverType: string = CometChat.RECEIVER_TYPE.GROUP; + +```javascript +let receiverId = "GUID"; +let receiverType = CometChat.RECEIVER_TYPE.GROUP; -let typingNotification: CometChat.TypingIndicator = new CometChat.TypingIndicator(receiverId, receiverType); +let typingNotification = new CometChat.TypingIndicator(receiverId,receiverType); CometChat.startTyping(typingNotification); ``` @@ -80,36 +76,28 @@ CometChat.startTyping(typingNotification); - -**startTyping called** — the typing indicator object sent to the receiver: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `receiverId` | string | Receiver's unique identifier | `"cometchat-uid-6"` | -| `receiverType` | string | Type of receiver | `"user"` | - - +`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. To send the typing indicator, you need to use the `TypingIndicator` class. +Use `endTyping()` to notify the receiver that you've stopped typing. - -```javascript -let receiverId = "UID"; -let receiverType = CometChat.RECEIVER_TYPE.USER; + +```typescript +let receiverId: string = "UID"; +let receiverType: string = CometChat.RECEIVER_TYPE.USER; -let typingNotification = new CometChat.TypingIndicator(receiverId, receiverType); +let typingNotification: CometChat.TypingIndicator = new CometChat.TypingIndicator(receiverId, receiverType); CometChat.endTyping(typingNotification); ``` - + ```javascript -let receiverId = "GUID"; -let receiverType = CometChat.RECEIVER_TYPE.GROUP; +let receiverId = "UID"; +let receiverType = CometChat.RECEIVER_TYPE.USER; let typingNotification = new CometChat.TypingIndicator(receiverId, receiverType); CometChat.endTyping(typingNotification); @@ -117,10 +105,10 @@ CometChat.endTyping(typingNotification); - + ```typescript -let receiverId: string = "UID"; -let receiverType: string = CometChat.RECEIVER_TYPE.USER; +let receiverId: string = "GUID"; +let receiverType: string = CometChat.RECEIVER_TYPE.GROUP; let typingNotification: CometChat.TypingIndicator = new CometChat.TypingIndicator(receiverId, receiverType); CometChat.endTyping(typingNotification); @@ -128,12 +116,12 @@ CometChat.endTyping(typingNotification); - -```typescript -let receiverId: string = "GUID"; -let receiverType: string = CometChat.RECEIVER_TYPE.GROUP; + +```javascript +let receiverId = "GUID"; +let receiverType = CometChat.RECEIVER_TYPE.GROUP; -let typingNotification: CometChat.TypingIndicator = new CometChat.TypingIndicator(receiverId, receiverType); +let typingNotification = new CometChat.TypingIndicator(receiverId, receiverType); CometChat.endTyping(typingNotification); ``` @@ -141,52 +129,20 @@ CometChat.endTyping(typingNotification); - -**endTyping called** — the typing indicator object sent to the receiver: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `receiverId` | string | Receiver's unique identifier | `"cometchat-uid-6"` | -| `receiverType` | string | Type of receiver | `"user"` | - - +`endTyping()` returns `void` — the typing indicator is sent as a fire-and-forget operation. -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`](/sdk/reference/auxiliary#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?* - -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. - -```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"; +let listenerId: string = "UNIQUE_LISTENER_ID"; CometChat.addMessageListener( listenerId, @@ -203,114 +159,46 @@ CometChat.addMessageListener( - - - -**onTypingStarted** — received when a user starts typing: - - - -**TypingIndicator Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `receiverId` | string | Receiver's unique identifier | `"cometchat-uid-7"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `sender` | object | User who is typing | [See below ↓](#typing-started-sender-object) | - ---- - - - -**`sender` Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | - ---- - -**onTypingEnded** — received when a user stops typing: - - - -**TypingIndicator Object:** - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `receiverId` | string | Receiver's unique identifier | `"cometchat-uid-7"` | -| `receiverType` | string | Type of receiver | `"user"` | -| `sender` | object | User who stopped typing | [See below ↓](#typing-ended-sender-object) | - ---- + +```javascript +let listenerId = "UNIQUE_LISTENER_ID"; - +CometChat.addMessageListener( +listenerId, +new CometChat.MessageListener({ + onTypingStarted: typingIndicator => { + console.log("Typing started :", typingIndicator); + }, + onTypingEnded: typingIndicator => { + console.log("Typing ended :", typingIndicator); + } +}) +); +``` -**`sender` Object:** + -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | -| `name` | string | User's display name | `"Ronald Jerry"` | -| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | -| `blockedByMe` | boolean | Whether current user blocked this user | `false` | -| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | -| `tags` | array | User tags | `[]` | + - +The received object is a [`TypingIndicator`](/sdk/reference/auxiliary#typingindicator). -**Listener Cleanup** — Always remove your message listeners when the component unmounts to prevent memory leaks and unexpected behavior. Use `CometChat.removeMessageListener("UNIQUE_LITENER_ID")` in your cleanup logic (e.g., inside a `useEffect` return function or `componentWillUnmount`). +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"); +``` -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 provide additional data. | - - - -- **Debounce start typing calls** — Avoid calling `startTyping()` on every keystroke. Instead, debounce the call so it fires once when the user begins typing and doesn't repeat until after a short pause. -- **Call endTyping() explicitly** — Always call `endTyping()` when the user clears the input field, sends a message, or navigates away from the chat screen. -- **Use unique listener IDs** — Each screen or component that registers a `MessageListener` should use a distinct `listenerId` to avoid conflicts. -- **Handle metadata sparingly** — Only attach `metadata` to typing indicators when you have a concrete use case (e.g., indicating which thread the user is typing in). - - -- **Typing indicator not appearing for the recipient** — Verify that the recipient has registered a `MessageListener` with `onTypingStarted` and `onTypingEnded` callbacks before the sender starts typing. -- **Typing indicator stuck in "typing" state** — Ensure `endTyping()` is called when the user stops typing or sends a message. CometChat automatically times out typing indicators after a short period, but explicitly ending them provides a better user experience. -- **Listener not firing** — Confirm that the `listenerId` used in `addMessageListener` is unique and that the listener has not been removed prematurely. -- **Indicators not working in groups** — Make sure you are using `CometChat.RECEIVER_TYPE.GROUP` with the correct group ID (`GUID`), not a user ID. - - +--- ## Next Steps - - Confirm when messages are delivered and read by recipients. - - - Learn how to send text, media, and custom messages. - - - Set up real-time and fetch-based message receiving. - - - Explore the full messaging feature set available in the SDK. - + + Track when messages are delivered and read + + + Send ephemeral real-time messages like live reactions + diff --git a/sdk/react-native/update-group.mdx b/sdk/react-native/update-group.mdx index 35ec4ed0e..23b61195c 100644 --- a/sdk/react-native/update-group.mdx +++ b/sdk/react-native/update-group.mdx @@ -1,53 +1,32 @@ --- title: "Update A Group" -description: "Update group details such as name, icon, description, and metadata using the CometChat React Native SDK." +sidebarTitle: "Update Group" +description: "Update group details such as name, type, icon, and description using the CometChat React Native SDK." --- - -**Quick Reference** - Update a group: + ```javascript -const group = new CometChat.Group("GUID", "Updated Name", CometChat.GROUP_TYPE.PUBLIC); -await CometChat.updateGroup(group); +// Update group details +const group = new CometChat.Group("GUID", "New Name", CometChat.GROUP_TYPE.PUBLIC); +const updated = await CometChat.updateGroup(group); ``` - + - -**Available via:** [SDK](/sdk/react-native/update-group) | [REST API](/rest-api/groups/update) - +Update a group's name, icon, description, or metadata. The GUID and group type cannot be changed after creation. See the [Group Class](/sdk/react-native/create-group#group-class) reference for all editable fields. ## 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`](/sdk/reference/entities#group) object with the updated values. - -```javascript -var GUID = "GUID"; -var groupName = "Hello Group"; -var groupType = CometChat.GROUP_TYPE.PUBLIC; -var 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 -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) => { @@ -60,77 +39,51 @@ 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` | - -After a successful update of the group, you will receive an instance of `Group` class containing update information of the group. - - -**On Success** — `updateGroup()` returns the updated `Group` object: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `hasJoined` | boolean | Whether the logged-in user has joined the group | `true` | -| `membersCount` | number | Total number of members in the group | `2` | -| `isBanned` | boolean | Whether the logged-in user is banned from the group | `false` | -| `guid` | string | Unique identifier of the group | `"group_1772427551785"` | -| `name` | string | Updated name of the group | `"Comet Group Updated"` | -| `type` | string | Type of the group (public, private, password) | `"public"` | -| `scope` | string | Scope of the logged-in user in the group | `"admin"` | -| `joinedAt` | number | Unix timestamp when the user joined | `1772427556` | -| `conversationId` | string | Conversation ID for the group | `"group_group_1772427551785"` | -| `createdAt` | number | Unix timestamp when the group was created | `1772427556` | -| `owner` | string | UID of the group owner | `"cometchat-uid-6"` | -| `updatedAt` | number | Unix timestamp when the group was last updated | `1772427918` | -| `updatedBy` | string | UID of the user who updated the group | `"cometchat-uid-6"` | -| `onlineMembersCount` | number | Number of online members in the group | `2` | + +```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); +} +); +``` -For more information on the `Group` class, please check [here](/sdk/react-native/create-group#group-class) + -## Best Practices + - - - The `Group` object passed to `updateGroup()` must have the correct GUID set. Only the fields you set on the object will be updated — unset fields remain unchanged. - - - The `updateGroup()` method requires the logged-in user to be the owner or an admin of the group. Participants and moderators cannot update group details. - - +| Parameter | Description | +| --------- | ----------- | +| `group` | An instance of [`Group`](/sdk/reference/entities#group) class with updated values | -## Troubleshooting +On success, returns a [`Group`](/sdk/reference/entities#group) object with the updated details. - - - Verify the logged-in user is the owner or an admin of the group. Use `getGroup()` to check the user's scope in the group. - - - The `type` field of a group is not editable after creation. To change a group's type, you would need to create a new group with the desired type. - - + +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()`. + --- ## Next Steps - - Fetch group lists, search groups, and get group details + + Permanently delete a group + + + Fetch and filter groups with pagination Manage members, roles, and permissions within groups - - Delete groups and handle related cleanup - Create public, private, or password-protected groups - \ No newline at end of file + diff --git a/sdk/react-native/upgrading-from-v3.mdx b/sdk/react-native/upgrading-from-v3.mdx index 1d9222872..40662589f 100644 --- a/sdk/react-native/upgrading-from-v3.mdx +++ b/sdk/react-native/upgrading-from-v3.mdx @@ -1,105 +1,71 @@ --- title: "Upgrading From V3" -description: "Learn how to upgrade your React Native app from CometChat SDK v3 to v4, including dependency changes and updated import statements." +description: "Migrate your CometChat React Native SDK integration from v3 to v4 with updated dependencies and import statements." --- - -**Quick Reference** -```bash -# Install v4 Chat SDK -npm i @cometchat/chat-sdk-react-native - -# Install v4 Calls SDK -npm i @cometchat/calls-sdk-react-native -``` -```javascript -// Updated imports -import { CometChat } from '@cometchat/chat-sdk-react-native'; -import { CometChatCalls } from '@cometchat/calls-sdk-react-native'; -``` - + -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 from v3 to v4: +- Chat SDK: `npm i @cometchat/chat-sdk-react-native` +- Calls SDK: `npm i @cometchat/calls-sdk-react-native` +- Import: `import { CometChat } from '@cometchat/chat-sdk-react-native'` +- Import Calls: `import { CometChatCalls } from '@cometchat/calls-sdk-react-native'` + -Please follow the [setup](/sdk/react-native/setup-sdk) instructions to upgrade to the latest V4 version. +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/react-native/setup-sdk) first, then update your dependencies and imports as shown below. -## Dependency Change +## Update Dependencies -### Chat SDK +| SDK | v3 Package | v4 Package | +| --- | --- | --- | +| Chat SDK | `@cometchat-pro/react-native-chat` | `@cometchat/chat-sdk-react-native` | +| Calls SDK | `@cometchat-pro/react-native-calls` | `@cometchat/calls-sdk-react-native` | - - ```bash -npm i @cometchat/chat-sdk-react-native -``` +# Remove v3 packages +npm uninstall @cometchat-pro/react-native-chat @cometchat-pro/react-native-calls - - - - -### Calls SDK - - - -```bash +# Install v4 packages +npm i @cometchat/chat-sdk-react-native npm i @cometchat/calls-sdk-react-native ``` - - - +## Update Import Statements -## Change The Import Statements +Find and replace all import statements across your project: -Change the import statements all around the project. +| SDK | v3 Import | v4 Import | +| --- | --- | --- | +| Chat SDK | `import { CometChat } from '@cometchat-pro/react-native-chat'` | `import { CometChat } from '@cometchat/chat-sdk-react-native'` | +| Calls SDK | `import { CometChatCalls } from '@cometchat-pro/react-native-calls'` | `import { CometChatCalls } from '@cometchat/calls-sdk-react-native'` | -### Chat SDK - - - ```javascript -import {CometChat} from '@cometchat/chat-sdk-react-native'; -``` - - - - - -### Calls SDK +// v4 Chat SDK +import { CometChat } from '@cometchat/chat-sdk-react-native'; - - -```javascript -import {CometChatCalls} from '@cometchat/calls-sdk-react-native'; +// v4 Calls SDK +import { CometChatCalls } from '@cometchat/calls-sdk-react-native'; ``` - + +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. + - - - - -- Update both the Chat SDK and Calls SDK together to avoid version incompatibilities -- After updating dependencies, do a clean build (`npx react-native start --reset-cache`) to clear any cached modules -- Search your entire project for old import paths (`@cometchat-pro/react-native-chat`) and replace them with the new v4 paths -- Test all listeners and callbacks after upgrading — some callback signatures may have changed between v3 and v4 - - - -- **Module not found errors**: Ensure you've removed the old v3 packages (`@cometchat-pro/react-native-chat`) and installed the new v4 packages. -- **Duplicate module errors**: Run `npm dedupe` or delete `node_modules` and reinstall to resolve conflicting versions. -- **iOS build fails after upgrade**: Run `pod install --repo-update` in the `ios/` directory to update native dependencies. -- **Android build fails**: Clean the build with `./gradlew clean` in the `android/` directory and rebuild. - - +--- ## Next Steps - -Complete the v4 SDK setup - - -Set up user authentication with v4 - + + Install and configure the CometChat React Native SDK + + + Latest SDK version and release notes + + + Set up user authentication with v4 + + + Learn the core concepts behind CometChat v4 + diff --git a/sdk/react-native/user-management.mdx b/sdk/react-native/user-management.mdx index e6a8b0afd..c89a8f6f6 100644 --- a/sdk/react-native/user-management.mdx +++ b/sdk/react-native/user-management.mdx @@ -1,10 +1,10 @@ --- title: "User Management" -description: "Create, update, and delete users in CometChat using the React Native SDK — including logged-in user updates and the User class reference." +sidebarTitle: "User Management" +description: "Create, update, and manage CometChat users programmatically using the React Native SDK. Includes user creation, profile updates, and the User class reference." --- - -**Quick Reference** - Create and update users: + ```javascript // Create a user @@ -12,286 +12,185 @@ const user = new CometChat.User("user1"); user.setName("Kevin"); await CometChat.createUser(user, "AUTH_KEY"); -// Update logged-in user -const me = new CometChat.User("user1"); -me.setName("Kevin Fernandez"); -await CometChat.updateCurrentUserDetails(me); -``` - - - -**Available via:** [SDK](/sdk/react-native/user-management) | [REST API](/rest-api/users/create) - +// Update a user +user.setName("Kevin Fernandez"); +await CometChat.updateUser(user, "AUTH_KEY"); -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. - -Summing up- - -**When a user registers in your app** +// Update logged-in user (no auth key needed) +await CometChat.updateCurrentUserDetails(user); +``` -1. You add the user details in your database -2. You create a user in CometChat +**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** +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. -1. You log in the user to your app -2. You [log in the user to CometChat](/sdk/react-native/authentication-overview) (programmatically) +The typical flow: +1. User registers in your app → Create user in CometChat +2. User logs into your app → [Log user into CometChat](/sdk/react-native/authentication-overview) -## Creating a user + +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. + -Ideally, user creation should take place at your backend. You can refer to our Rest API to learn more about [creating a user](https://www.cometchat.com/docs/rest-api/users/create) and use the appropriate code sample based on your backend language. +## Creating a User -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. +User creation should ideally happen on your backend via the [REST API](https://api-explorer.cometchat.com/reference/creates-user). -The `Auth Key` is intended for development and testing only. In production, create users from your backend using the [REST API](/rest-api/create-user) with your API Key instead. +**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. - - -```javascript -let authKey = "AUTH_KEY"; -var uid = "user1"; -var name = "Kevin"; - -var user = new CometChat.User(uid); - -user.setName(name); - -CometChat.createUser(user, authKey).then( - user => { - console.log("user created", user); - }, error => { - console.log("error", error); - } -) -``` - - +For client-side creation (development only), use `createUser()`: + ```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); 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); } ); ``` - - - - - -**On Success** — `createUser()` returns the created `User` object: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"test_user_1772166127823"` | -| `name` | string | Display name of the user | `"Test User"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | -| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | -| `createdAt` | number | Unix timestamp when user was created | `1772166128` | - -When creating a user with all optional fields set: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"test_full_1772166127993"` | -| `name` | string | Display name of the user | `"Full Test User"` | -| `avatar` | string | URL to user's avatar image | `"https://example.com/avatar.png"` | -| `link` | string | URL to user's profile page | `"https://example.com/profile"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"offline"` | -| `statusMessage` | string | Custom status message | `"Hello World"` | -| `metadata` | object | Custom metadata attached to the user | `{"custom": "data"}` | -| `tags` | array | Tags associated with the user | `["tag1", "tag2"]` | -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | -| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | -| `createdAt` | number | Unix timestamp when user was created | `1772166129` | - - - - - -UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. CometChat automatically converts any uppercase characters in the UID to lowercase. - - - -## 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://www.cometchat.com/docs/rest-api/users/update) 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. - - ```javascript let authKey = "AUTH_KEY"; let uid = "user1"; -let name = "Kevin Fernandez"; +let name = "Kevin"; -var user = new CometChat.User(uid); +let user = new CometChat.User(uid); user.setName(name); -CometChat.updateUser(user, authKey).then( +CometChat.createUser(user, authKey).then( user => { - console.log("user updated", user); + console.log("user created", user); }, error => { - console.log("error", error); + console.log("error", error); } ) ``` - + + +Returns a [`User`](/sdk/reference/entities#user) object. See [User Class](#user-class) for all available fields. + + +UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. + + + +## 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). + +For client-side updates (development only), use `updateUser()`: + + ```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); 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); } ) ``` - - - - - -**On Success** — `updateUser()` returns the updated `User` object: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"test_user_1772167015122"` | -| `name` | string | Display name of the user | `"Updated Test User"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"offline"` | -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | -| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | -| `createdAt` | number | Unix timestamp when user was created | `1772167016` | - -When updating a user with all optional fields: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"test_full_1772167015291"` | -| `name` | string | Display name of the user | `"Updated Full User"` | -| `avatar` | string | URL to user's avatar image | `"https://example.com/new-avatar.png"` | -| `link` | string | URL to user's profile page | `"https://example.com/new-profile"` | -| `role` | string | User's role | `"admin"` | -| `status` | string | User's online status | `"offline"` | -| `statusMessage` | string | Custom status message | `"Updated status"` | -| `metadata` | object | Custom metadata attached to the user | `{"updated": true}` | -| `tags` | array | Tags associated with the user | `["updated-tag"]` | -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | -| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | -| `createdAt` | number | Unix timestamp when user was created | `1772167016` | - - - -Please make sure the `User` object provided to the `updateUser()` method has the `UID` of the user to be updated set. - -## 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. - - ```javascript +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); -CometChat.updateCurrentUserDetails(user).then( +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); } -) +) ``` - + + +Ensure the [`User`](/sdk/reference/entities#user) object has the correct `UID` set. +Returns a [`User`](/sdk/reference/entities#user) object. See [User Class](#user-class) for all available fields. + +## Updating Logged-in User + +Use `updateCurrentUserDetails()` to update the current user without an Auth Key. Note: You cannot update the user's role with this method. + + ```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); 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); } ); ``` - + +```javascript +let uid = "user1"; +let name = "Kevin Fernandez"; - +let user = new CometChat.User(uid); - -**On Success** — `updateCurrentUserDetails()` returns the updated `User` object with additional session data: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"cometchat-uid-7"` | -| `name` | string | Display name of the user | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar image | `"https://artriva.com/media/k2/galleries/20/d.jpg"` | -| `authToken` | string | Authentication token for the user | `"cometchat-uid-7_177199269018c2c2995f0b69b3844abc9fdb9843"` | -| `role` | string | User's role | `"default"` | -| `status` | string | User's online status | `"online"` | -| `statusMessage` | string | Custom status message | `"Testing CometChat SDK"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1772163866` | -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | -| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | -| `tags` | array | Tags associated with the user | `["vip"]` | -| `wsChannel` | object | WebSocket channel information | `{"identity": "[2748663902141719]cometchat-uid-7"}` | -| `settings` | object | App settings and feature flags (large object with trial info, extensions, parameters) | See CometChat Dashboard | -| `jwt` | string | JSON Web Token for API authentication | JWT string | +user.setName(name); - +CometChat.updateCurrentUserDetails(user).then( + user => { + console.log("user updated", user); + }, 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. +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://www.cometchat.com/docs/rest-api/users/delete) section. +User deletion is only available via the [REST API](https://api-explorer.cometchat.com/reference/delete-user). ## User Class @@ -310,49 +209,21 @@ 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 | -## Best Practices - - - - Use the REST API with your API Key to create users server-side. The `createUser()` SDK method requires the Auth Key, which should not be exposed in production client apps. - - - Use the same user identifier from your backend as the CometChat UID. This simplifies mapping between your user system and CometChat. - - - When the logged-in user updates their own profile, use `updateCurrentUserDetails()` which doesn't require an Auth Key. Reserve `updateUser()` for admin-level operations from your backend. - - - -## Troubleshooting - - - - Each UID must be unique across your CometChat app. If the user already exists, use `updateUser()` instead, or skip creation and proceed to login. - - - Role updates are not allowed via `updateCurrentUserDetails()`. Use the REST API or `updateUser()` with Auth Key to change a user's role. - - - UIDs can only contain alphanumeric characters, underscores, and hyphens. Spaces, punctuation, and other special characters are not allowed. - - - --- ## Next Steps - Fetch user lists, search users, and get user details + Fetch and filter user lists with pagination. + + + Monitor real-time online/offline status. - Block and unblock users, retrieve blocked user lists + Block and unblock users. - Log users into CometChat after creation - - - Track online/offline status of users in real time + Log users into CometChat. - \ No newline at end of file + diff --git a/sdk/react-native/user-presence.mdx b/sdk/react-native/user-presence.mdx index f03f1fd85..cb79deb6e 100644 --- a/sdk/react-native/user-presence.mdx +++ b/sdk/react-native/user-presence.mdx @@ -1,194 +1,135 @@ --- title: "User Presence" -description: "Track real-time online/offline status of users in your React Native app using CometChat SDK presence subscriptions and user listeners." +sidebarTitle: "User Presence" +description: "Track real-time user online/offline status and configure presence subscriptions using the CometChat React Native SDK." --- - -**Quick Reference** - Listen for user presence changes: + ```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), + onUserOffline: (user) => console.log("Offline:", user) })); -// Cleanup +// Remove listener CometChat.removeUserListener("LISTENER_ID"); ``` - - - -**Available via:** [SDK](/sdk/react-native/user-presence) | [UI Kits](/ui-kit/react-native/users) - + -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?* - -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. +Configure presence subscription in `AppSettings` during SDK initialization. The `AppSettingsBuilder` provides three subscription options: -In the `AppSettings` class, you can set the type of Presence you wish to receive for that particular session of 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 | -For presence subscription, the AppSettingsBuilder provides 3 methods : +If none of these methods are called, no presence events will be delivered. -* `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. + +You must configure presence subscription in `AppSettings` during `CometChat.init()` before any presence events will be delivered. See [Setup SDK](/sdk/react-native/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: - -```javascript -let listenerID = "UNIQUE_LISTENER_ID"; + +```typescript +let listenerID: string = "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: CometChat.User) => { + console.log("On User Online:", { onlineUser }); + }, + 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) => { - console.log("On User Online:", { onlineUser }); - }, - onUserOffline: (offlineUser: CometChat.User) => { - console.log("On User Offline:", { offlineUser }); - } + onUserOnline: onlineUser => { + console.log("On User Online:", { onlineUser }); + }, + onUserOffline: offlineUser => { + console.log("On User Offline:", { offlineUser }); + } }) ); ``` - - - -**On Event** — `onUserOnline` returns a `User` object when a user comes online: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"cometchat-uid-7"` | -| `name` | string | Display name of the user | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar image | `"https://artriva.com/media/k2/galleries/20/d.jpg"` | -| `status` | string | User's online status | `"online"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1772174142305` | -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | -| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | +| Parameter | Description | +| --------- | ----------- | +| `listenerID` | Unique identifier for the listener | - - - -**On Event** — `onUserOffline` returns a `User` object when a user goes offline: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `uid` | string | Unique identifier of the user | `"cometchat-uid-7"` | -| `name` | string | Display name of the user | `"Henry Marino"` | -| `avatar` | string | URL to user's avatar image | `"https://artriva.com/media/k2/galleries/20/d.jpg"` | -| `status` | string | User's online status | `"offline"` | -| `role` | string | User's role | `"default"` | -| `lastActiveAt` | number | Unix timestamp of last activity | `1772174136215` | -| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | -| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | -| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | +Each callback receives a [`User`](/sdk/reference/entities#user) object with presence information. - +Relevant fields to access on returned users: -| Parameter | Description | -| ------------ | --------------------------------------------- | -| `listenerID` | An ID that uniquely identifies that listener. | - -You will receive an object of the `User` class in the listener methods. +| Field | Getter | Return Type | Description | +|-------|--------|-------------|-------------| +| status | `getStatus()` | `string` | Online status of the user (`"online"` or `"offline"`) | +| lastActiveAt | `getLastActiveAt()` | `number` | Timestamp when the user was last active | Presence events are triggered for other users, not for yourself. For example, if User 1 is logged in and User 2 comes online, User 1 receives `onUserOnline` for User 2. Neither User 1 nor User 2 receive presence events for their own status changes — only for others. - -Always remove user listeners when the component unmounts using `CometChat.removeUserListener(listenerID)`. Failing to remove listeners can cause memory leaks and duplicate event handling. - +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); -``` - - -## 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/react-native/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. - -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. + +Always remove your `UserListener` when the component or view unmounts to prevent memory leaks and duplicate event handling. -## Best Practices +```javascript +CometChat.removeUserListener("LISTENER_ID"); +``` + - - - Use `subscribePresenceForAllUsers()` only if your app needs to track all users. For most apps, `subscribePresenceForFriends()` or `subscribePresenceForRoles()` is more efficient and reduces unnecessary network traffic. - - - Presence subscription is configured in `AppSettings` during SDK initialization. You cannot change the subscription type without re-initializing the SDK. Plan your subscription strategy before calling `init()`. - - - When a user is offline, use the `lastActiveAt` timestamp to show "Last seen X minutes ago" in your UI. This gives users context about when the person was last available. - - +## User List Presence -## Troubleshooting +When fetching users via `UsersRequest`, each [`User`](/sdk/reference/entities#user) object includes presence fields: - - - Verify that you configured a presence subscription method (`subscribePresenceForAllUsers`, `subscribePresenceForRoles`, or `subscribePresenceForFriends`) in your `AppSettings` during `init()`. Without this, no presence events are delivered. - - - Offline events are triggered when the SDK detects the user has disconnected. This may have a short delay depending on network conditions. The event will fire once the server confirms the user is offline. - - - If using `subscribePresenceForRoles()`, ensure the target users have the specified roles assigned. If using `subscribePresenceForFriends()`, confirm the users are in each other's friends list. - - +| Field | Description | +| ----- | ----------- | +| `status` | `"online"` or `"offline"` | +| `lastActiveAt` | Timestamp of last activity (useful for "Last seen" display) | --- @@ -196,15 +137,15 @@ When you fetch the list of users, in the [User](/sdk/react-native/user-managemen - Fetch user lists with online/offline status + Fetch user lists with filtering and pagination. - Create, update, and delete users in CometChat + Create and update users programmatically. - Block and unblock users, retrieve blocked user lists + Block and unblock users to control communication. - Configure AppSettings including presence subscriptions + Configure AppSettings including presence subscriptions. - \ No newline at end of file + diff --git a/sdk/react-native/users-overview.mdx b/sdk/react-native/users-overview.mdx index 8c8c40333..64719b644 100644 --- a/sdk/react-native/users-overview.mdx +++ b/sdk/react-native/users-overview.mdx @@ -1,30 +1,37 @@ --- title: "Users" sidebarTitle: "Overview" -description: "Overview of user functionality in CometChat React Native SDK — create, retrieve, and manage users in your app." +description: "Overview of CometChat user functionality including user management, retrieval, and presence tracking in the React Native SDK." --- -## Overview + -The primary aim for our Users functionality is to allow you to quickly add users to CometChat. +- [User Management](/sdk/react-native/user-management) — Create and update users +- [Retrieve Users](/sdk/react-native/retrieve-users) — Fetch and filter user lists +- [User Presence](/sdk/react-native/user-presence) — Track online/offline status +- [Block Users](/sdk/react-native/block-users) — Block and unblock users + -You can begin with [user management](/sdk/react-native/user-management) to sync your users to CometChat. Once that is done, you can [retrieve users](/sdk/react-native/retrieve-users) and 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/react-native/user-management) — Create users when they sign up, update profiles, and delete accounts +- [Retrieve Users](/sdk/react-native/retrieve-users) — Fetch and filter user lists with pagination, search, and role-based filtering +- [User Presence](/sdk/react-native/user-presence) — Monitor real-time online/offline status and subscribe to presence changes +- [Block Users](/sdk/react-native/block-users) — Block and unblock users to prevent all communication ## Next Steps - Create, update, and delete users in CometChat + Create, update, and delete users in CometChat. - Fetch user lists, search users, and get user details - - - Block and unblock users, retrieve blocked user lists + Fetch user lists with filtering, sorting, and pagination. - Track online/offline status of users in real time + Monitor real-time online/offline status of users. + + + Block and unblock users to control communication. - \ No newline at end of file + diff --git a/sdk/react-native/video-view-customisation.mdx b/sdk/react-native/video-view-customisation.mdx index b38e36d98..e9901bd8f 100644 --- a/sdk/react-native/video-view-customisation.mdx +++ b/sdk/react-native/video-view-customisation.mdx @@ -1,101 +1,95 @@ --- title: "Video View Customisation" -description: "Customize the main video container in CometChat React Native calls, including aspect ratio, full-screen button, name labels, zoom, and user list button positioning." +sidebarTitle: "Video View Customisation" +description: "Customize the main video container in CometChat React Native calls — aspect ratio, full screen button, name label, zoom button, and user list button positioning." --- - -**Quick Reference** - Customize the main video container: + -```javascript -let videoSettings = new CometChat.MainVideoContainerSetting(); -videoSettings.setMainVideoAspectRatio(CometChatCalls.CallSettings.ASPECT_RATIO_CONTAIN); -videoSettings.setFullScreenButtonParams(CometChatCalls.CallSettings.POSITION_BOTTOM_RIGHT, true); -videoSettings.setNameLabelParams(CometChatCalls.CallSettings.POSITION_BOTTOM_LEFT, true, "#333333"); - -// Pass to CallSettingsBuilder -new CometChatCalls.CallSettingsBuilder() - .setMainVideoContainerSetting(videoSettings) - .build(); -``` - +- **Class:** `CometChat.MainVideoContainerSetting` +- **Apply via:** `CallSettingsBuilder.setMainVideoContainerSetting(videoSettings)` +- **Customizable elements:** Aspect ratio, full screen button, name label, zoom button, user list button +- **Position constants:** `POSITION_TOP_LEFT`, `POSITION_TOP_RIGHT`, `POSITION_BOTTOM_LEFT`, `POSITION_BOTTOM_RIGHT` +- **Requires:** [Default Calling](/sdk/react-native/default-call) or [Call Session](/sdk/react-native/direct-call) setup + -## Overview +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()`. -This section guides you through customizing the main video container in your call UI. +Before you begin, make sure you've set up [Ringing](/sdk/react-native/default-call) or [Call Session](/sdk/react-native/direct-call). -Once you have decided to implement [Ringing](/sdk/react-native/default-call) or [Call Session](/sdk/react-native/direct-call) calling and followed the steps to implement them, a few additional methods will help you quickly customize the main video container. +## MainVideoContainerSetting -Please make sure your callSettings is configured accordingly for [Ringing](/sdk/react-native/default-call) or [Call Session](/sdk/react-native/direct-call). +| 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, `#333333` | +| `setZoomButtonParams(position, visibility)` | Position and visibility of the zoom button. | Bottom-right, visible | +| `setUserListButtonParams(position, visibility)` | Position and visibility of the user list button. | Bottom-right, visible | -## Main Video Container Setting +### Position Constants -The `MainVideoContainerSetting` class is required when 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`. +All position parameters accept one of these values from `CometChatCalls.CallSettings`: -| 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. CometChatCalls.CallSettings. ASPECT\_RATIO\_CONTAIN**
**2. CometChatCalls.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. **CometChatCalls.CallSettings. POSITION\_TOP\_LEFT**
2. **CometChatCalls.CallSettings. POSITION\_TOP\_RIGHT**
3. **CometChatCalls.CallSettings. POSITION\_BOTTOM\_LEFT**
4. **CometChatCalls.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 **#333333**

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

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

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

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

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

Possible Values for **VISIBILITY:**
1. **true**
2. **false** | +- `POSITION_TOP_LEFT` +- `POSITION_TOP_RIGHT` +- `POSITION_BOTTOM_LEFT` +- `POSITION_BOTTOM_RIGHT` -Example: +### Example + +```typescript +let videoSettings = new CometChat.MainVideoContainerSetting(); + +videoSettings.setMainVideoAspectRatio(CometChatCalls.CallSettings.ASPECT_RATIO_CONTAIN); +videoSettings.setFullScreenButtonParams(CometChatCalls.CallSettings.POSITION_BOTTOM_RIGHT, true); +videoSettings.setNameLabelParams(CometChatCalls.CallSettings.POSITION_BOTTOM_LEFT, true, "#333333"); +videoSettings.setZoomButtonParams(CometChatCalls.CallSettings.POSITION_BOTTOM_RIGHT, true); +videoSettings.setUserListButtonParams(CometChatCalls.CallSettings.POSITION_BOTTOM_RIGHT, true); + +// Pass to CallSettingsBuilder +const callSettings = new CometChatCalls.CallSettingsBuilder() + .setMainVideoContainerSetting(videoSettings) + // ... other settings + .build(); +``` + ```javascript let videoSettings = new CometChat.MainVideoContainerSetting(); -videoSettings.setMainVideoAspectRatio(CometChatCalls.CallSettings.ASPECT_RATIO_CONTAIN); videoSettings.setFullScreenButtonParams(CometChatCalls.CallSettings.POSITION_BOTTOM_RIGHT, true); +videoSettings.setMainVideoAspectRatio(CometChatCalls.CallSettings.ASPECT_RATIO_CONTAIN); +videoSettings.setFullScreenButtonParams(CometChatCalls.CallSettings.POSITION_BOTTOM_RIGHT, true); videoSettings.setNameLabelParams(CometChatCalls.CallSettings.POSITION_BOTTOM_LEFT, true, "#333333"); videoSettings.setZoomButtonParams(CometChatCalls.CallSettings.POSITION_BOTTOM_RIGHT, true); videoSettings.setUserListButtonParams(CometChatCalls.CallSettings.POSITION_BOTTOM_RIGHT, true); -``` +// Pass to CallSettingsBuilder +const callSettings = new CometChatCalls.CallSettingsBuilder() + .setMainVideoContainerSetting(videoSettings) + // ... other settings + .build(); +``` - -## Best Practices - - - - Avoid placing multiple buttons in the same corner position. Overlapping controls can make the UI confusing and hard to interact with. Spread controls across different corners for a clean layout. - - - The `ASPECT_RATIO_CONTAIN` mode ensures the full video frame is visible without cropping. Use `ASPECT_RATIO_COVER` only when you want the video to fill the container and are okay with some edges being clipped. - - - Video container customizations can look different across devices. Test your button positions and label visibility on both small phones and larger tablets to ensure a consistent experience. - - - -## Troubleshooting - - - - Ensure you pass the `MainVideoContainerSetting` object to `setMainVideoContainerSetting()` on the `CallSettingsBuilder` before calling `.build()`. Settings applied after building won't take effect. - - - Check that the `visibility` parameter is set to `true` for the button you want to show. Also verify that `enableDefaultLayout(true)` is set in your `CallSettingsBuilder`, as custom video settings work alongside the default layout. - - - --- ## Next Steps - - Start and manage call sessions with full configuration options + + Implement default audio/video calling. - - Record call sessions for playback and compliance + + Implement direct calling without call events. - Enable screen sharing and presenter layouts in calls + Enable screen sharing and presenter layouts. - - Implement a complete calling experience with incoming and outgoing call UI + + Record calls for playback. - \ No newline at end of file + 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." --- diff --git a/ui-kit/android/v4/overview.mdx b/ui-kit/android/v4/overview.mdx index 2b07e946b..50fbec913 100644 --- a/ui-kit/android/v4/overview.mdx +++ b/ui-kit/android/v4/overview.mdx @@ -12,12 +12,12 @@ With CometChat's UI Kit for Android, you can effortlessly build a chat app equip -[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. diff --git a/ui-kit/ios/methods.mdx b/ui-kit/ios/methods.mdx index d59caae27..85d7233ba 100644 --- a/ui-kit/ios/methods.mdx +++ b/ui-kit/ios/methods.mdx @@ -1,49 +1,22 @@ --- title: "Methods" -description: "Reference for CometChat iOS UI Kit methods including init, login, logout, and message-sending wrappers." +description: "Reference for CometChatUIKit wrapper methods that manage SDK operations, internal eventing, login, logout, user creation, and message sending in the iOS UI Kit." +sidebar_label: "Methods" --- - -```json -{ - "category": "methods", - "wrapperClass": "CometChatUIKit", - "methodCategories": [ - { - "name": "initialization", - "methods": [ - {"name": "init", "signature": "CometChatUIKit.init(uiKitSettings: UIKitSettings, completion:)", "description": "Initialize UI Kit with settings"} - ] - }, - { - "name": "authentication", - "methods": [ - {"name": "loginWithUID", "signature": "CometChatUIKit.login(uid: String, completion:)", "description": "Login using UID and Auth Key"}, - {"name": "loginWithToken", "signature": "CometChatUIKit.login(authToken: String, completion:)", "description": "Login using Auth Token"}, - {"name": "logout", "signature": "CometChatUIKit.logout(user: User, completion:)", "description": "Logout current user"}, - {"name": "createUser", "signature": "CometChatUIKit.create(user: User, completion:)", "description": "Create new user"} - ] - }, - { - "name": "messaging", - "methods": [ - {"name": "sendTextMessage", "signature": "CometChatUIKit.sendTextMessage(message: TextMessage)", "description": "Send text message"}, - {"name": "sendMediaMessage", "signature": "CometChatUIKit.sendMediaMessage(message: MediaMessage)", "description": "Send media message"}, - {"name": "sendCustomMessage", "signature": "CometChatUIKit.sendCustomMessage(message: CustomMessage)", "description": "Send custom message"} - ] - }, - { - "name": "interactiveMessages", - "methods": [ - {"name": "sendFormMessage", "signature": "CometChatUIKit.sendFormMessage(formMessage: FormMessage, completion:)", "description": "Send form message"}, - {"name": "sendCardMessage", "signature": "CometChatUIKit.sendCardMessage(cardMessage: CardMessage, completion:)", "description": "Send card message"}, - {"name": "sendSchedulerMessage", "signature": "CometChatUIKit.sendSchedulerMessage(schedulerMessage: SchedulerMessage, completion:)", "description": "Send scheduler message"} - ] - } - ] -} -``` - +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +- **Class:** `CometChatUIKit` +- **Import:** `import CometChatUIKitSwift` +- **Init:** `CometChatUIKit.init(uiKitSettings:onSuccess:onError:)` +- **Login:** `CometChatUIKit.login(uid:onSuccess:onError:)` or `CometChatUIKit.login(authToken:onSuccess:onError:)` +- **Logout:** `CometChatUIKit.logout(user:result:)` +- **Create user:** `CometChatUIKit.createUser(user:onSuccess:onError:)` +- **Send message:** `CometChatUIKit.sendTextMessage(message:onSuccess:onError:)`, `sendMediaMessage`, `sendCustomMessage` +- **Related:** [Getting Started](/ui-kit/ios/getting-started) · [Events](/ui-kit/ios/events) · [SDK Overview](/sdk/ios/overview) + ## Overview @@ -361,23 +334,24 @@ CometChatUIKit.sendSchedulerMessage(schedulerMessage: schedulerMessage) { schedu +*** + + --- ## Next Steps - - Listen and respond to UI Kit events. + + Listen to UI Kit component events - - Set up CometChat iOS UI Kit. + + Set up the iOS UI Kit from scratch - - Display and customize chat messages. + + Explore all available UI components - - Manage conversation lists. + + Explore the underlying CometChat SDK - ----